Skip to content

feat(server): report per-request speculative acceptance - #1588

Merged
inureyes merged 5 commits into
mainfrom
feature/issue-1314-speculative-timings
Sep 2, 2026
Merged

inureyes merged 5 commits into
mainfrom
feature/issue-1314-speculative-timings

Conversation

@inureyes

@inureyes inureyes commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Summary

The scheduler already counts a drafted request's verify rounds and its proposed and accepted draft-token totals, and then dropped them into a tracing line no client can read. This carries them out on the response, so an operator tuning --draft-max / --draft-block-size and a client A/B-ing the two decode paths can answer "did speculation help this request" without server-log access.

What changed

GenerationResult gains speculative: Option<SpeculativeStats> (src/server/model_provider.rs): a Copy, allocation-free block of the drafter kind, the verify rounds, draft_n and draft_n_accepted. SpeculativeStats::from_counts returns None unless the run both executed a round and drafted a token, which is b10621's own draft_n > 0 gate, so "no drafter ran" and "the drafter accepted nothing" stay distinguishable instead of collapsing into zeros.

Three paths populate it, which are the three that own a request's whole round loop: the DFlash B=1 burst and the MTP B=1 burst (src/server/batch/speculative_burst.rs, from DFlashDiagnostics and MtpAcceptanceSummary respectively, read next to the existing log line and the adaptive-policy profile), and the tick-cooperative MTP slice (src/server/batch/scheduler.rs, whose session already accumulates the totals across every slice, so nothing new is accumulated here).

SequenceInfo::take_generation_result (src/server/batch/sequence.rs) takes the block as a parameter rather than growing a field, so the hot batch code is untouched: every classic-decode call site passes None, no allocation, clone or branch is added on the per-token path, and the non-speculative wire shape is byte-identical. The one measurable per-token delta is that GenerateEvent::Done holds GenerationResult unboxed, so the enum every Token send moves grew by 32 bytes, about a tenth of its existing size against a decode step measured in hundreds of microseconds; boxing that arm is a separate and larger win. The DFlash driver's return tuple became a named DFlashTargetRun struct so the diagnostics can escape it without a four-element tuple.

On the wire, NativeTimings gains a flattened Option<SpeculativeTimings> (src/server/types/native_completion.rs) attached through a with_speculative builder, so NativeTimings::new's measured-against-the-binary signature and its existing callers and tests are unchanged, and None flattens to nothing. draft_n and draft_n_accepted are b10621's own optional pair, spelled and gated as upstream spells and gates them, so a client that already reads llama-server timings reads mlxcel's unchanged; draft_rounds and draft_kind are mlxcel additions, because without the round count the mean accepted length per round ((draft_n_accepted + draft_rounds) / draft_rounds) is not recoverable and upstream has one draft-model concept where mlxcel serves drafted requests under more than one drafter. That difference is recorded as a checked divergence entry with its rationale on both native route entries in compat/llama-server/b10621/routes.json, not as prose in notes, and the entries' own count of permanent differences was corrected from two to three in the same edit.

/v1/chat/completions and /chat/completions gain the same object at the top level, built by chat_timings, which owns the presence rule for both the non-streaming body and the streaming finish chunk. It is upstream's whole block rather than the draft_* half alone: timings is a key b10621 clients already probe for and then read a base key off, so a partial object under it would turn a clean absent-branch into a live undefined. What remains is a presence difference, since upstream emits the block on every chat completion and mlxcel only for a drafted request; emitting it unconditionally changes the non-speculative chat response shape, which is a chat-route compatibility decision with its own blast radius rather than a side effect of adding acceptance reporting. Both chat route entries moved from supported with an empty divergence to by_design carrying that difference, its rationale and its revisit condition, and #1314 joins the routes shard's owner set in pin.json. Those entries were claiming supported while emitting no timings at all, so the claim was already wrong before this PR.

A mid-stream frame carries none of the four draft keys on either route: the counters are the run's totals, and a running value in a frame that looks like a total would be wrong.

Two serving paths deliberately report nothing, and both say so in the code and in docs/speculative-acceptance.md. The default-off B>1 batched burst has no per-row acceptance counters to report. The disaggregated router front assembles both its stream and its non-streaming body from the prefill/decode handoff protocol rather than from a GenerationResult, and that protocol carries a generated-token count and nothing else, so surfacing the block there is a handoff-protocol change rather than a response-shaping one.

