Skip to content

refactor: one per-row sampling step and token-bias composition - #2204

Merged
inureyes merged 7 commits into
mainfrom
refactor/issue-2169-row-sampler
Oct 7, 2026
Merged

inureyes merged 7 commits into
mainfrom
refactor/issue-2169-row-sampler

Conversation

@inureyes

@inureyes inureyes commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

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's SamplerState, created once at construction when needs_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 optional LogitMask runs before the chain, and resolve(sampled, override) returns (sampled, final) and confirms final to the feedback state. The existing chain functions are called; no stage is copied.
  • All four CxxGenerator loops (sample_next_step included) and the three server sites (execute_batched_decode per-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, and finish_prefill now follows the same creation rule instead of gating on needs_sampler_feedback_state() alone.
  • Because the state is now created eagerly, SamplerState::for_config maintains 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_eligible is derived from a SamplerStage list through exhaustive matches and keeps the lang-bias counters rule through lang_bias_counters::enabled(). config_supports_fused_batch_except_bias and row_supports_fused_batch_except_bias are 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 +inf or 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_eos stays 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 generate has no per-request logit_bias or ignore_eos; CxxGenerator::compose_sampling still lets a non-empty per-call bias replace the generator's composed map (only the parity harness's ignore_eos arm does that today); the pipeline-parallel path applies no output suppression because it loads no LoadedModel.

Behavior notes

  • finish_prefill: the structured mask now runs inside the draw, after seed_rng_if_needed, so a row whose mask fails reseeds the global RNG before aborting. Only unseeded streams are affected.
  • speculative/prompt_lookup.rs still calls the chain directly; out of scope.
  • The branch merges current 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

  • New tests: CLI loops and the server row step give identical streams for greedy, seeded full and windowed penalties, DRY, logit_bias, mirostat v2 and adaptive-p; the CLI carries mirostat state across steps (fails on the old code, which restarted mu every token); fused_eligible is 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.
  • mlxcel-core filters sampling (200), generate (61), decode_finish (9); root server::batch (508) and sampling (54); check, clippy -D warnings and fmt clean.
  • Real checkpoints (qwen3-1.7b-4bit, llama-3.2-1b-instruct-4bit) after the merge: CLI greedy, seeded, lang-bias and windowed-penalty output byte-identical to main 4c44e31 (10/10); mlxcel-engine-parity --no-prompt-cache-case --expect-identical 6/6 identical on both models, paged rows on the paged kernel.
  • Performance is measured once at the end of the epic run, not in this PR.

Closes #2169

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
@inureyes inureyes added status:review Under review type:refactor Code restructuring without changing functionality priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Oct 7, 2026
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
@inureyes

inureyes commented Oct 7, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

One per-row sampling step (RowSampler) and one token-bias composition used by the four CLI loops and the three server sampling sites, behaviour-preserving apart from the CLI now carrying mirostat and adaptive-p state.

Findings Addressed

  • RowSampler::new creates SamplerState for windowed penalty configs (penalty_last_n > 0, the server's default repeat_last_n is 64), and the state then absorbed the prompt and every token into aggregates the windowed path never reads. Before this PR that state was created lazily only for the full-history window. SamplerState::for_config now tracks the aggregates only for penalty_last_n < 0, and a new unit test pins it (HIGH, 8d37d03)

Remaining Items

  • The CLI-vs-server identity test drives a hand-written copy of the server row step rather than BatchScheduler itself. The engine-parity harness covers the real scheduler, so this is left as is (MEDIUM)
  • When the mask rejects every token, finish_prefill now reseeds the global RNG before it aborts the row. Only unseeded streams are affected, and the PR body already says so (LOW)
  • accept_drawn reads SamplerState::adaptive.pending directly, and the "Used by" lines on sample_token_optimized_with_state and sample_token_with_state_and_distribution still name the old callers (LOW)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow (CLI loops, execute_batched_decode, decode_single_step, finish_prefill, all SequenceInfo constructors)
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes (finish logic untouched)
  • Tests pass: mlxcel-core filters sampler_state sampling_row_step sampling_token_bias fused penalty (124) and sampling generate:: (238), check, clippy -D warnings. CLI output on qwen3-1.7b-4bit and llama-3.2-1b-instruct-4bit is byte-identical to main for greedy, seeded and lang-bias runs (6/6) and for four new windowed-penalty runs (4/4)

@inureyes

inureyes commented Oct 7, 2026

Copy link
Copy Markdown
Member Author

Security and Performance Review

No CRITICAL or HIGH findings at 8d37d03, so no fix commits.

Checked and clean

  • Output suppression cannot be bypassed by request bias. compose_token_bias runs suppress_tokens last, which overwrites the entry with -inf (an insert, not an add), so a request +inf, NaN, or +inf/-inf pair that accumulates to NaN on a suppressed id still ends at -inf. The fused path folds the same seq.sampling.token_bias map, and ignore_eos suppression after composition is idempotent.
  • Hot path: the greedy and no-history CLI step calls sample_token_optimized_with_state with None state, which ensure_sampler_state leaves None, so it runs the same core as sample_token_optimized. It adds no allocation and no host read, and accept_drawn returns early. The server per-row and single-step sites drop one copy per row on the unmasked path. Mirostat and adaptive-p already did their host reads inside the chain whether or not state existed, so carrying state on the CLI adds no sync.
  • An empty bias map stays empty end to end (mem::take plus a moved empty map, no allocation). The language map is cloned only once per request when it applies, which matches main.
  • SamplerState is bounded by the number of distinct tokens. Windowed and DRY-only configs only advance absorbed_len.
  • fused_eligible matches the old gate on every axis (the exhaustive oracle test covers this). The one difference is a NaN xtc_probability, and that is consistent because neither the per-row chain nor the fused dispatch applies XTC then. The new code adds no unwrap or index on request data.

Remaining (LOW, not fixed)

  • run_generation_mode clones the --lang-bias map once per CLI run where it used to suppress in place. This happens once, outside the decode loop.
  • Pre-existing: native logit_bias maps 1e39 to +inf (n as f32), and accumulate can produce NaN on a non-suppressed id, which can poison a stochastic row. Worth a separate sanitizing issue.
  • Pre-existing: the handoff prefill intake and the CLI pipeline path skip compose_token_bias. Both are text-only, so their suppressed sets are empty.
  • The PR now conflicts with main in src/lib/mlxcel-core/src/generate.rs after refactor: one post-sample finish step for every CLI and server decode site #2201. decode_tick.rs and prefill.rs auto-merge cleanly.

Verification

check and clippy -D warnings (lib, tests, bins) are clean. mlxcel-core filters sampling_row_step (7), sampling_token_bias (4), config_supports_fused (5) and sampler_state (6) pass under gpu-lock.

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
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 7, 2026
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.
@inureyes
inureyes merged commit 5976af8 into main Oct 7, 2026
49 of 51 checks passed
@inureyes
inureyes deleted the refactor/issue-2169-row-sampler branch October 7, 2026 09:52
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
@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:high High 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: one per-row sampling step and sampler-state lifecycle

1 participant