Skip to content

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.

Disk-first recurrent checkpoint cache: cap 0 legal, evictions spill to the prefix disk tier (#157)

Yaniss Amazouz66b63647b459
diff --git a/exllamav3/cache/recurrent.py b/exllamav3/cache/recurrent.py
index c346bfa..f68a87e 100644
--- a/exllamav3/cache/recurrent.py
+++ b/exllamav3/cache/recurrent.py
@@ -133,6 +133,9 @@ class RecurrentCache(OrderedDict):
state_size = stashed_state["checkpoint_size"]
while self.update_total_size() + state_size > self.max_size:
assert self.current_size >= 0, "Not enough space in cache for single state"
+ # disk-first (05/11): a cap below one entry (EXL3_RC_GB=0) is legal and keeps exactly the entry being stored
+ if len(self) == 0:
+ break
pt = self.pagetable
# A checkpoint whose anchor page chain has been broken by KV eviction can never be restored by
@@ -158,6 +161,12 @@ class RecurrentCache(OrderedDict):
self.metrics["stash_evictions"] += 1
self.exact_meta.pop(popped_key, None)
+ spill = getattr(self, "on_evict", None)
+ if spill is not None and "_ev" not in popped:
+ try:
+ spill(popped_key, popped) # PagedPrefixDisk.spill: queue the checkpoint for the disk tier (async write)
+ except Exception as e: # noqa: BLE001 the disk tier must never break a request
+ print(f"recurrent cache spill failed: {e}", flush=True)
note_freed(popped["checkpoint_size"])
if self.model.loaded_tp:
self.model.tp_dispatch_all(mp_cache_recurrent_del, (id(self), popped["tp_handle"]))
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index adff1c7..d8bfb8e 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -34,6 +34,7 @@ def _log_padded_vocab(model_vocab: int, piece_count: int):
from ..util.memory import malloc_trim
+from ..util.disk_store import env_dir as _disk_env_dir
from .pagetable import PageTable, is_content_hash
from .cpu_cache import CPUPageCache
from .draft_confidence import DraftConfidenceCalibrator
@@ -352,16 +353,26 @@ class Generator:
# Exact prompt-end checkpoints (see Job._tail_stash); EXL3_TAIL_CKPT=0 turns them off
self.tail_ckpts = []
- self.tail_ckpt_max = int(os.environ.get("EXL3_TAIL_CKPT", "8")) if tail_ckpt is None else int(tail_ckpt)
+ # Disk-first default: with the prefix disk tier on (EXL3_PREFIX_DISK_DIR) older checkpoints live on disk, so host RAM
+ # keeps few tail entries and a recurrent cache of one entry; without it the RAM tier is the only tier (8 / 8 / 4 GiB)
+ _disk_on = bool(_disk_env_dir())
+ self.tail_ckpt_max = int(os.environ.get("EXL3_TAIL_CKPT", "2" if _disk_on else "8")) if tail_ckpt is None else int(tail_ckpt)
# Sub-page prompt-tail checkpoints (EXL3_TAIL_SUB, see Job.sub_ckpt_rows): same entry format as tail_ckpts, kept in
# their own list so a long prompt's several entries never push the exact prompt-end checkpoints out. Host memory
# bound = sub_ckpt_max x one checkpoint (142 MiB on the KDA model, 75 MiB on the GDN one), oldest dropped first
self.sub_ckpts = []
- self.sub_ckpt_max = max(0, int(os.environ.get("EXL3_TAIL_SUB_MAX", "8"))) # 0 = keep no sub-page entry
+ self.sub_ckpt_max = max(0, int(os.environ.get("EXL3_TAIL_SUB_MAX", "1" if _disk_on else "8"))) # 0 = keep no sub-page entry
# prompts shorter than this never stash (the stash is 20-40 ms of host copy and 142 MiB per entry)
self.tail_ckpt_min = int(os.environ.get("EXL3_TAIL_MIN", "512"))
# Recurrent cache
+ # EXL3_RC_GB: host RAM cap of the recurrent checkpoint cache in GiB. Unset = 0 with the disk prefix tier on (the cache
+ # keeps the entry being stored, evictions spill to disk), else the argument (4 GiB by default). "" = the argument.
+ _rc_gb = os.environ.get("EXL3_RC_GB")
+ if _rc_gb is None and _disk_on:
+ _rc_gb = "0"
+ if _rc_gb:
+ recurrent_cache_size = int(float(_rc_gb) * 1024**3)
self.recurrent_cache_size = recurrent_cache_size
if self.model.caps.get("recurrent_states"):
self.recurrent_cache = RecurrentCache(self.model, recurrent_cache_size)
diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.py
index 855e244..ea86687 100644
--- a/exllamav3/generator/job.py
+++ b/exllamav3/generator/job.py
@@ -2220,6 +2220,12 @@ class Job:
continue
page = seq.allocated_pages[pos // PAGE_SIZE - 1]
assert page.kv_position == PAGE_SIZE
+ if pos == getattr(self, "kv_only_end", -1):
+ # EXL3_BRANCH_CKPT row (end of the shared run): the disk tier keeps it when it leaves host RAM (PagedPrefixDisk.spill)
+ bk = getattr(rc, "branch_keys", None)
+ if bk is None:
+ bk = rc.branch_keys = set()
+ bk.add(page.phash)
rc.put(page.phash, None, stashed = stashed)
rc.metrics["midchunk_stashes"] = rc.metrics.get("midchunk_stashes", 0) + 1
n += 1
diff --git a/exllamav3/generator/prefix_disk.py b/exllamav3/generator/prefix_disk.py
index b0199c7..b9c5b53 100644
--- a/exllamav3/generator/prefix_disk.py
+++ b/exllamav3/generator/prefix_disk.py
@@ -155,6 +155,8 @@ class PagedPrefixDisk:
sl = self.slots
g = sl.generator
rc = g.recurrent_cache
+ if rc is not None:
+ rc.on_evict = self.spill
ids = ids.view(1, -1).to("cpu", torch.long)
hashes, pages = sl._resident_chain(ids)
if rc is None or not hashes:
@@ -242,6 +244,26 @@ class PagedPrefixDisk:
self.stats["save_ms"] += ms
return {"saved": wrote, "stashes": sorted(want), "tail": tail is not None, "ms": ms}
+ # ---- spill (disk-first)
+
+ def spill(self, anchor: bytes, stash: dict) -> None:
+ """RecurrentCache eviction hook: a checkpoint leaving host RAM goes to the disk tier (async write) when save() would keep it
+ (page aligned, 2K/4K/8K... or inside the pinned first 8K tokens), so a small RAM cap loses no resume point. Deepest and
+ prompt-end checkpoints are written by save() at the end of the request."""
+ pos = stash.get("position", 0)
+ if "tp_handle" in stash or pos <= 0 or pos % PAGE_SIZE:
+ return
+ d = pos // PAGE_SIZE
+ branch = anchor in getattr(self.slots.generator.recurrent_cache, "branch_keys", ())
+ if not (_pow2(d) or d <= PIN_PAGES or branch):
+ return
+ if anchor in self.stashes and self._have(self.stashes[anchor][0]):
+ self.disk.touch(self.stashes[anchor][0])
+ return
+ name = f"c_{_hx(anchor)[:24]}"
+ self.disk.put(name, {"stash": stash}, {"ns": self.ns, "k": "stash", "anchor": anchor, "depth": d})
+ self.stashes[anchor] = (name, d)
+
# ---- restore
@torch.inference_mode()
@@ -252,6 +274,8 @@ class PagedPrefixDisk:
g = sl.generator
rc = g.recurrent_cache
pt = g.pagetable
+ if rc is not None:
+ rc.on_evict = self.spill
if rc is None or not self.pages:
return None
ids = ids.view(1, -1).to("cpu", torch.long)
diff --git a/tests/test_recurrent_disk_first_cpu.py b/tests/test_recurrent_disk_first_cpu.py
new file mode 100644
index 0000000..d636b8e
--- /dev/null
+++ b/tests/test_recurrent_disk_first_cpu.py
@@ -0,0 +1,95 @@
+"""Disk-first recurrent cache: cap 0 keeps one entry, evictions spill to the disk tier, spilled stashes read back. CPU only."""
+import os
+import types
+
+import torch
+
+from hardware import require
+require("ext")
+from exllamav3.cache.recurrent import RecurrentCache
+from exllamav3.constants import PAGE_SIZE
+from exllamav3.generator.prefix_disk import PagedPrefixDisk
+from exllamav3.util import disk_store as ds
+
+MIB = 1 << 20
+
+
+def stash(pos, mib = 1):
+ return {"checkpoint_size": mib * MIB, "position": pos, "x": torch.full((8,), float(pos))}
+
+
+def cache(max_size):
+ return RecurrentCache(types.SimpleNamespace(loaded_tp = False), max_size)
+
+
+def test_cap_zero_keeps_only_the_entry_in_flight():
+ rc = cache(0)
+ rc.put(b"a", None, stashed = stash(PAGE_SIZE))
+ assert list(rc) == [b"a"]
+ rc.put(b"b", None, stashed = stash(2 * PAGE_SIZE))
+ assert list(rc) == [b"b"] and rc.metrics["stash_evictions"] == 1
+
+
+def test_one_entry_cap():
+ rc = cache(MIB)
+ for i, k in enumerate((b"a", b"b", b"c")):
+ rc.put(k, None, stashed = stash((i + 1) * PAGE_SIZE))
+ assert list(rc) == [b"c"] and rc.metrics["stash_evictions"] == 2
+
+
+def test_four_gib_cap_evicts_nothing():
+ rc = cache(4 * 1024**3)
+ for i in range(6):
+ rc.put(bytes([i]), None, stashed = stash((i + 1) * PAGE_SIZE, mib = 142))
+ assert len(rc) == 6 and rc.metrics["stash_evictions"] == 0
+
+
+def test_eviction_hook_gets_the_victim_and_failures_are_swallowed():
+ rc = cache(0)
+ seen = []
+ rc.on_evict = lambda k, v: seen.append((k, v["position"]))
+ rc.put(b"a", None, stashed = stash(PAGE_SIZE))
+ rc.put(b"b", None, stashed = stash(2 * PAGE_SIZE))
+ assert seen == [(b"a", PAGE_SIZE)]
+ def boom(k, v):
+ raise RuntimeError("disk gone")
+ rc.on_evict = boom
+ rc.put(b"c", None, stashed = stash(3 * PAGE_SIZE)) # must not raise
+ assert list(rc) == [b"c"]
+
+
+def disk_tier(tmp_path, rc):
+ p = object.__new__(PagedPrefixDisk)
+ p.ns = "ns"
+ p.disk = ds.DiskStore(str(tmp_path), "ns", cap_gb = 1, floor_gb = 0, mb_per_min = 1e9)
+ p.stashes = {}
+ p.slots = types.SimpleNamespace(generator = types.SimpleNamespace(recurrent_cache = rc))
+ return p
+
+
+def test_spill_writes_aligned_anchors_and_restores_from_disk(tmp_path):
+ rc = cache(0)
+ p = disk_tier(tmp_path, rc)
+ rc.on_evict = p.spill
+ keys = {40: b"k40", 64: b"k64", 100: b"k100", 128: b"k128"} # depth in pages
+ for d in (40, 64, 100, 128):
+ rc.put(keys[d], None, stashed = stash(d * PAGE_SIZE))
+ rc.put(b"last", None, stashed = stash(129 * PAGE_SIZE))
+ p.disk.flush()
+ # depth 64 and 128 are powers of two (kept); 40 and 100 are neither pow2 nor in the pinned first 8K (32 pages): dropped
+ assert set(p.stashes) >= {b"k64", b"k128"} and b"k40" not in p.stashes and b"k100" not in p.stashes
+ name, depth = p.stashes[b"k64"]
+ got = p.disk.read(name)["stash"]
+ assert got["position"] == 64 * PAGE_SIZE and torch.equal(got["x"], torch.full((8,), float(64 * PAGE_SIZE)))
+ assert p.disk.read_idx(name)["depth"] == 64
+
+
+def test_spill_skips_unaligned_and_tp_and_keeps_branch_checkpoints(tmp_path):
+ rc = cache(0)
+ p = disk_tier(tmp_path, rc)
+ p.spill(b"u", stash(PAGE_SIZE + 1))
+ p.spill(b"t", {**stash(64 * PAGE_SIZE), "tp_handle": 1})
+ assert not p.stashes
+ rc.branch_keys = {b"br"}
+ p.spill(b"br", stash(40 * PAGE_SIZE)) # depth 40: not a power of two, kept as a branch checkpoint
+ assert b"br" in p.stashes