Skip to content

refactor: run mlxcel generate on the engine and retire CxxGenerator - #2225

Merged
inureyes merged 13 commits into
mainfrom
refactor/issue-2176-generate-on-engine
Oct 7, 2026
Merged

inureyes merged 13 commits into
mainfrom
refactor/issue-2176-generate-on-engine

Conversation

@inureyes

@inureyes inureyes commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

Phase 6 of epic #2166: mlxcel generate, --profile, --prompt-lookup, the decode benchmarks and the inference session decode on mlxcel_core::engine::Engine at B=1, and CxxGenerator is gone, so no decode fix needs a CLI-only twin and bench_decode times the path the server runs. Landed in seven stages (one commit each: generate on the engine client, the session wrapper, the benchmarks, prompt lookup as a drafter, the removal and docs, the B=1 lookahead pipeline, the drafter loop's plain-round pipeline).

Design decisions

  • Raw-completion client: the parity harness's DirectEngine probe is promoted to mlxcel_core::engine::DirectEngine<M>, the one single-sequence client (open, prefill plan pieces, complete_prefill, step until the finish step, close), with the request's KV mode (Boundary-V table, model-owned injection as the scheduler does) and token bias. LanguageModel is implemented for &M so the client can borrow a model its caller keeps. generate, MlxInferenceSession, the harness's a:cli and d:engine arms, mlxcel-bench-decode, mlxcel-bench-engine's CLI arm and speculative_bench's baseline all call it. evaluate_loglikelihoods is Engine::score, a prefill-only pass returning the whole window's logits. No shim: every caller had moved before the type was removed.
  • Template render: one front, server::chat_front, carries the enable_thinking default (think-marker tokenizers on, Gemma 4 thinking-off templates excepted). The server's load_chat_front, generate's load_cli_prompt, the harness's render_chat_prompt and mlxcel-bench-decode load the template through it. Output change: the harness's CLI-style arms and bench_decode now render Qwen3-class prompts with enable_thinking=true, as generate, run -p and the server already did; the Phase 6 divergence note in docs/CONTINUOUS_BATCHING.md is gone. --no-chat-template stays raw.
  • Prompt-lookup drafter: PromptLookupDrafter implements the server's Drafter trait (kind prompt-lookup, new drafts_from_tokens_only hook) and carries the governor and shadow probe; the round loop is the engine's token-only speculative loop (DirectEngine::generate_with_drafter over Engine::verify, Engine::commit_appends, Engine::unwind_appends). A server option is a follow-up: the scheduler's burst arms are per-family adapters, so offering prompt lookup there needs its own burst arm over the same two entries. Its plain rounds pipeline again as the old loop's did: after more than two rounds without a proposal, or at once while a gated governor is paused (Drafter::pipelines_plain_rounds); a proposal found while a step is in flight is retracted (Drafter::retract_draft, so the summary line still counts one round per forward) and verified from the in-flight token next round.
  • B=1 lookahead pipeline: after the first token DirectEngine overlaps step n+1's forward with step n's host read through the engine's split step (submit, finish_rows, unwind_appends), as the retired loop and the scheduler do. A finish (EOS or stop id, length, repetition loop) or a callback stop unwinds the one forward submitted past it, so stream, pool offset and KV state equal the synchronous loop's; nothing is submitted after the token that spends the budget. Eligibility is the scheduler's, now shared: shared_fused_params (fused-eligible sampling only; history penalties, masks, overrides, logprobs and feedback samplers stay synchronous) and the new Engine::can_unwind_lookahead (dense or pool-backed paged, or a model-owned family with supports_decode_lookahead_rewind), which the scheduler's gate now calls too; on DirectEngine a model-owned family that cannot rewind still pipelines with Teardown::Discard (the one step past the finish is dropped when the sequence closes, since every caller closes it right after decoding), with lookahead_feedback_input and force_sync_requested. The state machines stay separate: the scheduler's handles admission, preemption and membership changes and re-runs a finishing tick synchronously for completion and prompt-cache donation, which an in-call sequence does not need. MLXCEL_FORCE_SYNC forces the synchronous path again (DirectEngine::with_force_sync in code). The raised command-buffer budget wraps pipelined decode only, as in the scheduler. A zero budget (-n 0) runs no forward and emits nothing in generate and generate_with_drafter, as main did.
  • SpeculativeGenerator (classic draft-model path) is #[deprecated], prints a deprecation notice and is recorded in CHANGELOG Unreleased for removal in the next minor release; the server never ran it, and rg 'CxxGenerator|SpeculativeGenerator' src/server is empty.
  • --profile / [TTFT]: timings come from the client; the engine samples and evaluates the first token in one complete_prefill, so [TTFT] reports sample=0 and carries the sampler build inside eval (docs/environment-variables.md).
  • Dropped with the retired loops: MLXCEL_PROFILE_PIPELINE, MLXCEL_PROFILE_PIPELINE_DETAIL, MLXCEL_TRACE_ASTYPE, MLXCEL_EXPORT_DECODE_DOT and MLXCEL_CAPTURE_DECODE (one removal note in docs/environment-variables.md); MLXCEL_TRACE_DTYPE keeps its fused Mamba2 prints, and mlxcel-bench-decode honors MLXCEL_METAL_CAPTURE_PATH around its measured pass. scripts/bench_decode.sh gains a trailing decode_path CSV column; the historical columns are unchanged.
  • Docs: docs/CONTINUOUS_BATCHING.md, docs/architecture.md, docs/benchmarks.md, docs/environment-variables.md, docs/speculative-acceptance.md, ADR 0009 ("Raw completion" section) and ADR 0007's row.

