Skip to content

perf(server): Keep token-biased requests on the lookahead decode pipeline #1950

Closed

Description

@inureyes

Problem / Background

mlxcel-server implements ignore_eos as a -inf token bias on the EOG ids (src/server/config.rs:157, applied at admission in src/server/batch/scheduler/admission.rs:275-277, the same mechanism b10621 --ignore-eos uses), and logit_bias lands in the same per-sequence TokenBiasMap (src/server/batch/scheduler/admission.rs:215-220). Any request that carries a non-empty bias is therefore rejected by the batched-fused gate and, through it, by the lookahead decode pipeline, so it decodes on the synchronous path.

Measured 2026-09-23 on an M1 Ultra 128 GB, macOS 27, mlx-community/c4ai-command-r7b-12-2024-4bit, server /completion, 512-token prompt, 128 generated tokens, greedy, cache_prompt: false, after warmup requests, machine quiesced with scripts/with_indexers_paused.sh: without ignore_eos the server reports 111.0 to 113.3 tok/s (predicted_per_second) and mlxcel_batch_decode_lookahead_steps_total advances by 125 per request; with ignore_eos: true it reports 97.0 to 97.4 tok/s and the lookahead counter advances by 0. That is a 13% loss on every biased request.

It also skews server benchmark methodology, because ignore_eos is the usual way to make a server request generate an exact token count: any server decode measurement taken that way reports the synchronous path rather than the shipped default path, and is not comparable with one taken without it. This is a batch-scheduler path only; mlxcel generate samples through sample_token_optimized (src/lib/mlxcel-core/src/sampling.rs:662), which applies the bias in-graph, so the CLI is unaffected.

Current Behavior

The lookahead gate is BatchScheduler::lookahead_params (src/server/batch/scheduler/decode_tick.rs:341), which reuses BatchScheduler::batched_decode_fused_params (src/server/batch/scheduler/decode_tick.rs:1110), which calls mlxcel_core::sampling::row_supports_fused_batch (src/lib/mlxcel-core/src/sampling.rs:970) at src/server/batch/scheduler/decode_tick.rs:1119. That predicate delegates to config_supports_fused_batch (src/lib/mlxcel-core/src/sampling.rs:942), which requires config.token_bias.is_empty().

The rejection reason is an input-shape limitation, not sampler state: the fused [B, vocab] -> [B] dispatch (ffi::fused_sample via batched_fused_sample, src/lib/mlxcel-core/src/sampling.rs:1000) takes only shared scalar params (FusedSampleParams) and has no per-row bias input. Unlike a repetition, frequency, presence or DRY penalty, a token bias does not read the tokens generated so far, so it is a static additive edit that can be folded into the logits before the fused dispatch. The per-row sampler already does exactly that, at src/lib/mlxcel-core/src/sampling.rs:662: slice_last_logits, then apply_token_bias_stage, then the penalties and apply_row_filters.

Proposed Solution

  1. Split the predicate in src/lib/mlxcel-core/src/sampling.rs so the bias check is separable. Keep config_supports_fused_batch and row_supports_fused_batch with today's strict meaning ("the fused dispatch alone reproduces this row"), because uniform_fused_batch_params (src/lib/mlxcel-core/src/sampling.rs:841) and through it batched_sample (src/lib/mlxcel-core/src/sampling.rs:803) do NOT apply the bias and would drop it silently. Add config_supports_fused_batch_except_bias and row_supports_fused_batch_except_bias, which allow a non-empty token_bias for callers that apply it themselves; row_supports_fused_batch_except_bias additionally returns false for a biased row while lang_bias_counters_enabled() (src/lib/mlxcel-core/src/sampling.rs:594) is true, per item 4 below. Update the // Used by: line on every predicate touched, per docs/code-guidelines.md.
  2. Add a per-row bias helper in the same module, pub fn apply_token_bias_rows(logits: &MlxArray, biases: &[&TokenBiasMap]) -> UniquePtr<MlxArray>, modelled on apply_token_bias (src/lib/mlxcel-core/src/sampling.rs:227). Contract: accepts [B, vocab] or [B, 1, vocab] and flattens the leading dims to rows exactly as apply_token_bias does, with debug_assert_eq!(rows, biases.len()); when every map is empty it returns ffi::copy(logits) and adds no graph nodes; otherwise it takes the sorted union of in-range ids across all rows (negative and out-of-vocab ids ignored per row, the same tok >= 0 && (tok as usize) < vocab_size rule as src/lib/mlxcel-core/src/sampling.rs:244), builds a [B, K] f32 delta matrix carrying 0.0 where a row does not bias an id, and applies take_along_axis + add + put_along_axis before reshaping back. Cost stays O(biased ids) and never vocab-sized, which is the property apply_token_bias was rewritten for; adding exactly 0.0 leaves a value bitwise unchanged, so unbiased rows are untouched. For B == 1 this reduces to the same three ops as apply_token_bias.
  3. Apply it at the two server dispatch points, in the same chain position the per-row sampler uses (after the last-position slice, before the row filters). In the synchronous fused branch (src/server/batch/scheduler/decode_tick.rs:792) the scheduler holds the raw [B, 1, vocab] forward output and batched_fused_sample performs the slice and apply_row_filters internally, so the call goes immediately before batched_fused_sample. In prime_lookahead_with_input the call goes between slice_last_logits (src/server/batch/scheduler/decode_tick.rs:523) and apply_row_filters (src/server/batch/scheduler/decode_tick.rs:528). Add a small row_token_biases(&self, seq_ids: &[SequenceId]) -> Vec<&TokenBiasMap> helper on the scheduler that reads seq.sampling.token_bias per id, so both call sites build the slice the same way.
  4. Keep the B9 observability contract: increment LANG_BIAS_APPLIED_TOTAL (src/lib/mlxcel-core/src/sampling.rs:45) once per biased row, matching what apply_token_bias_stage (src/lib/mlxcel-core/src/sampling.rs:603) does per row today, and keep routing biased rows to the per-row sampler while the opt-in MLXCEL_LANG_BIAS_COUNTERS pre-bias suppression counters are enabled, because those need a per-step device readback the pipeline cannot afford.

