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 server: decode up to --sessions N requests together

Victor Nogueira6b228278513a
diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.md
index 1f96ea7..d8f7b42 100644
--- a/tools/qwen/SERVE.md
+++ b/tools/qwen/SERVE.md
@@ -20,7 +20,7 @@ The server prints its effective `EXL3_*` / `MPW*` environment at start-up.
The server prints a progress line every 15 s while it loads (target, drafter, vision, warm-up). The port opens only when
everything is ready, and the last line says so:
- qserve: READY on http://127.0.0.1:8000 model=Qwen3.8-Flash-Yamz ctx=65536 speculative=True vision=True (start-up N s)
+ qserve: READY on http://127.0.0.1:8000 model=Qwen3.8-Flash-Yamz ctx=65536 sessions=1 speculative=True vision=True (start-up N s)
Quick test:
@@ -44,6 +44,7 @@ Quick test:
| `--no-thinking` | off | thinking off unless a request turns it on |
| `--default-max-tokens` | 32768 | when a request omits `max_tokens` (always clipped to the free context) |
| `--slot-save-path` | `~/cache/llama-slots` | directory for slot files |
+| `--sessions` | 1 | requests decoded together; see below |
Environment: the server sets the measured Qwen configuration with `setdefault` before the engine loads (the list is
`SERVE_ENV` in `serve.py`; the start-up log prints the effective `EXL3_*` / `MPW*` environment). It covers decode and
@@ -80,13 +81,32 @@ environment wins. The engine modules read several of these when they are importe
template, one prompt, one choice (`n`, `best_of`, `echo` answer 400). The slot routes are CPU-tested only.
- Debug extensions (all optional): `"speculative": false` decodes plain for that request, `"cache_prompt": false`
forgets the prompt cache first (cold run), `"return_token_ids": true` adds the generated ids. Switching
- speculative mode or `cache_prompt: false` rebuilds the Generator and so drops the prompt cache.
+ speculative mode or `cache_prompt: false` rebuilds the Generator and so drops the prompt cache (400 with `--sessions` > 1).
## Prompt cache between turns
The Generator keeps KV pages (256 tokens) and GDN recurrent checkpoints in RAM (4 GiB, about 111 MiB each). A follow-up
turn re-prefills only the part after the last checkpoint: the tail of the previous prompt (under 256 tokens) plus the
-new text. `timings.prompt_n` shows how many tokens were prefilled. Requests are served one at a time, in order.
+new text. `timings.prompt_n` shows how many tokens were prefilled. By default requests are served one at a time, in order (see `--sessions` below).
+
+## Concurrent sessions
+
+`--sessions N` decodes up to N requests together (one recurrent slot each); more requests wait in order. A request
+reserves the pages for its prompt plus `max_tokens` when it starts, so one that does not fit next to the running ones
+waits. With N > 1, a request with `speculative: false` or `cache_prompt: false` answers 400 (both rebuild the Generator), and slot
+save/restore/erase wait until the running requests finish.
+
+Measured with `--ndt 3`, `-c 262144`, temperature 0, two short prompts sent together (four for `--sessions 4`):
+
+| `--sessions` | `--cache-bits` | greedy output equal to a solo run | second stream's first token | total tok/s |
+|---|---|---|---|---|
+| 1 | 8 | yes | 6.55 s (waits for the first) | 44.4 |
+| 2 | 8 | no (1 of 2 differs) | 1.16 s | 47.3 |
+| 2 | 0 | yes | 1.17 s | 49.6 |
+| 4 | 8 | no (2 of 4 differ) | 2.19 s | 51.4 |
+
+The server prints a warning when the output can differ from a solo run: past 8 verify rows (`N x (ndt + 1)`), or with
+N > 1 and the 8-bit cache.
## Tests
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 1446476..ca45847 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -28,6 +28,7 @@ import time
import urllib.request
import uuid
from collections.abc import AsyncIterator
+from functools import partial
from pathlib import Path
from typing import Any
@@ -603,7 +604,7 @@ class QwenEngine:
"""Target model + MTP drafter + (optional) vision tower + one Generator."""
def __init__(self, model_path: str, ctx: int, ndt: int = 3, draft_policy: str = "mix",
- vision: bool = True, max_chunk_size: int = 2048, cache_bits: int = 8):
+ vision: bool = True, max_chunk_size: int = 2048, cache_bits: int = 8, sessions: int = 1):
# The measured Qwen serving configuration. Read at import time by the engine:
# set before importing exllamav3. The caller's environment wins.
for k, v in SERVE_ENV:
@@ -615,6 +616,7 @@ class QwenEngine:
torch.set_grad_enabled(False)
self.torch, self.Generator, self.Job = torch, Generator, Job
self.model_path, self.ctx, self.ndt, self.draft_policy = model_path, ctx, ndt, draft_policy
+ self.sessions = sessions
self.config = Config.from_directory(model_path)
self.tokenizer = Tokenizer.from_config(self.config)
self.eos = list(self.config.eos_token_id_list)
@@ -624,7 +626,8 @@ class QwenEngine:
self.cache_bits = cache_bits
from exllamav3 import CacheLayer_quant
qkw = dict(layer_type=CacheLayer_quant, k_bits=cache_bits, v_bits=cache_bits) if cache_bits else {}
- self.cache = Cache(self.model, max_num_tokens=ctx, max_history=3, **qkw)
+ # one recurrent (GDN) slot per session; the Generator caps its batch at the slot count
+ self.cache = Cache(self.model, max_num_tokens=ctx, max_history=3, max_batch_size=sessions, **qkw)
if os.environ.get("EXL3_WARM_DENSE", "1") != "0":
from exllamav3.model.dense_warmup import seed_dense_tune
seed_dense_tune()
@@ -740,22 +743,127 @@ class QwenEngine:
self._think_close = (one[0] if len(one) == 1 else None, seq)
return self._think_close
- async def generate(self, prompt: str, **kw: Any) -> AsyncIterator[str]:
+ def _post(self, fn, *args) -> asyncio.Future:
+ """Queue fn(*args) for the driver task, which runs it between two iterate() calls. The driver is the only code that
+ touches the Generator, so concurrent requests never mutate it while a step runs in the executor."""
+ self._ensure_driver()
+ fut = asyncio.get_running_loop().create_future()
+ self._cmds.append((fn, args, fut))
+ self._wake.set()
+ return fut
+
+ def _ensure_driver(self) -> None:
+ loop = asyncio.get_running_loop()
+ if getattr(self, "_driver", None) is None or self._driver.get_loop() is not loop:
+ self._cmds, self._routes, self._wake = [], {}, asyncio.Event()
+ self._driver = loop.create_task(self._drive())
+ elif self._driver.done():
+ exc = None if self._driver.cancelled() else self._driver.exception()
+ raise RuntimeError("the engine driver has stopped") from exc
+
+ async def _drive(self) -> None:
+ try:
+ await self._drive_loop()
+ finally:
+ # cancelled (shutdown) or crashed: nothing will answer the waiting requests any more, so fail them now
+ stopped = RuntimeError("the engine driver has stopped")
+ for _, _, fut in self._cmds:
+ if not fut.done():
+ fut.set_exception(stopped)
+ self._cmds.clear()
+ for _, q in self._routes.values():
+ q.put_nowait(stopped)
+ self._routes.clear()
+
+ async def _drive_loop(self) -> None:
+ loop = asyncio.get_running_loop()
+ while True:
+ while self._cmds:
+ fn, args, fut = self._cmds.pop(0)
+ try:
+ res = await loop.run_in_executor(None, fn, *args)
+ except Exception as exc: # noqa: BLE001
+ if not fut.done():
+ fut.set_exception(exc)
+ else:
+ if not fut.done():
+ fut.set_result(res)
+ if not self.generator.num_remaining_jobs():
+ self._wake.clear()
+ if not self._cmds:
+ await self._wake.wait()
+ continue
+ try:
+ events = await loop.run_in_executor(None, lambda: list(self.generator.iterate()))
+ except Exception as exc: # noqa: BLE001
+ # a failed step leaves every job in an unknown state: fail them all, as the old serial loop did
+ for _, q in self._routes.values():
+ q.put_nowait(exc)
+ self._routes.clear()
+ self.generator.clear_queue()
+ continue
+ by_serial: dict[int, list] = {}
+ for ev in events:
+ by_serial.setdefault(ev["serial"], []).append(ev)
+ for serial, evs in by_serial.items():
+ route = self._routes.get(serial)
+ if route is not None: # None: cancelled after the step started
+ route[1].put_nowait(evs)
+
+ def _cancel_serial(self, serial: int) -> None:
+ for job in self.generator.active_jobs + self.generator.pending_jobs:
+ if job.serial_number == serial:
+ self.generator.cancel(job)
+
+ async def _submit(self, job) -> asyncio.Queue:
+ q: asyncio.Queue = asyncio.Queue()
+
+ def enqueue():
+ # on the driver, so no step can emit before the route exists. The job is kept with the route: a failed enqueue
+ # does not use up its serial, so the next job gets the same one
+ self._routes[self.generator.enqueue(job)] = (job, q)
+ await self._post(enqueue)
+ return q
+
+ def _drop(self, job) -> asyncio.Future:
+ """Stop routing the job and remove it from the Generator (a no-op when it already finished). Runs on the driver, after
+ any enqueue posted before it, so a job cancelled while its enqueue is still queued does not stay behind."""
+ def forget():
+ serial = getattr(job, "serial_number", None)
+ route = self._routes.get(serial)
+ if route is not None and route[0] is job:
+ del self._routes[serial]
+ self._cancel_serial(serial)
+ return self._post(forget)
+
+ async def run_exclusive(self, fn, *args):
+ """Run fn on the driver, between steps (slot save/restore/erase; the caller has drained the requests)."""
+ return await self._post(fn, *args)
+
+ async def generate(self, prompt: str, stats: dict[str, Any] | None = None, **kw: Any) -> AsyncIterator[str]:
"""See _generate. Whatever way the call ends (error in a step, client gone, cancelled task), no job of it stays in the
- Generator: a leftover job would run inside the next request and deliver its tokens there."""
+ Generator: a leftover job would run inside the next request and deliver its tokens there. Final stats land in
+ `stats` (per request) and in self.last_stats (the last request to finish)."""
+ stats = {} if stats is None else stats
+ mine: list = []
try:
- async for piece in self._generate(prompt, **kw):
+ async for piece in self._generate(prompt, stats=stats, _mine=mine, **kw):
yield piece
finally:
- if self.generator is not None and self.generator.num_remaining_jobs():
- self.generator.clear_queue()
+ self.last_stats = stats
+ if mine and not self._driver.done():
+ # wait for the cancels: when this returns, no job of the request is left (slot actions rely on it)
+ for res in await asyncio.shield(asyncio.gather(*[self._drop(job) for job in mine], return_exceptions=True)):
+ if isinstance(res, BaseException):
+ print(f"qserve: WARNING could not remove a finished request's job: {res!r}", file=sys.stderr, flush=True)
async def _generate(self, prompt: str, *, max_tokens: int, sampling: dict[str, Any], stop: list[str],
images: list[str] | None = None, speculative: bool = True, cache_prompt: bool = True,
cancel: asyncio.Event | None = None, seed: int | None = None, reasoning_first: bool = False,
thinking_budget: int | None = None, loop_guard: bool | None = None,
- loop_final: bool | None = None, logprobs: int | None = None) -> AsyncIterator[str]:
- """Yield decoded text pieces. The caller serializes calls. Final stats land in self.last_stats.
+ loop_final: bool | None = None, logprobs: int | None = None, stats: dict[str, Any],
+ _mine: list) -> AsyncIterator[str]:
+ """Yield decoded text pieces. Final stats land in `stats`. Every job enqueued is appended to `_mine`.
Final check (on with the guard, loop_final=False turns it off): when the turn ends normally and the visible text
(thinking + answer) trips the release-gate loop rule, the thinking is cut back (final_cut), the close is forced and
@@ -767,16 +875,14 @@ class QwenEngine:
Nothing is changed while no loop is detected.
logprobs (None = off, k = 0..20): per generated token the log-probability of the token and of the k most likely tokens,
- taken from the model distribution before temperature and truncation. They land in last_stats["logprobs"], one entry
+ taken from the model distribution before temperature and truncation. They land in stats["logprobs"], one entry
per entry of token_ids ((token_logprob, [(id, logprob), ...]), None for a token the guard forced)."""
- loop = asyncio.get_running_loop()
- self.last_stats = {}
if cancel is not None and cancel.is_set():
return # the client left while the request was queued: no rebuild, no prefill
want_spec = bool(speculative) and self.draft_model is not None
if want_spec != self.spec_on or not cache_prompt:
- await loop.run_in_executor(None, self._build, want_spec)
- ids, embs = await loop.run_in_executor(None, self._encode, prompt, images or [])
+ await self._post(self._build, want_spec)
+ ids, embs = await self._post(self._encode, prompt, images or [])
ctx = getattr(self, "ctx", None)
if ctx: # the chat handler counted a picture as one token; its embeddings take many
room = reply_room(ctx, int(ids.numel()), int(getattr(self.generator, "num_draft_tokens", 0)))
@@ -805,26 +911,29 @@ class QwenEngine:
gmarks: list[tuple[int, int]] = [(0, 0)] # (len(token_ids), chars) after each event, all segments
job_ids = ids
- def step():
- return list(self.generator.iterate())
-
while True:
job = self.Job(input_ids=job_ids, max_new_tokens=max(max_tokens - generated + discount, 1),
sampler=self._sampler(sampling), stop_conditions=self.eos + list(stop),
embeddings=embs or None, decode_special_tokens=True, seed=seed,
**({} if logprobs is None else {"return_probs": True, "return_top_tokens": logprobs}))
- self.generator.enqueue(job)
+ _mine.append(job)
+ q = await self._submit(job)
seg: list[int] = []
marks = [(0, 0)]
base_chars = chars
seg_t0 = time.perf_counter()
hit = None
redo = False
- while self.generator.num_remaining_jobs():
+ while True:
if cancel is not None and cancel.is_set():
- self.generator.cancel(job)
- return
- for ev in await loop.run_in_executor(None, step):
+ return # generate() drops the job
+ try:
+ batch = await asyncio.wait_for(q.get(), 0.5)
+ except asyncio.TimeoutError:
+ continue # a job waiting for cache pages sends nothing: still watch for the cancel
+ if isinstance(batch, Exception):
+ raise batch
+ for ev in batch:
if ev.get("error"):
raise RuntimeError(str(ev["error"]))
t = ev.get("token_ids")
@@ -850,24 +959,26 @@ class QwenEngine:
redo = True
break
if ev.get("eos"):
- self.last_stats = {k: v for k, v in ev.items() if k not in ("job", "token_ids", "text", "held") and not k.startswith("stop_token_")}
- self.last_stats["token_ids"] = token_ids
+ self._routes.pop(job.serial_number, None)
+ stats.update({k: v for k, v in ev.items() if k not in ("job", "token_ids", "text", "held") and not k.startswith("stop_token_")})
+ stats["token_ids"] = token_ids
if logprobs is not None:
- self.last_stats["logprobs"] = lps
+ stats["logprobs"] = lps
stop_lp = self._stop_logprobs(ev)
if stop_lp is not None: # the sampled stop token: no content, but its position is scored
- self.last_stats["logprobs"] = lps + [stop_lp]
- self.last_stats["logprob_token_ids"] = token_ids + [int(ev["eos_triggering_token_id"])]
+ stats["logprobs"] = lps + [stop_lp]
+ stats["logprob_token_ids"] = token_ids + [int(ev["eos_triggering_token_id"])]
if fired:
- self.last_stats.update(prompt_tokens=int(ids.numel()), new_tokens=generated,
- cached_tokens=min(int(self.last_stats.get("cached_tokens", 0)), int(ids.numel())),
- loop_guard=fired)
- if self.last_stats.get("time_generate") is not None:
- self.last_stats["time_generate"] += spent
+ stats.update(prompt_tokens=int(ids.numel()), new_tokens=generated,
+ cached_tokens=min(int(stats.get("cached_tokens", 0)), int(ids.numel())),
+ loop_guard=fired)
+ if stats.get("time_generate") is not None:
+ stats["time_generate"] += spent
return
if hit or redo:
break
if redo:
+ self._routes.pop(job.serial_number, None) # it sent its eos
cut_chars = final_cut(vis)
final_tries += 1
keep_tokens, keep_chars = max(m for m in gmarks if m[1] <= cut_chars)
@@ -895,16 +1006,16 @@ class QwenEngine:
continue
if not hit:
return
- self.generator.cancel(job)
+ await self._drop(job)
fired = dict(hit, tokens_streamed=len(token_ids))
print(f"qserve: loop guard {hit['kind']} in {hit['phase']} at {hit['at']} tokens (period {hit['period']}, "
f"keep {hit['cut']})", file=sys.stderr, flush=True)
n_total = int(ids.numel())
if hit["phase"] == "answer" or close_id is None:
- self.last_stats = {"prompt_tokens": n_total, "new_tokens": generated, "cached_tokens": 0,
- "eos_reason": "loop_guard", "token_ids": token_ids, "loop_guard": fired}
+ stats.update({"prompt_tokens": n_total, "new_tokens": generated, "cached_tokens": 0,
+ "eos_reason": "loop_guard", "token_ids": token_ids, "loop_guard": fired})
if logprobs is not None:
- self.last_stats["logprobs"] = lps
+ stats["logprobs"] = lps
return
# think block: keep the thinking up to the cut (on an event boundary), force the close, restart from there
keep_tokens, keep_chars = max(m for m in marks if m[0] <= hit["cut"])
@@ -925,10 +1036,10 @@ class QwenEngine:
gmarks[:] = [m for m in gmarks if m[0] <= len(token_ids) - len(close_seq) and m[1] <= chars - len(THINK_CLOSE_TEXT)]
gmarks.append((len(token_ids), chars))
if generated - discount >= max_tokens:
- self.last_stats = {"prompt_tokens": n_total, "new_tokens": generated, "cached_tokens": 0,
- "eos_reason": "max_new_tokens", "token_ids": token_ids, "loop_guard": fired}
+ stats.update({"prompt_tokens": n_total, "new_tokens": generated, "cached_tokens": 0,
+ "eos_reason": "max_new_tokens", "token_ids": token_ids, "loop_guard": fired})
if logprobs is not None:
- self.last_stats["logprobs"] = lps
+ stats["logprobs"] = lps
return
extra = self.torch.tensor([seg[:keep_tokens] + close_seq], dtype=ids.dtype)
job_ids = self.torch.cat([ids, extra.to(ids.device)], dim=-1)
@@ -1015,7 +1126,10 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
"""HTTP layer around a resident engine (also accepts a fake engine in tests)."""
defaults = defaults or load_defaults("/nonexistent")
queue: asyncio.Queue = asyncio.Queue()
- lock = asyncio.Lock()
+ sessions = getattr(engine, "sessions", 1)
+ gate = asyncio.Semaphore(sessions) # one permit per running request; slot actions take them all (drain)
+ lock = asyncio.Lock() # serializes the slot actions
+ running = 0
app = web.Application(client_max_size=64 * 1024**2)
app.update(engine=engine, model_id=model_id, template=template, defaults=defaults)
@@ -1033,21 +1147,31 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
**(engine.spec_stats() if hasattr(engine, "spec_stats") else {})})
async def worker() -> None:
+ nonlocal running
while True:
job, out = await queue.get()
store = getattr(engine, "slot_store", None)
+ stats: dict[str, Any] = {}
try:
- async with lock:
+ async with gate:
+ running += 1
if store is not None:
store.busy = True
- async for delta in engine.generate(
- job["prompt"], max_tokens=job["max_tokens"], sampling=job["sampling"],
- stop=job["stop"], images=job["images"], speculative=job["speculative"],
- cache_prompt=job["cache_prompt"], cancel=job["cancel"],
- seed=job.get("seed"), reasoning_first=job.get("reasoning_first", False),
- thinking_budget=job.get("thinking_budget"), loop_guard=job.get("loop_guard"), loop_final=job.get("loop_final"), logprobs=job.get("logprobs")):
- out.put_nowait(delta)
- done = dict(getattr(engine, "last_stats", None) or {})
+ try:
+ async for delta in engine.generate(
+ job["prompt"], stats=stats, max_tokens=job["max_tokens"], sampling=job["sampling"],
+ stop=job["stop"], images=job["images"], speculative=job["speculative"],
+ cache_prompt=job["cache_prompt"], cancel=job["cancel"],
+ seed=job.get("seed"), reasoning_first=job.get("reasoning_first", False),
+ thinking_budget=job.get("thinking_budget"), loop_guard=job.get("loop_guard"),
+ loop_final=job.get("loop_final"), logprobs=job.get("logprobs")):
+ out.put_nowait(delta)
+ finally:
+ running -= 1
+ if store is not None:
+ store.busy = running > 0
+ # a fake engine (tests) fills only last_stats
+ done = dict(stats or getattr(engine, "last_stats", None) or {})
print(f"qserve: request prompt={int(done.get('prompt_tokens') or 0)} cached={int(done.get('cached_tokens') or 0)} "
f"new={int(done.get('new_tokens') or 0)} prefill_s={float(done.get('time_prefill') or 0):.3f} "
f"generate_s={float(done.get('time_generate') or 0):.3f} stop={done.get('eos_reason')}",
@@ -1056,15 +1180,20 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
except Exception as exc: # noqa: BLE001
out.put_nowait(exc)
finally:
- if store is not None:
- store.busy = False
queue.task_done()
async def start(_: web.Application) -> None:
- app["worker_task"] = asyncio.create_task(worker())
+ app["worker_tasks"] = [asyncio.create_task(worker()) for _ in range(sessions)]
async def close(app_: web.Application) -> None:
- app_["worker_task"].cancel()
+ for t in app_["worker_tasks"]:
+ t.cancel()
+
+ def check_sessions(job: dict[str, Any]) -> None:
+ # both rebuild the Generator, which would drop the jobs of the other sessions (without a drafter there is
+ # no speculative mode to leave, so speculative=false changes nothing)
+ if sessions > 1 and (not job["cache_prompt"] or (not job["speculative"] and getattr(engine, "spec_on", False))):
+ raise BadRequest("speculative=false or cache_prompt=false needs a server started with --sessions 1")
def prepare(body: Any) -> dict[str, Any]:
"""Validate a request and build the engine job. Raises BadRequest."""
@@ -1117,12 +1246,14 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
lp = logprobs_arg(body.get("logprobs"), body.get("top_logprobs"), chat=True)
if lp is not None and body.get("stream"):
raise BadRequest("logprobs are returned on non-streaming requests only")
- return {"logprobs": lp, "seed": seed, "thinking_budget": budget, "loop_guard": body.get("loop_guard"), "loop_final": body.get("loop_final"), "prompt": prompt, "prompt_tokens": prompt_tokens, "max_tokens": max_tokens,
- "sampling": sampling_from(body, defaults), "stop": stops, "images": images,
- "speculative": body.get("speculative", True) is not False,
- "cache_prompt": body.get("cache_prompt", True) is not False,
- "reasoning_first": prompt.rstrip().endswith("<think>"), "tools": body.get("tools"),
- "return_token_ids": bool(body.get("return_token_ids")), "cancel": asyncio.Event()}
+ job = {"logprobs": lp, "seed": seed, "thinking_budget": budget, "loop_guard": body.get("loop_guard"), "loop_final": body.get("loop_final"), "prompt": prompt, "prompt_tokens": prompt_tokens, "max_tokens": max_tokens,
+ "sampling": sampling_from(body, defaults), "stop": stops, "images": images,
+ "speculative": body.get("speculative", True) is not False,
+ "cache_prompt": body.get("cache_prompt", True) is not False,
+ "reasoning_first": prompt.rstrip().endswith("<think>"), "tools": body.get("tools"),
+ "return_token_ids": bool(body.get("return_token_ids")), "cancel": asyncio.Event()}
+ check_sessions(job)
+ return job
async def completions(request: web.Request) -> web.StreamResponse:
try:
@@ -1308,6 +1439,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
"stop": stops, "images": [], "speculative": True,
"seed": body.get("seed") if isinstance(body.get("seed"), int) and not isinstance(body.get("seed"), bool) else None,
"cache_prompt": body.get("cache_prompt", True) is not False, "cancel": asyncio.Event()}
+ check_sessions(job)
except json.JSONDecodeError as exc:
return err(400, f"invalid JSON: {exc}")
except (BadRequest, TypeError, ValueError) as exc:
@@ -1378,6 +1510,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
job = {"logprobs": lp, "prompt": prompt, "max_tokens": max_tokens, "stop": stops, "images": [], "speculative": body.get("speculative", True) is not False, "seed": seed,
"sampling": sampling_from(body, defaults), "cache_prompt": body.get("cache_prompt", True) is not False,
"loop_guard": body.get("loop_guard"), "cancel": asyncio.Event()}
+ check_sessions(job)
except json.JSONDecodeError as exc:
return err(400, f"invalid JSON: {exc}")
except BadRequest as exc:
@@ -1477,13 +1610,21 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
action = request.query.get("action")
try:
body = await request.json() if request.can_read_body else {}
+ if action not in ("save", "restore", "erase"):
+ return err(400, "action must be save, restore or erase")
async with lock:
- if action == "erase":
- return web.json_response(store.erase())
- if action not in ("save", "restore"):
- return err(400, "action must be save, restore or erase")
- result = await asyncio.get_running_loop().run_in_executor(None, getattr(store, action), body.get("filename", ""))
- return web.json_response(result)
+ held = 0
+ try:
+ for _ in range(sessions): # wait for the running requests to finish
+ await gate.acquire()
+ held += 1
+ fn = store.erase if action == "erase" else partial(getattr(store, action), body.get("filename", ""))
+ if hasattr(engine, "run_exclusive"):
+ return web.json_response(await engine.run_exclusive(fn))
+ return web.json_response(await asyncio.get_running_loop().run_in_executor(None, fn))
+ finally:
+ for _ in range(held):
+ gate.release()
except (ValueError, FileNotFoundError, RuntimeError, json.JSONDecodeError) as exc:
return err(400, f"{type(exc).__name__}: {exc}")
@@ -1528,7 +1669,20 @@ def main() -> None:
parser.add_argument("--no-thinking", action="store_true", help="thinking off unless a request turns it on")
parser.add_argument("--default-max-tokens", type=int, default=32768, help="when a request omits max_tokens")
parser.add_argument("--slot-save-path", default="~/cache/llama-slots")
+ parser.add_argument("--sessions", type=int, default=1,
+ help="requests decoded together (default 1: one at a time, in order). Every session reserves the "
+ "pages for prompt + max_tokens when it starts, so a request that does not fit waits")
args = parser.parse_args()
+ if args.sessions < 1:
+ parser.error("--sessions must be at least 1")
+ # measured with --ndt 3: greedy output equal to a solo run at 2 sessions (8 verify rows) with --cache-bits 0; not at
+ # 4 sessions (16 rows), and not at 2 sessions with the 8-bit cache
+ if args.draft_policy != "off" and args.sessions * (args.ndt + 1) > 8:
+ print(f"qserve: WARNING --sessions {args.sessions} x (--ndt {args.ndt} + 1) = {args.sessions * (args.ndt + 1)} verify rows "
+ "is past 8: greedy output may differ from the same request run alone", flush=True)
+ if args.sessions > 1 and args.cache_bits:
+ print(f"qserve: WARNING --sessions {args.sessions} with --cache-bits {args.cache_bits}: greedy output may differ from the "
+ "same request run alone (--cache-bits 0 keeps it equal at 2 sessions)", flush=True)
if args.no_uncensor:
os.environ["EXL3_ABLIT_RUNTIME"] = "off"
@@ -1536,10 +1690,10 @@ def main() -> None:
template = (Path(model_dir) / "chat_template.jinja").read_text(encoding="utf-8")
defaults = load_defaults(model_dir, args)
t0 = time.time()
- print(f"qserve: starting, model={model_dir} ctx={args.ctx} draft_policy={args.draft_policy} "
+ print(f"qserve: starting, model={model_dir} ctx={args.ctx} sessions={args.sessions} draft_policy={args.draft_policy} "
f"defaults={ {k: v for k, v in defaults.items() if v is not None} }", flush=True)
engine = QwenEngine(model_dir, args.ctx, ndt=args.ndt, draft_policy=args.draft_policy, vision=not args.no_vision,
- cache_bits=args.cache_bits)
+ cache_bits=args.cache_bits, sessions=args.sessions)
env = {k: v for k, v in sorted(os.environ.items()) if k.startswith(("EXL3_", "MPW"))}
print(f"qserve: effective env {env}", flush=True)
from exllamav3.generator.slot_store import SlotStore
@@ -1553,7 +1707,7 @@ def main() -> None:
runner = web.AppRunner(app)
await runner.setup()
await web.TCPSite(runner, args.host, args.port).start()
- print(f"qserve: READY on http://{args.host}:{args.port} model={args.model_id} ctx={args.ctx} "
+ print(f"qserve: READY on http://{args.host}:{args.port} model={args.model_id} ctx={args.ctx} sessions={args.sessions} "
f"speculative={engine.spec_on} vision={engine.supports_vision} (start-up {time.time() - t0:.0f} s)",
flush=True)
await asyncio.Event().wait()
diff --git a/tools/qwen/test_guard.py b/tools/qwen/test_guard.py
index 0becaf5..6775855 100644
--- a/tools/qwen/test_guard.py
+++ b/tools/qwen/test_guard.py
@@ -38,16 +38,21 @@ class StubGenerator:
"""Emits `per_iter` tokens per iterate() call from model(context) -> token id (0 = eos)."""
def __init__(self, model, per_iter=3):
- self.model, self.per_iter, self.job, self.out = model, per_iter, None, []
+ self.model, self.per_iter, self.job, self.out, self.serial = model, per_iter, None, [], 0
+ self.active_jobs, self.pending_jobs = [], []
def enqueue(self, job):
self.job, self.out = job, []
+ self.active_jobs[:] = [job]
+ job.serial_number, self.serial = self.serial, self.serial + 1
+ return job.serial_number
def num_remaining_jobs(self):
return 1 if self.job is not None else 0
def cancel(self, job):
self.job = None
+ self.active_jobs[:] = []
def iterate(self):
j, toks, eos, reason = self.job, [], False, None
@@ -61,11 +66,12 @@ class StubGenerator:
if len(self.out) >= j.max_new:
eos, reason = True, "max_new_tokens"
break
- ev = {"job": j, "token_ids": torch.tensor(toks), "text": "".join("</think>" if t == CLOSE else f"<{t}>" for t in toks)}
+ ev = {"job": j, "serial": j.serial_number, "token_ids": torch.tensor(toks), "text": "".join("</think>" if t == CLOSE else f"<{t}>" for t in toks)}
if eos:
ev |= {"eos": True, "eos_reason": reason, "new_tokens": len(self.out), "prompt_tokens": len(j.ids),
"cached_tokens": 0}
self.job = None
+ self.active_jobs[:] = []
return [ev]
@@ -262,6 +268,139 @@ class GuardEngineTests(unittest.TestCase):
self.assertTrue(re.search(r"seed: int = None", src) and "random.Random(seed)" in src)
+class MultiStubGenerator(StubGenerator):
+ """StubGenerator with several jobs at once: each iterate() steps every job, like a batched decode."""
+
+ def __init__(self, model, per_iter=3, requeue_at=None):
+ super().__init__(model, per_iter)
+ self.jobs, self.peak, self.requeue_at = {}, 0, requeue_at
+
+ @property
+ def active_jobs(self):
+ return list(self.jobs)
+
+ @active_jobs.setter
+ def active_jobs(self, _):
+ pass
+
+ def enqueue(self, job):
+ job.serial_number = self.serial
+ if job.seed == 0: # like Job.prepare_for_queue's fit check: the serial is set, then the enqueue fails
+ raise AssertionError("job does not fit")
+ self.jobs[job] = []
+ self.serial += 1
+ return job.serial_number
+
+ def num_remaining_jobs(self):
+ return len(self.jobs)
+
+ def cancel(self, job):
+ self.jobs.pop(job, None)
+
+ def iterate(self):
+ self.peak = max(self.peak, len(self.jobs))
+ evs = []
+ for j in list(self.jobs):
+ self.job, self.out = j, self.jobs[j]
+ evs += StubGenerator.iterate(self)
+ if self.job is None:
+ del self.jobs[j]
+ elif self.requeue_at and len(self.out) >= self.requeue_at and not getattr(j, "rq", False):
+ # a requeue that hands back another Job object with the same serial (Generator.prepare_for_requeue reuses
+ # the object; routing by serial must not depend on that)
+ rq = object.__new__(StubJob)
+ rq.__dict__.update(j.__dict__, ids=j.ids + self.out, max_new=j.max_new - len(self.out), rq=True)
+ del self.jobs[j]
+ self.jobs[rq] = []
+ self.job = None
+ return evs
+
+
+class SessionTests(unittest.TestCase):
+ @staticmethod
+ def seeded(ctx, job):
+ n = len(ctx) - 3
+ return 10_000 * job.seed + 200 + n if n < 30 else 0
+
+ def run_two(self, cancel_first_after=None, requeue_at=None):
+ e = make_engine(self.seeded, per_iter=2)
+ e.generator = MultiStubGenerator(self.seeded, per_iter=2, requeue_at=requeue_at)
+
+ async def one(seed, cancel):
+ st, n = {}, 0
+ async for _ in e.generate("p", stats=st, sampling={"temperature": 0}, stop=[], max_tokens=600, seed=seed,
+ loop_guard=False, cancel=cancel):
+ n += 1
+ if cancel_first_after and seed == 1 and n == cancel_first_after:
+ cancel.set()
+ # generate() returns only after its cancels ran: no job of this request may be left at this point
+ self.assertFalse([j for j in e.generator.jobs if j.seed == seed])
+ return st.get("token_ids")
+
+ async def both():
+ # a lost route waits forever: fail instead of hanging
+ return await asyncio.wait_for(asyncio.gather(one(1, asyncio.Event()), one(2, asyncio.Event())), 10)
+ return asyncio.run(both()), e.generator
+
+ def test_concurrent_requests_get_their_own_tokens(self):
+ (a, b), gen = self.run_two()
+ self.assertEqual(a, [10_200 + i for i in range(30)])
+ self.assertEqual(b, [20_200 + i for i in range(30)])
+ self.assertEqual(gen.peak, 2)
+ self.assertEqual(gen.jobs, {})
+
+ def test_requeued_job_keeps_its_stream(self):
+ (a, b), gen = self.run_two(requeue_at=10)
+ self.assertEqual(a, [10_200 + i for i in range(30)])
+ self.assertEqual(b, [20_200 + i for i in range(30)])
+
+ def test_cancel_after_requeue_reaches_the_new_job(self):
+ (a, b), gen = self.run_two(cancel_first_after=8, requeue_at=4)
+ self.assertIsNone(a)
+ self.assertEqual(b, [20_200 + i for i in range(30)])
+ self.assertEqual(gen.jobs, {})
+
+ def test_failed_enqueue_does_not_cancel_the_job_that_reuses_its_serial(self):
+ e = make_engine(self.seeded, per_iter=2)
+ e.generator = MultiStubGenerator(self.seeded, per_iter=2)
+
+ async def one(seed):
+ st = {}
+ try:
+ async for _ in e.generate("p", stats=st, sampling={"temperature": 0}, stop=[], max_tokens=600, seed=seed,
+ loop_guard=False):
+ pass
+ except AssertionError:
+ return "failed"
+ return st.get("token_ids")
+
+ async def both():
+ return await asyncio.wait_for(asyncio.gather(one(0), one(2)), 10)
+ failed, b = asyncio.run(both())
+ self.assertEqual(failed, "failed")
+ self.assertEqual(b, [20_200 + i for i in range(30)])
+
+ def test_stopped_driver_fails_the_request_instead_of_hanging(self):
+ e = make_engine(self.seeded, per_iter=1)
+ e.generator = MultiStubGenerator(self.seeded, per_iter=1)
+
+ async def go():
+ n = 0
+ async for _ in e.generate("p", stats={}, sampling={"temperature": 0}, stop=[], max_tokens=600, seed=1,
+ loop_guard=False):
+ n += 1
+ if n == 2:
+ e._driver.cancel()
+ with self.assertRaisesRegex(RuntimeError, "driver has stopped"):
+ asyncio.run(asyncio.wait_for(go(), 10))
+
+ def test_cancel_leaves_the_other_session_running(self):
+ (a, b), gen = self.run_two(cancel_first_after=3)
+ self.assertIsNone(a)
+ self.assertEqual(b, [20_200 + i for i in range(30)])
+ self.assertEqual(gen.jobs, {})
+
+
class HttpFieldTests(unittest.TestCase):
def post(self, payload):
eng = FakeEngine("hi")
diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.py
index 0bd2852..fc363e6 100644
--- a/tools/qwen/test_serve.py
+++ b/tools/qwen/test_serve.py
@@ -367,6 +367,85 @@ class HttpTests(unittest.TestCase):
self.assertEqual(with_client(Slow("x"), fn), [200] * 4)
self.assertEqual(Slow.peak, 1)
+ def test_sessions_run_together_and_reject_rebuilds(self):
+ class Slow(FakeEngine):
+ sessions = 2
+ active = peak = 0
+
+ async def generate(self, prompt, **kw):
+ Slow.active += 1
+ Slow.peak = max(Slow.peak, Slow.active)
+ await asyncio.sleep(0.05)
+ yield "x"
+ Slow.active -= 1
+
+ async def fn(client):
+ body = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}
+ rs = await asyncio.gather(*[client.post("/v1/chat/completions", json=body) for _ in range(4)])
+ bad = [await client.post("/v1/chat/completions", json=body | flag) for flag in ({"speculative": False}, {"cache_prompt": False})]
+ bad.append(await client.post("/completion", json={"prompt": "hi", "cache_prompt": False}))
+ bad.append(await client.post("/v1/completions", json={"prompt": "hi", "cache_prompt": False}))
+ return [r.status for r in rs], [r.status for r in bad]
+ self.assertEqual(with_client(Slow("x"), fn), ([200] * 4, [400] * 4))
+ self.assertEqual(Slow.peak, 2)
+
+ def test_sessions_accept_speculative_false_without_a_drafter(self):
+ class Plain(FakeEngine):
+ sessions, spec_on = 2, False
+
+ async def fn(client):
+ body = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}
+ ok = await client.post("/v1/chat/completions", json=body | {"speculative": False})
+ cold = await client.post("/v1/chat/completions", json=body | {"cache_prompt": False})
+ return ok.status, cold.status
+ self.assertEqual(with_client(Plain("x"), fn), (200, 400))
+
+ def test_sessions_keep_their_own_stats(self):
+ class PerPrompt(FakeEngine):
+ sessions = 2
+
+ async def generate(self, prompt, stats=None, **kw):
+ await asyncio.sleep(0.05)
+ stats.update(new_tokens=len(prompt), prompt_tokens=1, eos_reason="stop_token")
+ yield "x"
+
+ async def fn(client):
+ bodies = [{"model": "m", "messages": [{"role": "user", "content": "a" * n}]} for n in (10, 200)]
+ rs = await asyncio.gather(*[client.post("/v1/chat/completions", json=b) for b in bodies])
+ return [(await r.json())["usage"]["completion_tokens"] for r in rs]
+ a, b = with_client(PerPrompt("x"), fn)
+ self.assertEqual(b - a, 190)
+
+ def test_slot_action_waits_for_running_requests(self):
+ order = []
+
+ class Store:
+ busy = False
+
+ def save(self, name):
+ order.append("save")
+ return {"saved": name}
+
+ class Slow(FakeEngine):
+ sessions = 2
+
+ async def generate(self, prompt, **kw):
+ await asyncio.sleep(0.2)
+ order.append("generated")
+ yield "x"
+
+ eng = Slow("x")
+ eng.slot_store = Store()
+
+ async def fn(client):
+ body = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}
+ req = asyncio.ensure_future(client.post("/v1/chat/completions", json=body))
+ await asyncio.sleep(0.05)
+ save = await client.post("/slots/0?action=save", json={"filename": "a.bin"})
+ return (await req).status, save.status
+ self.assertEqual(with_client(eng, fn), (200, 200))
+ self.assertEqual(order, ["generated", "save"])
+
def test_client_disconnect_cancels_the_job(self):
class Endless(FakeEngine):
stopped = False