Test plan

  • cargo clippy --profile test-fast --features cuda --lib --tests --bins --examples -- -D warnings
  • cargo test --profile test-fast --features cuda -p mlxcel-core --lib -- --test-threads=1 engine session generate:: speculative:: drafter:: generation_policy language_model_ref (new DirectEngine tests over the echo model, owned and borrowed; the induction rollback parity tests compare the engine loop against the engine's plain run; the prefill partition, span, KV-mode and token-bias tests ported from the retired loop)
  • cargo test --profile test-fast --features cuda --lib -- --test-threads=1 commands:: backend:: engine_probe cli_input server::batch::scheduler lang_analyzer (386 passed)
  • Real-checkpoint smoke runs, a few dozen tokens each, no timing claims: mlxcel generate on qwen3-1.7b-4bit (plain, --profile, --show-reasoning text identical to run -p --temp 0), --no-chat-template on llama-3.2-1b-instruct-4bit, --prompt-lookup on llama-3.2-1b-instruct-4bit (identical 32-token output to plain, 11 of 16 proposals accepted), mlxcel-bench-decode (Decode path: engine), speculative_bench --kind none
  • mlxcel-engine-parity --expect-identical under MLXCEL_SDPA_DETERMINISTIC=1 on qwen3-1.7b-4bit and llama-3.2-1b-instruct-4bit (after Stage C): every a:cli / b:dense / c:paged / d:engine pair and f:server vs e:run identical for the greedy and the seeded-penalties cases on both models; the only divergent pairs are the known prompt-cache miss-vs-hit near-tie rows (Qwen3 at 58 and 61, Llama seeded at 25), which docs/CONTINUOUS_BATCHING.md tracks as a measured divergence rather than a gate
  • Pipeline tests on stub models (engine::direct_decode_tests, engine::speculative_plain_tests): pipelined vs synchronous stream, callback deliveries, pool offset and KV length at EOS, stop id, every max_tokens up to 3 and callback stop, token bias, zero budget, and the fallbacks (history penalty, force sync, model-owned with and without a rewind); drafter plain rounds at length, stop id and callback finishes, a proposal during a pipelined run, a drafter that does not pipeline
  • Real checkpoints under MLXCEL_SDPA_DETERMINISTIC=1, no timing claims: mlxcel generate --temp 0 -n 96 on qwen3-1.7b-4bit and llama-3.2-1b-instruct-4bit prints the same text pipelined and under MLXCEL_FORCE_SYNC=1, plain and with --prompt-lookup (which also matches plain); -n 0 prints no generated text; mlxcel-engine-parity greedy streams are identical across a:cli, d:engine, b:dense, c:paged, e:run and f:server on both models, and the full run's pairs are unchanged (only the known prompt-cache miss-vs-hit rows diverge)
  • Final head, release build, MLXCEL_SDPA_DETERMINISTIC=1: fmt, both clippy gates, license headers, the audit tests, and the module tests above plus server::in_process, chat routes, models::gemma3, models::gemma4, models::nanochat, multimodal::, single_row_batch_parity and scheduler_real_batch_parity (--ignored), each with --test-threads=1
  • generate --temp 0 -n 96 prints the same text pipelined and under MLXCEL_FORCE_SYNC=1 on qwen3-1.7b, llama-3.2-1b, gemma-4-e2b, granite-4.0-h-350m, qwen3.5-0.8b and gemma-3-1b (4-bit); --prompt-lookup text equals plain on llama-3.2-1b; --profile prints one [TTFT] line; --no-chat-template, a Qwen2.5-VL image prompt (red square, blue circle, green triangle), gemma-3-1b with int8 KV under --profile and a mlxcel-bench-decode run (Decode path: engine) complete
  • mlxcel-engine-parity -n 400 on qwen3-1.7b, llama-3.2-1b and gemma-3-1b: every CLI, dense, paged, engine, e:run and f:server pair identical; only the prompt-cache rows diverge (Qwen3 now at 58 and 61 because the harness renders with enable_thinking=true like the server; Llama seeded at 25; Gemma 3 seeded dense vs cache miss at 51)
  • bench_decode throughput against the Phase 0 threshold: measured by the orchestrator at the end of the epic, not here
  • The classic draft-model deprecation notice was not exercised on a real draft checkpoint (none local); the path compiles and the notice precedes the loop

Changes during review

  • KV mode on model-owned families: the client injected the model's modes after Engine::open, whose prepare_sequence_state had already built the sequence's caches, so the first sequence on a fresh model decoded Fp16 under --kv-cache-mode int8|turbo4 (--profile, --image, bench_decode --warmup-tokens 0, the first session call and perplexity window). The modes now go in before open, loglikelihoods shares that path, and the KV-mode test records what prepare_sequence_state saw. On gemma-3-1b-it-4bit, greedy 200 tokens: before, --profile printed the fp16 text under int8 and turbo4; after, --profile matches the plain path for each mode.
  • scripts/capture_moe_decode_trace.sh gputrace mode runs on MLXCEL_METAL_CAPTURE_PATH with -n 2 (not run here: Metal only).
  • [TTFT] is opt-in per client (DirectEngine::with_ttft_report), set by --profile and the bench's measured pass, so warmups print nothing.
  • The client sets the pool prompt_len and current_offset after the first token as the scheduler does; nanochat overrides forward_last_logits_with_sequence_id; a new drafter test pins the Graded cooldown and paused_rounds.
  • Real checks at the final head, no timing claims: gemma-3-1b-it-4bit --profile vs plain text identical for fp16 and int8, with MLXCEL_PROFILE_TTFT=1 printing one [TTFT] line under --profile and none on the plain path, one for mlxcel-bench-decode (measured pass only); nanochat-d20-q8-mlx generate prints the same text before and after the override.
  • Stale references and docs: dead plan_single_sequence_prefill removed, Used-by notes and intra-doc links fixed, ADR 0007 amended-by note, the drafter loop's greedy claim carries the multi-token verify caveat.
  • Security review, HIGH performance (3fbb13b): requiring an exact rewind sent Gemma 4, Llama 4, Qwen 3.5, the SSM hybrids and most VLM wrappers to the synchronous chain, where the retired loop pipelined them; they now pipeline with Teardown::Discard, and the server keeps the exact rule. A failed submit after a discarded step ends the run with that error instead of falling back on state it could not undo.
  • Finalizer (3c9f001, 140fedc): verify and scoring return an error instead of panicking on unexpected logits shapes; the raised command-buffer budget covers only pipelined plain rounds in the drafter loop; an EOS inside a verify block leaves the pool offset where the synchronous step does; ADR 0009, README and CHANGELOG aligned.
  • Known follow-ups: requests with history penalties, DRY or feedback samplers decode synchronously (the retired loop overlapped them through its per-row sampler); a server option for prompt lookup needs its own burst arm.

Closes #2176

Phase 6 of epic #2166, stage A. `mlxcel generate`'s text and VLM-embedding paths no longer decode through `CxxGenerator`: they open one sequence on `mlxcel_core::engine::Engine` through the raw-completion client (`engine::DirectEngine`, promoted from the parity harness's `d:engine` probe) and run the same prefill plan, sampler, finish step and merged EOS set the server's B=1 row runs. `--profile` stats and the `[TTFT]` phases are read from that client; the sampler graph build and the first eval are one `complete_prefill` phase there, so `sample` reports 0 and `eval` carries both.

`LanguageModel` is now implemented for `&M`, so the client can open an `Engine<&M>` over a model its caller keeps (the Qwen3-Omni speech pass reuses the instance after generation). The client applies the request's KV mode (Boundary-V layer table, model-owned injection) and token bias the way the scheduler does.

One chat-template front (`server::chat_front`) carries the `enable_thinking` default: the server's `load_chat_front`, `generate`'s `load_cli_prompt`, the harness's `render_chat_prompt` and `mlxcel-bench-decode` all load the template through it, which removes the Qwen3 token-0 divergence recorded for the harness's CLI-style arms in docs/CONTINUOUS_BATCHING.md.

Validated with `cargo clippy --profile test-fast --features cuda --lib --tests --bins --examples -- -D warnings`, `-p mlxcel-core --lib engine` (new DirectEngine tests over the echo model, owned and borrowed) and a `mlxcel generate` smoke run on a local checkpoint.

Refs #2176
@inureyes inureyes added status:in-progress Currently being worked on type:refactor Code restructuring without changing functionality priority:medium Medium priority area:cli Command-line interface / CLI flags area:benchmark Benchmark harness and performance measurement (bench_*.sh, /update-benchmarks) labels Oct 7, 2026
Phase 6 of epic #2166, stage B. `MlxInferenceSession` no longer owns a `CxxGenerator`: each generation method opens the raw-completion client (`engine::DirectEngine`) over the borrowed model with the session's KV mode and token bias, runs one completion on a fresh sequence and closes it, so model-owned state (Gemma 3/4, Llama 4, Qwen 3.5) resets through the engine's open and close and `reset_with_model` has nothing left to do. The method signatures are unchanged, so `backend::Session` and its callers compile as before; an engine failure at the fallible MLX boundary is reported on stderr and yields no tokens, the shape the OpenXLA arm already had.

`evaluate_loglikelihoods` becomes a prefill-only scoring call: `Engine::score` runs the forward over the whole window for one sequence and returns its `[1, T, vocab]` logits, and `DirectEngine::loglikelihoods` computes the per-target log-likelihoods from them under the client's KV mode. The wikitext-2 perplexity gates (`tests/turbo_kv_e2e.rs`, `tests/pre_ampere_f16_quality.rs`) call it through the session.

Validated with `cargo clippy --profile test-fast --features cuda --lib --tests --bins --examples -- -D warnings` and `cargo test --profile test-fast --features cuda -p mlxcel-core --lib -- --test-threads=1 engine session language_model_ref`.

Refs #2176
…marks

Phase 6 of epic #2166, stage C. `mlxcel-bench-decode`, `mlxcel-bench-engine`'s `cli` arm (through the probe's `bench_like_bench_decode`) and `mlxcel-speculative-bench`'s baseline run their warmup and measured passes on `engine::DirectEngine`, the loop `mlxcel generate` and the server's B=1 row run, instead of `CxxGenerator`. The warmup's sequence is closed when it returns, so the measured pass starts from fresh model-owned state while the process keeps its warm allocator and kernel caches, which is what the old `reset_with_model` between passes provided.

`mlxcel-bench-decode` prints a `Decode path:` line in `[Profile Results]`, and `scripts/bench_decode.sh` records it in a new trailing `decode_path` CSV column (`engine`); the first seventeen columns and the ROCm extras are unchanged, so historical CSVs stay comparable, and a row's SKIP/FAIL token now follows an empty `decode_path`. docs/benchmarks.md documents the column. No benchmark was run here: the epic's end-of-run measurement compares the engine path against the Phase 0 baseline.

Validated with `cargo clippy --profile test-fast --features cuda --lib --tests --bins --examples -- -D warnings`, `bash -n scripts/bench_decode.sh` and a `mlxcel-bench-decode` smoke run of a few dozen tokens on a local checkpoint.

Refs #2176
…assic draft-model loop

Phase 6 of epic #2166, stage D. Prompt-lookup decoding is now a `Drafter` (`speculative::prompt_lookup_drafter::PromptLookupDrafter`, kind `prompt-lookup`): it proposes from the token context the round loop reports through `accept_verified_tokens`, and carries the adaptive governor and the shadow probe with it. The trait gains `drafts_from_tokens_only`, which such a drafter sets, so the engine's new token-only speculative loop (`DirectEngine::generate_with_drafter`, over `Engine::verify`, `Engine::unwind_appends` and `Engine::commit_appends`) can drive it on any model, and the server can offer the same drafter through the same two entries later; wiring a server option is left as a follow-up because the scheduler's burst arms are per-family adapters. `PromptLookupGenerator` and its own decode loop are gone; `mlxcel generate --prompt-lookup` runs the engine loop with the request's KV mode and token bias, and the plain-round pipelining the old loop had is not carried over (the end-of-epic measurement decides whether it is needed).

The classic draft-model path (`--draft-model` without `--draft-kind mtp` or `dflash`, the `SpeculativeGenerator` loop) prints a deprecation notice pointing at `--draft-kind mtp`, `--draft-kind dflash` and `--prompt-lookup`; `CHANGELOG.md` gains an Unreleased section recording the deprecation, its removal in the next minor release, and the paths that moved onto the engine.

Validated with `cargo clippy --profile test-fast --features cuda --lib --tests --bins --examples -- -D warnings` and `cargo test --profile test-fast --features cuda -p mlxcel-core --lib -- --test-threads=1 prompt_lookup engine:: drafter::` (the induction-model rollback parity tests now compare the engine loop against the engine's plain run), plus a `--prompt-lookup` smoke run on a local checkpoint.

Refs #2176
Phase 6 of epic #2166, stage E. `CxxGenerator`, its four decode loops and the CLI-only prefill helpers (`prefill_prompt_last_logits`, `chunked_prefill_last_logits`, `prefill_embeddings_last_logits`, the pad and trim helpers, `sample_next_step`, the `cli_finish_step` pair, `run_benchmark`) are gone from `mlxcel-core`, together with `generation_policy::ensure_model_caches`, which only they called. `rg -n 'CxxGenerator' src` returns nothing: no shim was needed, because every caller had moved onto `engine::DirectEngine` or `MlxInferenceSession` in the earlier stages.

The unit tests that pinned the retired loops now pin the engine client: the history-ordering and row-step parity suites run the four `MlxInferenceSession` entry points, the finish-step suite calls `finish_step` with `NoStopHooks` directly, and the engine tests gain the prefill-span announcement, the piece-by-piece partition parity against a single pass, the KV-mode injection into a model-owned family and the token-bias composition rule. The real-checkpoint integration tests construct `MlxInferenceSession` where they constructed `CxxGenerator`.

Stale comments describing the CLI/server split are rewritten across the model files, the scheduler, the probe binaries and the core helpers. docs/architecture.md points decode at `engine/`, docs/environment-variables.md marks the six retired per-token diagnostics and the `[TTFT]` phase change, docs/benchmarks.md and docs/speculative-acceptance.md name the engine client, and ADR 0009 gains a "Raw completion" section (ADR 0007's row links to it).

Validated with `cargo clippy --profile test-fast --features cuda --lib --tests --bins --examples -- -D warnings`, the core `engine`, `session`, `generate::`, `speculative::`, `drafter::`, `generation_policy` and `language_model_ref` tests, and the root `commands::`, `backend::`, `engine_probe`, `cli_input` and `server::batch::scheduler` tests, each under `--test-threads=1`.

Closes #2176
@inureyes
inureyes marked this pull request as ready for review October 7, 2026 20:01
@inureyes inureyes added status:review Under review and removed status:in-progress Currently being worked on labels Oct 7, 2026
The engine's raw-completion client decoded synchronously after the first token (forward, sample, host read, next forward), while the retired CLI generator and the server scheduler overlap step n+1's forward with step n's host read. `mlxcel generate`, the inference session, the decode bench and the parity harness's d:engine arm all run on this client, so single-stream decode lost that overlap.

DirectEngine now decodes on the lookahead pipeline through the engine's split step: each iteration submits the next forward fed by the still-unread device tokens, reads the current token and commits it with finish_rows. A finishing token (EOS, stop id, length, repetition loop) or a callback stop leaves one speculative append, which the teardown unwinds, so the stream and the sequence state equal the synchronous loop's. No forward is submitted after the token that spends the budget. Eligibility uses the scheduler's two rules, now shared: shared_fused_params (fused-eligible sampling only) and the new Engine::can_unwind_lookahead (trimmable state, or a model-owned family that rewinds its own). MLXCEL_FORCE_SYNC, probed once through the shared force_sync_requested, keeps every step synchronous; with_force_sync overrides it. Everything else falls back to the synchronous per-row chain. The scheduler's gate and its device feedback input now call the same helpers; its cross-tick state machine stays its own.

The raised command-buffer budget now wraps pipelined decode only, as in the scheduler. A zero budget (`-n 0`) returns before any forward from generate and generate_with_drafter, as the retired generator emitted nothing; the client had emitted the prefill's token. A needless-borrow clippy finding in the LanguageModel-by-reference test is fixed by naming the reference impl.

Tests: pipelined vs synchronous streams, callback deliveries, pool offset and KV length on the stub model at EOS, stop id, max_tokens and callback stop, token bias, a zero budget, and the fallbacks (history penalty, force sync, model-owned with and without a rewind).

Refs #2176
The retired prompt-lookup loop pipelined its rounds without a proposal once more than two had passed in a row, or at once while a gated governor was paused; waiting on each token before encoding the next step had cost 12 percent of decode time on an M4 Pro. The engine's drafter loop ran every plain round synchronously, so `--prompt-lookup` lost that on paused and no-match stretches.

DirectEngine::generate_with_drafter now pipelines those rounds on the same split step and teardown as generate's pipeline: the next one-token forward is submitted from the still-unread draw, and a finish or callback stop unwinds the forward submitted past it. A round that finds a proposal while a step is in flight reads that step and verifies from it synchronously on the next round, as the old loop did. The drafter decides when through two new Drafter defaults: pipelines_plain_rounds (prompt lookup keeps the old streak and paused-governor rule, with PLAIN_ROUNDS_BEFORE_PIPELINE restored) and retract_draft, which undoes the per-round accounting of a lookup no forward follows so the summary line still counts one round per forward. The loop now uses the shared DecodeState for its step rows. ADR 0009 and the MLXCEL_FORCE_SYNC row describe both pipelines.

Tests: on a stub model and a scripted drafter, pipelined vs synchronous rounds give the same stream, rounds, pool offset and KV length at length, stop id and callback finishes; a proposal during a pipelined run is retracted and verified next round; a drafter that does not ask stays synchronous.

Refs #2176
DirectEngine handed a model-owned family (Gemma 3/4, Llama 4, Qwen 3.5 and their VLM wrappers) its KV cache modes only after Engine::open, but open runs prepare_sequence_state, which builds the sequence's caches from the modes the model holds at that moment; the later set_kv_cache_layer_modes rebuilt only the fallback slot. The first sequence on a fresh model therefore decoded with Fp16 KV under --kv-cache-mode int8 or turbo4: generate --profile, the VLM --image path, bench_decode --warmup-tokens 0, the first MlxInferenceSession call and the first perplexity window. The plain generate path hid it because its one-token warmup set the modes for the measured run.

open_sequence now injects the model's modes before Engine::open and applies the pool modes after it, and loglikelihoods opens through open_sequence instead of its own copy of the old order. The KV-mode test records the modes the model held at each prepare_sequence_state and fails on the old order for both entries. ADR 0009 states the ordering.

Real check on gemma-3-1b-it-4bit, greedy, 200 tokens: before the fix, generate --profile printed the fp16 text under int8 and turbo4; after it, --profile int8 and turbo4 print the same text as the plain path's int8 and turbo4 runs, and fp16 is unchanged.

Refs #2176
- Metal trace: scripts/capture_moe_decode_trace.sh's default gputrace mode set the removed MLXCEL_CAPTURE_DECODE and wrote nothing. mlxcel-bench-decode now wraps its measured pass in MLXCEL_METAL_CAPTURE_PATH and the script uses it with -n 2 (prefill plus one warm decode token; -n 1 would capture no decode step).
- Env docs: MLXCEL_TRACE_DTYPE is still read by the fused Mamba2 C++ forward, so its row says that; the five variables nothing reads any more are one "removed in #2176" note instead of rows. CHANGELOG matches.
- [TTFT] is opt-in per client (DirectEngine::with_ttft_report), set by generate --profile and bench_decode's measured pass, so warmups no longer print a cold line.
- DirectEngine sets the pool entry's prompt_len and current_offset (prompt_len + 1) after the first token, as the scheduler does, in generate and in the drafter loop.
- SpeculativeGenerator carries #[deprecated] and a doc note naming removal in v0.8.0; the CLI call site, the re-export and its tests allow it.
- Stale references: the dead plan_single_sequence_prefill is removed, trim_state, the TTFT phase doc, gemma4 reset_caches and falcon_ocr name current callers, prompt_lookup.rs links resolve, ADR 0007 gains an amended-by note for its CxxGenerator arms, and the drafter loop's greedy claim states the multi-token verify caveat.
- nanochat overrides forward_last_logits_with_sequence_id so the engine prefill projects only the last row.
- New drafter test: scripted misses under Graded pause for 4 then 8 rounds and every paused round lands in paused_rounds.

Both clippy gates and the engine, session, speculative, drafter, prompt_lookup, models::gemma3, models::nanochat, engine_probe and commands test targets pass on CUDA.

Refs #2176
The engine client gated its B=1 lookahead pipeline on Engine::can_unwind_lookahead, so every model-owned family that does not rewind its own state (Gemma 4, Llama 4, Qwen 3.5, the SSM hybrids and most VLM wrappers, i.e. every family but Gemma 3) decoded `mlxcel generate`, the session and bench_decode on the synchronous chain, where the retired CxxGenerator pipelined every family.

The exact unwind only matters when the sequence outlives the decode. Every caller of DirectEngine::decode closes the sequence right after it, so such a family now pipelines with a Discard teardown: the one append past the finishing token is released by the close instead of unwound, and a failed submit that left an append in place ends the run with the submit's error rather than falling back to a synchronous loop over unrewound state. The scheduler and the drafter loop keep the exact rule.

Validated: mlxcel-core engine, speculative:: and drafter:: tests (419), root server::batch::scheduler and lookahead tests (188), workspace clippy -D warnings; gemma-4-e2b-it-4bit and granite-4.0-h-350m-4bit `generate --temp 0 -n 64` under MLXCEL_SDPA_DETERMINISTIC=1 print the same text pipelined and under MLXCEL_FORCE_SYNC=1.

Refs #2176
@inureyes

inureyes commented Oct 7, 2026

Copy link
Copy Markdown
Member Author

Security and performance review

Fixed in 3fbb13b (HIGH, performance): the B=1 pipeline was gated on Engine::can_unwind_lookahead, so every model-owned family without supports_decode_lookahead_rewind (Gemma 4, Llama 4, Qwen 3.5, the SSM hybrids, most VLM wrappers; everything but Gemma 3) ran mlxcel generate, the session and bench_decode on the synchronous chain, where CxxGenerator pipelined every family. Every caller of DirectEngine::decode closes the sequence right after it, so these families now pipeline with a discarding teardown (the append past the finishing token is released by the close) and a failed submit that left an append ends the run with the submit's error instead of a sync fallback over unrewound state. The scheduler and the drafter loop keep the exact rule. gemma-4-e2b-it-4bit and granite-4.0-h-350m-4bit print the same greedy text pipelined and under MLXCEL_FORCE_SYNC=1; core engine/speculative/drafter tests, scheduler and lookahead tests, and workspace clippy pass.

Not changed, for follow-up:

  • MEDIUM: history-penalty samplers (repetition, frequency/presence, DRY) now take the fully synchronous chain in generate; main's loop still submitted forward n+1 before reading token n. Any checkpoint whose generation config sets a penalty loses that overlap.
  • LOW: speculate and score_window index array_shape(&logits)[2] and targets[pos] with only a debug_assert; a model returning fewer dims or positions panics in release (same pattern as main).
  • LOW: speculate holds DecodeCommandBufferBudget across synchronous verify rounds, unlike the "pipelined only" rule elsewhere (Metal only).

Checked and clean: unwind counts on every finish, error and callback-stop path in direct_decode.rs and speculative_plain.rs; the scheduler gate refactor is equivalent (same rejections, MLXCEL_FORCE_SYNC probe unchanged); verify/commit_appends arithmetic (rejected = k - accepted never negative, budget capped at remaining - 1); no unsafe added; the &M impl forwards every trait method.

The drafter loop indexed `array_shape(&logits)[2]` and `targets[pos]` and the scoring window indexed `logits_shape[2]`, guarded only by `debug_assert`, so a model that returned logits of another rank or too few positions panicked in a release build. A new `logits_vocab` check returns a `DirectEngineError` on a rank, batch or position-count mismatch, and the batched argmax read is length-checked before it is indexed.

`speculate` no longer holds the raised command-buffer input budget for the whole run. It is entered when a pipelined plain round is submitted and dropped when the pipeline drains, so synchronous plain steps and verify blocks run under the default budget, matching `decode` and the scheduler's pipelined-only rule.

A verify block that ends on an EOS now commits only the positions before it. The synchronous step does not advance the pool offset for the EOS token, and the block advanced it by `accepted + 1`; the sequence closes right away so output is unchanged, but the offset invariant now matches.

Tests (engine test target, stub model): a short verify forward and a short scoring forward return an error for batched-argmax and sampled verification, `logits_vocab` accepts only `[1, >= n, vocab]`, and a stop id inside a verify block leaves the same offset, KV length and tokens as the synchronous steps. The budget scoping has no CUDA-observable effect (the override is Metal only) and is not unit tested.

Validation: cargo test --profile test-fast --features cuda -p mlxcel-core --lib engine (40 passed); speculative:: (161), drafter:: (223), session (12); clippy -D warnings on both gates; cargo fmt --check.

Refs #2176
ADR 0009's raw-completion section now names `Teardown::Unwind` and `Teardown::Discard`, lists exactly which requests take the synchronous chain (repetition, frequency and presence penalties, DRY, mask, override, per-token logprobs, mirostat, adaptive-p), states the KV-mode order on every open (inject into the model, open, apply to the pool), the per-client TTFT opt-in, the pipelined-only command-buffer budget, and the drafter loop's refusals, batched-argmax versus per-row verification, EOS offset rule and shape errors.

README gains a short note on `generate` as the raw-completion engine client, `--prompt-lookup` and the v0.8.0 removal of the classic draft-model path. CHANGELOG Unreleased now records the pipelined decode and `MLXCEL_FORCE_SYNC` scope, the prompt-lookup drafter and the removed `PromptLookupGenerator` and `CxxGenerator` exports, the `[TTFT]` phase change and the shared chat-template front. The speculative-acceptance table marks the classic loop deprecated. Two stale comments (`forward_last_logits` callers, `speculative_bench` baseline) name the engine client instead of the retired loops.

Validation: dead_doc_pointers, cli_help_consistency, vlm_wrapper_capability_delegation and model_loader_stdout_guard tests pass; insert_apache_header.py --check passes.

Refs #2176
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 7, 2026
@inureyes
inureyes merged commit 30ceea2 into main Oct 7, 2026
27 checks passed
@inureyes
inureyes deleted the refactor/issue-2176-generate-on-engine branch October 7, 2026 22:51
inureyes added a commit that referenced this pull request Oct 8, 2026
## Summary

End-of-run measurement for epic #2166 (ADR 0007's regression threshold and the speed questions the phases left open), on GB10 against two release builds: the pre-epic `CxxGenerator` build (4c44e31, PR #2194) and the final engine build (30ceea2, PR #2225). Adds `docs/benchmark_results/unified-engine-final-gb10-2026-10-08.md`, its raw records and drivers under `docs/benchmark_results/data/unified-engine-final-gb10-2026-10-08/`, and an index entry in `docs/benchmarks.md`. No code changes.

## Results

- `mlxcel generate` (the engine's `DirectEngine` client) decodes within the 1.0 percent threshold in every cell: +0.82 and +0.31 percent on Qwen3-1.7B (256 and 8192-token prompts), +0.51 and +0.19 percent on Llama-3.2-1B. TTFT at 256 tokens is about 1 ms higher (+4.4 percent unresolved on Qwen3, +9.0 percent on Llama).
- The server engine at B=1 with dense storage, the path `mlxcel run` and chat take since #2173, is 1.14 to 2.05 percent below the pre-epic CLI and misses the threshold in three of four cells. Phase 0 measured the same scheduler overhead before the epic, but `run` used `CxxGenerator` then, so `run` users see a 1 to 2 percent decode regression.
- The server's default single-stream configuration (paged at `--parallel 4`) decodes as before; its 8192-token TTFT dropped 19 percent (Qwen3) and 12 percent (Llama) with the 2048-token chunk.
- Batched serving: unchanged on Qwen3 defaults; Llama with Turbo4 KV is 16 and 18 percent higher at concurrency 4 and 8.
- Prefill chunk under live decode (four streams, one 8192-token admission, Llama): 2048 gives about 2.0 s admitted TTFT and 128 ms live-stream p95 ITL; 512 gives about 3.9 s and 56 ms. A policy trade, not a speed win.
- Gemma 3 paged vs dense under concurrency: dense 1 to 2 percent higher with overlapping ranges, unresolved; default unchanged.

## Test plan

- [x] Single-stream: `scripts/engine_bench_rounds.py`, 5 interleaved rounds with a null arm and the quiet-host gate, both builds through `pick.sh`, under the host `gpu-lock` with no other GPU work
- [x] Serving: `scripts/bench_serving_concurrency.py` and `scripts/bench_mixed_step_admission.py`, 3 alternating rounds per arm

Part of #2166
inureyes pushed a commit that referenced this pull request Oct 20, 2026
#2489)

## Summary

Fixes what is left of the two decode-path defects in #2177 after epic #2166 retired `CxxGenerator` (#2225), in the code that replaced it:

1. `Engine::prefill` now always evaluates an embedding (VLM) prefill's logits before running `LanguageModel::after_prefill`, instead of relying on every caller to set `PrefillStep::eval`. The hook may replace weight arrays the lazy prefill graph still references.
2. The remaining comments and docs that still describe `--no-batch` as bypassing the scheduler, or a "classic generator" speculative path, now match the unified engine.

## Related issues

Closes #2177

## Type of change

- [x] `fix` — bug fix

## Test plan

- [x] New `src/lib/mlxcel-core/src/engine/after_prefill_tests.rs` (stub model that records every forward and `after_prefill` call): `embedding_prefill_evaluates_its_logits_even_with_eval_off` fails on `main` (verified by reverting `prefill.rs`) and passes with the fix; plus text prefill keeps the eval deferred and skips the hook, both session embedding entry points (plain and `--profile`) run the hook exactly once between the prefill forward and the first decode forward with identical tokens, and text generation never runs the hook
- [x] `cargo test --profile test-fast -p mlxcel-core --lib` filters `after_prefill` (4), `engine::` (68), `session` (13), `generate` (52): all pass on both the CPU backend and Metal
- [x] `cargo clippy -p mlxcel-core --lib --tests -- -D warnings` and `cargo clippy -p mlxcel --lib --tests -- -D warnings` (Metal build): clean
- [x] `cargo fmt --all -- --check`
- [x] Validated with a real checkpoint on Metal (Apple M3 Pro): `mlx-community/Qwen2-VL-2B-Instruct-4bit`, `mlxcel generate --image <img> --temp 0 -n 64`, with and without `--profile`, fixed binary vs a baseline with `prefill.rs` from `main`: identical output text on two images in all four runs
- [ ] `make verify`, CUDA gate, server image path end to end: not run (the server's embedding prefill already passed `eval: true`, so its behavior does not change)

## Notes for reviewers

- The only behavioral line is `let eval = if step.eval || step.embeddings.is_some()`. Today all three embedding callers (`DirectEngine::prefill_embeddings` and the scheduler's `run_embedding_prefill`) already pass `eval: true` and no family overrides `after_prefill`, so output does not change; this moves the ordering guarantee into the one function that calls the hook.
- Text prefill is unchanged: the terminal piece's eval still waits for the first sample.
- Asserting eval-before-hook order directly would need a new FFI query for "is this array evaluated"; the tests instead observe that the eval happened and the call order, and the order is fixed structurally in `Engine::prefill`.
- Comment-only fixes: `docs/CONTINUOUS_BATCHING.md` (`--no-batch` runs the same scheduler at `max_batch_size=1`), `ServerConfig::no_batch`, `ModelProvider::new_with_server_config`, and `speculative_dispatch.rs` (now names `run_generation_mode`, drops stale CLI line numbers). `// Used by:` docs updated on `Engine::prefill`, `PrefillStep::eval` and `LanguageModel::after_prefill`.
- Not changed: the user-facing error string in `src/server/model_provider.rs` still says `--no-batch bypasses the batch scheduler`; the issue scoped this part to comments, so it is left for a follow-up.

## Checklist

- [x] PR title uses a Conventional Commits prefix
- [x] One logical change per PR
- [x] Updated `docs/`
- [x] Updated `// Used by: ...` comments on shared functions modified
- [x] No secrets, credentials, or `.env` files committed
inureyes added a commit that referenced this pull request Oct 22, 2026
…2542)

## Summary

The exaone-4.0 CLI decode loss after #2225 was a fixed per-call cost from stale state, not a slower engine step. ExaOne 4 cannot batch and keeps its KV caches inside the wrapper; its model-owned pool entry never calls `make_caches()`, so `DirectEngine` never reset them. `mlxcel generate`'s timed run prefilled the prompt on top of the one-token warmup's KV: the output was wrong, and the stale-offset prefill loaded about 290 ms (under nsys) of cuBLAS kernels (gdb on `cuLibraryLoadData`) inside the timed window.

`DirectEngine::open_sequence` now calls `make_caches()` when `supports_batching()` is false, the rule `BatchScheduler` applies at prefill time and the retired loop applied through `reset_with_model`. GPT-OSS, Ministral 3, Step 3.5, Mellum and Laguna hold their caches the same way. Server path unchanged.

**Behavior change:** `mlxcel generate` (and `loglikelihoods`, `MlxInferenceSession`) on these families now decodes from fresh caches, so its text changes: exaone4 greedy text now matches the d379d2f CxxGenerator build; gpt-oss-20b no longer opens with a different reply; laguna-xs-2.1-nvfp4 greedy text with a warmup now equals its `--profile` text without one (checked in review). `--prompt-lookup` refuses models that cannot batch, so it is unaffected.

## Measurement

GB10 sm_121, kernel 7.0.0-1019-nvidia, driver 580.178.04, `MLX_CUDA_ARCHITECTURES=121`, test-fast; ref d379d2f, main 8116e26, fix, null = fix binary again; rotated interleaving.

| model | ref | main | fix | null |
|---|---|---|---|---|
| exaone4-1.2b, -n 384, n=7 | 202.73 | 179.28 | 202.04 | 201.94 |
| llama-3.2-1b, -n 384, n=5 | 251.33 | 254.95 | 254.37 | 254.45 |
| granite-4.0-h-tiny, -n 256, n=7 | not in this block | 99.07 | 97.38 | 99.37 |

exaone fix vs ref paired -0.72% (-1.14..+0.82), null floor +0.11% (-1.48..+1.46). Fit `time = fixed + n * per_token`: main 302 ms + 4.85 ms/tok vs ref 70 ms + 4.77 ms/tok; fix 57 ms + 4.97 ms/tok vs ref 70 ms + 4.89 ms/tok in the same block. granite main vs fix +2.14% sits inside its null spread (+1.55% median, same binary). Full record: `docs/benchmark_results/exaone4-engine-decode-gb10-2026-10-22.md`.

## Test plan

- [x] New `engine::shared_cache_tests` (2): fail with the reset disabled, pass with it
- [x] `-p mlxcel-core --lib engine::` (70), `--lib exaone` (3), `granitemoehybrid` (17), `lfm2` (72), `--test-threads=1`, CUDA
- [x] `cargo clippy --profile test-fast --features cuda -p mlxcel-core --lib --tests -- -D warnings`, `cargo fmt --check`
- [x] Greedy `--show-reasoning -n 48` text: exaone4 fix == ref; granite-4.0-h and ministral-3b fix == main

## Unverified

- Step 3.5, Mellum and the `Ministral3` text wrapper on a real checkpoint (none local; ministral-3b-4bit loads as a `mistral3` VLM)
- Release-profile numbers; the issue's 198 vs 158 tok/s were release builds, these are test-fast
- No throughput measured for gpt-oss
- VLM `--image` prefill on a non-batching wrapper not exercised; it also goes through `open_sequence`, and the server applies the same reset before its embedding prefill

Closes #2494
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:benchmark Benchmark harness and performance measurement (bench_*.sh, /update-benchmarks) area:cli Command-line interface / CLI flags priority:medium Medium priority status:done Completed type:refactor Code restructuring without changing functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: run mlxcel generate on the engine and retire CxxGenerator

1 participant