Scope

In scope: src/lib/mlxcel-core/src/sampling.rs (the two _except_bias predicates, apply_token_bias_rows, and the tests below); src/server/batch/scheduler/decode_tick.rs (batched_decode_fused_params switches to row_supports_fused_batch_except_bias, plus the two bias call sites and row_token_biases).

Out of scope: the per-row sampler chain itself; batched_sample and uniform_fused_batch_params, which keep rejecting biased rows; speculative decoding and MTP paths; the pre-bias suppression counters, which keep their per-row fallback.

Implementation Notes

  • Reuse: apply_token_bias for the index/update construction and the in-range filtering rule, apply_token_bias_stage for the counter semantics, and apply_row_filters ordering as it already stands. Do not add a second vocab-sized bias vector path.
  • Constraints: the unbiased common case must stay bit-identical and add zero graph nodes, so the all-empty early return is mandatory; greedy output for a biased request must stay token-identical to today's per-row path.
  • Edge cases: all maps empty (early return); some rows biased and some not (0.0 deltas for the unbiased rows); ids duplicated across rows (a single union column); negative or out-of-vocab ids (ignored per row); every id of a row out of range (that row contributes nothing and the batch still dispatches); B == 1.
  • Error handling: no new failure path. The helper is pure graph construction, and a row whose sequence vanished is already handled by the self.active_batch.get(seq_id)? guard in batched_decode_fused_params, which routes the tick to the per-row fallback.

Acceptance Criteria

  • A request with ignore_eos: true, and one with a non-empty logit_bias, advances mlxcel_batch_decode_lookahead_steps_total (src/server/routes/metrics.rs:183-185) by about 125 per 128-token request and reports decode throughput within noise of the same request without the bias: about 112 tok/s instead of 97 on the machine above.
  • Greedy output is token-identical to the current per-row path for the same prompt and bias, verified against a binary built from main on a real checkpoint, not by synthetic test only.
  • Unbiased requests are unchanged: no extra graph nodes, no throughput change, apply_token_bias_rows returns early.
  • uniform_fused_batch_params and batched_sample still reject biased rows, because they do not apply the bias.
  • Unit tests in the inline mod tests of src/lib/mlxcel-core/src/sampling.rs, beside the existing config_supports_fused_batch_false_for_token_bias (src/lib/mlxcel-core/src/sampling.rs:2821): apply_token_bias_rows bit-identical to apply_token_bias for a single row; a mixed batch where only some rows carry a bias leaves the unbiased rows bitwise unchanged; out-of-range and negative ids ignored; both [B, vocab] and [B, 1, vocab] accepted; the strict predicate keeps its meaning while the _except_bias variant admits a biased config; and the counters-enabled fallback returns false for a biased row.
  • Integrated into the real decode flow: both server dispatch points apply the bias, with no standalone helper left unwired.

Verification

cargo test --workspace --profile test-fast --features metal,accelerate
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check

Real-checkpoint check, with mlxcel-server running mlx-community/c4ai-command-r7b-12-2024-4bit: issue the same 512-token prompt twice through /completion with temperature: 0, n_predict: 128, cache_prompt: false, once with ignore_eos: true and once without, reading curl -s localhost:PORT/metrics | grep mlxcel_batch_decode_lookahead_steps_total before and after each request. A pass is both arms advancing the counter by about 125, both reporting predicted_per_second in the same band, and the ignore_eos arm's content matching the main binary's content for the same request token for token.

Technical Considerations

Once this lands, server decode numbers taken with ignore_eos become comparable with the shipped default path again, so earlier server results taken that way are not comparable with post-fix ones. Related: #1436 (b10621 --ignore-eos), #1485 (additive logit_bias merge), #632 (the lookahead pipeline), #900 (the batched fused dispatch).

Activity

  1. added
    status:ready
    type:performance
    priority:medium
    area:inference
    area:core
    status:in-progress
    and removed
    status:ready
    on Sep 23, 2026
  2. added
    status:done
    and removed
    status:in-progress
    on Sep 23, 2026
  3. added a commit that references this issue on Sep 24, 2026
    db8a2ce
  4. added this to the 0.8 milestone on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corearea:inferencepriority:mediumstatus:donetype:performance

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions