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: ring for plain-attention models via a ring-only job state (KVWinState)

YanissAmzd6b1f0d41632
diff --git a/exllamav3/cache/kvwin.py b/exllamav3/cache/kvwin.py
index ec44e9b..3df9ab5 100644
--- a/exllamav3/cache/kvwin.py
+++ b/exllamav3/cache/kvwin.py
@@ -281,6 +281,47 @@ class KVWinLayerState:
dst[slot].index_copy_(0, rows, out.view(-1, m.num_kv_heads, m.head_dim))
+class KVWinState:
+ """Job state of a model whose only recurrent layers are KVWIN rings (plain attention). No checkpoints: a job resumed
+ from cached pages (or rewound past MAX_DRAFT rows) gets a cold ring, rebuilt from the quantized pool."""
+
+ exported = False
+ guaranteed_rollback = MAX_DRAFT # rows the positional ring can rewind in place
+
+ def __init__(self, cache, slot: int, position: int, clear: bool = True, stashed: dict = None, test_state: bool = False):
+ self.slot = slot
+ self.position = position
+ self.cache = cache
+ self.last_history = 0
+ layers = cache.get_all_recurrent_layers().values()
+ for l in layers:
+ if stashed is not None:
+ l.unstash_missing(slot)
+ elif clear:
+ l.clear(slot)
+ self.checkpoint_size = sum(l.get_checkpoint_size() for l in layers)
+
+ def free(self):
+ self.cache.release_state(self)
+
+ def rewind(self, num_tokens: int):
+ assert num_tokens <= self.rollback_capacity()
+ self.position -= num_tokens
+ self.last_history = 0
+
+ def rollback_capacity(self):
+ return min(self.position, MAX_DRAFT)
+
+ def post_advance(self):
+ pass
+
+ def tp_export(self):
+ raise NotImplementedError("EXL3_KVWIN does not support tensor parallel loading")
+
+ def reset(self):
+ self.position = 0
+
+
def any_cold(params: dict) -> bool:
"""True when a job of this call has a cold ring (restored from a checkpoint without ring blob): its rebuild from the pool is a
host-side step, so the whole-forward graph declines that step (the eager call fills it) and replays from the next one."""
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index 16056d9..88dfbb6 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -369,6 +369,13 @@ class Generator:
self.max_batch_size = min(self.max_batch_size, cache.num_slots)
else:
self.recurrent_cache = None
+ # Plain-attention model with a bound KVWIN ring: jobs carry a ring-only state (no checkpoints, prefix reuse stays
+ # page-hash based; a restored prefix has a cold ring that is rebuilt from the quantized pool)
+ self.ring_states = self.recurrent_cache is None and self.model.kvwin_ring_only() and \
+ any(getattr(l, "cfg", None) is not None for l in cache.recurrent_layers.values())
+ if self.ring_states:
+ cache.reset_states()
+ self.max_batch_size = min(self.max_batch_size, cache.num_slots)
if recurrent_checkpoint_interval is None:
recurrent_checkpoint_interval = model.caps.get("default_recurrent_checkpoint_interval", 2048)
@@ -1727,7 +1734,7 @@ class Generator:
# Recurrent models carry mutable state beside the K/V cache; pass one state object per compact batch job so
# the model can advance or rewind it consistently with accepted draft tokens.
batch_states = None
- if self.recurrent_cache is not None:
+ if self.recurrent_cache is not None or self.ring_states:
batch_states = [job.recurrent_state for job in batch_jobs]
# GPU workload is scheduled here, so launch any sampling filters that can run in the background
diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.py
index e096a7d..855e244 100644
--- a/exllamav3/generator/job.py
+++ b/exllamav3/generator/job.py
@@ -977,6 +977,9 @@ class Job:
rw = self.recurrent_state.position - target
if rw <= self.recurrent_state.rollback_capacity():
self.recurrent_state.rewind(rw)
+ elif self.generator.ring_states:
+ self.recurrent_state.free()
+ self.recurrent_state = self._cold_ring_state(target) # the K/V pool is complete: only the ring is rebuilt
else:
stashed = self.find_recurrent_stash(target)
self.recurrent_state.free()
@@ -1824,6 +1827,8 @@ class Job:
position = cached_pages * PAGE_SIZE,
)
self.last_recurrent_checkpoint_pos = self.recurrent_state.position
+ elif self.generator.ring_states:
+ self.recurrent_state = self._cold_ring_state(cached_pages * PAGE_SIZE)
# End of the pages found by hash past the recurrent checkpoint (K/V valid, state not), read by EXL3_BRANCH_CKPT. Taken
# here, before any chunk runs: a chunk's page bookkeeping touches the page after its end, so a later chunk can't rescan
@@ -2250,6 +2255,14 @@ class Job:
return 1
+ def _cold_ring_state(self, position: int):
+ """Ring-only job state at `position`; its rings are rebuilt from the quantized pool at the first attention."""
+ cache = self.generator.cache
+ if position == 0:
+ return cache.get_new_state()
+ return cache.new_from_stashed({"position": position}, position)
+
+
def find_recurrent_stash(self, target_pos: int):
"""
Return the most recent page-aligned recurrent state stash at or before target_pos, refreshing its LRU
diff --git a/exllamav3/model/model.py b/exllamav3/model/model.py
index dba29c0..9de6073 100644
--- a/exllamav3/model/model.py
+++ b/exllamav3/model/model.py
@@ -8,7 +8,7 @@ from ..util.memory import free_mem
from .model_tp import Model_TPMixin
from .model_ls import Model_LSMixin
from ..util.tensor import g_tensor_cache
-from ..cache.recurrent_util import advance_recurrent_states
+from ..cache.recurrent_util import advance_recurrent_states, prepare_for_recurrence
from . import cuda_graph as _cuda_graph
import os
@@ -30,7 +30,7 @@ class Model(Model_TPMixin, Model_LSMixin):
self.active_devices = []
self.output_device = None
self.cache_weakrefs = {}
- self.recurrent_state_cls = None
+ self._recurrent_state_cls = None
self.draft_verifier_params = {}
# Index of last layer that affects KV cache, used during prefill
@@ -67,13 +67,27 @@ class Model(Model_TPMixin, Model_LSMixin):
return self._get_cache_layers
+ @property
+ def recurrent_state_cls(self):
+ """The job state class. A model with no recurrent state of its own (plain attention) whose attention modules declare
+ a KVWIN ring gets KVWinState: a job state that only carries the rings."""
+ c = self._recurrent_state_cls
+ if c is None and self.kvwin_ring_only():
+ from ..cache.kvwin import KVWinState
+ return KVWinState
+ return c
+
+ @recurrent_state_cls.setter
+ def recurrent_state_cls(self, value):
+ self._recurrent_state_cls = value
+
+ def kvwin_ring_only(self) -> bool:
+ """True when the only recurrent layers are KVWIN rings (no GDN / SWA / conv state)."""
+ return self._recurrent_state_cls is None and bool(self._get_recurrent_layers)
+
@cached_property
def _get_recurrent_layers(self):
- rl = [m for m in self if m.caps.get("recurrent_cache")]
- if self.recurrent_state_cls is None:
- # KVWIN rings ride the job's recurrent state: a model without recurrent state slots has none
- rl = [m for m in rl if not getattr(getattr(m, "layer_state_cls", None), "kvwin", False)]
- return rl
+ return [m for m in self if m.caps.get("recurrent_cache")]
def get_recurrent_layers(self):
return self._get_recurrent_layers
@@ -214,6 +228,8 @@ class Model(Model_TPMixin, Model_LSMixin):
if params is None:
params = {}
x = self.prepare_inputs(input_ids, params)
+ if params.get("recurrent_states") is not None and "recurrent_slots" not in params:
+ prepare_for_recurrence(input_ids, params, self) # ring-only models: their prepare_inputs does not
if self.loaded_tp:
y = self.prefill_tp(x, params, self.last_kv_module_idx, self.modules)
advance_recurrent_states(input_ids, params, self)
@@ -239,6 +255,8 @@ class Model(Model_TPMixin, Model_LSMixin):
if params is None:
params = {}
x = self.prepare_inputs(input_ids, params)
+ if params.get("recurrent_states") is not None and "recurrent_slots" not in params:
+ prepare_for_recurrence(input_ids, params, self) # ring-only models: their prepare_inputs does not
if self.loaded_tp:
y = self.forward_tp(x, params, self.last_kv_module_idx, self.modules)
advance_recurrent_states(input_ids, params, self)
diff --git a/tests/test_kvwin.py b/tests/test_kvwin.py
index 96000a8..22120d6 100644
--- a/tests/test_kvwin.py
+++ b/tests/test_kvwin.py
@@ -599,15 +599,46 @@ def test_ring_declines_qsa_caches(monkeypatch):
assert st.cfg is None and getattr(cl, "kvwin", None) is None
-def test_models_without_recurrent_state_drop_ring_layers():
+def test_plain_attention_model_gets_a_ring_only_state():
from exllamav3.model.model import Model
+ from exllamav3.cache.kvwin import KVWinState
a = _FakeAttn()
- other = types.SimpleNamespace(caps = {"recurrent_cache": True}, layer_state_cls = object)
- fake = types.SimpleNamespace(recurrent_state_cls = None, __iter__ = None)
- fake = type("M", (), {"recurrent_state_cls": None, "__iter__": lambda self: iter([a, other])})()
- assert Model._get_recurrent_layers.func(fake) == [other]
- fake2 = type("M", (), {"recurrent_state_cls": object, "__iter__": lambda self: iter([a, other])})()
- assert Model._get_recurrent_layers.func(fake2) == [a, other]
+ plain = type("M", (), {"_recurrent_state_cls": None, "_get_recurrent_layers": [a]})()
+ assert Model.kvwin_ring_only(plain)
+ assert Model.recurrent_state_cls.fget(types.SimpleNamespace(_recurrent_state_cls = None, kvwin_ring_only = lambda: True)) is KVWinState
+ none = type("M", (), {"_recurrent_state_cls": None, "_get_recurrent_layers": []})()
+ assert not Model.kvwin_ring_only(none)
+ hybrid = type("M", (), {"_recurrent_state_cls": object, "_get_recurrent_layers": [a]})()
+ assert not Model.kvwin_ring_only(hybrid)
+
+
+def test_ring_only_state_lifecycle_cold_resume_and_rewind(monkeypatch):
+ from exllamav3.cache.kvwin import KVWinState, make_ctx, ensure_filled
+ cache, model, cl, st = _fake_cache(monkeypatch)
+ cache.recurrent_state_cls = KVWinState
+ state = cache.get_new_state()
+ assert isinstance(state, KVWinState) and not st.cold[state.slot]
+ k = torch.randn(1, 300, 2, 128, device = DEV).half(); v = torch.randn_like(k)
+ sl = torch.zeros(1, dtype = torch.int32, device = DEV)
+ bt = torch.tensor([[1, 4, 6, 0, 2, 3, 5, 7]], dtype = torch.int32, device = DEV)
+ cl.update_kv_direct(sl, bt[:, :5].contiguous(), k, v, 300)
+ ov_write(KVWinCtx(st, torch.tensor([state.slot], dtype = torch.int32, device = DEV)), k, v, sl, 300)
+ state.position = 300
+ state.rewind(3)
+ assert state.position == 297 and state.rollback_capacity() == kvwin.MAX_DRAFT
+ state.free()
+ # a job resumed from cached pages: cold ring, rebuilt from the pool at the first attention
+ state2 = cache.new_from_stashed({"position": 256}, 256)
+ assert state2.position == 256 and st.cold[state2.slot]
+ params = {"recurrent_states": [state2], "recurrent_slots": torch.tensor([state2.slot], dtype = torch.int32),
+ "cache_seqlens": torch.tensor([256], dtype = torch.int32)}
+ ctx = make_ctx(st, params, torch.device(DEV), 1)
+ ensure_filled(ctx, params, bt)
+ assert not st.cold[state2.slot] and st.ov_k[state2.slot].any()
+ # a new state clears its ring
+ state2.free()
+ state3 = cache.get_new_state()
+ assert not st.ov_k[state3.slot].any() and not st.cold[state3.slot]
def test_attention_kvwin_ctx_entry(monkeypatch):