Skip to content

update: pipeline penalty and DRY requests in the engine's B=1 client - #2256

Merged
inureyes merged 7 commits into
mainfrom
update/issue-2229-pipeline-penalty-rows
Oct 10, 2026
Merged

inureyes merged 7 commits into
mainfrom
update/issue-2229-pipeline-penalty-rows

Conversation

@inureyes

@inureyes inureyes commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

Summary

mlxcel generate requests with a repetition, frequency or presence penalty, DRY, mirostat, adaptive-p or the extended chain decoded on the engine's synchronous loop, leaving the device idle during every host read. They now decode on a per-row lookahead pipeline that keeps the next forward running while the current token is read and committed, as the retired CxxGenerator did.

  • Engine::submit_forward: the speculative forward of submit (both share speculative_forward and schedule, so submit is unchanged), scheduled lazily, no draw.
  • Engine::draw_row: one row's per-row-chain draw (RowSampler::draw_and_accept, token bias in its chain position), scheduled lazily; refuses rows with a mask, override or logprobs payload.
  • DirectEngine::decode_pipelined_rows (new direct_decode_rows.rs): submits the forward fed by the pending draw, waits on that draw through try_eval and reads it, commits it (pushing it to the history), then draws from the submitted logits. Same teardown and fallback rules as decode_pipelined.
  • Selection: fused pipeline unchanged; otherwise the per-row pipeline when the sequence can be unwound or discarded, MLXCEL_FORCE_SYNC is unset and the B9 pre-bias counters are off; otherwise decode_sync.
  • Overlap by sampler: penalties, DRY and the extended chain without adaptive-p keep the draw lazy, so the draw and the finish step both overlap the next forward. Mirostat and adaptive-p read their uniform draw on the host inside the sampler, so for them only the finish step overlaps.
  • mlxcel-bench-engine --repetition-penalty (default 1.0), wired through bench_sampling_config, which main and its test share.
  • ADR 0009, the module docs and the changelog record the new entries and the per-row pipeline.

The server scheduler's lookahead stays fused-only, and server-side prompt lookup is #2255.

Note on the issue's "inherited from generation_config.json" case: mlxcel generate inherits only EOS ids, temperature, top-k and top-p from that file (GenerationConfigDefaults), never a penalty, so no checkpoint reaches this path through it. Any penalty or DRY setting given by flag takes the per-row pipeline with no extra flag. Inheritance was left out because it would change output.

Changes during review

Test plan

All on GB10 under gpu-lock, --profile test-fast --features cuda, each CUDA test with -- --test-threads=1.

  • fmt; clippy -D warnings on --lib --tests --bins --examples and -p mlxcel-core --lib --tests; Apache header check; --test dead_doc_pointers, model_loader_stdout_guard, cli_help_consistency
  • mlxcel-core engine:: (46; new direct_decode_rows_tests.rs: token-for-token equality with the synchronous loop for repetition, frequency plus presence, DRY, DRY with a windowed penalty, seeded mirostat and seeded adaptive-p at EOS, budget and callback finishes; the path taken for a penalty request, which fails on main; model-owned teardowns; draw_row refusals), session, sampling, generate::, drafter::, speculative::, decode_finish
  • Root engine_probe, backend::, server::batch::scheduler, server::in_process, cli_input, commands::, mlxcel-bench-engine (12)
  • Real checkpoints, release build, MLXCEL_SDPA_DETERMINISTIC=1, 160 tokens, output identical with and without MLXCEL_FORCE_SYNC=1 in all 12 cases: Qwen3-1.7B (penalty, DRY, penalty plus DRY with --repeat-last-n 32, greedy; all with --show-reasoning, since without it every token goes to the hidden channel and the diff is empty), Llama-3.2-1B (penalty, DRY, seeded penalty at temperature 0.8), Gemma-3-1B, Gemma-4-E2B, Granite-4.0-H-350M and Qwen3.5-0.8B (the Teardown::Discard path), Hunyuan-1.8B (seeded penalty)
  • mlxcel-engine-parity -n 400 on Qwen3-1.7B, Llama-3.2-1B and Gemma-3-1B: the CLI arm equals server dense, server paged and the direct engine in every row, including seeded-penalties-DRY; only the server prompt-cache rows diverge, as before
  • Measurement: run at the end of the implementation run together with perf: offer prompt lookup on the server without slowing plain decode #2255

Closes #2229

Requests whose sampler the fused draw cannot run (repetition, frequency and presence penalties, DRY, mirostat, adaptive-p, the extended chain) decoded on the synchronous loop in DirectEngine, so the device sat idle during every host read. The retired CxxGenerator overlapped them by submitting the next forward fed by the still-unread token and building the next draw only after that token reached the history.

The engine gains submit_forward (the speculative forward of submit, factored out, without a draw) and draw_row (RowSampler::draw_and_accept for one row, scheduled lazily, refusing rows with a mask, override or logprobs payload). DirectEngine::decode_pipelined_rows drives them with decode_pipelined's loop shape and teardown rules, and decode picks it whenever the fused pipeline turns a request away but the sequence can be unwound or discarded, MLXCEL_FORCE_SYNC is unset and the B9 pre-bias counters are off.

Stub-model tests check token-for-token equality with the synchronous loop for every per-row sampler family at EOS, budget and callback finishes, the path taken for a penalty request, the model-owned teardowns and draw_row's refusals. ADR 0009 records the new entries.

Refs #2229
@inureyes inureyes added type:performance Performance improvements priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) status:in-progress Currently being worked on labels Oct 10, 2026
The #2229 measurement compares the CLI arm on a penalty request against the pre-epic baseline, which needs a way to put a history penalty into both arms' SamplingConfig. The flag defaults to 1.0 (off) and is applied to the neutral sampling parameters before the config is built, so the CLI arm decodes on the per-row lookahead pipeline and the server arm on the per-row sampler. A unit test checks the flag reaches the config and makes it read the token history.

Refs #2229
The Unreleased entry said penalty, DRY, mirostat and adaptive-p requests stay on the synchronous chain; after #2229 they pipeline the forward and match the synchronous output token for token. Also lists the new mlxcel-bench-engine --repetition-penalty flag.

Refs #2229
@inureyes inureyes added status:review Under review and removed status:in-progress Currently being worked on labels Oct 10, 2026
@inureyes
inureyes marked this pull request as ready for review October 10, 2026 12:53
The per-row lookahead pipeline read each pending draw with the infallible `ffi::item_i32`, a cxx entry without `Result`, so a backend error surfacing at that wait (for example an asynchronous CUDA fault) would abort the process instead of failing the run (#822). The synchronous step guards the same read with `try_eval` first.

The pipeline now calls `try_eval` on the pending draw before reading it. `try_eval` is the per-array `array::eval()` wait, which enqueues nothing behind the in-flight next forward, so the overlap is kept. On failure the read step's append and the next one are retired, as after a row error, and the run ends with the error.

Engine tests (`-p mlxcel-core --lib engine::`) and clippy pass.

Refs #2229
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Requests with a penalty, DRY, mirostat or adaptive-p decode on a per-row lookahead pipeline whose output matches decode_sync token for token.

Findings Addressed

Remaining Items

  • After a failed in-loop submit_forward or a failed draw schedule, the discarded draw has already been confirmed, so mirostat mu, adaptive-p and the seeded RNG advance twice when decode_sync redraws. This only happens after a backend error and follows the issue's fallback rule (LOW). Possible fix: commit pending and unwind only the failed submit
  • decode_pipelined, the scheduler's steady tick and speculative_plain still read through the infallible tokens_to_host. This is pre-existing; the same guard is a good follow-up (LOW)
  • Mirostat and adaptive-p read the draw on the host inside the chain, so for those two samplers only the finish step overlaps the forward (LOW, informational)
  • No test covers the failure and fallback paths because the stub models cannot make an eval throw (LOW)
  • The --repetition-penalty bench test rebuilds main's wiring by hand (LOW)

Verification

  • All stated requirements implemented (the measurement is still pending, as the issue plans)
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (engine tests: 46 pass. A mutation that draws before the commit fails the noisy-model parity test, so the stale-history failure is covered)

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance pass at ea1a45e: no fix commits needed. The per-row pipeline's error paths retire every speculative append (submit, draw, readback and row-error exits, finish and callback stops), the append scope and the command-buffer budget guard are RAII and released on every exit, sampler history is absorbed incrementally, and nothing in the new code indexes by user sampling parameters. The loop adds one host sync per token (the guarded try_eval + item_i32) and no history clones.

Open, all pre-existing and identical on decode_sync:

  • Mirostat and adaptive-p read the draw on the host inside the chain with infallible ffi::eval / item_f32 (sampling.rs:1437, 1495, 1522, 1570). On the per-row pipeline that read is the first wait on the in-flight forward, so a backend fault there still aborts (fix(server): catch MLX C++ aborts at the decode FFI boundary so a backend throw fails the request, not the process #822). Guarding only draw_row would move the abort into the decode_sync fallback, so the fix belongs in sampling.rs for both paths, in the planned follow-up with the tokens_to_host readbacks (direct_decode.rs:320, decode_tick.rs:596, speculative_plain.rs:87).
  • Full-history DRY (dry_penalty_last_n = -1) rebuilds a position map every step and its match scan is quadratic on a degenerate repeating stream; DRY and the rebuilt frequency/presence path allocate a vocab-sized buffer per step. The per-row pipeline now overlaps this host work with the next forward, so the PR improves it; a cap or an incremental DRY index is a separate issue if server exposure matters.

mlxcel-bench-engine built its sampling config inline in main, and the repetition-penalty test copied that wiring by hand, so a regression in main would not fail it. The wiring is now bench_sampling_config, which main and the test both call, and the test also checks that the default stays history-free.

Validation:
- cargo test --profile test-fast --features cuda --bin mlxcel-bench-engine -- --test-threads=1: 12 passed

Refs #2229
Mirostat and adaptive-p read the uniform draw on the host inside the sampler, so on the per-row pipeline only their finish step overlaps the next forward. Penalties, DRY and the extended chain without adaptive-p overlap the draw and the finish step fully. ADR 0009, the module docs of engine/direct.rs, direct_decode.rs and direct_decode_rows.rs, and the CHANGELOG Unreleased entry now state the difference instead of implying full pipelining for every listed sampler.

Validation:
- cargo clippy --profile test-fast --features cuda --lib --tests --bins --examples -- -D warnings: clean
- cargo test -p mlxcel-core --lib engine:: and --test dead_doc_pointers: pass

Refs #2229
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 10, 2026
@inureyes
inureyes merged commit d23e290 into main Oct 10, 2026
25 of 27 checks passed
@inureyes
inureyes deleted the update/issue-2229-pipeline-penalty-rows branch October 10, 2026 14:21
inureyes added a commit that referenced this pull request Oct 10, 2026
#2262)

## Summary

`mlxcel serve` / `mlxcel-server --draft-kind prompt-lookup` (no draft model) run prompt-lookup verify rounds per sequence inside the batch scheduler, at most one per tick, while ticks on which no row proposes stay on the lookahead pipeline exactly as without the flag.

- **Dispatch**: `SpeculativeDispatch::PromptLookup { config, max_batch }` resolves before the draft-model early return; a draft model with it is `InvalidKind`; `--draft-block-size` sets `max_draft`; `--spec-type none` drops it. `is_kind_specific()` stays false, so the burst path is never entered and the scheduler reads `prompt_lookup_config()`. New `--prompt-lookup-max-batch` on both server binaries, classified read-only in the runtime settings schema. `mlxcel generate --prompt-lookup` and its `--draft-kind` rejection are unchanged.
- **Shared round**: the verify round moved out of `DirectEngine::speculate` into `Engine::verify_round` (`engine/verify_round.rs`), with `Engine::verify_rounds_unsupported` as the one eligibility rule and `Engine::warm_up_verify_widths` as the one warmup; the CLI and the scheduler both run them. ADR 0009 amended.
- **Scheduler** (`scheduler/prompt_lookup.rs`): drafter on `SequenceInfo`, primed at prefill completion; proposing rows verify alone, the rest take the batched step. Switch rule: ask before the step n+1 prime; a proposal commits step n (through `try_eval`) with no prime, retracts the asks and makes the next tick synchronous; re-prime only when nobody proposed and every gated-in drafter `pipelines_plain_rounds()`. The module docs state invariants I1 to I8 (append ownership, admission, cancellation, errors), and each scheduler test pins one.
- **Gate**: a row verifies only while its governor grants a budget, the active batch is at most `--prompt-lookup-max-batch`, no unified KV budget is set, and the proposal fits under `max_tokens` and the context-bound stop. A gated-out row calls no `draft_block`, so its governor records no miss.
- **Warmup**: the first eligible prefill (normally the startup warmup request) runs one verify forward per block width and unwinds it, as the CLI does.
- Ineligible requests (multimodal, structured output, logprobs, feedback or extended sampler chains, state a trim cannot roll back such as Gemma 3's sliding-window cache) decode plainly with a `debug` log naming why.
- `scripts/bench_serving_concurrency.py --prompt-style plain|copy`.

## Provisional values for the end-of-run measurement

- `DEFAULT_PROMPT_LOOKUP_MAX_BATCH = 2` (`server/speculative_dispatch.rs`): one extra forward per proposing row at most doubles a step at B <= 2. Measurement (c) sets the final value.
- `PROMPT_LOOKUP_PAGED_CONTEXT_LIMIT = None` (`scheduler/prompt_lookup.rs`), no limit, pending measurement (d).

## Changes during review

- Review (2cd467a): server-side verify-width warmup (early requests paid each width's first-use kernel cost mid-decode); the n-gram index is built at the first lookup, so rows the gate declines no longer pay it at prefill.
- Security (a64431e): proposals capped at the context bound (a prompt ending just under `--max-kv-size` could make a verify forward append up to 63 positions the stop then discarded); the same bound in the warmup; an unchecked slice in the ask path replaced, since a scheduler panic stops all serving.
- Finalizer (953b03b): scheduler tests for a stop token inside an accepted block and a cancel during a round.
- Local CUDA gate (9f5b5a8): `prompt_lookup_max_batch` classified in the runtime settings schema (`server_config_schema_classifies_all_112_fields`).

## Test plan

All on GB10 under `gpu-lock`, `--profile test-fast --features cuda`, each CUDA test with `-- --test-threads=1`.

- [x] New: `speculative_dispatch_tests` (5), `engine::verify_round_tests` (3), `scheduler_prompt_lookup_tests` (11, a cycle-model dense Llama, KV offset checked against committed tokens after every tick; `proposal_free_ticks_stay_pipelined` fails on main)
- [x] fmt; clippy `-D warnings` (root and mlxcel-core); mlxcel-core `engine::`, `speculative::`, `drafter::`, `session`, `sampling`, `generate::`; root `server::batch`, `server::speculative_dispatch`, `server::in_process`, `server::runtime_settings`, `engine_probe`, `backend::`, `cli_input`, `commands::`, `mlxcel-server` bin; `cli_help_consistency`, `dead_doc_pointers`, `model_loader_stdout_guard`
- [x] `make verify-test-cuda`: 13,868 passed; the only failures are the pre-existing SSM bf16 parity tests (#2230) and the schema test fixed in 9f5b5a8
- [x] `mlxcel generate --prompt-lookup` on Llama-3.2-1B, greedy, 160 tokens: identical to the build before this PR
- [x] Server pairs, release build, `MLXCEL_SDPA_DETERMINISTIC=1`, `/completion` greedy, flag on vs off: Qwen3-1.7B at 140 tokens (auto, dense, paged) and Llama-3.2-1B at 160 tokens (auto, paged) identical for copy and plain prompts, concurrent copy + plain equal their solo outputs, `draft_kind` prompt-lookup with `draft_n_accepted > 0`; `mlxcel serve` identical; Gemma-3-1B identical with prompt lookup declined (non-trimmable sliding-window cache, as on the CLI). At 160 tokens the Qwen3 copy reply diverges once at about token 150 on an exact tie (top two logprobs both -1.625 on the flag-off server)
- [x] `mlxcel-engine-parity -n 400` on Qwen3-1.7B and Llama-3.2-1B: unchanged from #2256
- [ ] Speed (a) to (d): measured after merge together with #2229; results and the final constants land in a follow-up docs PR

Closes #2255
inureyes added a commit that referenced this pull request Oct 10, 2026
## Summary

End-of-run measurement for #2229 (PR #2256) and #2255 (PR #2262) on GB10, and the two values #2255 left provisional, now set from it. Report: `docs/benchmark_results/server-prompt-lookup-gb10-2026-10-11.md`; drivers, raw output and analysis script under `docs/benchmark_results/data/server-prompt-lookup-gb10-2026-10-11/`.

- `PROMPT_LOOKUP_PAGED_CONTEXT_LIMIT`: `None` to `Some(4096)`. A paged sequence stops running verify rounds past 4096 tokens of context and decodes plainly.
- `DEFAULT_PROMPT_LOOKUP_MAX_BATCH`: stays 2; the doc comment and the `--prompt-lookup-max-batch` help now cite the measurement instead of calling it provisional.
- `docs/CONTINUOUS_BATCHING.md` and the CHANGELOG entry state the measured gains and the cost on low-copy chat, and point to #2264.

## Results

**#2229, penalty requests on the CLI path** (`--repetition-penalty 1.1`, 5 rounds with a null arm): against main before #2229 the engine client now decodes 23 % (Qwen3-1.7B, 256 tokens), 16 % (Qwen3, 8192), 31 % (Llama-3.2-1B, 256) and 23 % (Llama, 8192) faster, every round above every round. Against the pre-epic `CxxGenerator` (`4c44e317`) it is equal on Qwen3 at 256 tokens (inside the null range) and 1.5 to 2.7 % faster in the other three cells.

**#2255, server prompt lookup** (Qwen3-1.7B, 256 tokens):

| Criterion | Result |
|---|---|
| (a) plain chat, B=1, flag on vs off, no worse than -1.0 % | **Not met.** -3.49 % (-3.73..-3.22) over 8 chat-template questions x 5 rounds, 25 to 45 % of proposed tokens accepted. Tracked in #2264. |
| (b) copy-heavy, B=1 | +53 to +67 %, 4.2 tokens per verify |
| (c) concurrency 4 and 8, default gate | on matches off in every workload; a gate of 8 loses 13 % on the chat-template copy workload at concurrency 4, so the default stays 2 |
| (d) paged, long prompts | on / off ratio for copy and open question: 2.69x / 1.27x at 1024, 2.79x / 1.64x at 2048, 1.42x / 1.12x at 4096, 1.15x / 0.62x at 8192; dense at 8192: 2.10x / 0.99x |

The flag is opt-in, so decode without it is unchanged.

## Test plan

- [x] clippy `--profile test-fast --features cuda --lib --tests --bins -D warnings`
- [x] `--lib server::batch` (526), `server::speculative_dispatch` (17), `--test cli_help_consistency` (27), `--test dead_doc_pointers`, Apache header check, all under `gpu-lock` with `--test-threads=1`
- [ ] `scripts/ci/check_binary_assets.py` fails on main's two undeclared tarballs from #2250 (`docs/benchmark_results/data/rocm-unified-engine-gfx1151-2026-10-08/`); this PR adds no binary file

Refs #2229, #2255, #2264
inureyes added a commit that referenced this pull request Oct 11, 2026
A full-history DRY step previously rescanned repeated suffixes quadratically, and checking every position against request-supplied breaker lists could multiply window length by breaker configuration size. This change computes suffix matches with reverse Z and breaker starts with a reversed-token Aho-Corasick matcher, bounding expected host work to `O(N + P)` for history length `N` and configured breaker-pattern tokens `P`.

DRY and rebuilt frequency/presence penalties now scatter only touched token IDs instead of constructing vocabulary-sized host buffers. The sparse paths preserve the pinned MLX backend semantics: CUDA bf16 mixed arithmetic remains bf16 on rebuild paths, while the pre-existing incremental frequency/presence path still explicitly promotes to f32.

Quiet GB10 host matching and lazy MLX graph-construction timing used vocabulary 4, a period-3 history, and no breakers. Reference iterations were 3/3/1 and new-path iterations were 20/20/20. Returned arrays were not evaluated, so these figures are not GPU end-to-end latency:

| Window | Reference µs/step | New µs/step | Speedup |
|---:|---:|---:|---:|
| 1,024 | 619.751 | 23.607 | 26.25× |
| 4,096 | 4889.370 | 29.997 | 163.00× |
| 16,384 | 77199.293 | 111.433 | 692.79× |

Validation on CUDA GB10:

- Core build and clippy passed; `cargo fmt --check` passed.
- Sampling suite: 210 passed, 1 ignored timing test.
- Engine suite: 63 passed.
- 512 deterministic DRY parity cases, direct breaker-position parity, f32/f16/bf16 penalty parity, and adversarial linear-work bounds passed.
- Independent implementation and security reviews reported no findings.

Timing evidence: `docs/benchmark_results/dry-penalty-step-cost-gb10-2026-10-11.md` and its linked raw package.

Closes #2259

Refs #2229, #2256
@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:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:medium Medium priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: pipeline penalty and DRY requests in the engine's B=1 client

1 participant