From b24e0a59c321851c89cd924738c9e27c4a8ca7d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 01:37:54 +0000 Subject: [PATCH 1/3] feat(engine): hand the DFlash drafter the prompt's hidden states on the hybrid prompt-cache path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a hybrid model the prompt cache prefills the stable render in a drafter-less call and stops at the anchor, so the decode call — the only one that runs the drafter — prefills just the generation prompt, and mlx-vlm's round loop hands the drafter those 7 tokens as its whole context. #131 measured what that costs on 64 real subagent turns at block 3: 2.27 tokens per round against 2.58 with the turn's own prefill in front of it (~+10% decode) and 2.62 with the last 2,047 tokens of the prompt. Every segment a turn prefills before its decode now runs with a capture the orchestrator threads through the fork stops: the prefill passes mlx-vlm's own `capture_layer_ids` kwarg to generate(), and a class-level post-hook on the language model's forward — armed per instance for the duration of that call — keeps the newest window (sliding_window - 1, 2047 on the shipped drafter) of each forward's hidden states in one sink. generate_step deletes every chunk's output, so the hook is the only observer, and the prefill itself runs exactly as before, so the KV cache is bit-identical. The decode assembles the tail — its own buffer, since a slice of the chunks would pin twice its size across the decode — and seeds it into per-instance wraps of the drafter's draft_block, draft_block_greedy and reset, which prepend it once, on the first draft call after the round loop's reset; the drafter's sliding attention keeps the newest window of tail plus own prompt itself. A sink that fails part-way voids itself rather than seed a tail that ends short of the generation prompt. unload() closes the context first: the wraps close over the drafter and the drafter binds the target's embedding and head, so the weights would otherwise outlive the unload. Nothing here changes a token — the verify is exact — so the gates are structural rather than source hashes, and a drift in mlx-vlm shows on the turn line as draft_context=7 (the capture lost) or as draft_context=0 beside draft_context=unavailable on the load line (a gate tripped), not as a different reply. Acceptance is logged from now on. The decode reads mlx-vlm's lifetime round counters before and after each call (its per-call accept_lens are reset every round loop) and the prompt cache assigns them as per-turn gauges on every decode path, the cache-off one included, so the turn line carries draft_rounds, drafted, accepted and draft_context beside decode_tps, and the load line and status document say whether the seeding is armed and with what window. tests/test_draftctx.py drives the real generate_step and _dflash_rounds on stub models to pin the two contracts this rests on (a CPU mlx build suffices); the model-marked tests check the captured prefill's cache against an uncaptured one bit for bit on the hybrid, and the default model's drafter context, acceptance and greedy equivalence. vlm.py is in the fork store's epoch, so every fork on disk is rebuilt once after deploy. Closes #142. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0124KgiJ3Cgpgotsdk58dicH --- CLAUDE.md | 43 ++ docs/configuration.md | 9 +- docs/observability.md | 28 +- src/sous/api/routes.py | 8 + src/sous/api/turn.py | 12 + src/sous/engine/base.py | 18 + src/sous/engine/draftctx.py | 404 +++++++++++++++ src/sous/engine/lm.py | 23 +- src/sous/engine/promptcache.py | 109 +++- src/sous/engine/vlm.py | 122 +++-- src/sous/tune/suite/runner.py | 5 +- tests/test_api_routes.py | 17 +- tests/test_api_turn.py | 10 + tests/test_draftctx.py | 855 ++++++++++++++++++++++++++++++++ tests/test_engine_base.py | 92 ++++ tests/test_engine_positions.py | 4 +- tests/test_engine_vlm.py | 130 +++++ tests/test_engine_vlm_greedy.py | 2 + tests/test_promptcache.py | 177 ++++++- 19 files changed, 1993 insertions(+), 75 deletions(-) create mode 100644 src/sous/engine/draftctx.py create mode 100644 tests/test_draftctx.py diff --git a/CLAUDE.md b/CLAUDE.md index 5309b1af..177cdce4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -312,6 +312,49 @@ goal. `MLX_METAL_GPU_ARCH` subprocesses. The module stays out of `forkstore._EPOCH_FILES` on purpose: prefill never enters the verifier and verify output is bit-identical. +- `engine/draftctx.py` hands the DFlash drafter the prompt's hidden states on + the hybrid prompt-cache path (#142). mlx-vlm's round loop + (`speculative/dflash.py:_dflash_rounds`) gives the drafter, on its first + draft call after `reset`, the hidden states of whatever the *decode call* + prefilled — the 7-token generation prompt there, since `PrefixCache._run` + prefills the stable render in a drafter-less call and stops at the anchor. + So every segment a turn prefills before its decode — the fork stops' + and the last — runs with a `capture` the orchestrator threads through + (`True` starts one, the engine's return continues it, None when the + engine has nothing to seed): the prefill passes mlx-vlm's own + `capture_layer_ids` kwarg to `generate()` and a class-level post-hook on + the language model's forward (armed per instance with + `object.__setattr__`, like int8's tags) keeps the newest window of each + forward's `hidden_states` in one `Sink` — `generate_step` deletes every + chunk's output, so the hook is the only observer, and the prefill itself + runs exactly as uncaptured, so the KV is bit-identical. A sink that fails + part-way voids itself: a tail ending short of the generation prompt would + seed the wrong positions. The decode assembles the tail (its own buffer: + a slice of the chunks would pin twice its size) and `seed()`s it into + instance-level wraps of the drafter's `draft_block`, `draft_block_greedy` + and `reset`, which prepend it once (the greedy wrap may delegate to the + sampled one — the first-call flag is consumed by the outer call). The + drafter's sliding attention keeps the newest `sliding_window - 1` rows of + tail plus own prompt itself. On the trimmable path the decode call + prefills the last segment itself, so only fork stops feed the capture + there. `unload()` must `close()` the context first: the wraps close over + the drafter and the drafter binds the target's embedding and head, so + the weights would outlive the unload. Nothing here changes a token — the + verify is exact — so the gates are structural (kind `dflash`, none of the + hooks the round loop looks for, target layers named, no + `_batch_invariant_decode`), not source hashes, and a drift shows on the + turn line as `draft_context=7` (the capture lost) or as `draft_context=0` + beside `draft_context=unavailable` on the load line (a gate tripped) — + the context gauge is measured only while the seeding is active; the + count gauges are 0 only when no drafter ran, the prompt cache off + included. + `tests/test_draftctx.py` drives the real `generate_step` and + `_dflash_rounds` on stubs (CPU mlx suffices) to pin both contracts. + Per-decode acceptance (`rounds_since`, mlx-vlm's lifetime counters, + which its per-call `accept_lens` are not) reaches the turn line through + the prompt cache's per-turn gauges (`draft_rounds`, `drafted_tokens`, + `accepted_tokens`, `draft_context`) via `hooks.speculation()` after every + decode. ## Security boundary diff --git a/docs/configuration.md b/docs/configuration.md index d9ef92c0..777f2710 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -173,7 +173,14 @@ M5 Pro (+3% on prose, +13% on code re-emission over the drafter's adaptive policy); 0 lets that policy pick the depth; anything above 5 is clamped, because mlx's fused attention kernel takes at most 5 verify rows on this model and 6–8 rows run 5–6x slower per layer. It auto-disables with a -warning when the drafter can't serve the configured model. +warning when the drafter can't serve the configured model. On the prompt-cache +path of a hybrid model the decode call itself prefills only the generation +prompt, so the drafter is handed the newest window (2047 positions on the +default drafter) of the hidden states of everything the turn prefilled +before it, and drafts from the conversation rather than from those 7 tokens (#142); the +turn line's `draft_context` says how much it saw, and `draft_rounds`, +`drafted` and `accepted` what it made of it (see +[Observability](observability.md#the-turn-line)). ## Smaller machines diff --git a/docs/observability.md b/docs/observability.md index d673a7ac..7e8aab5b 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -87,7 +87,8 @@ example (wrapped here): stream=1 status=200 input_tokens=84335 output_tokens=2887 stop=end_turn cache=hit took=turn@82647 reused_tokens=82647 prefilled_tokens=1681 forks=0 evicted=1 pressure=0 load_s=0.0 queue_s=2.5 engine_wait_s=0.0 tokenize_s=1.1 ttft_s=9.8 prefill_s=7.9 decode_s=196.6 - prefill_tps=212.8 decode_tps=14.7 seconds=207.4 tools=1b21cd75 system=9f8e7d6c + prefill_tps=212.8 decode_tps=14.7 draft_rounds=1104 drafted=2208 accepted=1782 draft_context=1688 + seconds=207.4 tools=1b21cd75 system=9f8e7d6c ``` `id` is the response's message id (the same one in `message_start`, so the @@ -129,7 +130,23 @@ so adding every field this way can just as easily run past `seconds` as fall short of it. `prefill_tps`/`decode_tps` are that same phase attribution expressed as a rate, not a throughput measurement — `prefill_s` also carries fork copies and the snapshot, so a turn that publishes forks reports a lower -`prefill_tps` than its real prefill speed. `seconds` is the total, running +`prefill_tps` than its real prefill speed. `draft_rounds`, `drafted` and +`accepted` are the speculative drafter's part of that decode: how many +draft-verify rounds it ran, how many tokens it proposed over them and how +many of those the exact verify kept — each round also yields one bonus +token, in neither count, so tokens per round is `(accepted + draft_rounds) +/ draft_rounds` and the acceptance rate `accepted / drafted`. +`draft_context` is how many positions of context the drafter's first draft +ran with, at most its window (2047 on the default drafter): on the hybrid +prompt-cache path the decode call itself prefills only the generation +prompt (7 tokens on Qwen3.8), and the drafter is handed the newest window +of the hidden states of everything the turn prefilled before it, so a +warm turn whose delta since the previous one was short reads short here +too, and `7` means the drafter saw the generation prompt alone. It is +measured only while the load line says `draft_context=active` and reads 0 +otherwise, whatever the drafter saw; the three counts are 0 only when no +drafter ran (with the prompt cache off the drafter sees the whole prompt, +and they are logged the same way). `seconds` is the total, running from the moment the turn takes the endpoint lock, so client-visible latency is `seconds` plus `queue_s`. On a miss the line adds `lcp=` (how many leading tokens the render shared with the closest resident slot), `lcp_region=` @@ -166,7 +183,12 @@ seconds=N.N model=` when it loads, plus `positions=engine|model` on the VLM backend (which side supplies the rotary positions behind a warm cache) and `verify_attention=active|unavailable|off` (whether speculative verify runs its attention as grouped exact calls; with -`verify_attention_probe_s=` when the load-time exactness probe ran). One +`verify_attention_probe_s=` when the load-time exactness probe ran) and +`draft_context=active|unavailable|off` (whether the drafter is handed the +prompt's hidden states on the prompt-cache path, with +`draft_context_window=` when it is; `off` means no drafter loaded, and +`unavailable` a drafter this cannot seed — the status document's +`draft_context` block carries the reason). One more line names the Anthropic tool *types* a turn dropped, when any. Each forwarded request logs one line too: `upstream`, method, path, the model id when the body named one, the upstream's status, and seconds to diff --git a/src/sous/api/routes.py b/src/sous/api/routes.py index 290637a9..31b35d80 100644 --- a/src/sous/api/routes.py +++ b/src/sous/api/routes.py @@ -237,6 +237,12 @@ def _turn_summary( "restore_s": result.restore_seconds, "prefill_tps": _per_second(result.prefilled_tokens, result.prefill_seconds), "decode_tps": _per_second(result.output_tokens, result.decode_seconds), + # The drafter's rounds behind decode_tps: what it proposed, what the + # exact verify accepted, and how much context its first draft saw. + "draft_rounds": result.draft_rounds, + "drafted": result.drafted_tokens, + "accepted": result.accepted_tokens, + "draft_context": result.draft_context, "seconds": result.seconds, "tools_hash": chat.tools_hash or None, "system_hash": chat.system_hash or None, @@ -263,6 +269,8 @@ def _turn_line(s: dict) -> str: f"prefill_s={s['prefill_s']:.1f} decode_s={s['decode_s']:.1f} " f"persist_s={s['persist_s']:.1f} restore_s={s['restore_s']:.1f} " f"prefill_tps={_opt(s['prefill_tps'])} decode_tps={_opt(s['decode_tps'])} " + f"draft_rounds={s['draft_rounds']} drafted={s['drafted']} accepted={s['accepted']} " + f"draft_context={s['draft_context']} " f"seconds={s['seconds']:.1f}{diag} " f"tools={s['tools_hash'] or '-'} system={s['system_hash'] or '-'}" ) diff --git a/src/sous/api/turn.py b/src/sous/api/turn.py index ad2749a7..3fa061f7 100644 --- a/src/sous/api/turn.py +++ b/src/sous/api/turn.py @@ -98,6 +98,14 @@ class TurnResult: persist_seconds: float = 0.0 # writing a fork at a boundary; in no phase restore_seconds: float = 0.0 # reading a fork off disk; in no phase bounds: tuple[int, int] = (0, 0) # the probe's (tools, header) boundaries; 0 = absent + # The drafter's part of the decode: rounds run, draft tokens proposed and + # accepted (each round's bonus token is in neither), and the positions + # of context its first draft saw. The counts are 0 without a drafter; + # the context is measured only while the engine seeds it. + draft_rounds: int = 0 + drafted_tokens: int = 0 + accepted_tokens: int = 0 + draft_context: int = 0 @dataclass(frozen=True) @@ -332,6 +340,10 @@ def delta_of(key: str) -> int: persist_seconds=after.get("persist_seconds", 0.0), restore_seconds=after.get("restore_seconds", 0.0), bounds=(after.get("bound_lo", 0), after.get("bound_hi", 0)), + draft_rounds=after.get("draft_rounds", 0), + drafted_tokens=after.get("drafted_tokens", 0), + accepted_tokens=after.get("accepted_tokens", 0), + draft_context=after.get("draft_context", 0), ) finally: self._engines.touch() diff --git a/src/sous/engine/base.py b/src/sous/engine/base.py index ad9308eb..b6d19736 100644 --- a/src/sous/engine/base.py +++ b/src/sous/engine/base.py @@ -392,6 +392,12 @@ def verify_attention_status(self) -> dict | None: # and fakes have no such attribute. return getattr(self._inner, "verify_attention_status", None) + @property + def draft_context_status(self) -> dict | None: + # Optional on purpose, like verify_attention_status: the VLM backend's + # word on whether its drafter is seeded with the prompt's hidden states. + return getattr(self._inner, "draft_context_status", None) + @property def positions(self) -> str | None: # Optional on purpose: only the VLM backend sets this; the LM backend @@ -668,6 +674,11 @@ def get(self) -> ManagedEngine: line += f" verify_attention={verify['state']}" if verify.get("probe_seconds") is not None: line += f" verify_attention_probe_s={verify['probe_seconds']}" + context = engine.draft_context_status + if context is not None: + line += f" draft_context={context['state']}" + if context["state"] == "active": + line += f" draft_context_window={context['window']}" _logger.info(line) return engine @@ -977,6 +988,13 @@ def status(self) -> dict: "state": verify["state"], "reason": verify["reason"], } + context = self._engine.draft_context_status + if context is not None: + out["draft_context"] = { + "state": context["state"], + "reason": context["reason"], + "window": context["window"], + } # Which side supplies the rotary positions behind a warm # cache: the load line says it once, this says it for as long # as the model is resident. diff --git a/src/sous/engine/draftctx.py b/src/sous/engine/draftctx.py new file mode 100644 index 00000000..dc0cb046 --- /dev/null +++ b/src/sous/engine/draftctx.py @@ -0,0 +1,404 @@ +"""The DFlash drafter's context on the prompt-cache path. + +mlx-vlm's DFlash round loop (`speculative/dflash.py:_dflash_rounds`) hands the +drafter, on its first draft call after `reset`, the target-layer hidden +states of every token the decode call's own prefill processed, and the +drafter's per-layer rotating cache (`sliding_window - 1` positions) attends +over them on every later round. On a hybrid model sous prefills the stable +prompt in a drafter-less call and decodes only the generation prompt — 7 +tokens on Qwen3.8 — so the drafter drafted every subagent turn from those 7 +tokens. On 64 real subagent turns at block 3 (#131's findings, #142) that +was 2.27 tokens per round against 2.58 with the turn's own prefill in front +of it (~+10% decode) and 2.62 with the last 2,047 tokens of the prompt. + +This module captures the newest `window` positions of the hidden states of +everything a turn prefills before its decode, and prepends them to the +decode call's own on that first draft call. Two hooks, both inert until +armed: + +- a class-level post-hook on the language model's forward that copies + `output.hidden_states` into the sink armed on that instance (`_SINK`, set + with `object.__setattr__` so it stays out of mlx's parameter tree). The sink + keeps only the newest `window` positions: ~105 MB per 2048-token chunk on + the default model (five layers x 5120, bf16), ~210 MB while a second chunk + is being taken, and ~105 MB for the assembled tail across the decode, + whatever the prompt's length; +- instance-level wraps of the drafter's `draft_block`, `draft_block_greedy` + and `reset` that prepend the pending context once, on the first draft call + after a reset, and record how many positions that call saw. + +Neither changes a token: the verify is exact, so a missing or wrong context +costs acceptance, never output. That is also why the gates here are +structural (drafter kind, the hooks the round loop looks for, the layers the +drafter names, a language model that runs single tokens through its forward) +rather than source hashes: a drift in mlx-vlm shows on the turn line as +`draft_context=7` (the capture lost) or as `draft_context=0` beside +`draft_context=unavailable` on the load line (a gate tripped), not as a +different reply. +""" + +from __future__ import annotations + +import functools +import logging +import warnings +from collections.abc import Sequence +from typing import Any + +from sous.engine.int8prefill import _root + +logger = logging.getLogger("sous.engine.draftctx") + +# The context a drafter with an unbounded (plain KVCache) context gets: the +# window the shipped DFlash2 checkpoints train with, so the first round's +# projection over the context stays bounded whatever the prompt's length. +DEFAULT_WINDOW = 2048 +# Set with object.__setattr__ so they stay out of mlx's parameter tree. +_SINK = "_sous_draft_sink" # on the language model: the armed Sink, or None +_PENDING = "_sous_draft_pending" # on the drafter: the context to prepend, or None +_FIRST = "_sous_draft_first" # on the drafter: no draft call since the last reset +_FED = "_sous_draft_fed" # on the drafter: positions the first draft call saw +_WRAPPED_DRAFTER = "_sous_draft_wrapped" # on the drafter: its calls are shadowed +_WRAPPED: set[type] = set() + + +class Sink: + """The newest `keep` positions of the hidden states a turn's prefills + produced, per forward as the layers' arrays concatenated along the last + axis — the shape the round loop hands the drafter — and evaluated as they + arrive: a lazy hidden state would pin that forward's whole graph. One + sink spans every segment a turn prefills before its decode, so a cold + turn's tail ends where the generation prompt begins whatever fork stops + split the prefill.""" + + def __init__(self, layer_ids: list[int], keep: int): + self.layer_ids = list(layer_ids) + self.keep = keep + self._chunks: list[Any] = [] + self._held = 0 + self._failed = False + + def fail(self) -> None: + """Void the capture: a tail missing a forward's rows would end short + of the generation prompt and seed the drafter with the wrong + positions, which costs more acceptance than no context at all.""" + self._failed = True + self._chunks = [] + self._held = 0 + + def take(self, hidden_states: Any) -> None: + import mlx.core as mx + + # A list of per-layer arrays is what the forward returns; anything + # else (None from a model that does not capture) is nothing to keep. + if self._failed or self.keep <= 0: + return + if not isinstance(hidden_states, list | tuple) or not hidden_states: + return + h = mx.concatenate(list(hidden_states), axis=-1) + mx.async_eval(h) + self._chunks.append(h) + self._held += int(h.shape[1]) + # Drop whole chunks the tail can no longer reach; the slice at the + # end trims the rest. + while self._chunks and self._held - int(self._chunks[0].shape[1]) >= self.keep: + self._held -= int(self._chunks[0].shape[1]) + self._chunks.pop(0) + + def finish(self) -> Any | None: + """The tail as one evaluated array of its own, or None when nothing + was captured (a model whose forward returns no hidden states).""" + import mlx.core as mx + + if not self._chunks: + return None + parts, excess = list(self._chunks), self._held - self.keep + if excess > 0: + # Cut the excess off the oldest chunk before assembling: a slice + # of the assembled array would be a view keeping every row of it + # alive for the whole decode, twice the tail at a chunk boundary. + parts[0] = parts[0][:, excess:, :] + if len(parts) > 1: + tail = mx.concatenate(parts, axis=1) + elif excess > 0: + tail = mx.array(parts[0]) # a copy: the slice alone is a view + else: + tail = parts[0] + mx.eval(tail) + self._chunks = [] + self._held = 0 + return tail + + +def _forward_hook(cls: type) -> None: + orig = cls.__call__ + + @functools.wraps(orig) + def __call__(self, *args, **kwargs): + out = orig(self, *args, **kwargs) + sink = getattr(self, _SINK, None) + if sink is not None: + try: + sink.take(getattr(out, "hidden_states", None)) + except Exception as e: # noqa: BLE001 — a capture must never fail a turn + object.__setattr__(self, _SINK, None) + sink.fail() + warnings.warn( + f"sous: drafter context capture failed ({type(e).__name__}: {e}); " + "this turn's drafter starts from the generation prompt", + stacklevel=2, + ) + return out + + cls.__call__ = __call__ # ty: ignore[invalid-assignment] + + +def install_forward_hook(cls: type) -> None: + """Hook one language-model class's forward, once per process. The hook + reads only an instance that has a sink armed, so installing it changes + nothing for any other model or turn.""" + if cls not in _WRAPPED: + _forward_hook(cls) + _WRAPPED.add(cls) + + +def _wrap_drafter(drafter: Any) -> None: + """Shadow the drafter's draft calls and reset per instance, the way + mlx-vlm binds the target's argmax onto the drafter (`argmax_from_hidden`). + Once: a second engine over the same drafter would otherwise nest them.""" + import mlx.core as mx + + if getattr(drafter, _WRAPPED_DRAFTER, False): + return + object.__setattr__(drafter, _WRAPPED_DRAFTER, True) + reset = drafter.reset + + @functools.wraps(reset) + def _reset(*args, **kwargs): + object.__setattr__(drafter, _FIRST, True) + object.__setattr__(drafter, _FED, 0) + return reset(*args, **kwargs) + + object.__setattr__(drafter, "reset", _reset) + + for name in ("draft_block", "draft_block_greedy"): + orig = getattr(drafter, name, None) + if orig is None: + continue + + @functools.wraps(orig) + def _draft(last_bonus, hidden, cache, block_size, sampler, *args, _orig=orig, **kwargs): + if getattr(drafter, _FIRST, False): + object.__setattr__(drafter, _FIRST, False) + pending = getattr(drafter, _PENDING, None) + object.__setattr__(drafter, _PENDING, None) + if ( + pending is not None + and pending.ndim == hidden.ndim == 3 + and pending.shape[0] == hidden.shape[0] + and pending.shape[-1] == hidden.shape[-1] + ): + hidden = mx.concatenate([pending, hidden], axis=1) + object.__setattr__(drafter, _FED, int(hidden.shape[1])) + return _orig(last_bonus, hidden, cache, block_size, sampler, *args, **kwargs) + + object.__setattr__(drafter, name, _draft) + + +def _unwrap_drafter(drafter: Any) -> None: + """Undo `_wrap_drafter`: the wraps close over the drafter, a cycle that + only a gc pass collects, and the drafter holds the target's embedding + and head through `bind` — so an unload that left them would keep the + weights resident until some later collection.""" + for name in ("reset", "draft_block", "draft_block_greedy", _WRAPPED_DRAFTER): + if name in getattr(drafter, "__dict__", {}): + object.__delattr__(drafter, name) + + +def window(drafter: Any) -> int: + """How many context positions the drafter keeps, read off its config the + way its `make_cache` does: a buffered window, else a sliding layer's + window less one, else DEFAULT_WINDOW for an unbounded context.""" + config = getattr(drafter, "config", None) + buffered = getattr(config, "draft_window_size", None) + if buffered is not None and int(buffered) > 0: + return int(buffered) + sliding = getattr(config, "sliding_window", None) + if sliding is not None and int(sliding) > 1: + layer_types = getattr(config, "layer_types", None) or [] + if any(kind == "sliding_attention" for kind in layer_types): + return int(sliding) - 1 + return DEFAULT_WINDOW + + +class DraftContext: + """What one engine's prefills capture and its decodes seed. `off` when the + engine has no drafter, `unavailable` when it has one this module cannot + serve; either way every method is a no-op and `status` says why.""" + + def __init__(self, status: dict[str, Any], drafter: Any = None, layer_ids: Sequence[int] = ()): + self.status = status + self._drafter = drafter + self.layer_ids = list(layer_ids) + self.keep = int(status.get("window") or 0) + + @property + def active(self) -> bool: + return self.status["state"] == "active" + + def sink(self, capture: Any) -> Sink | None: + """The sink a prefill captures into: `capture` continued when it is + one this engine handed out, a fresh one when the turn asks to start + capturing, None when it asks for nothing or there is nothing to seed.""" + if isinstance(capture, Sink): + return capture + return Sink(self.layer_ids, self.keep) if capture and self.active else None + + @staticmethod + def tail(capture: Any) -> Any | None: + """What a turn's capture holds, assembled — None for no capture.""" + return capture.finish() if isinstance(capture, Sink) else None + + def close(self) -> None: + """Let go of the drafter: undo its wraps and drop the reference, so an + unload frees the drafter and, through it, the target's modules.""" + if self._drafter is not None: + _unwrap_drafter(self._drafter) + self._drafter = None + + @staticmethod + def capture_kwargs(sink: Sink | None) -> dict[str, Any]: + """The kwarg that makes every prefill forward return the target-layer + hidden states — what mlx-vlm's own speculative prefill asks for.""" + return {} if sink is None else {"capture_layer_ids": list(sink.layer_ids)} + + def arm(self, model: Any, sink: Sink | None) -> _Armed: + """Arm `sink` on `model`'s language model for the duration of a `with` + block; a None sink arms nothing.""" + return _Armed(_root(model) if sink is not None else None, sink) + + def seed(self, context: Any) -> _Seeded: + """Hand `context` (or nothing) to the drafter's next first draft call, + for the duration of a `with` block: a decode that never drafts — one + token asked for, or a stop on the first — leaves nothing pending for + a later turn and reads as no context at all.""" + return _Seeded(self._drafter if self.active else None, context) + + def fed(self) -> int: + """The context the most recent decode drafted from: the positions its + first draft call was handed, capped at the window — the drafter's + sliding attention drops the oldest rows past it, so a full tail plus + the generation prompt is still one window. 0 when it never drafted.""" + if not self.active: + return 0 + return min(int(getattr(self._drafter, _FED, 0) or 0), self.keep) + + +class _Armed: + def __init__(self, lm: Any, sink: Sink | None): + self._lm, self._sink = lm, sink + + def __enter__(self) -> Sink | None: + if self._lm is not None: + object.__setattr__(self._lm, _SINK, self._sink) + return self._sink + + def __exit__(self, *exc: object) -> None: + if self._lm is not None: + object.__setattr__(self._lm, _SINK, None) + + +class _Seeded: + def __init__(self, drafter: Any, context: Any): + self._drafter, self._context = drafter, context + + def __enter__(self) -> None: + if self._drafter is not None: + object.__setattr__(self._drafter, _PENDING, self._context) + # The round loop's reset zeroes this too, but a decode that stops + # before the loop runs never resets, and must not read the + # previous decode's context as its own. + object.__setattr__(self._drafter, _FED, 0) + + def __exit__(self, *exc: object) -> None: + if self._drafter is not None: + object.__setattr__(self._drafter, _PENDING, None) + + +OFF = DraftContext({"state": "off", "reason": None, "window": 0, "layers": 0}) + + +def rounds_snapshot(drafter: Any) -> Any: + """The drafter's lifetime round counters before a decode, or None + without a drafter — `rounds_since` reads the decode's own share off it.""" + if drafter is None: + return None + from mlx_vlm.speculative.utils import speculative_stats_snapshot + + return speculative_stats_snapshot(drafter) + + +def rounds_since(drafter: Any, snapshot: Any) -> tuple[int, int, int]: + """(rounds, accepted, drafted) the drafter recorded since `snapshot`: + mlx-vlm's lifetime counters survive the reset every decode starts with, + unlike its per-call `accept_lens`, and a call that never drafted (one + token asked for) reads as zeros.""" + if drafter is None or snapshot is None: + return (0, 0, 0) + from mlx_vlm.speculative.utils import speculative_stats_since + + rounds, accepted, drafted = speculative_stats_since(drafter, snapshot) + return (int(rounds or 0), int(accepted or 0), int(drafted or 0)) + + +def _refuse(reason: str) -> DraftContext: + warnings.warn( + f"sous: drafter context unavailable ({reason}); the drafter starts every turn " + "from the generation prompt", + stacklevel=3, + ) + return DraftContext({"state": "unavailable", "reason": reason, "window": 0, "layers": 0}) + + +def enable(model: Any, drafter: Any, kind: str) -> DraftContext: + """Arm one loaded model and its drafter. Never raises: a model load must not + fail because of an optimisation, and without it the drafter simply keeps + starting from the generation prompt.""" + if drafter is None: + return OFF + try: + if kind != "dflash": + return _refuse(f"drafter kind {kind!r} (dflash only)") + # A drafter the round loop prepares hidden states for consumes them + # under a different contract than the plain draft call this seeds; + # one that sizes its block from the prompt length the loop shows it + # would size it for the 7 tokens the decode call prefilled while + # drafting from a full window, off whatever that policy assumes. + for hook in ("prepare_target_hidden", "choose_block_ceiling", "choose_initial_block_size"): + if callable(getattr(drafter, hook, None)): + return _refuse(f"drafter defines {hook}") + config = getattr(drafter, "config", None) + layer_ids = [int(i) for i in getattr(config, "target_layer_ids", None) or ()] + if not layer_ids: + return _refuse("drafter names no target layers") + for name in ("reset", "draft_block"): + if not callable(getattr(drafter, name, None)): + return _refuse(f"drafter has no {name}") + lm = _root(model) + if lm is model: + return _refuse("model has no language_model") + # A language model that routes one-token forwards around its forward + # (qwen4_exp does) would capture nothing for the prefill's last token. + if callable(getattr(lm, "_batch_invariant_decode", None)): + return _refuse("language model decodes single tokens outside its forward") + keep = window(drafter) + install_forward_hook(type(lm)) + _wrap_drafter(drafter) + except Exception as e: # noqa: BLE001 — degrade, never block the model + return _refuse(str(e) or type(e).__name__) + logger.info("drafter context: %d target layers, window %d", len(layer_ids), keep) + return DraftContext( + {"state": "active", "reason": None, "window": keep, "layers": len(layer_ids)}, + drafter, + layer_ids, + ) diff --git a/src/sous/engine/lm.py b/src/sous/engine/lm.py index 1ef6fc43..f07b2753 100644 --- a/src/sous/engine/lm.py +++ b/src/sous/engine/lm.py @@ -11,7 +11,13 @@ from sous.engine import forkio from sous.engine.base import Delta, OnDelta from sous.engine.forkstore import ForkStore, fork_key_fields -from sous.engine.promptcache import FORK_MIN_TOKENS, PrefixCache, PromptMemo, probe_boundaries +from sous.engine.promptcache import ( + FORK_MIN_TOKENS, + PrefixCache, + PromptMemo, + Speculation, + probe_boundaries, +) class LMEngine: @@ -150,13 +156,15 @@ def new_cache(self) -> list: model, _ = self._loaded() return make_prompt_cache(model) - def prefill(self, cache: list, token_ids: list[int]) -> None: + def prefill(self, cache: list, token_ids: list[int], capture: Any = None) -> None: # mlx-lm has no prefill-only entry point: stream_generate raises on # max_tokens=0 because its `token` local is unbound when the loop never # runs. Calling the model directly is what generate_step does anyway, # and RoPE offsets come from the cache, so a warm suffix needs nothing # extra. The non-trimmable path and any turn that forks at the header # reach here; the trimmable path otherwise fuses prefill into decode. + # `capture` is the VLM backend's: this backend runs no drafter, so + # there is nothing to capture for. import mlx.core as mx model, _ = self._loaded() @@ -172,7 +180,12 @@ def prefill(self, cache: list, token_ids: list[int]) -> None: mx.eval([c.state for c in cache]) def decode( - self, cache: list, token_ids: list[int], max_tokens: int, on_delta: OnDelta | None = None + self, + cache: list, + token_ids: list[int], + max_tokens: int, + on_delta: OnDelta | None = None, + context: Any = None, ) -> str: from mlx_lm import stream_generate @@ -191,6 +204,10 @@ def decode( on_delta(Delta(r.text, r.generation_tokens, r.finish_reason)) return "".join(chunks) + def speculation(self) -> Speculation: + # No drafter on this backend: every decode is plain. + return Speculation() + def copy_array(self, a: object) -> object: import mlx.core as mx diff --git a/src/sous/engine/promptcache.py b/src/sous/engine/promptcache.py index 4ee82e03..77be8d35 100644 --- a/src/sous/engine/promptcache.py +++ b/src/sous/engine/promptcache.py @@ -306,6 +306,10 @@ def auto_cache_budget(*, working_set: int, active: int, reserve_bytes: int) -> i "decode_seconds", "persist_seconds", "restore_seconds", + "draft_rounds", + "drafted_tokens", + "accepted_tokens", + "draft_context", } ) _GAUGES = frozenset({"snapshot_bytes", "miss_lcp"}) | TURN_GAUGES @@ -386,6 +390,16 @@ class PromptCacheStats: decode_seconds: float = 0.0 # hooks.decode, plus the restore persist_seconds: float = 0.0 # writing the live cache at a boundary; never prefill time restore_seconds: float = 0.0 # time spent attempting a restore, charged on a skip too + # What the drafter did in the decode that produced the text: rounds run, + # draft tokens proposed and accepted (the bonus token each round also + # yields is in neither), and the positions of context its first draft + # saw — the generation prompt alone reads 7 on Qwen3.8. The counts are + # zero without a drafter; the context is measured only while the engine + # seeds it, so it also reads zero when the seeding is unavailable. + draft_rounds: int = 0 + drafted_tokens: int = 0 + accepted_tokens: int = 0 + draft_context: int = 0 def as_dict(self) -> dict: return dataclasses.asdict(self) @@ -446,21 +460,49 @@ def clear(self) -> None: self._slots = dict.fromkeys(_MEMO_SLOTS) +@dataclass(frozen=True) +class Speculation: + """What the drafter did in one decode call: rounds run, draft tokens + proposed and accepted (the bonus token each round also yields is in + neither), and the positions of context its first draft saw. The counts + are zero without a drafter, or when the call never drafted; the context + is measured only while the engine seeds it, and reads zero otherwise + whatever the drafter saw.""" + + rounds: int = 0 + drafted: int = 0 + accepted: int = 0 + context: int = 0 + + class CacheHooks(Protocol): """The things only an engine can do. Everything else is shared. - `eval_cache` materialises a cache's arrays on the calling thread (a fork - copy is lazy, and the pressure valve reads active memory). `persist` - writes the live working cache at a boundary to `path` — called on the - owner thread, holding no lock, never with a Slot; `restore` fills a fresh - cache from `path` on the calling thread and evaluates it, raising the - store's verification error on any mismatch.""" + `prefill` with `capture` keeps the newest window of the segment's + target-layer hidden states for `decode` to seed the drafter with, and + returns the capture — an opaque object the orchestrator only carries: + `True` starts one, a value an earlier prefill of the turn returned + continues it, None asks for none (the engine returns None when it has + nothing to seed with, and that passes back in unchanged). `speculation` + is the drafter's count for the most recent decode call. `eval_cache` + materialises a cache's arrays on the calling thread (a fork copy is lazy, + and the pressure valve reads active memory). `persist` writes the live + working cache at a boundary to `path` — called on the owner thread, + holding no lock, never with a Slot; `restore` fills a fresh cache from + `path` on the calling thread and evaluates it, raising the store's + verification error on any mismatch.""" def new_cache(self) -> list: ... - def prefill(self, cache: list, token_ids: list[int]) -> None: ... + def prefill(self, cache: list, token_ids: list[int], capture: Any = None) -> Any: ... def decode( - self, cache: list, token_ids: list[int], max_tokens: int, on_delta: OnDelta | None + self, + cache: list, + token_ids: list[int], + max_tokens: int, + on_delta: OnDelta | None, + context: Any = None, ) -> str: ... + def speculation(self) -> Speculation: ... def copy_array(self, a: object) -> object: ... # Bytes the machine can still give a cache right now, or None when it # cannot tell (no mlx). Read on the owner thread; must not release thread @@ -1064,7 +1106,15 @@ def generate( budget to fork into or a store to write to.""" hooks = self._hooks if not self.enabled: - return hooks.decode(hooks.new_cache(), list(full_ids), max_tokens, on_delta) + # Nothing is cached or counted, but the drafter still runs — over + # the whole prompt, which the decode call prefills itself — and + # the turn line's acceptance is read off the same gauges as ever. + with self._lock: + stats = self._stats_for(threading.current_thread()) + stats.begin_turn() + text = hooks.decode(hooks.new_cache(), list(full_ids), max_tokens, on_delta) + _note_speculation(stats, hooks) + return text owner = threading.current_thread() with self._lock: @@ -1098,7 +1148,9 @@ def generate( "plus a generation suffix; decoding cold this turn", stacklevel=2, ) - return hooks.decode(hooks.new_cache(), list(full_ids), max_tokens, on_delta) + text = hooks.decode(hooks.new_cache(), list(full_ids), max_tokens, on_delta) + _note_speculation(stats, hooks) + return text with self._lock: # Owner-filtered: the arrays live only on the publishing thread's @@ -1325,6 +1377,11 @@ def _run( entry_reuse = reuse stats.prefilled_tokens += anchor - entry_reuse published: list[Slot] = [] + # Everything this turn prefills before its decode is captured into + # one context for the drafter — the newest window of it — whatever + # segments the fork stops cut it into: what the decode call itself + # prefills is all the drafter would otherwise see. + capture: Any = True for boundary, need_slot, need_file in self._fork_boundaries( stats, owner, stable_ids, fork_at, reuse ): @@ -1334,7 +1391,7 @@ def _run( # a prefix already prefilled. An empty segment (a turn that # started exactly here) is a no-op on both backends. started = _clock() - hooks.prefill(cache, list(stable_ids[reuse:boundary])) + capture = hooks.prefill(cache, list(stable_ids[reuse:boundary]), capture=capture) reuse = boundary stats.prefill_seconds += _clock() - started if need_file: @@ -1397,24 +1454,44 @@ def _run( # evicts during the decode below is freed then, not pinned by this # frame until the turn ends. published = [] + # A capture the engine never started (no drafter) is None from here on. + context = None if capture is True else capture if all_trimmable(cache): # Everything rewinds, so (the rest of) prefill and decode fuse into # one pass and the generation block plus the generated tokens are - # simply trimmed back off afterwards. + # simply trimmed back off afterwards. The decode call prefills the + # rest itself, so the drafter sees it; the fork stops' segments, + # when there were any, are what the capture adds in front. started = _clock() - text = hooks.decode(cache, list(full_ids[reuse:]), max_tokens, on_delta) + text = hooks.decode( + cache, list(full_ids[reuse:]), max_tokens, on_delta, context=context + ) trim_to(cache, anchor) stats.decode_seconds += _clock() - started + _note_speculation(stats, hooks) return text # A recurrent layer cannot rewind, so stop at the anchor, record it, - # and put the cache back there once the generation is done. + # and put the cache back there once the generation is done. The decode + # call then prefills only the generation prompt, which is all the + # drafter would see of the conversation without the capture. started = _clock() - hooks.prefill(cache, list(stable_ids[reuse:])) + context = hooks.prefill(cache, list(stable_ids[reuse:]), capture=capture) snap, nbytes = snapshot(cache, hooks.copy_array) stats.snapshot_bytes = nbytes stats.prefill_seconds += _clock() - started started = _clock() - text = hooks.decode(cache, list(full_ids[anchor:]), max_tokens, on_delta) + text = hooks.decode(cache, list(full_ids[anchor:]), max_tokens, on_delta, context=context) restore(cache, snap, hooks.copy_array) stats.decode_seconds += _clock() - started + _note_speculation(stats, hooks) return text + + +def _note_speculation(stats: PromptCacheStats, hooks: CacheHooks) -> None: + """Assign the decode's drafter gauges — the last decode call's, so a cold + retry's counts replace the failed warm attempt's.""" + spec = hooks.speculation() + stats.draft_rounds = spec.rounds + stats.drafted_tokens = spec.drafted + stats.accepted_tokens = spec.accepted + stats.draft_context = spec.context diff --git a/src/sous/engine/vlm.py b/src/sous/engine/vlm.py index bcde6906..b38bfd20 100644 --- a/src/sous/engine/vlm.py +++ b/src/sous/engine/vlm.py @@ -8,10 +8,16 @@ from pathlib import Path from typing import Any, cast -from sous.engine import forkio +from sous.engine import draftctx, forkio from sous.engine.base import Delta, OnDelta from sous.engine.forkstore import ForkStore, fork_key_fields -from sous.engine.promptcache import FORK_MIN_TOKENS, PrefixCache, PromptMemo, probe_boundaries +from sous.engine.promptcache import ( + FORK_MIN_TOKENS, + PrefixCache, + PromptMemo, + Speculation, + probe_boundaries, +) def _load_quantized_drafter(model: object, draft_id: str) -> tuple[Any, str]: @@ -106,6 +112,10 @@ def __init__( self.verify_attention_status = verifyattn.enable( self._model, enabled=self._draft is not None ) + # The drafter's context on the prompt-cache path: armed once the + # drafter has settled, so one that failed to load leaves it off. + self._draft_context = draftctx.enable(self._model, self._draft, self._draft_kind) + self._speculation = Speculation() # Forks on disk, when the factory handed us a directory: built after # the drafter and int8 have settled, since the key reads both. Tests # and sous tune never pass one, so nothing they build touches ~/.sous. @@ -155,6 +165,13 @@ def drafter(self) -> str: engine survives with a warning rather than an error.""" return self._draft_id + @property + def draft_context_status(self) -> dict: + """Whether the drafter is seeded with the prompt's hidden states on + the prompt-cache path — the model-load line's and the status + document's `draft_context` block.""" + return dict(self._draft_context.status) + def _fork_key_fields(self, weights: str) -> dict[str, str]: from importlib.metadata import version @@ -232,26 +249,37 @@ def new_cache(self) -> list: # all-plain KVCache and loses the model's real cache layout. return make_prompt_cache(model.language_model) - def prefill(self, cache: list, token_ids: list[int]) -> None: + def prefill(self, cache: list, token_ids: list[int], capture: Any = None) -> Any: import mlx.core as mx from mlx_vlm import generate model, processor = self._loaded() + # A captured prefill keeps the newest window of its target-layer + # hidden states in the sink it hands back, for the turn's later + # prefills to add to and its decode to seed the drafter with. The + # kwarg is the one mlx-vlm's own speculative prefill passes, so every + # forward of this call returns them, and the hook that keeps them + # reads only this model's language model while the sink is armed — + # the prefill itself runs exactly as it does uncaptured. + sink = self._draft_context.sink(capture) if not token_ids: - return + return sink # max_tokens=0 is prefill-only: dispatch has an explicit # `if not generated_tokens:` branch that yields a result and returns # without touching any cache state. - generate( - model, - processor, - "", - max_tokens=0, - verbose=False, - prompt_cache=cache, - input_ids=mx.array(token_ids)[None], - **self._positions(cache, len(token_ids)), - ) + with self._draft_context.arm(model, sink): + generate( + model, + processor, + "", + max_tokens=0, + verbose=False, + prompt_cache=cache, + input_ids=mx.array(token_ids)[None], + **self._positions(cache, len(token_ids)), + **draftctx.DraftContext.capture_kwargs(sink), + ) + return sink def _positions(self, cache: list, n_tokens: int) -> dict[str, Any]: """Explicit rotary positions for `n_tokens` appended behind `cache`, @@ -327,7 +355,12 @@ def _helper_returns_positions(self) -> bool: return getattr(out, "position_ids", None) is not None def decode( - self, cache: list, token_ids: list[int], max_tokens: int, on_delta: OnDelta | None = None + self, + cache: list, + token_ids: list[int], + max_tokens: int, + on_delta: OnDelta | None = None, + context: Any = None, ) -> str: import mlx.core as mx from mlx_vlm import stream_generate @@ -335,8 +368,11 @@ def decode( model, processor = self._loaded() # Speculative decoding rides on the decode call only: prefill has no # tokens to draft, and generate_step captures the hidden states the - # drafter needs during its own prefill of these input_ids. block size - # 0 means None — let the drafter's own policy pick the depth. + # drafter needs during its own prefill of these input_ids — which on + # the hybrid prompt-cache path are the generation prompt alone, so + # `context`, what the turn's prefills captured before it, goes in + # front of them on the drafter's first draft. block size 0 means + # None — let the drafter's own policy pick the depth. draft_kwargs = ( { "draft_model": self._draft, @@ -363,27 +399,36 @@ def decode( # prompt_cache plus input_ids, not prompt_cache_state: sous owns the # cache outright rather than driving mlx-vlm's reuse path, and so # also owns the positions the suffix is encoded at (_positions). - for r in stream_generate( - model, - processor, - "", - max_tokens=max_tokens, - verbose=False, - prompt_cache=cache, - input_ids=mx.array(token_ids)[None], - **self._positions(cache, len(token_ids)), - **sampling, - **draft_kwargs, - ): - # Draft rows are the speculator's proposals, not accepted output; - # generate() skips them the same way. - if r.is_draft: - continue - chunks.append(r.text) - if on_delta is not None: - on_delta(Delta(r.text, r.generation_tokens, r.finish_reason)) + before = draftctx.rounds_snapshot(self._draft) + with self._draft_context.seed(draftctx.DraftContext.tail(context)): + for r in stream_generate( + model, + processor, + "", + max_tokens=max_tokens, + verbose=False, + prompt_cache=cache, + input_ids=mx.array(token_ids)[None], + **self._positions(cache, len(token_ids)), + **sampling, + **draft_kwargs, + ): + # Draft rows are the speculator's proposals, not accepted output; + # generate() skips them the same way. + if r.is_draft: + continue + chunks.append(r.text) + if on_delta is not None: + on_delta(Delta(r.text, r.generation_tokens, r.finish_reason)) + rounds, accepted, drafted = draftctx.rounds_since(self._draft, before) + self._speculation = Speculation( + rounds=rounds, drafted=drafted, accepted=accepted, context=self._draft_context.fed() + ) return "".join(chunks) + def speculation(self) -> Speculation: + return self._speculation + def copy_array(self, a: object) -> object: import mlx.core as mx @@ -493,5 +538,10 @@ def unload(self) -> None: self._model = None self._processor = None self._draft = None + # The context's wraps close over the drafter, and the drafter holds + # the target's embedding and head: let go before collecting, or the + # weights outlive the unload. + self._draft_context.close() + self._draft_context = draftctx.OFF gc.collect() mx.clear_cache() diff --git a/src/sous/tune/suite/runner.py b/src/sous/tune/suite/runner.py index 7303a3f4..eee7eec1 100644 --- a/src/sous/tune/suite/runner.py +++ b/src/sous/tune/suite/runner.py @@ -118,8 +118,9 @@ def model_id(self) -> str: return self._inner.model_id def __getattr__(self, name: str): - # drafter, positions, int8_prefill_status, verify_attention_status: - # whatever the backend has, read through getattr(..., None) by ManagedEngine. + # drafter, positions, int8_prefill_status, verify_attention_status, + # draft_context_status: whatever the backend has, read through + # getattr(..., None) by ManagedEngine. return getattr(self._inner, name) def generate( diff --git a/tests/test_api_routes.py b/tests/test_api_routes.py index 5385f551..93ad8a29 100644 --- a/tests/test_api_routes.py +++ b/tests/test_api_routes.py @@ -1660,9 +1660,10 @@ def test_a_claimed_model_id_cannot_forge_or_bloat_a_log_line(tmp_path: Path, cap lines = [line for line in err.splitlines() if "sous.api:" in line] assert lines, "expected at least one log line" for line in lines: - # The attributed turn line is ~410 chars with its prefix; the cap is - # here to catch an unbounded client string, not to pin a length. - assert len(line) < 500, line + # The attributed turn line is ~470 chars with its prefix (~510 with a + # miss's diagnostics); the cap is here to catch an unbounded client + # string, not to pin a length. + assert len(line) < 600, line assert "A" * 20 not in line, line # the oversized id never reaches it if "model=" in line: assert "model=-" in line, line @@ -1719,6 +1720,10 @@ def generate(messages, tools, max_tokens, on_delta=None): "pressure_evictions": 1, "prefill_seconds": 2.0, "decode_seconds": 4.0, + "draft_rounds": 2, + "drafted_tokens": 4, + "accepted_tokens": 1, + "draft_context": 2054, } return out @@ -1736,6 +1741,9 @@ def generate(messages, tools, max_tokens, on_delta=None): assert f["prefill_s"] == "2.0" and f["decode_s"] == "4.0" # 6 prefilled tokens / 2.0 s; "second reply here" is 3 words = 3 output tokens / 4.0 s assert f["prefill_tps"] == "3.0" and f["decode_tps"] == "0.8" + # the drafter's rounds behind that decode: what it drafted, what the verify kept + assert (f["draft_rounds"], f["drafted"], f["accepted"]) == ("2", "4", "1") + assert f["draft_context"] == "2054" assert f["persist_s"] == "0.0" and f["restore_s"] == "0.0" for key in ("load_s", "queue_s", "engine_wait_s", "tokenize_s", "ttft_s", "seconds"): assert key in f, key @@ -1942,7 +1950,8 @@ def generate(messages, tools, max_tokens, on_delta=None): "input_tokens", "output_tokens", "reused_tokens", "prefilled_tokens", "lcp", "lcp_region", "bounds", "forks", "evicted", "pressure", "load_s", "queue_s", "engine_wait_s", "tokenize_s", "ttft_s", "prefill_s", "decode_s", "persist_s", - "restore_s", "prefill_tps", "decode_tps", "seconds", "tools_hash", "system_hash", + "restore_s", "prefill_tps", "decode_tps", "draft_rounds", "drafted", "accepted", + "draft_context", "seconds", "tools_hash", "system_hash", } # fmt: skip _post(app, _body(stream=False)) ids = [t["id"] for t in _recent(endpoint)] diff --git a/tests/test_api_turn.py b/tests/test_api_turn.py index 71fabe2a..e8e7560f 100644 --- a/tests/test_api_turn.py +++ b/tests/test_api_turn.py @@ -579,6 +579,10 @@ def test_gauge_fields_are_read_directly_not_as_deltas(tmp_path: Path): "probe_seconds": 5.0, "prefill_seconds": 5.0, "decode_seconds": 5.0, + "draft_rounds": 50, + "drafted_tokens": 100, + "accepted_tokens": 70, + "draft_context": 2054, } original = inner.generate @@ -593,6 +597,10 @@ def generate(messages, tools, max_tokens, on_delta=None): "probe_seconds": 3.0, "prefill_seconds": 2.0, "decode_seconds": 2.5, + "draft_rounds": 12, + "drafted_tokens": 24, + "accepted_tokens": 17, + "draft_context": 305, } return out @@ -601,6 +609,8 @@ def generate(messages, tools, max_tokens, on_delta=None): result = runner.run(MSGS, [], 100, RecordingSink()) assert (result.prefilled_tokens, result.took_len, result.bounds) == (40, 40, (10, 20)) assert (result.prefill_seconds, result.decode_seconds) == (2.0, 2.5) + assert (result.draft_rounds, result.drafted_tokens, result.accepted_tokens) == (12, 24, 17) + assert result.draft_context == 305 # probe_seconds is added into tokenize_seconds rather than exposed on its # own; a delta (3.0 - 5.0, clamped to 0) would land near zero on a fast # FakeEngine.count_tokens, far below this window. diff --git a/tests/test_draftctx.py b/tests/test_draftctx.py new file mode 100644 index 00000000..b239a9c8 --- /dev/null +++ b/tests/test_draftctx.py @@ -0,0 +1,855 @@ +"""The DFlash drafter's context (sous.engine.draftctx). + +The sink, the forward hook and the drafter wraps are exercised on stubs; the +two contracts they rest on — that mlx-vlm's generate_step passes an extra +`capture_layer_ids` into every prefill forward, chunked the way it is, and +that its DFlash round loop hands the drafter's first draft after a reset the +whole prompt hidden — are driven through the real functions on stub models, +the way tests/test_engine_positions.py drives generate_step. No weights. +""" + +import sys +import threading +import types +from typing import Any + +import pytest + +mx = pytest.importorskip("mlx.core") + +from sous.engine import draftctx # noqa: E402 — after the importorskip guard +from sous.engine.promptcache import PromptMemo, Speculation # noqa: E402 +from sous.engine.vlm import VLMEngine # noqa: E402 + + +def _states(layers: int, start: int, n: int, width: int = 2) -> list: + """One forward's hidden states: per layer an [1, n, width] array whose + values name the absolute position plus 100 x the layer, so a slice of the + sink's tail can be checked exactly.""" + positions = mx.arange(start, start + n, dtype=mx.float32)[None, :, None] + return [mx.broadcast_to(positions + 100 * layer, (1, n, width)) for layer in range(layers)] + + +# ---- the sink ----------------------------------------------------------------- + + +def test_sink_keeps_the_newest_positions_across_forwards(): + sink = draftctx.Sink([0, 1], keep=5) + sink.take(_states(2, 0, 4)) + sink.take(_states(2, 4, 4)) + sink.take(_states(2, 8, 1)) + tail = sink.finish() + assert tail is not None and tail.shape == (1, 5, 4) # layers along the last axis + assert tail[0, :, 0].tolist() == [4, 5, 6, 7, 8] + assert tail[0, :, 2].tolist() == [104, 105, 106, 107, 108] + + +def test_sink_drops_the_chunks_the_tail_can_no_longer_reach(): + sink = draftctx.Sink([0], keep=3) + sink.take(_states(1, 0, 10)) + sink.take(_states(1, 10, 10)) + tail = sink.finish() + assert tail is not None and tail[0, :, 0].tolist() == [17, 18, 19] + + +def test_a_sink_that_keeps_nothing_takes_nothing(): + sink = draftctx.Sink([0], keep=0) + sink.take(_states(1, 0, 4)) + assert sink.finish() is None + + +def test_sink_hands_back_everything_when_the_prefill_is_shorter_than_the_window(): + sink = draftctx.Sink([0], keep=2047) + sink.take(_states(1, 0, 6)) + tail = sink.finish() + assert tail is not None and tail.shape == (1, 6, 2) + + +def test_sink_ignores_forwards_that_captured_nothing(): + sink = draftctx.Sink([0], keep=4) + sink.take(None) + sink.take([]) + sink.take(mx.zeros((1, 3, 2))) # not the list a forward returns + assert sink.finish() is None + + +def _active_bytes() -> int: + """Active memory once every completed op's inputs are released: on Metal + they go with the command buffer's completion handler, which mx.eval + does not wait for.""" + import gc + + gc.collect() + mx.synchronize() + return mx.get_active_memory() + + +@pytest.mark.parametrize( + ("forwards", "keep"), + [ + ([2048, 1024], 2047), # a chunk boundary inside the tail: a view would hold 3072 rows + ([1200, 1200], 2047), # ... 2400 rows + ([2048, 100], 2047), + ([2048], 2047), # one forward longer than the tail: a view would hold it whole + ([2047], 2047), # exactly the tail + ([1500, 500, 3, 1], 2047), # the tail is everything + ], +) +def test_the_tail_holds_no_more_memory_than_its_own_rows(forwards, keep): + """A slice of an mlx array is a view on its parent: sliced off the + assembled chunks, the tail would keep every row of them alive across the + decode — half again to twice its size when a chunk boundary falls inside + it. The assembled tail must own exactly its rows, to within the + allocator's page.""" + width = 256 + sink = draftctx.Sink([0], keep) + base = _active_bytes() + for i, n in enumerate(forwards): + sink.take([mx.zeros((1, n, width), dtype=mx.bfloat16) + i]) + tail = sink.finish() + assert tail is not None + rows = min(keep, sum(forwards)) + assert tail.shape == (1, rows, width) and tail.dtype == mx.bfloat16 + assert tail[0, -1, 0].item() == len(forwards) - 1 # the newest forward's rows last + held = _active_bytes() - base + assert held <= rows * width * 2 + 16 * 1024, (held, rows * width * 2) + + +def test_sink_finish_empties_it(): + sink = draftctx.Sink([0], keep=4) + sink.take(_states(1, 0, 2)) + assert sink.finish() is not None + assert sink.finish() is None + + +# ---- the window --------------------------------------------------------------- + + +def _config(**kw) -> types.SimpleNamespace: + base = {"draft_window_size": None, "sliding_window": 2048, "layer_types": ["full_attention"]} + return types.SimpleNamespace(**{**base, **kw}) + + +def test_window_reads_the_drafters_cache_geometry(): + sliding = _config(layer_types=["sliding_attention"] * 5) + assert draftctx.window(types.SimpleNamespace(config=sliding)) == 2047 + buffered = _config(draft_window_size=512, layer_types=["sliding_attention"]) + assert draftctx.window(types.SimpleNamespace(config=buffered)) == 512 + unbounded = _config() + assert draftctx.window(types.SimpleNamespace(config=unbounded)) == draftctx.DEFAULT_WINDOW + assert draftctx.window(object()) == draftctx.DEFAULT_WINDOW + + +# ---- stubs for the hooks ----------------------------------------------------- + + +class _LM: + """A language model whose forward returns hidden states for the layers + asked for, numbered by the cache's offset — the shape the hook reads.""" + + def __init__(self): + self.calls: list[dict] = [] + + def __call__(self, inputs: Any = None, inputs_embeds=None, cache=None, **kwargs): + self.calls.append(dict(kwargs, n=int(inputs.shape[1]))) + n = int(inputs.shape[1]) + offset = cache[0].offset if cache else 0 + if cache: + cache[0].offset += n + layers = kwargs.get("capture_layer_ids") + return types.SimpleNamespace( + logits=mx.zeros((1, n, 8)), + cross_attention_states=None, + encoder_outputs=None, + hidden_states=None if layers is None else _states(len(layers), offset, n), + ) + + +class _Drafter: + """A DFlash drafter reduced to what the round loop and the wraps touch.""" + + prefer_requested_block_size = True + + def __init__(self, layer_ids=(5, 19)): + self.config = _config(target_layer_ids=list(layer_ids), layer_types=["sliding_attention"]) + self.calls: list[tuple[str, Any]] = [] + self.resets = 0 + self.accept_lens: list[int] = [] + self.draft_lens: list[int] = [] + + def reset(self, target_model): + self.resets += 1 + return ["cache"] + + def draft_block(self, last_bonus, hidden, cache, block_size, sampler, token_dtype=mx.int32): + self.calls.append(("sampled", hidden)) + return self._propose(last_bonus, block_size, token_dtype) + + def draft_block_greedy( + self, last_bonus, hidden, cache, block_size, sampler, token_dtype=mx.int32 + ): + self.calls.append(("greedy", hidden)) + return self._propose(last_bonus, block_size, token_dtype) + + @staticmethod + def _propose(last_bonus, block_size, token_dtype): + # The target below always says "next = current + 1", so proposing + # exactly that is a full acceptance and anything else a rejection. + bonus = last_bonus if isinstance(last_bonus, int) else int(last_bonus.item()) + return mx.array([[bonus + i for i in range(1, block_size)]], dtype=token_dtype) + + +def _model(lm=None) -> types.SimpleNamespace: + return types.SimpleNamespace(language_model=lm or _LM()) + + +def _cache() -> types.SimpleNamespace: + return types.SimpleNamespace(offset=0, state=None) + + +# ---- enable() ----------------------------------------------------------------- + + +def test_enable_is_off_without_a_drafter(): + ctx = draftctx.enable(_model(), None, "") + assert ctx is draftctx.OFF and ctx.status["state"] == "off" and not ctx.active + assert ctx.sink(True) is None and ctx.fed() == 0 + with ctx.seed(mx.zeros((1, 1, 1))): + pass # nothing to seed, nothing raised + + +def _without(name: str) -> _Drafter: + drafter = _Drafter() + setattr(drafter, name, None) # shadows the method: not callable + return drafter + + +def _with_hook(name: str) -> _Drafter: + drafter = _Drafter() + setattr(drafter, name, lambda *a: a) + return drafter + + +@pytest.mark.parametrize( + ("drafter", "kind", "reason"), + [ + (_Drafter(), "eagle3", "drafter kind 'eagle3'"), + (_Drafter(layer_ids=()), "dflash", "names no target layers"), + (types.SimpleNamespace(prefer_requested_block_size=False), "dflash", "no target layers"), + (_without("reset"), "dflash", "has no reset"), + (_without("draft_block"), "dflash", "has no draft_block"), + (_with_hook("choose_block_ceiling"), "dflash", "defines choose_block_ceiling"), + (_with_hook("choose_initial_block_size"), "dflash", "defines choose_initial_block_size"), + ], +) +def test_enable_refuses_what_it_cannot_seed_with_a_warning(drafter, kind, reason): + with pytest.warns(UserWarning, match=f"drafter context unavailable \\(.*{reason}"): + ctx = draftctx.enable(_model(), drafter, kind) + assert ctx.status["state"] == "unavailable" and reason in ctx.status["reason"] + assert not ctx.active and ctx.sink(True) is None + + +def test_enable_refuses_a_drafter_the_round_loop_prepares_hidden_states_for(): + drafter = _Drafter() + drafter.prepare_target_hidden = lambda hidden: hidden # ty: ignore[unresolved-attribute] + with pytest.warns(UserWarning, match="defines prepare_target_hidden"): + assert draftctx.enable(_model(), drafter, "dflash").status["state"] == "unavailable" + + +def test_enable_refuses_a_model_without_a_language_model(): + with pytest.warns(UserWarning, match="no language_model"): + ctx = draftctx.enable(types.SimpleNamespace(), _Drafter(), "dflash") + assert ctx.status["state"] == "unavailable" + + +def test_enable_refuses_a_language_model_that_decodes_outside_its_forward(): + lm = _LM() + lm._batch_invariant_decode = lambda *a, **kw: None # ty: ignore[unresolved-attribute] + with pytest.warns(UserWarning, match="outside its forward"): + assert draftctx.enable(_model(lm), _Drafter(), "dflash").status["state"] == "unavailable" + + +def test_enable_never_raises(): + class Explosive: + prefer_requested_block_size = True + + @property + def config(self): + raise RuntimeError("no config today") + + with pytest.warns(UserWarning, match="no config today"): + assert draftctx.enable(_model(), Explosive(), "dflash").status["state"] == "unavailable" + + +def test_enable_arms_the_model_and_wraps_the_drafter(): + lm, drafter = _LM(), _Drafter() + ctx = draftctx.enable(_model(lm), drafter, "dflash") + assert ctx.status == {"state": "active", "reason": None, "window": 2047, "layers": 2} + assert ctx.active and ctx.layer_ids == [5, 19] and ctx.keep == 2047 + assert type(lm) in draftctx._WRAPPED + # Per-instance shadows, the way mlx-vlm's prefer_requested_block_size rides. + assert {"reset", "draft_block", "draft_block_greedy"} <= set(vars(drafter)) + sink = ctx.sink(True) + assert sink is not None and sink.layer_ids == [5, 19] and sink.keep == 2047 + assert draftctx.DraftContext.capture_kwargs(sink) == {"capture_layer_ids": [5, 19]} + assert draftctx.DraftContext.capture_kwargs(None) == {} + + +# ---- the forward hook --------------------------------------------------------- + + +def test_the_hook_captures_only_while_a_sink_is_armed(): + lm = _LM() + ctx = draftctx.enable(_model(lm), _Drafter(), "dflash") + cache = [_cache()] + lm(mx.zeros((1, 3), dtype=mx.int32), cache=cache, capture_layer_ids=[5, 19]) # unarmed + sink = ctx.sink(True) + with ctx.arm(_model(lm), sink) as armed: + assert armed is sink and getattr(lm, draftctx._SINK) is sink + lm(mx.zeros((1, 2), dtype=mx.int32), cache=cache, capture_layer_ids=[5, 19]) + assert getattr(lm, draftctx._SINK) is None + lm(mx.zeros((1, 4), dtype=mx.int32), cache=cache, capture_layer_ids=[5, 19]) # disarmed again + tail = sink.finish() + assert tail is not None and tail[0, :, 0].tolist() == [3, 4] # the armed forward alone + + +def test_arming_no_sink_touches_nothing(): + lm = _LM() + ctx = draftctx.enable(_model(lm), _Drafter(), "dflash") + with ctx.arm(_model(lm), None) as armed: + assert armed is None and draftctx._SINK not in vars(lm) + + +def test_install_forward_hook_is_idempotent(): + class Once: + calls = 0 + + def __call__(self, inputs=None, **kwargs): + Once.calls += 1 + return types.SimpleNamespace(hidden_states=None) + + try: + draftctx.install_forward_hook(Once) + draftctx.install_forward_hook(Once) + Once()(None) + assert Once.calls == 1 + # One layer of wrapping: the hook's __wrapped__ is the class's own forward. + inner = Once.__call__.__wrapped__ # ty: ignore[unresolved-attribute] + assert not hasattr(inner, "__wrapped__") + finally: + draftctx._WRAPPED.discard(Once) + + +def test_a_sink_that_fails_disarms_itself_and_the_forward_still_returns(): + lm = _LM() + ctx = draftctx.enable(_model(lm), _Drafter(), "dflash") + + class Broken(draftctx.Sink): + def take(self, hidden_states): + raise ValueError("boom") + + sink = Broken([5, 19], 4) + with ctx.arm(_model(lm), sink), pytest.warns(UserWarning, match="capture failed"): + out = lm(mx.zeros((1, 2), dtype=mx.int32), cache=[_cache()], capture_layer_ids=[5, 19]) + assert out.logits.shape == (1, 2, 8) + assert getattr(lm, draftctx._SINK) is None + + +# ---- the drafter wraps -------------------------------------------------------- + + +def _draft(drafter, name: str, bonus: int, hidden): + return getattr(drafter, name)(bonus, hidden, ["cache"], 3, lambda logits: logits) + + +@pytest.mark.parametrize("name", ["draft_block", "draft_block_greedy"]) +def test_the_first_draft_after_a_reset_gets_the_seeded_context_in_front(name): + drafter = _Drafter() + ctx = draftctx.enable(_model(), drafter, "dflash") + tail = mx.full((1, 3, 4), 7.0) + own = mx.zeros((1, 2, 4)) + with ctx.seed(tail): + drafter.reset(_model()) + _draft(drafter, name, 1, own) + _draft(drafter, name, 2, own) + kind = {"draft_block": "sampled", "draft_block_greedy": "greedy"}[name] + assert [k for k, _ in drafter.calls] == [kind, kind] + first, second = (hidden for _, hidden in drafter.calls) + assert first.shape == (1, 5, 4) and first[0, :, 0].tolist() == [7, 7, 7, 0, 0] + assert second.shape == (1, 2, 4) # later rounds carry only their own rows + assert ctx.fed() == 5 and drafter.resets == 1 + + +def test_a_seed_the_decode_never_drew_on_does_not_leak_into_the_next(): + drafter = _Drafter() + ctx = draftctx.enable(_model(), drafter, "dflash") + with ctx.seed(mx.full((1, 3, 4), 7.0)): + drafter.reset(_model()) # one token asked for: no round, no draft call + assert ctx.fed() == 0 + drafter.reset(_model()) + _draft(drafter, "draft_block", 1, mx.zeros((1, 2, 4))) + assert drafter.calls[-1][1].shape == (1, 2, 4) and ctx.fed() == 2 + + +def test_a_decode_that_stops_before_the_round_loop_reads_as_no_context(): + """stream_generate can stop on the first token, before the round loop + ever resets the drafter: the previous decode's context must not be + reported as this one's.""" + drafter = _Drafter() + ctx = draftctx.enable(_model(), drafter, "dflash") + with ctx.seed(mx.full((1, 3, 4), 7.0)): + drafter.reset(_model()) + _draft(drafter, "draft_block", 1, mx.zeros((1, 2, 4))) + assert ctx.fed() == 5 + with ctx.seed(mx.full((1, 3, 4), 8.0)): + pass # no reset, no draft call + assert ctx.fed() == 0 + + +def test_enable_wraps_a_drafter_once(): + import inspect + + drafter = _Drafter() + model = _model() + draftctx.enable(model, drafter, "dflash") + draftctx.enable(model, drafter, "dflash") + for name in ("reset", "draft_block", "draft_block_greedy"): + wrapper = vars(drafter)[name] + assert inspect.ismethod(wrapper.__wrapped__) # one layer over the class's own + + +@pytest.mark.parametrize( + "tail", + [ + mx.full((1, 3, 8), 7.0), # another width: another model's layers + mx.full((2, 3, 4), 7.0), # another batch: rows the loop never handed out + mx.full((3, 4), 7.0), # not the round loop's rank at all + ], + ids=["width", "batch", "rank"], +) +def test_a_context_of_another_shape_is_left_out_rather_than_forced(tail): + drafter = _Drafter() + ctx = draftctx.enable(_model(), drafter, "dflash") + with ctx.seed(tail): + drafter.reset(_model()) + _draft(drafter, "draft_block", 1, mx.zeros((1, 2, 4))) + assert drafter.calls[-1][1].shape == (1, 2, 4) and ctx.fed() == 2 + + +def test_the_context_fed_is_reported_no_larger_than_the_window(): + """A full tail plus the generation prompt is handed over whole — the + drafter drops the oldest rows past its window itself — but what it + drafted from is one window, and that is the number logged.""" + drafter = _Drafter() + drafter.config.sliding_window = 4 # a window of 3 + ctx = draftctx.enable(_model(), drafter, "dflash") + assert ctx.keep == 3 + with ctx.seed(mx.full((1, 3, 4), 7.0)): + drafter.reset(_model()) + _draft(drafter, "draft_block", 1, mx.zeros((1, 2, 4))) + assert drafter.calls[-1][1].shape == (1, 5, 4) # handed over whole + assert ctx.fed() == 3 + + +def test_seeding_nothing_leaves_the_drafters_own_context_alone(): + drafter = _Drafter() + ctx = draftctx.enable(_model(), drafter, "dflash") + with ctx.seed(None): + drafter.reset(_model()) + _draft(drafter, "draft_block_greedy", 1, mx.zeros((1, 6, 4))) + assert drafter.calls[-1][1].shape == (1, 6, 4) and ctx.fed() == 6 + + +# ---- the contract with mlx-vlm's generate_step -------------------------------- + + +class _Wrapper: + """A wrapper model whose text-only helper embeds the ids; its language + model is an _LM, so the class hook sees every forward generate_step makes.""" + + def __init__(self): + self.language_model = _LM() + self.config = types.SimpleNamespace(model_type="fake", eos_token_id=0) + + def get_input_embeddings(self, input_ids, pixel_values=None, mask=None, **kwargs): + n = input_ids.shape[1] + return types.SimpleNamespace( + inputs_embeds=mx.zeros((1, n, 4)), + to_dict=lambda: {"inputs_embeds": None, "position_ids": None, "rope_deltas": None}, + ) + + +def _prefill_through_generate_step(n_tokens: int, keep: int, layer_ids: list[int]): + """Run the real generate_step over an n-token prompt with the capture + kwarg, a sink armed; return the forwards it made and the sink's tail.""" + from mlx_vlm.generate.ar import generate_step + + model = _Wrapper() + ctx = draftctx.enable(model, _Drafter(layer_ids), "dflash") + sink = draftctx.Sink(layer_ids, keep) + with ctx.arm(model, sink): + list( + generate_step( + mx.arange(n_tokens, dtype=mx.int32)[None], + model, # ty: ignore[invalid-argument-type] + None, + None, + prompt_cache=[_cache()], + max_tokens=0, + sampler=lambda logprobs: mx.zeros((logprobs.shape[0],), dtype=mx.int32), + **draftctx.DraftContext.capture_kwargs(sink), + ) + ) + return model.language_model.calls, sink.finish() + + +def test_generate_step_hands_the_capture_kwarg_to_every_prefill_forward(): + """The contract the prefill capture rests on: the extra kwarg reaches + each chunk of the chunk loop and the final one-token step alike, so the + forwards' hidden states cover every prompt token in order — and the + chunking is generate_step's own (2048-token chunks, then the last token), + which is why capturing through it leaves the KV cache exactly as an + uncaptured prefill does.""" + calls, tail = _prefill_through_generate_step(4100, keep=3000, layer_ids=[5, 19]) + assert [c["n"] for c in calls] == [2048, 2048, 3, 1] + assert all(c["capture_layer_ids"] == [5, 19] for c in calls) + assert tail is not None and tail.shape == (1, 3000, 4) + assert tail[0, :, 0].tolist() == list(range(1100, 4100)) + assert tail[0, :, 2].tolist() == [100 + p for p in range(1100, 4100)] + + +def test_a_prompt_shorter_than_the_window_is_captured_whole(): + calls, tail = _prefill_through_generate_step(9, keep=2047, layer_ids=[0]) + assert [c["n"] for c in calls] == [8, 1] + assert tail is not None and tail[0, :, 0].tolist() == list(range(9)) + + +class _Processor: + """What stream_generate reads off a processor on a max_tokens=0 call: + stopping criteria it resets, and a detokenizer it copies and resets but + never feeds.""" + + class _Stopping: + def reset(self, eos): + pass + + def add_eos_token_ids(self, ids): + pass + + def __call__(self, token): + return False + + class _Detokenizer: + last_segment = "" + + def reset(self): + pass + + def add_token(self, *args, **kwargs): + raise AssertionError("a prefill has nothing to detokenize") + + def finalize(self): + pass + + def __init__(self): + self.tokenizer = types.SimpleNamespace(stopping_criteria=self._Stopping()) + self.detokenizer = self._Detokenizer() + + +def test_mlx_vlm_generate_passes_the_capture_kwarg_through_to_every_forward(): + """The engine's entry is generate(), whose dispatch pops the kwargs it + knows and hands the rest to generate_step: an undeclared one such as + capture_layer_ids (GenerateKwargs lists it no more than position_ids) + has to survive that, or every capture is silently empty.""" + from mlx_vlm import generate + + model = _Wrapper() + ctx = draftctx.enable(model, _Drafter(), "dflash") + sink = draftctx.Sink([5, 19], 2047) + with ctx.arm(model, sink): + generate( + model, # ty: ignore[invalid-argument-type] + _Processor(), + "", + max_tokens=0, + verbose=False, + prompt_cache=[_cache()], + input_ids=mx.arange(30, dtype=mx.int32)[None], + **draftctx.DraftContext.capture_kwargs(sink), + ) + calls = model.language_model.calls + assert [c["n"] for c in calls] == [29, 1] + assert all(c["capture_layer_ids"] == [5, 19] for c in calls) + tail = sink.finish() + assert tail is not None and tail[0, :, 0].tolist() == list(range(30)) + + +# ---- the contract with mlx-vlm's DFlash round loop ---------------------------- + + +class _Target: + """A target whose greedy pick is always "the token after this one", so a + drafter proposing that is fully accepted and the test can count rounds. + Its hidden states carry the token id, so the rows a draft saw are legible; + two captured layers of width 2 concatenate to the width 4 the seeded and + prompt hidden states below have.""" + + def __init__(self): + self.verify_calls = 0 + + def __call__(self, inputs, cache=None, **kwargs): + self.verify_calls += 1 + n = int(inputs.shape[1]) + vocab = 64 + logits = (mx.arange(vocab)[None, None, :] == (inputs + 1)[:, :, None]).astype(mx.float32) + tokens = inputs.astype(mx.float32)[:, :, None] + layers = kwargs.get("capture_layer_ids") or [] + return types.SimpleNamespace( + logits=logits, + hidden_states=[mx.broadcast_to(tokens, (1, n, 2)) for _ in layers], + gdn_states=None, + shared_kv_states=None, + ) + + +@pytest.mark.parametrize("greedy", [True, False], ids=["greedy", "sampled"]) +def test_the_round_loop_hands_the_first_draft_the_prompt_hidden_with_the_seed_in_front(greedy): + """The contract the seeding rests on: _dflash_rounds resets the drafter, + then gives its first draft call the prompt hidden it was handed — whole + — and every later call only the verify rows the target accepted. The + wrap prepends the seeded tail there and nowhere else, and the lifetime + counters count exactly this call's rounds.""" + from mlx_vlm.speculative.dflash import _dflash_rounds + + target = _Target() + drafter = _Drafter() + model = types.SimpleNamespace(language_model=target) + ctx = draftctx.enable(model, drafter, "dflash") + prompt_hidden = mx.full((1, 7, 4), -1.0) # the decode call's own prefill: 7 tokens + tail = mx.full((1, 5, 4), -2.0) # what the prefill before it captured + before = draftctx.rounds_snapshot(drafter) + with ctx.seed(tail): + produced = [ + tok + for tok, _ in _dflash_rounds( + model, # ty: ignore[invalid-argument-type] + drafter, # ty: ignore[invalid-argument-type] + [], + prompt_hidden, + first_bonus=10, + max_tokens=6, + sampler=lambda logits: mx.argmax(logits, axis=-1), + draft_block_size=3, + greedy_sampling=greedy, + ) + ] + # Two rounds of a fully accepted 2-token draft plus its bonus: 11 12 13, 14 15 16 — capped at 6. + assert produced == [11, 12, 13, 14, 15] + assert drafter.resets == 1 + kinds = {kind for kind, _ in drafter.calls} + assert kinds == ({"greedy"} if greedy else {"sampled"}) + first, second = (hidden for _, hidden in drafter.calls) + assert first.shape == (1, 12, 4) and first[0, :, 0].tolist() == [-2] * 5 + [-1] * 7 + assert second.shape == (1, 3, 4) and second[0, :, 0].tolist() == [10, 11, 12] + assert ctx.fed() == 12 + assert draftctx.rounds_since(drafter, before) == (2, 4, 4) + assert draftctx.rounds_since(None, None) == (0, 0, 0) + + +# ---- the engine's wiring ------------------------------------------------------- + + +def _engine(model, drafter=None) -> VLMEngine: + engine = object.__new__(VLMEngine) + engine.model_id = "test/model" + engine._model = model + stopping = types.SimpleNamespace(reset=lambda eos: None) + engine._processor = types.SimpleNamespace( # ty: ignore[invalid-assignment] + tokenizer=types.SimpleNamespace(stopping_criteria=stopping) + ) + engine._sampler = object() + engine._positional = False + engine._memo = PromptMemo() + engine._tokenize_lock = threading.Lock() + engine._draft = drafter + engine._draft_kind = "dflash" if drafter is not None else "" + engine._draft_block_size = 3 + engine._draft_context = draftctx.enable(model, drafter, engine._draft_kind) + engine._speculation = Speculation() + return engine + + +def _stub_mlx_vlm(monkeypatch, model, calls: dict, rounds: int = 0) -> None: + """generate() runs two forwards of the model's language model with the + kwargs it was given, the way generate_step would; stream_generate() runs + a reset and one draft call on the drafter, the way the round loop would, + and bumps the drafter's lifetime counters by `rounds` rounds.""" + + def generate(m, processor, prompt, **kwargs): + calls["prefill"] = kwargs + extra = {k: v for k, v in kwargs.items() if k == "capture_layer_ids"} + cache = kwargs["prompt_cache"] + ids = kwargs["input_ids"] + n = ids.shape[1] + m.language_model(ids[:, : n - 1], inputs_embeds=None, cache=cache, **extra) + m.language_model(ids[:, n - 1 :], inputs_embeds=None, cache=cache, **extra) + + def stream_generate(m, processor, prompt, **kwargs): + calls["decode"] = kwargs + drafter = kwargs.get("draft_model") + if drafter is not None: + drafter.reset(m) + drafter.draft_block(1, mx.zeros((1, kwargs["input_ids"].shape[1], 4)), [], 3, None) + # The lifetime counters _record_speculative_round keeps, which + # survive the reset above: rounds, accepted drafts, drafted. + for attr, step in ( + ("speculative_total_rounds", rounds), + ("speculative_total_accepted", 1.5 * rounds), + ("speculative_total_drafted", 2 * rounds), + ): + setattr(drafter, attr, getattr(drafter, attr, 0) + step) + return iter(()) + + monkeypatch.setitem( + sys.modules, + "mlx_vlm", + types.SimpleNamespace(generate=generate, stream_generate=stream_generate), + ) + + +def test_a_captured_prefill_asks_for_the_target_layers_and_keeps_the_tail(monkeypatch): + model, calls = _Wrapper(), {} + _stub_mlx_vlm(monkeypatch, model, calls) + engine = _engine(model, _Drafter()) + cache = [_cache()] + capture = engine.prefill(cache, list(range(10)), capture=True) + assert calls["prefill"]["capture_layer_ids"] == [5, 19] + assert isinstance(capture, draftctx.Sink) + assert getattr(model.language_model, draftctx._SINK) is None # disarmed after + assert cache[0].offset == 10 + tail = draftctx.DraftContext.tail(capture) + assert tail is not None and tail[0, :, 0].tolist() == list(range(10)) + + +def test_a_capture_continues_across_a_turns_prefills(monkeypatch): + """Fork stops split a cold prefill into segments; the capture an earlier + segment returned is handed back in, and the tail spans them.""" + model, calls = _Wrapper(), {} + _stub_mlx_vlm(monkeypatch, model, calls) + engine = _engine(model, _Drafter()) + cache = [_cache()] + capture = engine.prefill(cache, [], capture=True) # an empty stop still starts one + assert isinstance(capture, draftctx.Sink) + assert engine.prefill(cache, list(range(10)), capture=capture) is capture + assert engine.prefill(cache, list(range(10, 15)), capture=capture) is capture + tail = draftctx.DraftContext.tail(capture) + assert tail is not None and tail[0, :, 0].tolist() == list(range(15)) + assert draftctx.DraftContext.tail(capture) is None # assembled once + + +def test_a_plain_prefill_captures_nothing_and_asks_for_nothing(monkeypatch): + model, calls = _Wrapper(), {} + _stub_mlx_vlm(monkeypatch, model, calls) + engine = _engine(model, _Drafter()) + assert engine.prefill([_cache()], [1, 2, 3]) is None + assert "capture_layer_ids" not in calls["prefill"] + assert draftctx.DraftContext.tail(None) is None + + +def test_a_captured_prefill_without_a_drafter_is_a_plain_prefill(monkeypatch): + model, calls = _Wrapper(), {} + _stub_mlx_vlm(monkeypatch, model, calls) + engine = _engine(model) + assert engine.prefill([_cache()], [1, 2, 3], capture=True) is None + assert "capture_layer_ids" not in calls["prefill"] + + +def test_decode_seeds_the_drafter_and_reports_the_rounds(monkeypatch): + model, calls = _Wrapper(), {} + _stub_mlx_vlm(monkeypatch, model, calls, rounds=4) + drafter = _Drafter() + engine = _engine(model, drafter) + capture = draftctx.Sink([5, 19], 2047) + capture.take([mx.full((1, 5, 2), 9.0), mx.full((1, 5, 2), 9.0)]) + engine.decode([_cache()], [1, 2], 8, context=capture) + assert calls["decode"]["draft_model"] is drafter + ((_, hidden),) = drafter.calls + assert hidden.shape == (1, 7, 4) and hidden[0, :, 0].tolist() == [9] * 5 + [0] * 2 + spec = engine.speculation() + assert (spec.rounds, spec.accepted, spec.drafted, spec.context) == (4, 6, 8, 7) + assert getattr(drafter, draftctx._PENDING) is None # nothing left for a later turn + + +def test_a_capture_that_failed_part_way_seeds_nothing(monkeypatch): + """A tail missing a forward's rows would end short of the generation + prompt: the wrong positions cost more acceptance than none, so a sink + that fails voids what it held and refuses the rest of the turn.""" + model, calls = _Wrapper(), {} + _stub_mlx_vlm(monkeypatch, model, calls) + engine = _engine(model, _Drafter()) + + class Flaky(draftctx.Sink): + def take(self, hidden_states): + if self._held >= 4: # the forward after the first rows + raise ValueError("boom") + super().take(hidden_states) + + capture = Flaky([5, 19], 2047) + with pytest.warns(UserWarning, match="capture failed"): + assert engine.prefill([_cache()], list(range(10)), capture=capture) is capture + assert draftctx.DraftContext.tail(capture) is None + engine.prefill([_cache()], list(range(10, 14)), capture=capture) + assert draftctx.DraftContext.tail(capture) is None + + +def test_close_lets_go_of_the_drafter_and_unload_calls_it(): + """The wraps close over the drafter and the drafter binds the target's + embedding and head: an unload that kept either would keep the weights.""" + import gc + import weakref + + from sous.engine.promptcache import PrefixCache + + model, drafter = _Wrapper(), _Drafter() + engine = _engine(model, drafter) + engine._cache = PrefixCache(engine, enabled=False) + assert engine._draft_context.active + gone = weakref.ref(drafter) + lm = weakref.ref(model.language_model) + del drafter + engine.unload() + del model + gc.collect() + assert gone() is None and lm() is None + assert engine._draft_context is draftctx.OFF and engine.draft_context_status["state"] == "off" + + +def test_a_decode_that_never_drafted_reports_zero_rounds_and_its_context(monkeypatch): + """mlx-vlm answers None for the counts of a call with no rounds (one + token asked for); the line must read zeros, not raise.""" + model, calls = _Wrapper(), {} + _stub_mlx_vlm(monkeypatch, model, calls, rounds=0) + engine = _engine(model, _Drafter()) + assert engine.speculation() == Speculation() # before any decode + engine.decode([_cache()], [1, 2], 1, context=None) + assert engine.speculation() == Speculation(rounds=0, drafted=0, accepted=0, context=2) + + +def test_decode_without_a_drafter_reports_zeros(monkeypatch): + model, calls = _Wrapper(), {} + _stub_mlx_vlm(monkeypatch, model, calls) + engine = _engine(model) + engine.decode([_cache()], [1, 2], 8, context=None) + assert "draft_model" not in calls["decode"] + assert engine.speculation() == Speculation() + + +def test_the_engine_exposes_the_status(): + engine = _engine(_Wrapper(), _Drafter()) + assert engine.draft_context_status == { + "state": "active", + "reason": None, + "window": 2047, + "layers": 2, + } + assert _engine(_Wrapper()).draft_context_status["state"] == "off" diff --git a/tests/test_engine_base.py b/tests/test_engine_base.py index 74b7af2a..14ece10e 100644 --- a/tests/test_engine_base.py +++ b/tests/test_engine_base.py @@ -2206,3 +2206,95 @@ def test_status_carries_the_verify_attention_view_when_the_engine_reports_one(tm "state": "unavailable", "reason": "mlx 0.33.0 not validated", } + + +@pytest.mark.parametrize("drafter_loads", [True, False]) +def test_vlm_engine_arms_the_drafters_context_once_the_drafter_has_settled( + monkeypatch, drafter_loads +): + from sous.engine import draftctx, verifyattn, vlm + + model = _positionless_model() + processor = types.SimpleNamespace(tokenizer=_RecordingTokenizer()) + _stub(monkeypatch, "mlx_vlm", load=lambda model_id: (model, processor)) + _stub(monkeypatch, "mlx_vlm.sample_utils", make_sampler=lambda **kw: None) + drafter = types.SimpleNamespace(prefer_requested_block_size=False) + + def load_drafter(m, draft_id): + if not drafter_loads: + raise RuntimeError("no such repo") + return drafter, "dflash" + + monkeypatch.setattr(vlm, "_load_quantized_drafter", load_drafter) + monkeypatch.setattr(verifyattn, "enable", lambda m, *, enabled: {"state": "off"}) + seen: dict[str, object] = {} + + def fake_enable(m, d, kind): + seen["model"], seen["drafter"], seen["kind"] = m, d, kind + status = {"state": "active" if d is not None else "off", "reason": None, "window": 2047} + return draftctx.DraftContext(status) + + monkeypatch.setattr(draftctx, "enable", fake_enable) + if drafter_loads: + engine = vlm.VLMEngine("test/model", cache_budget=0, draft_id="z-lab/drafter") + else: + with pytest.warns(UserWarning, match="speculative drafter"): + engine = vlm.VLMEngine("test/model", cache_budget=0, draft_id="z-lab/drafter") + expected = {"model": model, "drafter": drafter, "kind": "dflash"} + assert seen == (expected if drafter_loads else {**expected, "drafter": None, "kind": ""}) + assert engine.draft_context_status["state"] == ("active" if drafter_loads else "off") + + +def test_get_logs_the_drafter_context_state_and_its_window(caplog): + import logging + + def factory(model_id): + engine = _positional_factory(model_id) + engine.draft_context_status = { # ty: ignore[unresolved-attribute] + "state": "active", + "reason": None, + "window": 2047, + "layers": 5, + } + return engine + + mgr = EngineManager(SousConfig(), engine_factory=factory) + with caplog.at_level(logging.INFO, logger="sous.engine"): + mgr.get() + lines = [r.getMessage() for r in caplog.records if r.name == "sous.engine"] + assert len(lines) == 1 + assert lines[0].endswith(" positions=engine draft_context=active draft_context_window=2047") + + +def test_get_logs_no_window_when_the_drafter_context_is_not_active(caplog): + import logging + + def factory(model_id): + engine = _positional_factory(model_id) + engine.draft_context_status = { # ty: ignore[unresolved-attribute] + "state": "unavailable", + "reason": "drafter kind 'eagle3' (dflash only)", + "window": 0, + "layers": 0, + } + return engine + + mgr = EngineManager(SousConfig(), engine_factory=factory) + with caplog.at_level(logging.INFO, logger="sous.engine"): + mgr.get() + lines = [r.getMessage() for r in caplog.records if r.name == "sous.engine"] + assert lines[0].endswith(" draft_context=unavailable") + + +def test_status_carries_the_drafter_context_view_when_the_engine_reports_one(tmp_path): + inner = FakeEngine([]) + manager = EngineManager(_cfg(tmp_path), engine_factory=lambda mid: inner) + manager.get() + assert "draft_context" not in manager.status(), "fakes without the attribute stay silent" + inner.draft_context_status = { # ty: ignore[unresolved-attribute] + "state": "active", + "reason": None, + "window": 2047, + "layers": 5, + } + assert manager.status()["draft_context"] == {"state": "active", "reason": None, "window": 2047} diff --git a/tests/test_engine_positions.py b/tests/test_engine_positions.py index b18e83fc..01e188ba 100644 --- a/tests/test_engine_positions.py +++ b/tests/test_engine_positions.py @@ -18,7 +18,8 @@ mx = pytest.importorskip("mlx.core") -from sous.engine.vlm import VLMEngine # noqa: E402 — after the importorskip guard +from sous.engine import draftctx # noqa: E402 — after the importorskip guard +from sous.engine.vlm import VLMEngine # noqa: E402 class _Layer: @@ -70,6 +71,7 @@ def _engine(model: _Model, positional: bool = True) -> VLMEngine: engine._draft = None engine._draft_kind = "" engine._draft_block_size = 0 + engine._draft_context = draftctx.OFF return engine diff --git a/tests/test_engine_vlm.py b/tests/test_engine_vlm.py index f4f17eb7..2f3a660b 100644 --- a/tests/test_engine_vlm.py +++ b/tests/test_engine_vlm.py @@ -668,3 +668,133 @@ def test_vlm_engine_serves_a_second_session_from_a_fork_on_disk(tmp_path): assert s["reused_tokens"] >= FORK_MIN_TOKENS and s["took_kind"] == "disk" assert s["disk"]["forks"] == 1 and s["forks"] >= 1 # republished as a resident fork second.unload() + + +class _TargetLayersDrafter: + """What draftctx.enable reads off a drafter, without one: HYBRID_VLM has + no published DFlash checkpoint, and the capture side needs none — only + the target layers to ask the forward for and a window to keep.""" + + prefer_requested_block_size = True + + def __init__(self, layer_ids, sliding_window=2048): + import types + + self.config = types.SimpleNamespace( + target_layer_ids=list(layer_ids), + sliding_window=sliding_window, + layer_types=["sliding_attention"], + draft_window_size=None, + ) + + def reset(self, target_model): + return [] + + def draft_block(self, last_bonus, hidden, cache, block_size, sampler, token_dtype=None): + raise AssertionError("the capture side never drafts") + + +def test_vlm_a_captured_prefill_leaves_the_cache_bit_identical_and_keeps_the_tail(): + """The prefill that captures the drafter's context runs mlx-vlm's own + generate_step, chunking included, with one extra kwarg the forward + honours by handing its hidden states out; the KV it builds must be the + uncaptured prefill's to the bit, and the capture it hands back holds the + newest window of the target layers' outputs for those tokens. A hybrid because + that is the path that needs the capture (a trimmable model's decode call + prefills the delta itself), and because Qwen2-VL's forward captures + nothing.""" + import mlx.core as mx + + from sous.engine import draftctx + from sous.engine.vlm import VLMEngine + + e = VLMEngine(HYBRID_VLM, cache_budget=0) + model, _ = e._loaded() + layers = list(range(0, len(model.language_model.layers), 8)) + e._draft_context = draftctx.enable( + model, _TargetLayersDrafter(layers, sliding_window=9), "dflash" + ) + assert e._draft_context.status["state"] == "active" + ids = e._encode("def f(x):\n return x + 1\n" * 40) + head, tail_ids = ids[: len(ids) // 2], ids[len(ids) // 2 :] + + plain = e.new_cache() + e.prefill(plain, head) + assert e.prefill(plain, tail_ids) is None + + captured = e.new_cache() + e.prefill(captured, head) + tail = draftctx.DraftContext.tail(e.prefill(captured, tail_ids, capture=True)) + + for a, b in zip(plain, captured, strict=True): + off = int(getattr(a, "offset", 0) or 0) + assert off == int(getattr(b, "offset", 0) or 0) + for xa, xb in zip(a.state, b.state, strict=True): + if xa is None or xb is None: + assert xa is None and xb is None + continue + if hasattr(a, "trim") and xa.ndim >= 3 and off: + xa, xb = xa[..., :off, :], xb[..., :off, :] + d = mx.max(mx.abs(xa.astype(mx.float32) - xb.astype(mx.float32))) + mx.eval(d) + assert d.item() == 0.0 + # The window is 8 positions; every target layer's hidden state, side by side. + hidden = model.language_model.args.hidden_size + assert tail is not None and tail.shape == (1, 8, hidden * len(layers)) + # What the sink kept is the forward's own output: the same tokens run the + # way generate_step runs a segment under 2048 tokens — one forward over + # all but the last, one over the last — with the capture kwarg give the + # same tail to the bit. + reference = e.new_cache() + e.prefill(reference, head) + parts = [] + for chunk in (tail_ids[:-1], tail_ids[-1:]): + out = model.language_model( + mx.array(chunk)[None], + cache=reference, + capture_layer_ids=layers, + **e._positions(reference, len(chunk)), + ) + parts.append(mx.concatenate(out.hidden_states, axis=-1)) + want = mx.concatenate(parts, axis=1)[:, -8:, :] + d = mx.max(mx.abs(tail.astype(mx.float32) - want.astype(mx.float32))) + mx.eval(d) + assert d.item() == 0.0 + e.unload() + + +@pytest.mark.parametrize("temperature", [0.0, 0.7], ids=["greedy", "sampled"]) +def test_vlm_drafter_drafts_from_the_prompts_context_on_the_hybrid_path(temperature): + """The #142 gate, on one turn: a hybrid turn's drafter sees the tail of + what the turn prefilled in front of the generation prompt (draft_context + well past the 7 tokens of the generation prompt alone), the turn's + acceptance is logged, and greedy output is token-identical to the same + turn drafted from the generation prompt alone. Heavy — the default model + and its drafter, local only.""" + from sous.engine import draftctx + from sous.engine.vlm import VLMEngine + from sous.tune.payload import TOOLS + + e = VLMEngine(DEFAULT_27B, draft_id=DRAFTER, prompt_cache=True, temperature=temperature) + assert e._draft is not None, "drafter should load and validate on the default model" + assert e.draft_context_status["state"] == "active" + assert e.draft_context_status["window"] == 2047 + msgs = [ + {"role": "system", "content": "Answer in two short sentences. " * 40}, + {"role": "user", "content": "List three uses of a paper clip."}, + ] + seeded = e.generate(msgs, TOOLS, max_tokens=48) + s = e.prompt_cache_stats() + assert s["draft_rounds"] > 0 and s["drafted_tokens"] >= s["accepted_tokens"] > 0 + assert 7 < s["draft_context"] <= 2047, s + # The same turn with the seeding off: the prefill captures nothing and + # the drafter starts from the generation prompt, as before #142. + armed = e._draft_context + e._draft_context = draftctx.OFF + e.reset_prompt_cache() + plain = e.generate(msgs, TOOLS, max_tokens=48) + e._draft_context = armed + assert e.prompt_cache_stats()["draft_context"] == 0 # not measured when off + if temperature == 0: + assert plain == seeded + e.unload() diff --git a/tests/test_engine_vlm_greedy.py b/tests/test_engine_vlm_greedy.py index 5f0a188d..cb46f56c 100644 --- a/tests/test_engine_vlm_greedy.py +++ b/tests/test_engine_vlm_greedy.py @@ -8,6 +8,7 @@ import threading import types +from sous.engine import draftctx from sous.engine.promptcache import PromptMemo from sous.engine.vlm import VLMEngine @@ -32,6 +33,7 @@ def _engine(sampler) -> VLMEngine: engine._draft = None engine._draft_kind = "" engine._draft_block_size = 0 + engine._draft_context = draftctx.OFF return engine diff --git a/tests/test_promptcache.py b/tests/test_promptcache.py index 694c2b69..3a16e7e1 100644 --- a/tests/test_promptcache.py +++ b/tests/test_promptcache.py @@ -22,6 +22,7 @@ PrefixCache, PromptCacheStats, PromptMemo, + Speculation, all_trimmable, auto_cache_budget, common_prefix_length, @@ -332,6 +333,16 @@ def __init__( self.caches: list[list] = [] self.prefilled: list[list[int]] = [] self.decoded: list[list[int]] = [] + # Which prefills were asked to capture the drafter's context, the + # token each such prefill handed back, and the context each decode + # was given — pins that the last stable segment's capture, and only + # it, reaches the decode that follows. + self.captured: list[bool] = [] + self.contexts_given: list[object] = [] + self.contexts_seen: list[object] = [] + # What speculation() answers after a decode; a test sets it to pin + # the gauges the orchestrator assigns from it. + self.speculation_value = Speculation() self.generated = [7, 8, 9] self.headroom_value: int | None = None self.pressure_value: int | None = None # the kernel's level: 1 normal, 2 warn, 4 critical @@ -359,14 +370,28 @@ def _advance(self, cache, n): if isinstance(c, FakeTrimmable): c.offset += n - def prefill(self, cache, token_ids): + def prefill(self, cache, token_ids, capture=None): self.log.append("prefill") self.prefilled.append(list(token_ids)) + self.captured.append(capture is not None) self._advance(cache, len(token_ids)) - - def decode(self, cache, token_ids, max_tokens, on_delta=None): + if capture is None: + return None + # A capture names every segment it saw, in order: `True` starts one, + # an earlier segment's capture continues it. + context = ( + f"context:{list(token_ids)}" if capture is True else f"{capture}+{list(token_ids)}" + ) + self.contexts_given.append(context) + return context + + def speculation(self): + return self.speculation_value + + def decode(self, cache, token_ids, max_tokens, on_delta=None, context=None): self.log.append("decode") self.on_deltas.append(on_delta) + self.contexts_seen.append(context) if self.fail_once: self.fail_once = False if self.stream_before_fail and on_delta is not None: @@ -532,6 +557,120 @@ def test_non_trimmable_second_turn_prefills_the_delta_then_the_suffix(): assert pc.stats()["hits"] == 1 +def test_non_trimmable_hands_its_capture_to_the_decode_that_follows(): + """The decode call prefills only the generation suffix, so the drafter + would see nothing of the conversation: what the turn prefills before it + is captured, and that capture — the same object — reaches the decode.""" + h = FakeHooks(trimmable=False) + pc = PrefixCache(h) + pc.generate(STABLE_1, FULL_1, 16) + pc.generate(STABLE_2, FULL_2, 16) + assert h.captured == [True, True] + assert h.contexts_given == ["context:[1, 2, 3, 4]", "context:[5, 6]"] + assert h.contexts_seen == h.contexts_given + + +def test_the_trimmable_path_captures_nothing_without_fork_stops(): + # The decode call prefills the delta itself, so the drafter already sees it. + h = FakeHooks(trimmable=True) + pc = PrefixCache(h) + pc.generate(STABLE_1, FULL_1, 16) + pc.generate(STABLE_2, FULL_2, 16) + assert h.captured == [] and h.contexts_seen == [None, None] + + +def test_every_segment_a_turn_prefills_feeds_one_capture(): + """A turn that stops at two fork boundaries prefills three segments; the + drafter's context is the newest window of all of them, so one capture + runs through every prefill and the decode gets it whole.""" + h = FakeHooks(trimmable=False) + pc = PrefixCache(h, max_bytes=ROOMY) + pc.generate(AX1, AX1_FULL, 16, fork_at=BOUNDS_A) + assert h.captured == [True, True, True] + assert h.contexts_seen == [f"context:{T}+{HA[len(T) :]}+{AX1[len(HA) :]}"] + + +def test_a_trimmable_turn_with_fork_stops_seeds_its_decode_with_them(): + """The decode call prefills the last segment itself, so the capture + carries only the fork stops' segments — everything prefilled before it.""" + h = FakeHooks(trimmable=True) + pc = PrefixCache(h, max_bytes=ROOMY) + pc.generate(AX1, AX1_FULL, 16, fork_at=BOUNDS_A) + assert h.captured == [True, True] + assert h.decoded == [AX1_FULL[len(HA) :]] + assert h.contexts_seen == [f"context:{T}+{HA[len(T) :]}"] + + +def test_an_engine_that_captures_nothing_is_asked_once_and_left_alone(): + """The engine answers None to a capture it cannot serve (no drafter): + the later segments of the turn are not asked again.""" + + asked: list[object] = [] + + class Plain(FakeHooks): + def prefill(self, cache, token_ids, capture=None): + self.log.append("prefill") + asked.append(capture) + self._advance(cache, len(token_ids)) + return None + + h = Plain(trimmable=False) + pc = PrefixCache(h, max_bytes=ROOMY) + pc.generate(AX1, AX1_FULL, 16, fork_at=BOUNDS_A) + assert asked == [True, None, None] and h.contexts_seen == [None] + + +def test_a_cold_retry_captures_again_and_the_decode_gets_the_retrys_context(): + h = FakeHooks(trimmable=False) + pc = PrefixCache(h) + pc.generate(STABLE_1, FULL_1, 16) + h.fail_once = True + with pytest.warns(UserWarning, match="retrying cold"): + pc.generate(STABLE_2, FULL_2, 16) + # the warm attempt's capture (the delta), then the cold one's (everything) + assert h.contexts_given == ["context:[1, 2, 3, 4]", "context:[5, 6]", f"context:{STABLE_2}"] + assert h.contexts_seen[-1] == f"context:{STABLE_2}" + + +def test_the_drafters_gauges_are_assigned_per_turn_from_the_last_decode(): + """Rounds, drafted, accepted and the context the drafter saw are per-turn + gauges like the phase timings: assigned after each decode, zeroed with + the next turn, and the daemon-wide view drops them.""" + from sous.engine.promptcache import without_turn_gauges + + h = FakeHooks(trimmable=False) + pc = PrefixCache(h) + h.speculation_value = Speculation(rounds=12, accepted=17, drafted=24, context=2054) + pc.generate(STABLE_1, FULL_1, 16) + st = pc.stats() + assert (st["draft_rounds"], st["drafted_tokens"], st["accepted_tokens"]) == (12, 24, 17) + assert st["draft_context"] == 2054 + assert not {"draft_rounds", "drafted_tokens", "accepted_tokens", "draft_context"} & set( + without_turn_gauges(st) + ) + h.speculation_value = Speculation() + pc.generate(STABLE_2, FULL_2, 16) + st = pc.stats() + assert (st["draft_rounds"], st["drafted_tokens"], st["accepted_tokens"]) == (0, 0, 0) + assert st["draft_context"] == 0 + + +@pytest.mark.parametrize("trimmable", [True, False]) +def test_the_drafters_gauges_follow_every_decode_path(trimmable): + h = FakeHooks(trimmable=trimmable) + pc = PrefixCache(h) + h.speculation_value = Speculation(rounds=3, accepted=4, drafted=6, context=9) + pc.generate(STABLE_1, FULL_1, 16) + assert pc.stats()["draft_context"] == 9 + # The render that is not a strict prefix of the full prompt decodes cold + # outside the cache's own run, and still reports its decode's drafter. + h.speculation_value = Speculation(rounds=1, accepted=0, drafted=2, context=3) + with pytest.warns(UserWarning, match="not the stable render"): + pc.generate([7, 8], [9, 9, 9], 16) + st = pc.stats() + assert (st["draft_rounds"], st["drafted_tokens"], st["draft_context"]) == (1, 2, 3) + + def test_non_trimmable_restores_the_cache_to_the_stable_boundary(): h = FakeHooks(trimmable=False) pc = PrefixCache(h) @@ -599,6 +738,21 @@ def test_disabled_never_reuses_and_never_counts(): assert pc.stats()["prefill_seconds"] == 0.0 and pc.stats()["took_len"] == 0 +def test_disabled_still_reports_the_drafters_gauges(): + """The drafter runs over the whole prompt when nothing is cached, and + the turn line reads its rounds off the same gauges as on a cached turn.""" + h = FakeHooks(trimmable=True) + pc = PrefixCache(h, enabled=False) + h.speculation_value = Speculation(rounds=9, drafted=18, accepted=11, context=40) + pc.generate(STABLE_1, FULL_1, 16) + st = pc.stats() + assert (st["draft_rounds"], st["drafted_tokens"], st["accepted_tokens"]) == (9, 18, 11) + assert st["draft_context"] == 40 and st["hits"] == 0 and st["misses"] == 0 + h.speculation_value = Speculation() + pc.generate(STABLE_2, FULL_2, 16) + assert pc.stats()["draft_rounds"] == 0 + + def test_disabled_never_reads_stable_ids(): """LMEngine/VLMEngine.generate skip computing the stable render whenever the cache is disabled, and pass `[]` in its place — safe only because the @@ -1032,6 +1186,10 @@ def test_stats_as_dict_reports_every_counter(): "decode_seconds": 0.0, "persist_seconds": 0.0, "restore_seconds": 0.0, + "draft_rounds": 0, + "drafted_tokens": 0, + "accepted_tokens": 0, + "draft_context": 0, } @@ -2168,9 +2326,10 @@ def test_a_retired_owner_still_persists_though_its_fork_is_refused(): pc = PrefixCache(h, max_bytes=ROOMY, store=s) original = h.prefill - def prefill(cache, token_ids): - original(cache, token_ids) + def prefill(cache, token_ids, capture=False): + context = original(cache, token_ids, capture) pc.reset(threading.current_thread()) # the endpoint retiring this session + return context h.prefill = prefill # ty: ignore[invalid-assignment] pc.generate(AX1, AX1_FULL, 16, fork_at=BOUNDS_A) @@ -2718,13 +2877,13 @@ def __init__(self, clock: FakeClock, **kw): super().__init__(**kw) self.clock = clock - def prefill(self, cache, token_ids): + def prefill(self, cache, token_ids, capture=False): self.clock.advance(2.0) - super().prefill(cache, token_ids) + return super().prefill(cache, token_ids, capture) - def decode(self, cache, token_ids, max_tokens, on_delta=None): + def decode(self, cache, token_ids, max_tokens, on_delta=None, context=None): self.clock.advance(5.0) - return super().decode(cache, token_ids, max_tokens, on_delta) + return super().decode(cache, token_ids, max_tokens, on_delta, context) @pytest.fixture() From 4e84f2a936ef0fe9e2cd8b07babc5d511c0f9445 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 12:56:43 +0000 Subject: [PATCH 2/3] test(engine): read the tail's memory budget off the allocator The bound on what the assembled drafter context holds allowed the tail's bytes plus one 16 KiB page, which is the CPU allocator's rounding; Metal rounds a buffer up to its size class, and on macos-15 a 2004-row tail came back as 1 MiB and failed the bound by 6 KiB. Measuring one array of the tail's own shape the same way gives the budget the platform actually charges, and the discriminating geometries (a chunk boundary well inside the window) still exceed it under the naive slice-of-the-chunks assembly. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0124KgiJ3Cgpgotsdk58dicH --- tests/test_draftctx.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/tests/test_draftctx.py b/tests/test_draftctx.py index b239a9c8..c132999f 100644 --- a/tests/test_draftctx.py +++ b/tests/test_draftctx.py @@ -99,20 +99,26 @@ def test_the_tail_holds_no_more_memory_than_its_own_rows(forwards, keep): """A slice of an mlx array is a view on its parent: sliced off the assembled chunks, the tail would keep every row of them alive across the decode — half again to twice its size when a chunk boundary falls inside - it. The assembled tail must own exactly its rows, to within the - allocator's page.""" + it. The assembled tail must cost what one array of its own shape costs, + measured the same way: Metal rounds a buffer up to its size class, so + the budget is read off the allocator rather than computed.""" width = 256 + rows = min(keep, sum(forwards)) + base = _active_bytes() + reference = mx.zeros((1, rows, width), dtype=mx.bfloat16) + mx.eval(reference) + budget = _active_bytes() - base + del reference sink = draftctx.Sink([0], keep) base = _active_bytes() for i, n in enumerate(forwards): sink.take([mx.zeros((1, n, width), dtype=mx.bfloat16) + i]) tail = sink.finish() assert tail is not None - rows = min(keep, sum(forwards)) assert tail.shape == (1, rows, width) and tail.dtype == mx.bfloat16 assert tail[0, -1, 0].item() == len(forwards) - 1 # the newest forward's rows last held = _active_bytes() - base - assert held <= rows * width * 2 + 16 * 1024, (held, rows * width * 2) + assert 0 < held <= budget, (held, budget) def test_sink_finish_empties_it(): From ac2129c557a5f8a97f224a3bf5e4fa3166ab914f Mon Sep 17 00:00:00 2001 From: krcm0209 <17315774+krcm0209@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:37:34 -0400 Subject: [PATCH 3/3] fix(engine): hand the drafter one window and free the tail after its first draft The first-draft wrap prepended the whole captured tail whatever the decode call's own rows: on the trimmable path with fork stops those rows are everything after the last stop, so the concat copied a multi-GB hidden to add context the drafter's sliding layers skip anyway. It now hands over at most one window - the newest rows of the tail that fit beside the call's own, none when those already fill it - which leaves the rows the drafter keeps on the hybrid path unchanged. The seeding context also drops its reference to the tail once the drafter holds it, so the ~105 MB is freed by the first draft call rather than held for the whole decode; a capture that voided itself is answered with None for the rest of the turn instead of being re-armed on every later segment; and the sink attribute is seeded on the language model at enable so the hook's per-forward read is a dict hit rather than mlx's __getattr__ miss on every decode step. Tests: the mlx-vlm stub patches the real module's attributes instead of replacing sys.modules["mlx_vlm"], which made the decode-wiring tests fail in isolation (the engine's decode imports mlx_vlm.speculative.utils, and a stand-in that is not a package refuses that unless an earlier test had imported it). The unloaded-engine fixture carries the context unload() now leaves, and the prompt-cache prefill overrides default capture to None like the protocol. Docs: the count gauges also read 0 when the drafter ran no round, not only without a drafter. Co-Authored-By: Claude --- CLAUDE.md | 14 ++++++++---- docs/observability.md | 5 +++-- src/sous/engine/draftctx.py | 42 +++++++++++++++++++++++++++-------- tests/test_draftctx.py | 40 +++++++++++++++++++++------------ tests/test_engine_unloaded.py | 4 ++++ tests/test_promptcache.py | 4 ++-- 6 files changed, 78 insertions(+), 31 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 177cdce4..dcba944e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -334,8 +334,13 @@ goal. instance-level wraps of the drafter's `draft_block`, `draft_block_greedy` and `reset`, which prepend it once (the greedy wrap may delegate to the sampled one — the first-call flag is consumed by the outer call). The - drafter's sliding attention keeps the newest `sliding_window - 1` rows of - tail plus own prompt itself. On the trimmable path the decode call + wrap hands over at most one window — the newest rows of the tail that + fit beside the call's own rows, none when those already fill it: the + drafter's sliding layers would skip the rest, and on the trimmable path + the call's own rows are everything after the last fork stop. The + `_Seeded` context drops its reference once the drafter holds the tail, + so the tail is freed by the first draft call, not the end of the decode. + On the trimmable path the decode call prefills the last segment itself, so only fork stops feed the capture there. `unload()` must `close()` the context first: the wraps close over the drafter and the drafter binds the target's embedding and head, so @@ -346,8 +351,9 @@ goal. turn line as `draft_context=7` (the capture lost) or as `draft_context=0` beside `draft_context=unavailable` on the load line (a gate tripped) — the context gauge is measured only while the seeding is active; the - count gauges are 0 only when no drafter ran, the prompt cache off - included. + count gauges are 0 when no drafter ran and when it ran no round (one + token asked for), the prompt cache off included — there the drafter runs + over the whole prompt and the counts are logged the same way. `tests/test_draftctx.py` drives the real `generate_step` and `_dflash_rounds` on stubs (CPU mlx suffices) to pin both contracts. Per-decode acceptance (`rounds_since`, mlx-vlm's lifetime counters, diff --git a/docs/observability.md b/docs/observability.md index 7e8aab5b..2b8ba324 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -144,8 +144,9 @@ of the hidden states of everything the turn prefilled before it, so a warm turn whose delta since the previous one was short reads short here too, and `7` means the drafter saw the generation prompt alone. It is measured only while the load line says `draft_context=active` and reads 0 -otherwise, whatever the drafter saw; the three counts are 0 only when no -drafter ran (with the prompt cache off the drafter sees the whole prompt, +otherwise, whatever the drafter saw; the three counts are 0 when no +drafter ran, and when it ran no round — one token asked for, or a stop on +the first (with the prompt cache off the drafter sees the whole prompt, and they are logged the same way). `seconds` is the total, running from the moment the turn takes the endpoint lock, so client-visible latency is `seconds` plus `queue_s`. On a miss the line adds `lcp=` (how many leading diff --git a/src/sous/engine/draftctx.py b/src/sous/engine/draftctx.py index dc0cb046..e0e89670 100644 --- a/src/sous/engine/draftctx.py +++ b/src/sous/engine/draftctx.py @@ -25,7 +25,9 @@ whatever the prompt's length; - instance-level wraps of the drafter's `draft_block`, `draft_block_greedy` and `reset` that prepend the pending context once, on the first draft call - after a reset, and record how many positions that call saw. + after a reset — as much of it as fills the window beside the call's own + rows, the newest rows of a longer tail being all the drafter's sliding + layers would keep — and record how many positions that call saw. Neither changes a token: the verify is exact, so a missing or wrong context costs acceptance, never output. That is also why the gates here are @@ -86,6 +88,10 @@ def fail(self) -> None: self._chunks = [] self._held = 0 + @property + def failed(self) -> bool: + return self._failed + def take(self, hidden_states: Any) -> None: import mlx.core as mx @@ -162,10 +168,11 @@ def install_forward_hook(cls: type) -> None: _WRAPPED.add(cls) -def _wrap_drafter(drafter: Any) -> None: +def _wrap_drafter(drafter: Any, keep: int) -> None: """Shadow the drafter's draft calls and reset per instance, the way mlx-vlm binds the target's argmax onto the drafter (`argmax_from_hidden`). - Once: a second engine over the same drafter would otherwise nest them.""" + Once: a second engine over the same drafter would otherwise nest them. + `keep` bounds what the first draft call is handed.""" import mlx.core as mx if getattr(drafter, _WRAPPED_DRAFTER, False): @@ -192,12 +199,21 @@ def _draft(last_bonus, hidden, cache, block_size, sampler, *args, _orig=orig, ** object.__setattr__(drafter, _FIRST, False) pending = getattr(drafter, _PENDING, None) object.__setattr__(drafter, _PENDING, None) + # Only what fills the window beside the call's own rows: the + # drafter's sliding layers skip older context themselves, so + # a longer hand-over — the trimmable path's decode call + # prefills everything after the last fork stop — would copy + # rows they never keep. + room = keep - int(hidden.shape[1]) if ( - pending is not None + room > 0 + and pending is not None and pending.ndim == hidden.ndim == 3 and pending.shape[0] == hidden.shape[0] and pending.shape[-1] == hidden.shape[-1] ): + if int(pending.shape[1]) > room: + pending = pending[:, -room:, :] hidden = mx.concatenate([pending, hidden], axis=1) object.__setattr__(drafter, _FED, int(hidden.shape[1])) return _orig(last_bonus, hidden, cache, block_size, sampler, *args, **kwargs) @@ -251,7 +267,9 @@ def sink(self, capture: Any) -> Sink | None: one this engine handed out, a fresh one when the turn asks to start capturing, None when it asks for nothing or there is nothing to seed.""" if isinstance(capture, Sink): - return capture + # A capture that voided itself is done for the turn: nothing it + # takes from here reaches the decode, so stop asking for it. + return None if capture.failed else capture return Sink(self.layer_ids, self.keep) if capture and self.active else None @staticmethod @@ -286,9 +304,8 @@ def seed(self, context: Any) -> _Seeded: def fed(self) -> int: """The context the most recent decode drafted from: the positions its - first draft call was handed, capped at the window — the drafter's - sliding attention drops the oldest rows past it, so a full tail plus - the generation prompt is still one window. 0 when it never drafted.""" + first draft call was handed — at most the window, which is all the + wrap hands over. 0 when it never drafted.""" if not self.active: return 0 return min(int(getattr(self._drafter, _FED, 0) or 0), self.keep) @@ -319,6 +336,10 @@ def __enter__(self) -> None: # before the loop runs never resets, and must not read the # previous decode's context as its own. object.__setattr__(self._drafter, _FED, 0) + # The drafter's is the only reference from here: the wrap drops it on + # the first draft call, so the tail is freed then rather than held + # for the rest of the decode. + self._context = None def __exit__(self, *exc: object) -> None: if self._drafter is not None: @@ -393,7 +414,10 @@ def enable(model: Any, drafter: Any, kind: str) -> DraftContext: return _refuse("language model decodes single tokens outside its forward") keep = window(drafter) install_forward_hook(type(lm)) - _wrap_drafter(drafter) + # Seeded so the hook's read on an unarmed forward is a plain __dict__ + # hit rather than mlx's __getattr__ miss on every decode step. + object.__setattr__(lm, _SINK, None) + _wrap_drafter(drafter, keep) except Exception as e: # noqa: BLE001 — degrade, never block the model return _refuse(str(e) or type(e).__name__) logger.info("drafter context: %d target layers, window %d", len(layer_ids), keep) diff --git a/tests/test_draftctx.py b/tests/test_draftctx.py index c132999f..713f01f6 100644 --- a/tests/test_draftctx.py +++ b/tests/test_draftctx.py @@ -8,7 +8,6 @@ the way tests/test_engine_positions.py drives generate_step. No weights. """ -import sys import threading import types from typing import Any @@ -323,7 +322,7 @@ def test_arming_no_sink_touches_nothing(): lm = _LM() ctx = draftctx.enable(_model(lm), _Drafter(), "dflash") with ctx.arm(_model(lm), None) as armed: - assert armed is None and draftctx._SINK not in vars(lm) + assert armed is None and vars(lm)[draftctx._SINK] is None # enable() seeds it def test_install_forward_hook_is_idempotent(): @@ -442,19 +441,26 @@ def test_a_context_of_another_shape_is_left_out_rather_than_forced(tail): assert drafter.calls[-1][1].shape == (1, 2, 4) and ctx.fed() == 2 -def test_the_context_fed_is_reported_no_larger_than_the_window(): - """A full tail plus the generation prompt is handed over whole — the - drafter drops the oldest rows past its window itself — but what it +def test_the_first_draft_is_handed_at_most_one_window(): + """A tail longer than the room beside the call's own rows is cut to its + newest rows — the drafter's sliding layers would skip the rest — and own + rows that already fill the window get no tail at all; what the drafter drafted from is one window, and that is the number logged.""" drafter = _Drafter() drafter.config.sliding_window = 4 # a window of 3 ctx = draftctx.enable(_model(), drafter, "dflash") assert ctx.keep == 3 - with ctx.seed(mx.full((1, 3, 4), 7.0)): + tail = mx.arange(3, dtype=mx.float32)[None, :, None] + mx.zeros((1, 3, 4)) + with ctx.seed(tail): drafter.reset(_model()) - _draft(drafter, "draft_block", 1, mx.zeros((1, 2, 4))) - assert drafter.calls[-1][1].shape == (1, 5, 4) # handed over whole + _draft(drafter, "draft_block", 1, mx.full((1, 2, 4), 9.0)) + handed = drafter.calls[-1][1] + assert handed.shape == (1, 3, 4) and handed[0, :, 0].tolist() == [2, 9, 9] assert ctx.fed() == 3 + with ctx.seed(mx.full((1, 3, 4), 7.0)): + drafter.reset(_model()) + _draft(drafter, "draft_block", 1, mx.full((1, 3, 4), 9.0)) + assert drafter.calls[-1][1].shape == (1, 3, 4) and ctx.fed() == 3 def test_seeding_nothing_leaves_the_drafters_own_context_alone(): @@ -716,11 +722,13 @@ def stream_generate(m, processor, prompt, **kwargs): setattr(drafter, attr, getattr(drafter, attr, 0) + step) return iter(()) - monkeypatch.setitem( - sys.modules, - "mlx_vlm", - types.SimpleNamespace(generate=generate, stream_generate=stream_generate), - ) + # On the real module, not a stand-in for it in sys.modules: the engine's + # decode also imports mlx_vlm.speculative.utils, which a stand-in that is + # not a package refuses whenever nothing imported that submodule earlier. + import mlx_vlm + + monkeypatch.setattr(mlx_vlm, "generate", generate) + monkeypatch.setattr(mlx_vlm, "stream_generate", stream_generate) def test_a_captured_prefill_asks_for_the_target_layers_and_keeps_the_tail(monkeypatch): @@ -804,7 +812,11 @@ def take(self, hidden_states): with pytest.warns(UserWarning, match="capture failed"): assert engine.prefill([_cache()], list(range(10)), capture=capture) is capture assert draftctx.DraftContext.tail(capture) is None - engine.prefill([_cache()], list(range(10, 14)), capture=capture) + # The rest of the turn is not asked to capture: the engine answers None + # and the forward is not asked for the target layers again. + calls.clear() + assert engine.prefill([_cache()], list(range(10, 14)), capture=capture) is None + assert "capture_layer_ids" not in calls["prefill"] assert draftctx.DraftContext.tail(capture) is None diff --git a/tests/test_engine_unloaded.py b/tests/test_engine_unloaded.py index d7bcf619..df1c077b 100644 --- a/tests/test_engine_unloaded.py +++ b/tests/test_engine_unloaded.py @@ -9,6 +9,7 @@ import pytest +from sous.engine import draftctx from sous.engine.lm import LMEngine from sous.engine.vlm import VLMEngine @@ -36,6 +37,9 @@ def _unloaded_vlm() -> VLMEngine: engine._model = None engine._processor = None engine._positional = True # unload() leaves the load-time probe's answer alone + engine._draft = None + engine._draft_kind = "" + engine._draft_context = draftctx.OFF # unload() closes the drafter's context engine._memo = PromptMemo() engine._tokenize_lock = threading.Lock() engine._cache = PrefixCache(engine, enabled=True) diff --git a/tests/test_promptcache.py b/tests/test_promptcache.py index 3a16e7e1..95614a9d 100644 --- a/tests/test_promptcache.py +++ b/tests/test_promptcache.py @@ -2326,7 +2326,7 @@ def test_a_retired_owner_still_persists_though_its_fork_is_refused(): pc = PrefixCache(h, max_bytes=ROOMY, store=s) original = h.prefill - def prefill(cache, token_ids, capture=False): + def prefill(cache, token_ids, capture=None): context = original(cache, token_ids, capture) pc.reset(threading.current_thread()) # the endpoint retiring this session return context @@ -2877,7 +2877,7 @@ def __init__(self, clock: FakeClock, **kw): super().__init__(**kw) self.clock = clock - def prefill(self, cache, token_ids, capture=False): + def prefill(self, cache, token_ids, capture=None): self.clock.advance(2.0) return super().prefill(cache, token_ids, capture)