Repository navigation
refactor: one per-row sampling step and token-bias composition - #2204
Merged
Merged
Conversation
The CLI and the server each owned a per-row sampling step and the copies drifted: the CLI created SamplerState only for history-reading samplers, so mirostat and adaptive-p lost their feedback state between tokens, and token-bias precedence was composed separately on each side. RowSampler (mlxcel-core sampling_row_step) now owns one sequence's step: state creation once at construction (needs_token_history or needs_sampler_feedback_state), the #2090 history-ordering rule exposed as needs_host_token_before_sample, a LogitMask hook before the chain, and resolve() applying a post-draw override and confirming the final token. The four CxxGenerator loops, execute_batched_decode's per-row loop, decode_single_step and finish_prefill all draw through it. Fused eligibility is derived from the step's SamplerStage list; config_supports_fused_batch_except_bias and row_supports_fused_batch_except_bias delegate to RowSampler::fused_eligible. compose_token_bias (sampling_token_bias) is the one precedence rule for request bias, language bias and output suppression, called once per request by the CLI and by enqueue_request. Validated with the mlxcel-core sampling and server::batch test suites, byte-identical CLI output on qwen3-1.7b-4bit and llama-3.2-1b-instruct-4bit, and engine parity 6/6 identical on both. Refs #2169
5 of 6 tasks
RowSampler creates a SamplerState for every history-reading config, including a positive penalty_last_n window. Before #2169 the server and CLI created the state lazily only for the full-history window, so a windowed repetition, frequency or presence penalty (the server's default repeat_last_n is 64) never maintained the sorted seen set or the count map. With the eager state those aggregates absorbed the whole prompt on the first draw and every token after it, although preprocess_penalty_stages never reads them when the window is positive or zero. SamplerState::for_config now tracks the aggregates only for penalty_last_n < 0. Token streams are unchanged, because the windowed path always rebuilds over its slice; a new unit test pins that a windowed or zero-window state absorbs nothing. Validated with the mlxcel-core sampler_state, sampling_row_step, sampling, generate and fused test filters, check and clippy with -D warnings. Refs #2169
Member
Author
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
Member
Author
Security and Performance ReviewNo CRITICAL or HIGH findings at 8d37d03, so no fix commits. Checked and clean
Remaining (LOW, not fixed)
Verificationcheck and clippy |
Brings in #2201 (one post-sample finish step, sibling #2168). The only conflict was the generate.rs import block: #2201 dropped detect_repetition_loop and this branch replaced SamplerState and sample_token_optimized_with_state with RowSampler, so the merged imports keep LoopDetectionConfig, TokenBiasMap, sample_token_optimized and RowSampler. The new finish_step_tests.rs SequenceInfo literal now builds `sampler: Default::default()` in place of the removed `sampler_state` field.
compose_token_bias applies output suppression last, so a suppressed id must stay at -inf whatever the request or language bias says. The existing test only covered finite biases. The new test checks a request bias of +inf, NaN, and an +inf/-inf pair that accumulates to NaN, plus a +inf language bias, and asserts the suppressed id is -inf in every case. Validation: - cargo test --profile test-fast --features cuda -p mlxcel-core --lib sampling_token_bias: 5 passed Refs #2169
The "Used by" lines on sample_token_optimized_with_state and sample_token_with_state_and_distribution still named BatchScheduler and CxxGenerator as direct callers; they now name RowSampler and the prompt-lookup loop. RowSampler::accept_drawn no longer reaches into SamplerState's adaptive-p pending pair: the new SamplerState::accept_pending_token does the same accept_token call, so behavior is unchanged. In the batch scheduler module, `use run_loop::StructuredMask` moves next to the other local `use pad_trim::...` import instead of sitting between mod declarations. Validation: - cargo check and clippy -D warnings (root lib/tests/bins and mlxcel-core lib/tests) clean - mlxcel-core lib tests for sampling, generate, decode_finish, sampler_state, and root lib tests for server::batch and sampling pass Refs #2169
Brings in #2205 (one prefill plan and one trim hook). The only conflict was the import block in generate.rs (prefill_plan alongside RowSampler, the replaced sampler-state import dropped). Post-merge clippy, the sampling, finish-step and prefill-plan test modules, and the real-checkpoint parity runs match the baseline.
5 of 6 tasks
inureyes
added a commit
that referenced
this pull request
Oct 7, 2026
## Summary Epic #2166 Phase 4a ([ADR 0008](docs/adr/0008-kv-attention-dispatch-in-the-cache.md), amending ADR 0007): the choice between dense and paged attention moves from each model forward into the KV cache. A model calls one entry; the storage behind the cache picks the kernel. - `KVCache::attend(q, k, v, scale, mask)` and `cache::attend_batched(q, k, v, caches, scale, mask)` (new `src/lib/mlxcel-core/src/cache/attend.rs`) append the step's K/V and dispatch on the cache's own fields: - pool-backed cache, single unmasked token: the #899 pooled paged entry, which decides whether to decline before it writes anything; - pool-backed cache otherwise: the pool intercept plus SDPA; - dense Turbo4Asym / Turbo4 / Turbo4Delegated: the dequant-first SDPA variants the mode and its env gates already select (ADR 0002); - dense FP16 / Int8: dense update plus fused SDPA (causal when unmasked). - A masked step (prefill, speculative or MTP verify) never takes the paged single-token kernel. Dispatch is a match, not a trait object per layer per token (ADR 0004). `attend_batched` keys the pooled launch on `caches[0].is_paged_backed()` instead of `DecodeBatchContext`, so callers that pass no context (lookahead prime, `forward_batched`) also reach the fused launch at single-token steps. - Qwen3 and Llama 3, and the families that reuse their attention (Qwen2, Qwen2.5, Helium, the VLM text backbones), call the entry and no longer read `is_paged_backed()` or `DecodeBatchContext`. Their batched forwards drop the context parameter. - `MlaLatentCache::attend` owns the absorbed MLA decode policy (split-KV when `split_kv_enabled()` and the plan accepts, else `absorbed_decode`). DeepSeek V2's single-token absorbed decode calls it; prefill stays in the model because it needs `kv_b_proj`. - Storage is decided once per sequence where `CachePool::allocate_with_layout` builds the cache. The server's `--decode-storage-backend` policy is unchanged. A lone sequence is dense wherever the worker runs at `max_batch_size=1` (the CLI path from Phase 5 on), which is the ADR 0007 measured default; migrating a sequence between storages as the batch grows is out of scope. - Deferred to Phase 4b (#2172, scope comment posted there): Gemma 3, Llama 4 and the `model_owned` helpers still read `DecodeBatchContext` and keep their dense-pointer paged kernels; qwen3_5, qwen3_moe and muse_glimmer take a context argument they ignore. `rg 'is_paged_backed\(\)|is_paged_decode\(\)' src/models` now finds only `gemma3.rs` and `model_owned.rs`. ## Numeric changes Same attention, different op order, not bit-identical to the old routes: - **FP16 boundary layers under a non-FP16 paged layout.** The dense-pointer route `paged_decode_attention_dense_compat` is removed from the Qwen3 and Llama 3 batched forwards. It only served the FP16 layers a non-FP16 paged layout keeps dense: the Turbo Boundary-V layers (`MLXCEL_KV_BOUNDARY_V_LAYERS`, two at each end by default) and the last layer `--kv-skip-last-layer` (default on) keeps under `--kv-bits`. Those layers now run per-row dense update plus SDPA. The removed C++ entry was itself a per-row loop of block slices, a concat and SDPA, so this drops the concat copy. It also removes the `*const MlxArray` pointer vectors the route built. - **Batched Turbo rows.** Rows the pooled launch declines go through `attend`, so batched Turbo decode takes the dequant-first variants single-sequence decode already used, instead of a full dequant per step. Batched rows now match single-sequence decode bit for bit (pinned by a test). FP16 dense and pool-backed routes run the same ops as before. ## Changes during review - **Review, HIGH (c22e08b):** `MlaLatentCache::attend` existed but no production code called it. DeepSeek V2's absorbed decode now goes through it with the same calls and arguments. - **Review, MEDIUM:** the first version of this PR called the dense-compat route unreachable for Qwen3 and Llama 3. It was reachable through the FP16 boundary layers above; ADR 0008 and this description now say so. - **Tests added:** batched Turbo4Asym rows bit-identical to the single-sequence dequant-first call and within relative RMS 1e-2 of the old full-dequant route; `attend_batched` on an empty batch (panics, as the old `remove(0)` did), a one-row dense batch (bit-identical to `attend`), a one-row pool-backed batch with no context (one pooled launch), and a mixed pool-backed plus dense batch in both orders (the pooled entry declines before writing; each row matches `attend` on its own storage). - **Security review:** no CRITICAL or HIGH. The decline path, where each pool-backed row retries after a refused batch, was kept: a per-row variant that skipped the pooled attempt would fall back to the slower gather path. - **Docs:** `docs/CONTINUOUS_BATCHING.md` gains "Where the dense-versus-paged choice lives"; `docs/turbo-kv-cache.md`, `docs/environment-variables.md` (`use_native_paged_kernel` now only governs the model-owned families) and `docs/architecture.md` updated; ADR 0008 is listed in `docs/adr/README.md`. - **Merge from `main`:** #2204 (row sampler) merged cleanly. ## Test plan - [x] `cargo fmt --all -- --check`; `cargo clippy --profile test-fast --features cuda --lib --tests --bins -- -D warnings` and the same for `-p mlxcel-core --lib --tests` - [x] mlxcel-core, `--test-threads=1`: `cache::attend` (11), `mla::` (42), `cache::paged_batch_decode`, `cache::decode_undo`, `cache::paged_detach` (40), `sampling` (200), `generate::`, `prefill`, `decode_finish` - [x] Root crate, one module at a time after merging `main`: `models::qwen3::`, `models::llama3::`, `models::helium`, `models::deepseek_v2`, `server::batch::scheduler::tests` (94), `scheduler_prompt_cache_tests` (31), `scheduler_prompt_cache_plan_tests`, `scheduler_model_owned` (12, serialized 6 of 6), `finish_step_tests`, `speculative_burst_tests`, `distributed::disaggregated` (189), `server::batch::sequence`, `prefill_span_coverage`, `cli_input` (146) - [x] `--test vlm_wrapper_capability_delegation`, `--test dead_doc_pointers`, `scripts/insert_apache_header.py --check` - [x] Real checkpoints, release `mlxcel-engine-parity` under `MLXCEL_SDPA_DETERMINISTIC=1` on qwen3-1.7b-4bit and llama-3.2-1b-instruct-4bit, before, after, and after merging `main`: CLI vs server dense vs server paged identical on both; the only divergences are the documented prompt-cache-hit pairs, unchanged from the baseline (Qwen3 8 of 10 identical, Llama 9 of 10) - [ ] Throughput, including one Turbo paged batch: measured by the epic run at the end on a quiet host Closes #2171
9 of 14 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Phase 2 of #2166 (ADR 0007, "Sampling step"): one per-row sampling step and one token-bias composition, shared by the CLI and the server.
RowSampler(mlxcel-core/src/sampling_row_step.rs) owns a sequence'sSamplerState, created once at construction whenneeds_token_history() || needs_sampler_feedback_state().needs_host_token_before_sample()is true only for history-reading samplers, so the CLI pipeline gains no host sync on the greedy, plain-stochastic or feedback-only paths. An optionalLogitMaskruns before the chain, andresolve(sampled, override)returns(sampled, final)and confirmsfinalto the feedback state. The existing chain functions are called; no stage is copied.CxxGeneratorloops (sample_next_stepincluded) and the three server sites (execute_batched_decodeper-row loop,decode_single_step,finish_prefill) draw through it. This fixes the latent CLI bug where mirostat and adaptive-p state was dropped between tokens, andfinish_prefillnow follows the same creation rule instead of gating onneeds_sampler_feedback_state()alone.SamplerState::for_configmaintains the penalty aggregates (seen set, count map) only for the full-history window (penalty_last_n < 0). A positive window, such as the server default of 64, rebuilds over its slice and never reads them, so it no longer absorbs the prompt and every token into them.RowSampler::fused_eligibleis derived from aSamplerStagelist through exhaustive matches and keeps the lang-bias counters rule throughlang_bias_counters::enabled().config_supports_fused_batch_except_biasandrow_supports_fused_batch_except_biasare thin delegates.compose_token_bias(request, language, output_suppression)(sampling_token_bias.rs) holds the precedence, documented in its module doc: request bias (additive; on the server it starts from the live-settings bias), language bias only when the request map is empty, and output suppression last, always-inf(an overwrite, so+infor NaN request biases cannot lift a suppressed id).enqueue_request,run_generation_mode, the chat REPL and the CLI pipeline path each call it once per request.ignore_eosstays a separate suppression right after composition because its EOS set depends on the request's stop tokens; suppression is idempotent, so it still wins.CLI vs server bias order
The merge order for the sources the CLI has is unchanged (language bias, then suppression). Remaining CLI-only differences:
mlxcel generatehas no per-requestlogit_biasorignore_eos;CxxGenerator::compose_samplingstill lets a non-empty per-call bias replace the generator's composed map (only the parity harness'signore_eosarm does that today); the pipeline-parallel path applies no output suppression because it loads noLoadedModel.Behavior notes
finish_prefill: the structured mask now runs inside the draw, afterseed_rng_if_needed, so a row whose mask fails reseeds the global RNG before aborting. Only unseeded streams are affected.speculative/prompt_lookup.rsstill calls the chain directly; out of scope.main, including refactor: one post-sample finish step for every CLI and server decode site #2201 (one post-sample finish step); the finish logic is untouched here.Validation
logit_bias, mirostat v2 and adaptive-p; the CLI carries mirostat state across steps (fails on the old code, which restartedmuevery token);fused_eligibleis false for every per-row stage and for a biased row with counters on, and equals the old gate over a 4608-config grid; windowed states skip the aggregates; suppression beats non-finite request bias.sampling(200),generate(61),decode_finish(9); rootserver::batch(508) andsampling(54); check, clippy-D warningsand fmt clean.mlxcel-engine-parity --no-prompt-cache-case --expect-identical6/6 identical on both models, paged rows on the paged kernel.Closes #2169