Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Prefix disk restore: one pinned bulk copy per cache tensor instead of per-page copies
YanissAmza496e2e8cd5d
diff --git a/exllamav3/generator/prefix_disk.py b/exllamav3/generator/prefix_disk.pyindex 4ff9d61..a5dac23 100644--- a/exllamav3/generator/prefix_disk.py+++ b/exllamav3/generator/prefix_disk.py@@ -33,6 +33,12 @@ from .pagetable import PAGE_SIZE, _randomhash, tensor_hash_checksumfrom .slot_store import SlotStoreFORMAT = "paged1"+_BULK_OFF_FILE = os.environ.get("EXL3_PD_BULK_OFF_FILE", "") # bench switch: while this file exists the per-page copies run+++def bulk_on() -> bool:+ """pinned bulk restore (default); EXL3_PD_BULK=0 = the per-page copies"""+ return os.environ.get("EXL3_PD_BULK", "1") != "0" and not (_BULK_OFF_FILE and os.path.exists(_BULK_OFF_FILE))def weights_identity(model_dir: str) -> str:@@ -85,6 +91,7 @@ class PagedPrefixDisk:self.stashes: dict[bytes, tuple[str, int]] = {} # anchor hash -> (entry, depth in pages)self.tails: dict[str, dict] = {} # entry -> idxself.pending: list[torch.Tensor] = []+ self._staging = ([None, None], [None, None]) # pinned host buffers + their last device-copy eventsself.stats = {"saves": 0, "save_ms": 0.0, "restores": 0, "restore_ms": 0.0, "restored_tokens": 0}self.load_index()@@ -316,9 +323,10 @@ class PagedPrefixDisk:if take > pt.num_unreferenced_pages():return Noneloaded = {}+ BULK = bulk_on()try:for nm in want:- loaded[nm] = self.disk.read(nm)+ loaded[nm] = self.disk.read(nm, mmap=BULK)stash = self.disk.read(self.stashes[disk_anchor][0])["stash"]tail_data = self.disk.read(tail_name) if tail_name else Noneexcept Exception: # noqa: BLE001 torn / evicted under us: drop, no restore@@ -335,6 +343,7 @@ class PagedPrefixDisk:order = Nonecopied = 0prev = None+ plan = {}for i in range(need_pages):h = hashes[i]live = pt.referenced_pages.get(h) or pt.unreferenced_pages.get(h)@@ -357,11 +366,20 @@ class PagedPrefixDisk:page.prev_hash = prevpage.sequence.copy_(d["sequences"][pos])page.kv_position = PAGE_SIZE- for s, t in zip(d["tensors"], tensors):- t[page.page_index].copy_(s[pos], non_blocking=False)+ if BULK:+ plan.setdefault(nm, ([], []))+ plan[nm][0].append(pos)+ plan[nm][1].append(page.page_index)+ else:+ for s, t in zip(d["tensors"], tensors):+ t[page.page_index].copy_(s[pos], non_blocking=False)page.sub_ref()copied += 1prev = h+ t_copy = time.perf_counter()+ if plan:+ self._bulk_copy(plan, loaded, tensors)+ copy_ms = (time.perf_counter() - t_copy) * 1000if disk_anchor not in rc:rc[disk_anchor] = stashrc.move_to_end(disk_anchor)@@ -376,4 +394,47 @@ class PagedPrefixDisk:self.stats["restores"] += 1self.stats["restore_ms"] += msself.stats["restored_tokens"] += disk_pos+ if os.environ.get("EXL3_PD_DEBUG"): print(f"PDDBG restored pages={copied} bulk={BULK} total_ms={ms:.0f} read_ms={(t_copy - t0) * 1000:.0f} copy_ms={copy_ms:.0f}", flush=True)return {"resume_at": disk_pos, "ram_at": ram_pos, "pages": copied, "ms": ms}++ def _bulk_copy(self, plan: dict, loaded: dict, tensors: list) -> None:+ """+ All restored pages in one pass per cache tensor: gather the rows of every segment into a pinned staging buffer (CPU, straight+ from the mmapped file), one host-to-device copy, one index_copy_ into the page pool. Two staging buffers: the gather of+ tensor j+1 overlaps the device copy of tensor j. Same bytes as the per-page copies, so the restored pages are identical.+ """+ dev = tensors[0].device+ order = list(plan)+ src = {nm: torch.tensor(plan[nm][0], dtype=torch.long) for nm in order}+ dst = torch.tensor([i for nm in order for i in plan[nm][1]], dtype=torch.long, device=dev)+ n = int(dst.numel())+ stream = torch.cuda.current_stream(dev)+ bufs, events = self._staging+ for j, t in enumerate(tensors):+ row = t[0].numel() * t.element_size()+ need = n * row+ b = j & 1+ if bufs[b] is None or bufs[b].numel() < need:+ if events[b] is not None:+ events[b].synchronize()+ bufs[b] = torch.empty(max(need, 1 << 20), dtype=torch.uint8, pin_memory=True)+ if events[b] is not None:+ events[b].synchronize() # the device copy that read this buffer last has finished+ stage = bufs[b][:need].view(t.dtype).view((n,) + tuple(t.shape[1:]))+ o = 0+ for nm in order:+ k = src[nm].numel()+ torch.index_select(loaded[nm]["tensors"][j], 0, src[nm], out=stage[o:o + k])+ o += k+ g = stage.to(dev, non_blocking=True)+ t.index_copy_(0, dst, g)+ ev = events[b] = torch.cuda.Event()+ ev.record(stream)+ del g+ if os.environ.get("EXL3_PD_VERIFY"): # test aid: every restored page equals its file bytes+ torch.cuda.synchronize()+ for j, t in enumerate(tensors):+ got = t.index_select(0, dst).cpu()+ want = torch.cat([loaded[nm]["tensors"][j].index_select(0, src[nm]) for nm in order])+ assert torch.equal(got.view(torch.uint8), want.view(torch.uint8)), f"bulk restore mismatch in tensor {j}"+ print(f"PDVERIFY ok pages={n} tensors={len(tensors)}", flush=True)diff --git a/exllamav3/util/disk_store.py b/exllamav3/util/disk_store.pyindex 1f2dac3..eaeae30 100644--- a/exllamav3/util/disk_store.py+++ b/exllamav3/util/disk_store.py@@ -84,8 +84,9 @@ class DiskStore:except Exception: # noqa: BLE001 torn / foreignreturn None- def read(self, name: str):- d = torch.load(self._p(name, ".pt"), map_location="cpu", weights_only=False)+ def read(self, name: str, mmap: bool = False):+ """mmap: tensors stay backed by the file (page cache), so a reader that copies only part of them pays only that part"""+ d = torch.load(self._p(name, ".pt"), map_location="cpu", weights_only=False, mmap=mmap)self.touch(name)self.stats["hits"] += 1return d