Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,55 @@ 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
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
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 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,
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

Expand Down
9 changes: 8 additions & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
29 changes: 26 additions & 3 deletions docs/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -129,7 +130,24 @@ 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 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
tokens the render shared with the closest resident slot), `lcp_region=`
Expand Down Expand Up @@ -166,7 +184,12 @@ seconds=N.N model=<model_id>` 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
Expand Down
8 changes: 8 additions & 0 deletions src/sous/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 '-'}"
)
Expand Down
12 changes: 12 additions & 0 deletions src/sous/api/turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
18 changes: 18 additions & 0 deletions src/sous/engine/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading