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.

Qwen tail-reply resume: reply-end tail checkpoint + deferred page release (follow-up turn prefill x0.90)

YanissAmz08b79148007c
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index f04585e..05eb157 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -19,7 +19,12 @@ 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, _ttrace_begin, _ttrace_end
+from .job import Job, _ttrace_begin, _ttrace_end, _TAIL_REPLY as _TAIL_REPLY_GEN
+# EXL3_REPLY_FIRST=1 (default off): a job that finishes inside iterate() is released (deallocate_pages: reply-end tail
+# stash, draft flush, page / slot release) by flush_deferred() AFTER its last results are returned, not before. The server calls it
+# once the results are handed out; every iterate / cancel / clear_queue runs it first, so later work sees the same cache state in
+# the same order (exact by construction). Pays where the stash is a blocking copy (HIP .cpu(), CUDA EXL3_TAIL_PIN=0).
+_REPLY_FIRST = os.environ.get("EXL3_REPLY_FIRST", "0") == "1"
from . import spec_sample
from .filter import Filter
from concurrent.futures import ThreadPoolExecutor
@@ -260,6 +265,7 @@ class Generator:
self.job_serial = 0
self.pending_jobs = []
self.active_jobs = []
+ self.deferred_jobs = [] # EXL3_REPLY_FIRST: finished jobs not yet released
# Filter threads
self.filter_pool = ThreadPoolExecutor(max_workers = 16)
@@ -464,6 +470,7 @@ class Generator:
Abort all active and pending jobs
"""
+ self.flush_deferred()
num_jobs = self.num_remaining_jobs()
for job in self.active_jobs + self.pending_jobs:
job.deallocate_pages()
@@ -516,6 +523,7 @@ class Generator:
block tables still depend on the current physical page ordering.
"""
+ self.flush_deferred()
num_jobs = self.num_remaining_jobs()
if job in self.pending_jobs:
@@ -527,8 +535,23 @@ class Generator:
self.on_queue_drained()
+ def flush_deferred(self):
+ """
+ EXL3_REPLY_FIRST: release the jobs that finished in the last iterate() (see _REPLY_FIRST). No-op when none.
+ """
+ if not self.deferred_jobs:
+ return
+ jobs, self.deferred_jobs = self.deferred_jobs, []
+ with torch.inference_mode():
+ for job in jobs:
+ job.deallocate_pages()
+ if not self.num_remaining_jobs():
+ self.on_queue_drained()
+
+
@torch.inference_mode
def iterate(self) -> list[dict]:
+ self.flush_deferred()
results = self._iterate_inner()
if _moe_fused_check is not None:
_moe_fused_check(self.model)
@@ -1563,6 +1586,18 @@ class Generator:
# The EOS stream event was already built inside receive_sample, so patch its counter too
if eos:
num_unresolved = batch_logits.shape[1] - 1 - i if draft_tokens is not None else 0
+ # EXL3_TAIL_REPLY: roll the recurrent state and page positions back to the accepted
+ # position (as a rejection would) so the finished job can stash an exact reply-end tail
+ if _TAIL_REPLY_GEN and draft_tokens is not None and batch_states is not None \
+ and len(job.sequences) == 1:
+ batch_states[j].rewind(num_unresolved) # rewind(0) too: it normalises the per-token history
+ r_ = num_unresolved
+ seq_ = job.sequences[0]
+ while r_:
+ page = seq_.allocated_pages[(seq_.kv_position + r_ - 1) // PAGE_SIZE]
+ rp = min(page.kv_position, r_)
+ page.kv_position -= rp
+ r_ -= rp
if num_unresolved:
job.rejected_draft_tokens += num_unresolved
for r_ in reversed(results):
@@ -1734,7 +1769,10 @@ class Generator:
for job in completed_jobs + requeuing_jobs:
if job in requeuing_jobs and self.recurrent_cache is not None:
job.maybe_stash_recurrent(self.recurrent_cache, PAGE_SIZE)
- job.deallocate_pages()
+ if _REPLY_FIRST and job not in requeuing_jobs:
+ self.deferred_jobs.append(job) # released by flush_deferred() after the results are out
+ else:
+ job.deallocate_pages()
self.active_jobs.remove(job)
# Requeue jobs. Puts replacement jobs at the front so long generations continue promptly after they yield
@@ -1744,7 +1782,7 @@ class Generator:
self.pending_jobs.insert(0, rq_job)
# Defrag. Physical page indices can only be compacted when no active block tables are using them.
- if num_jobs and not self.num_remaining_jobs():
+ if num_jobs and not self.num_remaining_jobs() and not self.deferred_jobs:
self.on_queue_drained()
diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.py
index 9ae6c5a..6742ffe 100644
--- a/exllamav3/generator/job.py
+++ b/exllamav3/generator/job.py
@@ -45,6 +45,9 @@ def _strings_to_utf32(strings: tuple[str]) -> tuple[np.ndarray, np.ndarray] | No
_TT = bool(os.environ.get("KYO_TURN_TRACE"))
+# EXL3_TAIL_REPLY=1 (default off): a finished job also stashes a tail checkpoint at the END of its reply, so the
+# next turn (prompt = old prompt + reply + new message) resumes after the reply instead of replaying its last page
+_TAIL_REPLY = os.environ.get("EXL3_TAIL_REPLY", "0") == "1"
def _ttrace_begin():
if not _TT: return 0.0
torch.cuda.synchronize()
@@ -1717,6 +1720,11 @@ class Job:
def deallocate_pages(self):
+ if _TAIL_REPLY and self.is_finished and len(self.sequences) == 1 and self.sequences[0].allocated_pages:
+ try:
+ self._tail_stash(self.sequences[0], reply = True) # BEFORE the mtp_defer flush -> honest draft_ok
+ except Exception as e: # cleanup must not raise: a missed stash only costs a replay next turn
+ logging.warning("EXL3_TAIL_REPLY stash failed: %r", e)
if self.mtp_defer:
try:
self.generator._flush_mtp_defer(self, with_tail = self.mtp_defer_plain)
@@ -1930,7 +1938,7 @@ class Job:
)
- def _tail_stash(self, seq):
+ def _tail_stash(self, seq, reply = False):
"""
Exact prompt-end checkpoint. Recurrent checkpoints sit on page boundaries, so a follow-up request replays
the prompt tail after the last full page (up to 255 tokens, each turn). Keep the recurrent state at the very
@@ -1941,7 +1949,9 @@ class Job:
if not self._tail_ok(seq):
return
end = seq.kv_position
- if end != len(seq.sequence_ids) - 1 or end % PAGE_SIZE == 0 or self.recurrent_state.position != end:
+ # reply = True (EXL3_TAIL_REPLY, job finished): the last sampled token has no K/V yet, so end <= len - 1
+ if (end > len(seq.sequence_ids) - 1 if reply else end != len(seq.sequence_ids) - 1) or \
+ end % PAGE_SIZE == 0 or self.recurrent_state is None 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
@@ -1951,7 +1961,8 @@ class Job:
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
+ # reply: the live decode carry; seq.mtp_carry_hidden still holds the prompt-end carry
+ carry_now = self.mtp_last_hidden if reply else 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
@@ -1965,7 +1976,7 @@ class Job:
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
+ carry = self.mtp_last_hidden if reply else 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):
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 7ddb085..0c9c7eb 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -439,6 +439,7 @@ def load_image(url: str) -> tuple[Any, str]:
MAX_SESSIONS = 16 # upper bound of --sessions (the Cache default max_batch_size)
+
class ResidentEngine:
"""One loaded target model, optional MTP model, and resident paged caches."""
supports_prefix_reuse = True
@@ -555,8 +556,17 @@ class ResidentEngine:
self.slot_store.generator = self.greedy_generator
self.slot_store.erase()
+ async def settle_reply(self) -> None:
+ """EXL3_REPLY_FIRST, single-session path: the previous request's finished job is released in an executor
+ thread after its reply went out (see generate's finally); wait for it before anything touches the Generator or Cache."""
+ fut = getattr(self, "_reply_first_fut", None)
+ if fut is not None:
+ self._reply_first_fut = None
+ await fut
+
async def reset_prefix_cache(self) -> None:
"""Forget every cached prompt prefix (cache_salt namespace change). The caller has drained the requests."""
+ await self.settle_reply()
if self.sessions > 1:
await self._post(self._rebuild_generator) # on the driver, between two steps
else:
@@ -616,6 +626,7 @@ class ResidentEngine:
import torch
from exllamav3.generator.sampler import ComboSampler, GreedySampler
t0 = time.perf_counter()
+ await self.settle_reply()
probe = getattr(self, "rss_probe", None)
embs = []
if prompt_ids is not None: # token-id prompt: exactly these ids, no template, no BOS, no re-encoding
@@ -654,8 +665,8 @@ class ResidentEngine:
async for piece in self._run_shared(job, ids, cancel, stats if stats is not None else {}, t0, probe):
yield piece
return
- generator.enqueue(job)
loop = asyncio.get_running_loop()
+ generator.enqueue(job)
try:
while generator.num_remaining_jobs():
if cancel is not None and cancel.is_set():
@@ -680,6 +691,8 @@ class ResidentEngine:
# a leftover job would run inside the next request.
if generator.num_remaining_jobs():
generator.clear_queue()
+ if getattr(generator, "deferred_jobs", None): # EXL3_REPLY_FIRST: release (reply-end stash) while the reply goes out
+ self._reply_first_fut = loop.run_in_executor(None, generator.flush_deferred)
# Shared mode (sessions > 1). One driver task is the only code that touches the Generator: it runs queued commands
# (enqueue, cancel, image tower, slot actions) between two iterate() calls and routes the events of each step to the
@@ -716,6 +729,7 @@ class ResidentEngine:
async def _drive_loop(self) -> None:
loop = asyncio.get_running_loop()
+ rf_wait = 0.0
while True:
while self._cmds:
fn, args, fut = self._cmds.pop(0)
@@ -734,6 +748,22 @@ class ResidentEngine:
# read every round: _rebuild_generator (cache_salt change) replaces the Generator between two steps
generator = self.greedy_generator
if not generator.num_remaining_jobs():
+ # EXL3_REPLY_FIRST: release the finished jobs (reply-end stash) once idle AND their handlers have
+ # dropped their routes (forget is the last driver command a request waits for before its reply ends), at most
+ # 50 ms after the step; a new request's iterate() releases them first anyway
+ dj = getattr(generator, "deferred_jobs", None)
+ if dj and not self._cmds:
+ if rf_wait < 0.05 and any(self._routes.get(getattr(j, "serial_number", None)) is not None for j in dj):
+ self._wake.clear()
+ try:
+ await asyncio.wait_for(self._wake.wait(), 0.005)
+ except asyncio.TimeoutError:
+ pass
+ rf_wait += 0.005
+ continue
+ rf_wait = 0.0
+ await loop.run_in_executor(None, generator.flush_deferred)
+ continue
self._wake.clear()
if not self._cmds:
await self._wake.wait()
@@ -1484,6 +1514,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
body = await request.json() if request.can_read_body else {}
try:
async with exclusive():
+ if hasattr(engine, "settle_reply"):
+ await engine.settle_reply()
if action == "erase":
return web.json_response(store.erase())
if action not in ("save", "restore"):
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 34501d5..bdead19 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -73,6 +73,7 @@ DEFAULT_TEMPLATE = Path(__file__).with_name("chat_template.jinja")
EFFORT_ALIASES = {"high": "xhigh", "minimal": "low"}
+
class BadRequest(Exception):
pass
@@ -936,6 +937,7 @@ class QwenEngine:
async def _drive_loop(self) -> None:
loop = asyncio.get_running_loop()
+ rf_wait = 0.0
while True:
while self._cmds:
fn, args, fut = self._cmds.pop(0)
@@ -953,6 +955,22 @@ class QwenEngine:
if not fut.done():
fut.set_result(res)
if not self.generator.num_remaining_jobs():
+ # EXL3_REPLY_FIRST: release the finished jobs (reply-end stash) once idle AND their handlers have
+ # dropped their routes (_drop is the last driver command a request waits for before its reply ends), at most
+ # 50 ms after the step; a new request's iterate() releases them first anyway
+ dj = getattr(self.generator, "deferred_jobs", None)
+ if dj and not self._cmds:
+ if rf_wait < 0.05 and any(self._routes.get(getattr(j, "serial_number", None), (None,))[0] is j for j in dj):
+ self._wake.clear()
+ try:
+ await asyncio.wait_for(self._wake.wait(), 0.005)
+ except asyncio.TimeoutError:
+ pass
+ rf_wait += 0.005
+ continue
+ rf_wait = 0.0
+ await loop.run_in_executor(None, self.generator.flush_deferred)
+ continue
self._wake.clear()
if not self._cmds:
await self._wake.wait()