Test plan

  • cargo test --profile test-fast --features metal,accelerate --lib server::batch (432 passed), --lib server::routes (383), --lib server::types (98), --lib server::model_provider (57), --lib server::llama_compat_tests (3). All green.
  • cargo clippy --profile test-fast --lib --tests --features metal,accelerate -- -D warnings clean; cargo fmt --all -- --check clean; cargo check --profile test-fast --features metal,accelerate --bins clean.
  • make verify-llama-compat passes with the amended manifest entries and the new shard owner, including its own negative cases.
  • Type level: the block is absent without a drafter (the nine b10621 keys, unchanged) and present with one (the full thirteen-key order, upstream's pair appended where upstream appends it, then the two extensions); a zero-round run yields no block; each DrafterKind renders its canonical name.
  • Scheduler level: speculative_slice_tests drives the real two-round generator script and asserts the Done event carries the counters it produced (draft_rounds > 0, 0 < draft_n_accepted <= draft_n) and carries nothing for an undrafted finish.
  • Route level: the four keys on /completion, /completions and /v1/chat/completions plus the chat body's full thirteen-key order; their absence without a drafter on both shapes; only the finish_reason chunk of a chat stream carries timings, asserted against a stream driven through the scripted provider so the negative half runs against real content frames; and a drafted native stream's timings_per_token partial frames carry exactly the nine base keys while its final frame carries all thirteen.
  • Bilingual technical report committed at TECHNICAL_REPORTS/1588-speculative-acceptance-timings-20260902.{en,ko}.md.

End-to-end check with a real drafter (for the merge orchestrator)

./target/release/mlxcel-server \
  -m models/mlx/qwen3.5-4b-4bit \
  --draft-model models/mlx/qwen3.5-4b-dflash \
  --draft-kind dflash \
  --draft-block-size 16 \
  --port 8080

curl -s localhost:8080/completion -H 'content-type: application/json' \
  -d '{"prompt":"Write the numbers one to thirty in words.","n_predict":96,"temperature":0}' \
  | jq '.timings | {draft_kind, draft_rounds, draft_n, draft_n_accepted, predicted_n}'

curl -s localhost:8080/v1/chat/completions -H 'content-type: application/json' \
  -d '{"model":"qwen3.5-4b-4bit","messages":[{"role":"user","content":"Write the numbers one to thirty in words."}],"max_tokens":96,"temperature":0}' \
  | jq '.timings'

Expected: draft_kind == "dflash", draft_rounds > 0, 0 < draft_n_accepted <= draft_n, and predicted_n == draft_n_accepted + draft_rounds within one for the EOS round (each round emits its accepted drafts plus one bonus token). The chat body's timings is the same thirteen-key object the native route answered with, reporting the same figures for the same request. The same figures appear in the server's DFlash diagnostics log line. Restarting without --draft-model must answer a /completion timings with none of the four draft keys and a chat body with no timings key at all.

Closes #1314

The scheduler already counts a drafted request's rounds, proposed and accepted draft tokens, and then dropped them into a `tracing` line no client can read. An operator tuning `--draft-max` / `--draft-block-size` and a client A/B-ing the two decode paths both need the answer for their own request, not an aggregate the server keeps to itself.

`GenerationResult` gains `speculative: Option<SpeculativeStats>`, four machine words carrying the drafter kind, the verify rounds, and the proposed and accepted draft-token totals. It is `Some` only when at least one verify round ran, so "no drafter" and "drafter accepted nothing" stay distinguishable rather than collapsing into a block of zeros. The three paths that own a request's whole round loop populate it: the DFlash B=1 burst, the MTP B=1 burst, and the tick-cooperative MTP slice, whose session already accumulates the totals across slices. The default-off B>1 batched burst reports nothing, because its round loops return per-row tokens without per-row acceptance counters.

`SequenceInfo::take_generation_result` takes the block as a parameter rather than a field, so every classic-decode call site passes `None` and the non-speculative path keeps its allocations and its wire shape unchanged.

On the wire, the native `/completion` and `/completions` `timings` object gains b10621's own optional `draft_n` / `draft_n_accepted` pair, spelled and gated as upstream spells and gates them, so a client already reading llama-server timings reads mlxcel's unchanged. Two mlxcel keys sit beside them: `draft_rounds`, without which the mean accepted length per round is not recoverable, and `draft_kind`, which names which of the three drafters ran. `/v1/chat/completions` carries the same four keys as a top-level `timings` object on the non-streaming response and on the chunk that carries `finish_reason`; a mid-stream chunk carries none of them, because the counters are the run's totals and a running value there would read as one.

Validated with `cargo test --profile test-fast --features metal,accelerate` over the touched modules (server::batch::speculative, server::types, server::routes::chat, server::batch::scheduler, native_route_tests, stream_route_tests, server::model_provider, server::llama_compat_tests), plus `cargo clippy --profile test-fast --lib --tests --features metal,accelerate -- -D warnings`, `cargo fmt --all -- --check` and `make verify-llama-compat`. The end-to-end check against a real target/drafter pair is in the PR body.

Refs #1314
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:low Low priority area:inference Generation, sampling, decoding (incl. speculative, DRY) modeltype:text Text-only language model status:review Under review labels Sep 2, 2026
The disaggregated router front assembles its chat stream from the prefill/decode handoff protocol rather than from a finished `GenerationResult`, and that protocol carries a generated-token count and no acceptance counters. Its finish chunk therefore carries no `timings` block, unlike the single-node one. Left undocumented, that asymmetry reads as an oversight in the path that has one and a bug in the path that does not.

Recorded where each reader looks: a note on `chat_chunk_finish` saying surfacing the counters there is a handoff-protocol change rather than a response-shaping one, and a paragraph in the speculative-acceptance doc beside the existing note on the default-off B>1 batched burst.

Also adds the bilingual technical report for PR #1588.

Refs #1314
`#[serde(flatten)]` makes serde serialize `NativeTimings` through `serialize_map` rather than `serialize_struct`, so the guard that the nine b10621 keys keep their captured order is worth having in the flattened case too, not only in the case where the option is `None`. The existing `the_timings_block_leads_with_cache_n` covers the latter.

Asserts the full thirteen-key order instead of the length alone: the nine base keys unchanged, then upstream's `draft_n` / `draft_n_accepted` pair where upstream appends it, then the two mlxcel keys.

Refs #1314
`DrafterKind::as_str` has three values and the wire field can carry any of them, but only two are reachable in the server today: `internal-mtp` resolves to the classic dispatch, which the burst gate declines, so no request is served speculatively under it and none reports a block. Listing all three flat implied a coverage the code does not have.

Refs #1314
The first cut put only the four `draft_*` keys under `timings` on the OpenAI chat routes, on the reasoning that the nine base keys would appear and vanish with the drafter since the whole object is gated on speculation being active. That misses the sharper consequence: `timings` is a key b10621 clients already probe for, and every one of them reads a base key off it. A client written as `if (res.timings) show(res.timings.predicted_per_second)` previously took the absent branch every time and would now take the present branch and read `undefined`. A partial object under a key upstream already defines is worse than no key at all, and the flicker argument does not separate the two shapes, because presence is gated either way.

The chat `timings` is now upstream's whole object, `cache_n` through `predicted_per_second` plus the flattened draft half, which is what b10621 puts on its own OpenAI chat responses. One `chat_timings` function builds it and owns the presence rule for both the non-streaming body and the finish chunk.

What remains is a presence difference, not a content one: upstream emits the block on every chat completion, mlxcel only for a drafted request. Both chat route entries in the compat manifest moved from `supported` with an empty `divergence` to `by_design` carrying that difference, its rationale and its revisit condition, and #1314 joins the routes shard's owner set in pin.json. Those entries were claiming `supported` while emitting no `timings` at all, so the claim was already wrong before this change.

Also from review: `SpeculativeStats::from_counts` now requires a non-zero `draft_n` as well as a non-zero round count, so the gate is upstream's `draft_n > 0` rather than a condition that merely coincides with it; the native `/completion` divergence text no longer claims three drafter kinds when only two can reach the block; `chat_completion_json` in the disaggregated front gets the note its streaming counterpart already had; and a redundant `too_many_arguments` allow is dropped.

Two test gaps closed. The scripted streaming provider gained a speculative variant, so the chat "only the finish chunk carries timings" assertion now runs against a stream with real content frames rather than one that emits none. And a new native streaming test drives a drafted request with `timings_per_token`, asserting every partial frame carries exactly the nine base keys while the final frame carries all thirteen, which is the mid-stream-totals hazard the docs make the loudest claim about.

Validated with `cargo test --profile test-fast --features metal,accelerate` over server::batch (432), server::routes (383), server::types (98), server::model_provider (57) and server::llama_compat_tests (3), plus clippy, fmt, `cargo check --bins` and `make verify-llama-compat`.

Refs #1314
@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 2, 2026
@inureyes
inureyes merged commit 2fddec1 into main Sep 2, 2026
12 checks passed
@inureyes
inureyes deleted the feature/issue-1314-speculative-timings branch September 2, 2026 07:56
@inureyes inureyes added this to the 0.7 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) modeltype:text Text-only language model priority:low Low priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(server): expose per-request speculative decoding acceptance stats in response timings

1 participant