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.

KVWIN: a bound ring no longer disables page-boundary checkpoints or the async stash

YanissAmz5cab6c6ace0b
diff --git a/exllamav3/cache/kvwin.py b/exllamav3/cache/kvwin.py
index 89611da..c53ab75 100644
--- a/exllamav3/cache/kvwin.py
+++ b/exllamav3/cache/kvwin.py
@@ -203,6 +203,29 @@ class KVWinLayerState:
return out
return (self.ov_k[slot].cpu(), self.ov_v[slot].cpu())
+ def stash_async(self, slot, pin_pool: dict = None):
+ """Non-blocking D2H of the slot's ring into pinned host tensors (reused from pin_pool, see GDNLayerState.stash_async):
+ a ring that stashed through a blocking .cpu() kept the whole checkpoint synchronous, stalling every session's decode."""
+ if not self.active:
+ return None
+ return self.stash_from_snapshot((self.ov_k[slot], self.ov_v[slot]), pin_pool)
+
+ def snapshot(self, slot):
+ if not self.active:
+ return None
+ return (self.ov_k[slot].clone(), self.ov_v[slot].clone())
+
+ def stash_from_snapshot(self, snap, pin_pool: dict = None):
+ if snap is None:
+ return None
+ out = []
+ for src in snap:
+ free = None if pin_pool is None else pin_pool.get((tuple(src.shape), src.dtype))
+ dst = free.pop() if free else torch.empty(src.shape, dtype = src.dtype, pin_memory = True)
+ dst.copy_(src, non_blocking = True)
+ out.append(dst)
+ return tuple(out)
+
def unstash(self, slot, stashed, position: int = 0):
if not self.active:
return
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index 9467afc..8543fb7 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -406,7 +406,7 @@ class Generator:
if v is None:
from ..modules.block_sparse_mlp import BlockSparseMLP
from ..modules.sliding_attn import SlidingAttention
- swa_only = all(isinstance(m, SlidingAttention) for m in self.model.get_recurrent_layers())
+ swa_only = all(isinstance(m, SlidingAttention) for m in self.model.get_checkpoint_layers())
moe = not torch.version.hip and any(
isinstance(m, BlockSparseMLP) and getattr(m, "fused_mode_buffers", None) is not None
for m in self.model
diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.py
index 4dbb806..e096a7d 100644
--- a/exllamav3/generator/job.py
+++ b/exllamav3/generator/job.py
@@ -1903,7 +1903,7 @@ class Job:
if ok is None:
from ..modules.gated_delta_net import GatedDeltaNet
from ..modules.ple import PLELayer # Qwen 3.8: one PLE layer also holds a recurrent state (it saves its own mid-chunk state)
- rl = g.model.get_recurrent_layers()
+ rl = g.model.get_checkpoint_layers()
ok = bool(rl) and not g.model.loaded_tp and \
all(isinstance(m, PLELayer) or (isinstance(m, GatedDeltaNet) and not m.kda) for m in rl) and \
any(isinstance(m, GatedDeltaNet) for m in rl)
@@ -1924,7 +1924,7 @@ class Job:
ok = getattr(g, "_big_tail_ok", None)
if ok is None:
from ..modules.gated_delta_net import GatedDeltaNet
- rl = g.model.get_recurrent_layers()
+ rl = g.model.get_checkpoint_layers()
ok = bool(rl) and not g.model.loaded_tp and \
all(isinstance(m, GatedDeltaNet) and m.kda for m in rl)
g._big_tail_ok = ok
diff --git a/exllamav3/generator/prefix_disk.py b/exllamav3/generator/prefix_disk.py
index 791168e..74895c7 100644
--- a/exllamav3/generator/prefix_disk.py
+++ b/exllamav3/generator/prefix_disk.py
@@ -158,6 +158,7 @@ class PagedPrefixDisk:
if tail is not None and (tail[0] < deepest or "tp_handle" in tail[1]["stashed"]):
tail = None
keep_depth = max(deepest, 0 if tail is None else tail[0])
+ if os.environ.get("EXL3_PD_DEBUG"): print(f"PDDBG save N={ids.shape[1]} pages={len(hashes)} stash_depths={sorted(stash_at)} tail={None if tail is None else tail[0]} keep={keep_depth}", flush=True)
if keep_depth == 0:
return {"saved": 0}
want = {d for d in stash_at if d == deepest or _pow2(d) or d <= PIN_PAGES}
@@ -292,6 +293,7 @@ class PagedPrefixDisk:
if k * PAGE_SIZE + L > tail_pos:
tail_ix, tail_name, tail_pos = ix, nm, k * PAGE_SIZE + L
disk_pos = max(disk_depth * PAGE_SIZE, tail_pos)
+ if os.environ.get("EXL3_PD_DEBUG"): print(f"PDDBG restore N={N} ram_pos={ram_pos} ram_depth={ram_depth} avail={avail} disk_depth={disk_depth} tail_pos={tail_pos} disk_pos={disk_pos} stashes={len(self.stashes)} tails={len(self.tails)} rc={len(rc)}", flush=True)
if disk_pos <= ram_pos:
return None
need_pages = max(disk_depth, 0 if tail_ix is None else tail_ix["pages"])
diff --git a/exllamav3/model/model.py b/exllamav3/model/model.py
index 25957cf..dba29c0 100644
--- a/exllamav3/model/model.py
+++ b/exllamav3/model/model.py
@@ -78,6 +78,15 @@ class Model(Model_TPMixin, Model_LSMixin):
def get_recurrent_layers(self):
return self._get_recurrent_layers
+ @cached_property
+ def _get_checkpoint_layers(self):
+ return [m for m in self._get_recurrent_layers if not getattr(getattr(m, "layer_state_cls", None), "kvwin", False)]
+ def get_checkpoint_layers(self):
+ """Recurrent layers whose state shapes the checkpoint cadence (GDN / KDA / SWA / conv): the recurrent layers without the
+ KVWIN rings, which ride the job state but are not a state kind. Path eligibility checks (GDN no-tail, big tail, wide
+ prefill chunks) must see the same layers with the ring declared as without it."""
+ return self._get_checkpoint_layers
+
@cached_property
def _get_prefetch_layers(self):
# modules that stage input-dependent data (PLE n-gram rows) on a worker thread before the
diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.py
index a34fc82..c336707 100644
--- a/exllamav3/modules/gated_delta_net.py
+++ b/exllamav3/modules/gated_delta_net.py
@@ -241,7 +241,7 @@ class GDNState:
}
if not self.cache.model.loaded_tp:
layers = self.cache.get_all_recurrent_layers()
- if async_ and all(isinstance(l, GDNLayerState) for l in layers.values()):
+ if async_ and all(isinstance(l, GDNLayerState) or getattr(l, "kvwin", False) for l in layers.values()):
if os.environ.get("EXL3_STASH_SIDE", "0") == "1" and torch.cuda.is_available():
# Snapshot every layer's state on the device (one D2D copy each, 153 MB at 27B: ~0.4 ms) and run the D2H
# on a side stream: the copies (40 ms over a x4 link) overlap the first decode steps instead of delaying
diff --git a/tests/test_kvwin.py b/tests/test_kvwin.py
index e41c36d..96000a8 100644
--- a/tests/test_kvwin.py
+++ b/tests/test_kvwin.py
@@ -328,6 +328,53 @@ def test_stash_restore_bitwise():
assert ok, (err, mx)
+def test_stash_async_matches_sync():
+ """GDNState.stash(async_) needs every layer state to stash without a host sync: the ring's pinned D2H (pool reuse included)
+ reads the same bytes as the blocking stash, and the recurrent cache's finisher turns it into pageable clones."""
+ from exllamav3.cache.recurrent import RecurrentCache
+ rig = Rig(CFGS[0], slots = (1, 2), seed = 11)
+ rig.append(0, 450)
+ sync = rig.st.stash(1)
+ pool = {}
+ a = rig.st.stash_async(1, pool)
+ snap = rig.st.snapshot(1)
+ rig.st.ov_k[1].zero_() # the live ring moves on after the snapshot
+ b = rig.st.stash_from_snapshot(snap, pool)
+ ev = torch.cuda.Event(); ev.record(); ev.synchronize()
+ for x in (a, b):
+ assert all(t.is_pinned() for t in x)
+ assert torch.equal(x[0], sync[0]) and torch.equal(x[1], sync[1])
+ rc = RecurrentCache.__new__(RecurrentCache)
+ rc._pin_pool = pool
+ st = {"k": a, "_ev": ev}
+ RecurrentCache._finish(rc, st)
+ assert not st["k"][0].is_pinned() and torch.equal(st["k"][0], sync[0])
+ assert len(pool[(tuple(sync[0].shape), sync[0].dtype)]) == 1 # the pinned buffers went back to the pool
+ assert rig.st.stash_async(1) is not None and KVWinLayerState(rig.st.module, 2, 0, 0).stash_async(0) is None # inert: nothing to copy
+
+
+def test_ring_layers_do_not_change_path_eligibility(monkeypatch):
+ """A declared ring puts attention modules into get_recurrent_layers(); the checkpoint-cadence checks (GDN no-tail
+ mid-chunk checkpoints, big tail, wide prefill chunks) must see the GDN layers alone, as without the ring."""
+ from exllamav3.model.model import Model
+ from exllamav3.generator.job import Job
+ from exllamav3.modules.gated_delta_net import GatedDeltaNet
+ gdn = object.__new__(GatedDeltaNet)
+ gdn.kda = False
+ gdn.caps = {"recurrent_cache": True}
+ a = _FakeAttn()
+ plain = types.SimpleNamespace(caps = {"recurrent_cache": True}, layer_state_cls = object)
+ m = type("M", (), {"recurrent_state_cls": object, "__iter__": lambda self: iter([gdn, a, plain]),
+ "_get_recurrent_layers": property(lambda self: Model._get_recurrent_layers.func(self))})()
+ assert Model._get_recurrent_layers.func(m) == [gdn, a, plain]
+ assert Model._get_checkpoint_layers.func(m) == [gdn, plain]
+ mm = types.SimpleNamespace(loaded_tp = False, get_checkpoint_layers = lambda: [gdn])
+ fake = types.SimpleNamespace(recurrent_state = object(), embeddings = None, generator = types.SimpleNamespace(model = mm))
+ for k, v in (("EXL3_PF_NO_TAIL", "1"), ("EXL3_GDN_FUSE", "1")):
+ monkeypatch.setenv(k, v)
+ assert Job.gdn_no_tail_enabled(fake) is True
+
+
def test_cold_fill_from_pool():
"""A checkpoint without ring blob: fill rebuilds sinks + window from the dequantized pool (quant-level window)."""
cfg = CFGS[0]