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.

nc2 S4: asynchronous recurrent stash behind EXL3_NC2_ASYNC_STASH

yanissd0e15b835134
diff --git a/exllamav3/cache/recurrent.py b/exllamav3/cache/recurrent.py
index 4d750c7..ddb2b0d 100644
--- a/exllamav3/cache/recurrent.py
+++ b/exllamav3/cache/recurrent.py
@@ -1,4 +1,6 @@
+import os
from collections import OrderedDict
+from concurrent.futures import ThreadPoolExecutor
from ..constants import PAGE_SIZE
from ..util.memory import malloc_trim, set_host_mmap_threshold
@@ -34,6 +36,10 @@ class RecurrentCache(OrderedDict):
# Optionally set by the Generator; enables stranded-first eviction and staleness metrics
self.pagetable = None
+ # EXL3_NC2_ASYNC_STASH: stashes whose D2H is still in flight (see settle)
+ self._pending = []
+ self._pin_pool = {} # (shape, dtype) -> pinned host tensors free for reuse
+ self._worker = None
self.metrics = {
"stash_evictions": 0, # checkpoints dropped by LRU pressure
"stash_evictions_stranded": 0, # of those, checkpoints that were already unrestorable
@@ -42,10 +48,63 @@ class RecurrentCache(OrderedDict):
}
+ def _finish(self, st: dict):
+ """Worker thread: wait for the stash's D2H event, replace the pinned copies by pageable clones (the cache
+ never retains pinned memory), return the pinned buffers to the pool."""
+ st.pop("_ev").synchronize()
+ for k, v in st.items():
+ if isinstance(v, tuple) and v and all(hasattr(t, "is_pinned") and t.is_pinned() for t in v):
+ st[k] = tuple(t.clone() for t in v)
+ for t in v:
+ self._pin_pool.setdefault((tuple(t.shape), t.dtype), []).append(t)
+
+ def settle(self):
+ """
+ EXL3_NC2_ASYNC_STASH: wait until every pending asynchronous stash is finished (_finish). Called before any
+ reader sees an entry; normally a no-op since the worker ran during the next chunk.
+ """
+ pend = self._pending
+ if not pend:
+ return
+ self._pending = []
+ for f in pend:
+ f.result()
+
+ def async_stash_ok(self, state) -> bool:
+ return os.environ.get("EXL3_NC2_ASYNC_STASH", "0") == "1" and not self.model.loaded_tp and \
+ getattr(state, "supports_async_stash", False)
+
+ def stash_async(self, state) -> dict:
+ """Stash state without a host sync; the copies are pending until settle()."""
+ self.settle()
+ stashed_state = state.stash(async_ = True, pin_pool = self._pin_pool)
+ if "_ev" in stashed_state:
+ if self._worker is None:
+ self._worker = ThreadPoolExecutor(1, thread_name_prefix = "rc-stash")
+ self._pending.append(self._worker.submit(self._finish, stashed_state))
+ return stashed_state
+
+ def get(self, key, default = None):
+ self.settle()
+ return super().get(key, default)
+
+ def __getitem__(self, key):
+ self.settle()
+ return super().__getitem__(key)
+
+ def items(self):
+ self.settle()
+ return super().items()
+
+ def values(self):
+ self.settle()
+ return super().values()
+
def get_stashed(self, key, default = None):
"""
Fetch state from cache and move it to the end of the queue
"""
+ self.settle()
if key in self:
self.move_to_end(key)
return self[key]
@@ -60,7 +119,10 @@ class RecurrentCache(OrderedDict):
if key in self:
self.move_to_end(key)
else:
- stashed_state = state.stash() if stashed is None else stashed
+ if stashed is None and self.async_stash_ok(state):
+ stashed_state = self.stash_async(state)
+ else:
+ stashed_state = state.stash() if stashed is None else stashed
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"
@@ -130,7 +192,7 @@ class RecurrentCache(OrderedDict):
def update_total_size(self):
seen = set()
total = 0
- for v in self.values():
+ for v in OrderedDict.values(self): # sizes only: must not settle in-flight stashes
if id(v) in seen:
continue
seen.add(id(v))
diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.py
index 615436c..7149bfb 100644
--- a/exllamav3/generator/job.py
+++ b/exllamav3/generator/job.py
@@ -1931,8 +1931,13 @@ class Job:
t = _ttrace_begin()
carry = seq.mtp_carry_hidden
if _TT: print(f"trace: tail checkpoint size {self.recurrent_state.checkpoint_size / 2**20:.0f} MiB", flush=True)
+ rc = g.recurrent_cache
+ if rc is not None and rc.async_stash_ok(self.recurrent_state):
+ stashed = rc.stash_async(self.recurrent_state) # EXL3_NC2_ASYNC_STASH: settled before _tail_restore reads it
+ else:
+ stashed = self.recurrent_state.stash()
g.tail_ckpts.append({
- "prev_hash": prev_hash, "ids": ids, "stashed": self.recurrent_state.stash(),
+ "prev_hash": prev_hash, "ids": ids, "stashed": stashed,
"carry": None if carry is None else carry.clone(), "page": seq.allocated_pages[p0],
# EXL3_PF_DEFER: the draft K/V of this page is written after the first token, maybe never
"draft_ok": not self.mtp_defer,
@@ -1993,6 +1998,8 @@ class Job:
dst.can_revert = False
_ttrace_end(f"tail restore page copy rows={L}", t)
self.free_recurrent_state()
+ if g.recurrent_cache is not None:
+ g.recurrent_cache.settle()
self.recurrent_state = g.cache.new_from_stashed(e["stashed"], position = pos + L)
self.last_recurrent_checkpoint_pos = pos + L
if e["carry"] is not None:
diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.py
index 200df98..f8c3aa1 100644
--- a/exllamav3/modules/gated_delta_net.py
+++ b/exllamav3/modules/gated_delta_net.py
@@ -98,6 +98,8 @@ class GDNState:
# Prompt-end checkpoints (Job._tail_stash) are validated for this state class only
supports_tail_ckpt = True
+ # RecurrentCache.put may call stash(async_ = True) (EXL3_NC2_ASYNC_STASH)
+ supports_async_stash = True
def __init__(
self,
@@ -156,13 +158,24 @@ class GDNState:
return 0
- def stash(self):
+ def stash(self, async_: bool = False, pin_pool: dict = None):
+ """async_ (EXL3_NC2_ASYNC_STASH, via RecurrentCache.stash_async only): non-blocking D2H into pinned host tensors on the
+ current stream plus one event in stashed["_ev"]; the cache syncs it and moves the copies to pageable memory
+ (RecurrentCache._finish, worker thread) before any reader sees the entry."""
stashed = {
"position": self.position,
"checkpoint_size": self.checkpoint_size
}
if not self.cache.model.loaded_tp:
- for k, l in self.cache.get_all_recurrent_layers().items():
+ layers = self.cache.get_all_recurrent_layers()
+ if async_ and all(isinstance(l, GDNLayerState) for l in layers.values()):
+ for k, l in layers.items():
+ stashed[k] = l.stash_async(self.slot, pin_pool)
+ ev = torch.cuda.Event()
+ ev.record()
+ stashed["_ev"] = ev
+ return stashed
+ for k, l in layers.items():
stashed[k] = l.stash(self.slot)
else:
cp_handle = new_checkpoint_handle()
@@ -313,6 +326,19 @@ class GDNLayerState:
)
+ def stash_async(self, slot, pin_pool: dict = None):
+ """Non-blocking D2H into pinned host tensors, reused from pin_pool ((shape, dtype) -> free list) when given:
+ a pinned allocation costs ~1 ms of host time, more than the blocking copy it replaces."""
+ cdim = self.module.conv_kernel_size
+ out = []
+ for src in (self.recurrent_state[slot, :1], self.conv_state[slot, :, :cdim]):
+ 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):
cdim = self.module.conv_kernel_size
s, c = stashed