Repository navigation
Description
Part of #2574
Problem / Background
Five text families keep one mixed full / sliding cache set in a RefCell, ignore the scheduler's per-sequence cache slice, and reset that one set in make_caches(). Their supports_batching() returns false, so mlxcel-server --parallel N clamps them to one decode row (src/server/model_worker.rs:570), and the clamp is what keeps concurrent requests from overwriting each other's KV. The pattern predates ModelOwnedSequenceState (src/models/model_owned.rs), which Gemma 3, Gemma 4, Llama 4, AFMoE and Qwen3.5 already use for exactly this kind of mixed cache. gpt-oss has the same shape and is a sibling sub-issue because of its attention sinks and size; these five are mechanical repeats of one pattern and belong in one PR.
Current Behavior
| Family | Type and state | supports_batching |
Cache enum | Family-specific attention detail |
|---|---|---|---|---|
| ministral3 | Ministral3Wrapper, caches: RefCell<Vec<Cache>> (src/models/ministral3.rs:658-670) |
:702 |
Cache::{Standard, Rotating} (:426) |
position-dependent Llama-4 query scaling from the cache offset (llama_4_scaling_beta, :68, schedule at :116-125) |
| exaone4 | ExaOne4Wrapper (src/models/exaone4.rs:690-702) |
:734 |
Cache (:411) |
Q/K norm (:125-126); RoPE only on local layers |
| mellum | MellumWrapper (src/models/mellum.rs:927-939) |
:970 |
Cache (:688) |
MoE (SwitchGLU) |
| laguna | LagunaWrapper (src/models/laguna.rs:611-623) |
:654 |
LagunaCache (src/models/laguna_layers.rs, built at laguna.rs:509-520) |
Q norm, optional output gate g_proj (laguna_layers.rs:74-102), optional attention sinks (:125, :180-185), MoE |
| step3p5 | Step3p5Model.internal_caches (src/models/step3p5.rs:1032, reset at :1049) |
:1294 |
private Cache (:915) |
per-layer rope_theta and partial rotary, head-wise sigmoid gate (use_head_wise_attn_gate, :80), MoE, an embeddings entry (:1117) used by Step3p7-VL |
Step3p7VlModel (src/vision/step3p7.rs:212) hardcodes supports_batching() == false over its Step3p5Model backbone, so it will not follow the backbone on its own. LagunaWrapper also implements DFlashTargetModel (src/server/batch/dflash_target.rs:349) with its own make_dflash_caches, independent of the RefCell.
Proposed Solution
For each family, the same two steps as the gpt-oss sub-issue, following Gemma3Wrapper (src/models/gemma3.rs:1408, hooks :1549-1650, dispatch :1862-1906):
- Per-sequence state. Replace the
RefCell<Vec<Cache>>withsequence_state: ModelOwnedSequenceState<Cache>. Overridesequence_state_layout()to returnSequenceStateLayout::model_owned(num_layers)(today's effective layout; the default would switch to dense oncesupports_batchingflips,src/lib/mlxcel-core/src/generate.rs:593-600).prepare_sequence_stateinserts fresh caches,release_sequence_state_by_idremoves them,make_cachesonly resets the fallback slot,forwarduses the fallback (CLI),forward_with_sequence_iduseswith_or_create_sequence_state,supports_padded_prefill()returnsfalse(notrim_stateyet; feat(scheduler): sequence-aware cache trim hook so model-owned families can use padded prefill #1755), andsupports_batching()returnstrue. For step3p5 also overrideforward_with_embeddings_and_sequence_id. - Batched decode. Override
forward_batched_with_ids(the trait default dropsseq_idsand callsforward()per row, which would put every row on the fallback slot): B = 1 viaroute_batched_decode_with_ids; multi-token steps or a mask loop rows throughforward_with_sequence_id; single-token B >= 2 runswith_batched_sequence_statesinto a newforward_batched_decode_with_cacheson the inner model that runs embedding, norms, projections, MLP or MoE, final norm and LM head once on[B, 1, hidden]. Attention per row: implementmlxcel_core::cache::KvAttentionfor each cache enum (asgemma3.rs:891does) and callattend_batched_rows(src/lib/mlxcel-core/src/cache/attend.rs:364), with RoPE throughfast_rope_batched/fast_rope_batched_with_freqs(src/lib/mlxcel-core/src/lib.rs:3827,:3916) at each row's offset. Laguna layers with sinks cannot useKvAttention(no sinks argument): those layers loop rows callingfast_scaled_dot_product_attention_with_sinks, in one helper whose comment names the reason. Per-row position terms (ministral3's Llama-4 scaling, step3p5's per-layer theta and partial rotary) are computed from each row's own offset. Gates (g_proj, head-wise gate) and Q/K norms run batched on[B, 1, ...]. ReturnBatchedDecodeKind::Native.
Step3p7VlModel: delegate supports_batching, sequence_state_layout, prepare_sequence_state, release_sequence_state_by_id, forward_with_sequence_id, forward_batched_with_ids and batched_decode_kind to the backbone for text decode rows, after confirming from its forward that a text row is exactly the backbone's forward. Any other VLM wrapper that delegates supports_batching() to one of these five towers must start batching once the tower does; list each one found in the PR body and confirm it with a VLM checkpoint where one exists locally.
Shared contract (from #2555, which must be merged first)
If #2555 landed these under other names, use what is on main and say so in the PR body.
BatchedDecodeKind::{Native, PerRowFallback},LanguageModel::batched_decode_kind(), androute_batched_decode_with_ids(model, input_ids, seq_ids, batch_caches, |caches| ...)inmlxcel_core::generate: B = 0 returns[0, 1, 1]zeros, B = 1 runsforward_with_sequence_id, B >= 2 runs the closure.mlxcel_core::batched_decode::forward_split_attentiontakes&mut KVCacherows and does not fit these enums; use its RoPE and Q/K-norm conventions withattend_batched_rowsas above.- Harness
crate::models::batched_decode_harness::*_with_idsvariants plusassert_empty_batch_returns_empty_logits, at least three rows of distinct prompt lengths. - Coverage test
src/models/batched_decode_coverage_tests.rs: add every converted type toEXPECTED_NATIVEandStep3p7VlModeltoEXPECTED_DELEGATING. Sibling PRs edit the same lists anddocs/CONTINUOUS_BATCHING.md; take the union on conflict. - Logit trace
MLXCEL_TRACE_BATCH_ROWS=N; if it does not pass sequence ids for model-owned families yet, add it (allocate ids,prepare_sequence_state, passSome(ids)), keeping whichever sibling version landed first.
Scope
In scope: src/models/{ministral3,exaone4,mellum,laguna,laguna_layers,step3p5}.rs, src/vision/step3p7.rs, their tests, the coverage lists, docs/CONTINUOUS_BATCHING.md.
Out of scope: gpt-oss (sibling sub-issue), trim_state / padded prefill, decode lookahead rewind, paged decode backend, KV-mode injection into these caches, any DFlash change (Laguna's DFlash target keeps its own caches and must keep passing its tests).
Implementation Notes
- Reuse:
ModelOwnedSequenceState::with_batched_sequence_states,KvAttention,attend_batched_rows, each family's existing MLP / MoE block unchanged. If the gpt-oss PR has merged first, mirror its wrapper code exactly. - Constraints: B = 1 byte-identical. Mixed wrap states and offsets across rows. Each family stays a separate type; do not merge the five
Cacheenums in this PR. - Edge cases: one row with a wrapped sliding window and one without; exaone4 global (no RoPE) versus local layers in the same step; laguna with and without sinks and both
g_projvariants; step3p5 per-layer partial rotary;seq_ids == Noneat B >= 2 panics with a message saying sequence ids are required. - Error handling: missing per-sequence state panics naming the id, never falls back to the shared slot.
Acceptance Criteria
- Per family, a concurrent-isolation test on a tiny synthetic config with at least one sliding and one full layer and a window smaller than the longest prompt: three prompts of different lengths prefilled and decoded 6 steps under three
SequenceIds, calls interleaved; each row's logits equal that prompt alone (max abs diff at most 1e-5). - Per family, a test that
make_caches()plusprepare_sequence_statefor a new sequence leaves an in-flight sequence's next-step logits unchanged. - Harness tests (matches-sequential with ids, single-row at 0.0, empty) per family, plus a delegation test for
Step3p7VlModel. - B = 1:
mlxcel generate -p "Hello" -n 128 --temp 0byte-identical before and after onmodels/ministral-3-3b-instruct-2512-4bit,models/exaone-4.0-1.2b-4bit,models/mellum2-12b-a2.5b-base,models/laguna-xs.2-4bit. - Logit trace
MLXCEL_TRACE_BATCH_ROWS=4against=1at decode width on those four checkpoints, disagreement at decided positions in the PR body. - Serving ladder
scripts/bench_serving_concurrency.py --concurrency 1,2,4on Metal on the same four, main (clamped) against branch: B = 4 aggregate above B = 1 and B = 1 not regressed. step3p5 and Step3p7-VL have no local checkpoint: synthetic tests only, listed as unmeasured. - Laguna DFlash tests still pass.
- Integrated into the real server path: no clamp line,
decode path: native batched forwardat startup for each measured checkpoint;docs/CONTINUOUS_BATCHING.mdupdated. - One PR, one verification pass at the end, few pushes.
Verification
cargo build --release --features metal,accelerate
cargo test --workspace --profile test-fast --features metal,accelerate
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
# per checkpoint, main and branch (rebuild before measuring)
./target/release/mlxcel generate -m models/<ckpt> -p "Hello" -n 128 --temp 0
MLXCEL_TRACE_BATCH_ROWS=1 ./target/release/examples/logit_trace models/<ckpt> docs/architecture.md 64 4 8 512 > b1.tsv
MLXCEL_TRACE_BATCH_ROWS=4 ./target/release/examples/logit_trace models/<ckpt> docs/architecture.md 64 4 8 512 > b4.tsv
python3 scripts/compare_logit_traces.py b1.tsv b4.tsv
./target/release/mlxcel-server -m models/<ckpt> --parallel 4 --port 8080
python3 scripts/bench_serving_concurrency.py --concurrency 1,2,4 --prompt-tokens 512 --max-tokens 128A pass is a green gate, identical B = 1 greedy text, recorded trace numbers, and B = 4 aggregate above B = 1 on each measured checkpoint.
Activity
fix: validate model-owned mixed-cache batches
fix: sync mixed-cache paged state lengths
update: batch decode for mixed-cache model families
fix: validate model-owned mixed-cache batches
fix: sync mixed-cache paged state lengths
update: batch decode for mixed-cache model families
fix: validate model-owned mixed-cache batches
fix: sync mixed-cache paged state lengths
update: batch decode for model-owned cache families (#2672)