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.

Review fixes for prompt-end checkpoints: per-class opt-in gate, reset of the unaligned flag on requeue, draft K/V flag, refreshed duplicate entries, trim before append, minimum prompt length, Generator argument and clear_prompt_ckpts; add sequence regression check

YanissAmz5ed9e7f206de
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index f352440..c885869 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -19,7 +19,7 @@ from ..util.memory import malloc_trim
from .pagetable import PageTable, is_content_hash
from .cpu_cache import CPUPageCache
from .draft_confidence import DraftConfidenceCalibrator
-from .job import Job
+from .job import Job, _ttrace_begin, _ttrace_end
from .filter import Filter
from concurrent.futures import ThreadPoolExecutor
from .sampler import Sampler
@@ -99,6 +99,7 @@ class Generator:
num_draft_tokens: int | None = None,
show_visualizer: bool = False,
enable_defrag: bool = True,
+ tail_ckpt: int | None = None,
cpu_cache_size: int = 0,
recurrent_cache_size: int = 4 * 1024**3,
recurrent_checkpoint_interval: int = None,
@@ -300,7 +301,9 @@ 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"))
+ self.tail_ckpt_max = int(os.environ.get("EXL3_TAIL_CKPT", "8")) if tail_ckpt is None else int(tail_ckpt)
+ # 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
self.recurrent_cache_size = recurrent_cache_size
@@ -608,7 +611,6 @@ class Generator:
assert self.draft_cache is None or self.draft_cache.initialized, \
"Draft cache tensors were never allocated. Construct the draft Cache BEFORE calling draft_model.load()"
- from .job import _ttrace_begin, _ttrace_end
results = []
_t0 = _ttrace_begin()
self.iterate_start_jobs(results)
@@ -799,6 +801,11 @@ class Generator:
return self.draft_ids_pinned[:, :window]
+ def clear_prompt_ckpts(self):
+ """Drop every prompt-end recurrent checkpoint (host memory, ~142 MiB each)."""
+ self.tail_ckpts.clear()
+
+
def _flush_mtp_defer(self, job, with_tail: bool):
"""EXL3_PF_DEFER: run the draft prefill chunks that Job.prefill stashed instead of running them before the first
token. with_tail also writes the draft K/V row of the last prompt token (token L-1 paired with the hidden state
diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.py
index dcdb17a..ae35ecb 100644
--- a/exllamav3/generator/job.py
+++ b/exllamav3/generator/job.py
@@ -342,6 +342,8 @@ class Job:
self.mtp_defer_plain = False
self.mtp_defer_end = 0
self.mtp_defer_carry = None
+ # set by _tail_restore: this job resumed mid-page, later chunks may start unaligned (reset on requeue)
+ self._unaligned_start = False
def get_pinned_logit_mask(self):
@@ -1334,7 +1336,7 @@ class Job:
if prefill_end <= prefill_start:
continue
- assert prefill_start % PAGE_SIZE == 0 or mm_exact_chunks or getattr(self, '_unaligned_start', False)
+ assert prefill_start % PAGE_SIZE == 0 or mm_exact_chunks or self._unaligned_start
prefill_ids = seq.sequence_ids.torch_slice(prefill_start, prefill_end)
# Special case for partial last page, check if there's a page anywhere in the cache that
@@ -1883,7 +1885,7 @@ class Job:
return (
g.tail_ckpt_max > 0 and g.recurrent_cache is not None and self.recurrent_state is not None
and not self.embeddings and len(self.sequences) == 1 and not g.model.loaded_tp
- and getattr(g.cache.recurrent_state_cls, "__name__", "") == "GDNState" # sliding-window states (MiMo) are not covered
+ and getattr(g.cache.recurrent_state_cls, "supports_tail_ckpt", False) # opt-in per state class (GDNState only)
)
@@ -1901,25 +1903,35 @@ class Job:
if end != len(seq.sequence_ids) - 1 or end % PAGE_SIZE == 0 or self.recurrent_state.position != end:
return
g = self.generator
+ if end < g.tail_ckpt_min: # short one-shot prompts: the stash costs more than a replay
+ return
p0 = end // PAGE_SIZE
if len(seq.allocated_pages) <= p0 or (p0 > 0 and seq.allocated_pages[p0 - 1].kv_position != PAGE_SIZE):
return
prev_hash = None if p0 == 0 else seq.allocated_pages[p0 - 1].phash
ids = seq.sequence_ids.torch_slice(p0 * PAGE_SIZE, end).clone()
+ carry_now = seq.mtp_carry_hidden
for e in g.tail_ckpts:
if e["prev_hash"] == prev_hash and e["ids"].shape == ids.shape and torch.equal(e["ids"], ids):
+ # same content: refresh the page (the old one may be recycled) and the carry, move to MRU
+ e["page"] = seq.allocated_pages[p0]
+ e["draft_ok"] = not self.mtp_defer
+ if carry_now is not None:
+ e["carry"] = carry_now.clone()
g.tail_ckpts[:] = [x for x in g.tail_ckpts if x is not e]
g.tail_ckpts.append(e)
return
+ while len(g.tail_ckpts) >= g.tail_ckpt_max: # trim before the append: the peak stays at the bound
+ g.tail_ckpts.pop(0)
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)
g.tail_ckpts.append({
"prev_hash": prev_hash, "ids": ids, "stashed": self.recurrent_state.stash(),
"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,
})
- while len(g.tail_ckpts) > g.tail_ckpt_max:
- g.tail_ckpts.pop(0)
_ttrace_end("tail checkpoint stash", t)
@@ -1957,6 +1969,10 @@ class Job:
if pos + L > total or not torch.equal(e["ids"], seq.sequence_ids.torch_slice(pos, pos + L)):
continue
dst = pages[i]
+ if dst.kv_position == PAGE_SIZE and dst.prev_hash != ph: # a complete revived page must follow the entry's chain
+ continue
+ if dst.kv_position != PAGE_SIZE and g.draft_model and not e.get("draft_ok", True):
+ continue
if dst.kv_position != PAGE_SIZE: # a complete revived page already holds this K/V
src = e["page"]
if src is dst or src.prev_hash != ph or src.kv_position < L or \
diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.py
index 4fda754..09cb29a 100644
--- a/exllamav3/modules/gated_delta_net.py
+++ b/exllamav3/modules/gated_delta_net.py
@@ -96,6 +96,9 @@ QWD3 = {"skip": 0} # harness-only kill test: 1 = reuse the last b / a outputs
class GDNState:
+ # Prompt-end checkpoints (Job._tail_stash) are validated for this state class only
+ supports_tail_ckpt = True
+
def __init__(
self,
cache: Cache,
diff --git a/tests/check_tail_ckpt_sequences.py b/tests/check_tail_ckpt_sequences.py
new file mode 100644
index 0000000..116c6bb
--- /dev/null
+++ b/tests/check_tail_ckpt_sequences.py
@@ -0,0 +1,53 @@
+# check_tail_ckpt_sequences.py PORT TAG MODELID : tail-checkpoint regression sequences against a running server (follow-up, edited history, shorter prefix, shared tail, 9-way interleave). ONLY=name,.. runs listed requests once (oracle on a stock server). Compare md5s: stock-cold == new, repeat == cold.
+import sys, json, urllib.request, hashlib
+port, tag, mid = sys.argv[1], sys.argv[2], sys.argv[3]
+def post(msgs, mt=48):
+ body = json.dumps({"model": mid, "messages": msgs, "max_tokens": mt, "temperature": 0}).encode()
+ r = json.load(urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", body, {"Content-Type": "application/json"}), timeout=900))
+ c = r["choices"][0]["message"]; tm = r["timings"]
+ return [hashlib.md5(((c.get("content") or "") + "|" + (c.get("reasoning_content") or "")).encode()).hexdigest()[:8], tm["cache_n"], tm["prompt_n"], round(tm["prompt_ms"])]
+W = ["alpha","river","stone","lamp","orbit","violin","cedar","harbor","quartz","meadow","ember","tundra"]
+def fill(n, seed): return " ".join(f"{W[(i*7+seed)%12]}{(i*31+seed)%97}" for i in range(n))
+def U(t): return {"role":"user","content":t}
+def A(t): return {"role":"assistant","content":t}
+S = {"role":"system","content":"Be terse. " + fill(150, 1)}
+base = fill(500, 11)
+seq = []
+c1 = [S, U("Context: " + base + " Q1: name a river from the text.")]
+seq.append(("c1", c1))
+c2 = c1 + [A("river12"), U("Q2: and a stone?")]
+seq.append(("c2_follow", c2))
+c3 = c2 + [A("stone5"), U("Q3: and a lamp? Answer in two words.")]
+seq.append(("c3_follow", c3))
+# edited history: one word changed deep in the first turn, then same follow-up
+base_e = base.replace("cedar", "cedarx", 3)
+seq.append(("edit_deep", [S, U("Context: " + base_e + " Q1: name a river from the text."), A("river12"), U("Q2: and a stone?")]))
+# edit of the assistant turn only
+seq.append(("edit_asst", c1 + [A("it is river99"), U("Q2: and a stone?")]))
+# shorter prefix: first ~300 words of the context only, same system
+seq.append(("short_prefix", [S, U("Context: " + " ".join(base.split()[:300]) + " Q1: name a river from the text.")]))
+# shared page k, different earlier pages: same big tail text after different heads
+tailtxt = fill(400, 21)
+for k, head in enumerate([fill(40, 31), fill(40, 32), fill(300, 33)]):
+ seq.append((f"sharedtail{k}", [U(head + " " + tailtxt + " Q: say one word.")]))
+# 9 interleaved conversations, then continue the first ones (eviction of the tail LRU)
+convs = [[U("Topic %d: " % j + fill(450 + 13*j, 40 + j) + " Q1: say one word.")] for j in range(9)]
+for j, c in enumerate(convs): seq.append((f"il{j}", c))
+for j in range(3):
+ seq.append((f"il{j}_cont", convs[j] + [A("word"), U("Q2: another word?")]))
+import os
+only = os.environ.get("ONLY")
+out = {}
+if only: # oracle mode: fresh server, listed requests, first-time (cold) only
+ for name, m in seq:
+ if name in only.split(","):
+ out[f"cold_{name}"] = post(m); print(tag, "cold", name, out[f"cold_{name}"], flush=True)
+else:
+ for name, m in seq: # cold then immediate repeat
+ if name.startswith("il"): continue
+ out[f"a_{name}"] = post(m); out[f"b_{name}"] = post(m)
+ print(tag, name, out[f"a_{name}"], out[f"b_{name}"], flush=True)
+ for name, m in seq: # 9 interleaved, then continue the first 3
+ if name.startswith("il"):
+ out[f"a_{name}"] = post(m); print(tag, name, out[f"a_{name}"], flush=True)
+json.dump(out, open(f"res_{tag}_ident3.json", "w"))