Skip to content

feat(evaluate): BatchTokenIterator for parallel decoding of B sequences - #57

Closed
ekryski wants to merge 2 commits into
alphafrom
ek/batch-decode
Closed

ekryski wants to merge 2 commits into
alphafrom
ek/batch-decode

Conversation

@ekryski

@ekryski ekryski commented Apr 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds `BatchTokenIterator` for running B prompts through one model in lockstep. Emits `[Int]` of length B per step, amortising model compute across the batch via `[B, L]` input tensors.

Usage

```swift
let inputs: [LMInput] = prompts.map { LMInput(tokens: tokenise($0)) }
var iter = try BatchTokenIterator(
inputs: inputs, model: model, parameters: parameters)
for batchTokens in iter {
// batchTokens is [Int] of length B — batchTokens[i] is the token
// just emitted for sequence i.
}
```

Scope (v1)

  • Same-length prompts only (pad in Swift if needed).
  • Pure-attention models (Gemma4, GPT-OSS, Nemotron H). GatedDelta / Mamba hybrids (Qwen3.5) are follow-up — their sequential SSM state needs per-sequence isolation.
  • No LogitProcessor penalty chain yet — repetition/frequency/presence penalties need per-sequence state. Greedy / top-p / top-k / categorical samplers work on `[B, V]` and are supported.
  • No speculative / n-gram draft on the batched path.

Implementation

The cache and sampler machinery were already batch-shape-correct. Main additions:

  1. Stacking `[LMInput]` into `[B, L]` at init.
  2. Per-step `[B] → [Int]` drain to the caller.

Matches `TokenIterator`'s `asyncEval` pattern so the next forward pass kicks off while the caller drains this step.

Test plan

New `BatchTokenIteratorTests`:

  • B=4 forward pass: identical rows produce identical logits — pins the model's batch-safety at 1e-4. The critical correctness invariant.
  • B=1 degeneracy — iterator emits the correct shape.
  • B=4 returns correct count per step — every step emits exactly B tokens.

Bit-exact token equality vs `TokenIterator` is deliberately not tested — argmax at tiny random-weight scale flips on sub-1e-4 kernel-path differences. Real-model `--ppl` / correctness validation is the right acceptance gate for production parity.

Existing safety suite (`KVCacheTests`, `SpeculativeDecodingTests`, `Gemma3nOffsetTests`, `MaskedScatterTests`) continues to pass.

Follow-up

  • Per-sequence penalty processor state.
  • Variable-length prompt support (per-sequence cache offsets).
  • Hybrid Mamba/GatedDelta support.
  • Real-model benchmarks: `benchmark.sh --batch 2,4`.

Adds `BatchTokenIterator` for running B prompts through one model in
lockstep — emits a `[Int]` of length B per step, amortising model
compute across the batch via [B, L] input tensors.

## Scope (v1)

- Same-length prompts only (pad in Swift if needed).
- Pure-attention models (Gemma4, GPT-OSS, Nemotron H). GatedDelta /
  Mamba hybrids (Qwen3.5) are follow-up — their sequential SSM state
  needs per-sequence isolation that's beyond the scope of a single PR.
- No LogitProcessor penalty chain — repetition / frequency / presence
  penalties would need per-sequence state. Greedy / top-p / top-k /
  categorical samplers work row-wise on [B, V] and are supported.
- No speculative / n-gram draft on the batched path.

## Implementation

Key simplifications:

- **KV caches are already [B, H, L, D]-shaped** in `KVCacheSimple` and
  `RotatingKVCache`. No cache changes needed — the first `update()`
  call sizes the cache from the input's batch dim.
- **Samplers already work on [B, V]** — `argMax(axis: -1)` and
  `categorical` both reduce along the last axis.
- The only real additions are (1) stacking `[LMInput]` into `[B, L]`
  in the initializer and (2) the per-step `[B] → [Int]` GPU→CPU
  drain.

Step structure mirrors `TokenIterator`: previous batch of sampled
tokens drained via `asArray(Int.self)` while the next forward pass
runs via `asyncEval`.

## Tests

`Tests/MLXLMTests/BatchTokenIteratorTests.swift`:

1. **B=4 forward pass: identical rows → identical logits** — direct
   sanity check that the underlying model is batch-safe. Pins
   row-wise logit equality at 1e-4.
2. **B=1 degeneracy** — iterator emits the correct count and per-step
   shape. (Bit-exact token equality vs `TokenIterator` is unreliable
   with tiny random-weight test models because argmax flips on
   sub-1e-4 kernel-path differences; real-model parity is the
   acceptance test for production.)
3. **B=4 step shape** — every step emits exactly B tokens.

## Follow-up

- Per-sequence penalty processor chains (repetition / frequency / presence).
- Variable-length prompt support (per-sequence cache offsets).
- Hybrid / Mamba model support with per-sequence SSM state.
- Real-model benchmarks: `benchmark.sh --batch 2,4` to validate
  amortisation on Gemma4 E2B and GPT-OSS-20B.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@TheTom

TheTom commented Apr 23, 2026

Copy link
Copy Markdown

Regression Test Results (M5 Max 128GB)

Cherry-picked onto alpha (with #56 already applied). All 5 models tested with --method summarization --quick.

Note: Had to rename my existing BatchTokenIterator (multi-session orchestrator using stepAsync()/readToken()) to BatchSessionIterator to avoid collision with this PR's true-batched BatchTokenIterator. Different designs — mine coordinates independent TokenIterator sessions, yours does single [B, L] matmul. Both useful, just needed distinct names.

Results @ 1k context

Model Prefill Δ Decode Δ
Gemma 4 E2B -2.5% (noise) -0.8%
GPT-OSS 20B +3.1% +1.1%
Qwen3.5 2B (GDN) +0.4% -0.4%
Qwen3.5 35B MoE +1.9% +0.8%
Gemma 4 26B MoE +4.7% +1.4%

Verdict: No regressions. All within noise.

TheTom added a commit to TheTom/mlx-swift-lm that referenced this pull request Apr 24, 2026
Avoids collision with Eric's BatchTokenIterator in PR ekryski#57.
Different designs — ours orchestrates independent TokenIterator
sessions, his does true batched [B,L] forward pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Tom Turney <tturney@psyguard.ai>
TheTom added a commit to TheTom/mlx-swift-lm that referenced this pull request Apr 24, 2026
Avoids collision with Eric's BatchTokenIterator in PR ekryski#57.
Different designs — ours orchestrates independent TokenIterator
sessions, his does true batched [B,L] forward pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Tom Turney <tturney@psyguard.ai>
ekryski pushed a commit that referenced this pull request Apr 24, 2026
Avoids collision with Eric's BatchTokenIterator in PR #57.
Different designs — ours orchestrates independent TokenIterator
sessions, his does true batched [B,L] forward pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Tom Turney <tturney@psyguard.ai>
@ekryski

ekryski commented Apr 26, 2026

Copy link
Copy Markdown
Owner Author

Closing as already-applied.

The content of this PR landed on alpha as commit d0ae8bd (same author, same date, byte-identical diff) alongside the broader batched-decode stack in #79. BatchTokenIterator and its tests are present on alpha today at Libraries/MLXLMCommon/Evaluate.swift:1197 and Tests/MLXLMTests/BatchTokenIteratorTests.swift.

GitHub still shows this PR as mergeable because the SHA 189f011 isn't an ancestor of alpha — but the line-content already matches, so the merge would be a no-op. Closing rather than merging to avoid a redundant merge commit.

Complementary work that landed in #79 on top of this foundation:

  • BatchSessionIterator (TheTom) — orchestrates N independent TokenIterator sessions via stepAsync/readToken; renamed from BatchTokenIterator to avoid collision with this PR's true-batched [B, L] design.
  • BatchedKVCache + BatchedDecoder + Qwen3 batched SDPA fast path — the high-throughput stack reaching 3,690 tok/s @ B=128 on Qwen3-0.6B-4bit.

@ekryski ekryski closed this Apr 26, 2026
@ekryski
ekryski deleted the ek/batch-decode branch May 12, 2026 06:31
@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature (auto-applied from feat: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants