"""Bounded exact file-backed replacement for EngramEmbedding's owned-row gather. The original hash, gating, projections, TP all-reduce and model remain unchanged. Native callback executes IO inside CUDA graphs without calling the CUDA API. """ import ctypes as C import glob import json import logging import os from pathlib import Path import struct import torch P, U = C.c_void_p, C.c_uint64 _lib = C.CDLL(str(Path(__file__).with_name('librow_store.so'))) _lib.row_store_open.argtypes = [C.c_char_p, U, U, U, U] _lib.row_store_open.restype = P _lib.row_store_range.argtypes = [P, U, U] _lib.row_store_stats.argtypes = [P, C.POINTER(U)] _lib.row_store_attach_packed.argtypes = [P, C.c_char_p, U] _lib.row_store_attach_packed.restype = C.c_int # Present only in images built with -DDSV41_ROW_STORE_DRM (the TP4 canary Dockerfiles). # The default image's librow_store.so does not export it, and ./start.sh never calls it. _drm_next = getattr(_lib, "row_store_next_cache_on_drm", None) if _drm_next is not None: _drm_next.argtypes = [C.c_char_p, U] _DRM_USED = [False] class Work(C.Structure): _fields_ = [('store', P), ('ids', P), ('weights', P), ('scales', P), ('count', U)] _STORES = [] def _stats(store): out = (U * 9)() _lib.row_store_stats(store, out) hits, misses, reads, cache_bytes, slots, scale_bytes, ways, threads, packed = out return dict(hits=hits, misses=misses, reads=reads, cache_bytes=cache_bytes, slots=slots, scale_bytes=scale_bytes, ways=ways, threads=threads, packed=bool(packed)) def _report(): """Miss rate and read volume decide decode latency here; log them.""" import threading import time period = float(os.getenv('DSV41_STATS_SECONDS', '60')) if period <= 0: return log = logging.getLogger(__name__) def loop(): previous = {} while True: time.sleep(period) for store, layer_id in _STORES: now = _stats(store) was = previous.get(layer_id) previous[layer_id] = now if was is None: continue hits = now['hits'] - was['hits'] misses = now['misses'] - was['misses'] total = hits + misses if not total: continue log.info('Engram layer=%s lookups=%s hit_rate=%.1f%% reads=%s ' 'cache=%.1fGiB(%s-way) scales=%.1fGiB threads=%s packed=%s', layer_id, total, 100.0*hits/total, now['reads']-was['reads'], now['cache_bytes']/2**30, now['ways'], now['scale_bytes']/2**30, now['threads'], now['packed']) threading.Thread(target=loop, daemon=True, name='engram-stats').start() def _register_store(store, layer_id): _STORES.append((store, layer_id)) if len(_STORES) == 1: _report() def _load_cudart(): paths = [] paths += glob.glob('/usr/local/cuda*/targets/aarch64-linux/lib/libcudart.so*') paths += glob.glob('/usr/local/cuda*/targets/x86_64-linux/lib/libcudart.so*') paths += glob.glob('/usr/local/cuda/lib64/libcudart.so*') paths += glob.glob('/usr/local/lib/python*/dist-packages/nvidia/cuda_runtime/lib/libcudart.so*') paths += glob.glob('/usr/local/lib/python*/site-packages/nvidia/cuda_runtime/lib/libcudart.so*') seen, errors = set(), [] for path in paths: if path in seen or path.endswith('.a') or not os.path.isfile(path): continue seen.add(path) try: lib = C.CDLL(path) lib.cudaLaunchHostFunc.argtypes = [P, P, P] lib.cudaLaunchHostFunc.restype = C.c_int return lib except OSError as exc: errors.append(f'{path}: {exc}') raise RuntimeError('libcudart.so not found (need CUDA runtime for Engram host callbacks). Tried: ' + '; '.join(errors or paths or [''])) _cuda = _load_cudart() def install(module): cls = module.EngramEmbedding def init(self, num_embeddings, dim, layer_id): torch.nn.Module.__init__(self) assert dim == 256 self.dim, self.tp_size = dim, module.get_parallel().tp_size rank = module.get_parallel().tp_rank self.row_start = num_embeddings * rank // self.tp_size end = num_embeddings * (rank + 1) // self.tp_size self.rows, self.host_table = end - self.row_start, None root = Path(os.environ['DSV41_SOURCE']) index = json.loads((root/'model.safetensors.index.json').read_text())['weight_map'] prefix = f'layers.{layer_id}.engram.embed.' filename = root/index[prefix+'weight'] assert index[prefix+'weight'] == index[prefix+'scale'] with filename.open('rb') as f: length = struct.unpack('