Skip to content

feat: batched decode infrastructure for vllm-swift - #79

Merged
ekryski merged 11 commits into
ekryski:alphafrom
TheTom:vllm_sync_up
Apr 24, 2026
Merged

ekryski merged 11 commits into
ekryski:alphafrom
TheTom:vllm_sync_up

Conversation

@TheTom

@TheTom TheTom commented Apr 24, 2026 •

Copy link
Copy Markdown

Summary

Batched decode infrastructure needed by vllm-swift for concurrent request serving. Enables multiple independent decode sessions to share GPU compute via two-phase stepAsync/readToken API.

Commits

Batched Decode Core

  • batch decode API — stepAsync/readToken + BatchTokenIterator: Two-phase decode on TokenIterator. Phase 1 (stepAsync) builds forward graph + asyncEval without sync. Phase 2 (readToken) forces GPU sync. Batches N sessions' Metal command buffers.

  • BatchedDecoder: Higher-level class managing multiple BatchSession instances. Sequential forward passes with deferred eval — single eval() for all tokens.

  • Qwen3 batched decode with SDPA fast path: Model-level batched attention for Qwen3. When all caches have the same offset, uses batched SDPA (stacked K/V). Falls back to sequential for mixed-offset caches.

  • BatchedKVCache + fully batched decode: Wraps N per-request caches, exposes stacked K/V for batched SDPA. True batched projection (embed + QKV + MLP + lm_head across B requests).

  • vectorized mask + direct K/V slice: Vectorized causal mask construction and direct K/V slicing. 3,690 tok/s @ B=128.

  • mixed-offset RoPE + cache support: Batched decode when requests have different cache offsets. RoPE positions computed per-request within the batch.

Evaluate Extensions

  • BatchTokenIterator for parallel decoding: Parallel decode of B sequences through the standard TokenIterator API. Includes test suite.

  • NGramSpeculativeTokenIterator: Prompt-lookup speculative decoding via n-gram matching. Includes test suite.

  • rename BatchTokenIterator → BatchSessionIterator: Naming fix to avoid collision with the lower-level batch iterator.

Bug Fix

  • TurboFlash fallback for unsupported (kb,vb) configs: Whitelist of TurboFlash-supported bit-width combos. Unsupported configs fall through to the separated score+softmax+value path instead of crashing.

Cleanup

  • inline temp variable in quantized attention sliding window mask: Minor cleanup in quantizedScaledDotProductAttention.

Regression Test (9B @ 4K, M5 Max 128GB)

Config alpha vllm_sync_up Δ
none 90.6 91.8 +1.3%
turbo3 80.6 79.1 -1.9%
turbo4 79.1 81.8 +3.4%

All within noise. No single-request regression from batched decode commits.

Test Plan

  • Single-request regression: alpha vs vllm_sync_up on 9B (none/turbo3/turbo4)
  • BatchTokenIterator unit tests
  • NGramSpeculative unit tests
  • No regressions on baseline (kv=none)
  • vllm-swift integration test (concurrent multi-request serving)

🤖 Generated with Claude Code

TheTom and others added 11 commits April 24, 2026 16:09
Adds two-phase decode to TokenIterator for concurrent request serving:
  stepAsync() — build forward graph + asyncEval without sync
  readToken() — read computed token (GPU sync happens here)

BatchTokenIterator orchestrates N sessions with phase-separated
stepping. Not yet faster than sequential (MLX can't batch separate
KV cache graphs), but the API is ready for true batch inference.

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

BatchedDecoder: orchestrates multiple sessions with deferred eval.
stepAsync/readToken split: 8% throughput improvement from async pipelining.

32x50 decode benchmark: 157.4 tok/s (up from 145 sequential).
Not yet at 276 tok/s target — needs true batched projections where
model processes [B, 1, hidden] in single matmul with per-request
attention against separate KV caches.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Batched forward pass for Qwen3 attention: sequential per-request
attention with deferred eval, batched SDPA fast path when all caches
have the same offset. Supports vllm-swift concurrent request serving.
BatchedKVCache: single pre-allocated [B, heads, max_seq, dim] tensor
for all requests. Eliminates per-request KVCacheSimple objects.

Batched cache update: single slice write when all requests have same
offset (common during continuous decode). No per-request loop.

Fully batched SDPA: one call with mask for variable-length requests.

Benchmark (Qwen3-0.6B-4bit, M5 Max, debug):
  B=8:   381.7 tok/s (2.62ms/req)
  B=32:  560.4 tok/s (1.78ms/req)
  B=64:  591.8 tok/s (1.69ms/req)

3.7x faster than sequential baseline (158 tok/s).

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Eliminated per-layer getCachedWithMask() call. Build mask once in
ModelInner, pass to all layers. Direct K/V slice instead of method
call. Vectorized mask construction (no per-request loop).

Benchmark (Qwen3-0.6B-4bit, M5 Max, debug):
  B=8:    779 tok/s (1.28ms/req)
  B=32: 2,130 tok/s (0.47ms/req) — matches vllm-metal!
  B=64: 2,884 tok/s (0.35ms/req)
  B=128: 3,690 tok/s (0.27ms/req) — EXCEEDS vllm-metal!

vs vllm-metal: 2,300 tok/s @ B=32

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
fullyBatchedForward now handles requests with different cache lengths:
  - Same offset: batched RoPE (fast path, no change)
  - Mixed offset: per-request RoPE with split/concat, proper mask

Mask construction uses max offset across all requests.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
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>
…ive decoding)

Builds out the n-gram prompt-lookup speculative decoding path that
`GenerateParameters.ngramSize` / `maxNgramDraftTokens` were documented
for but never actually wired up.

Unlike the existing `SpeculativeTokenIterator` which needs a separate
draft *model*, this iterator sources draft tokens from the token
history itself (prompt + already-accepted generations) via a rolling
FNV-1a hash table over the last-`ngramSize`-token suffixes. Wins when
the generation has repetitive structure (boilerplate, code,
templates, or factual re-quoting of the prompt); degrades to one
hash lookup per step on a miss.

## Guarantees

- **Greedy-equivalent** under temperature=0: verification accepts a
  drafted token only when it matches the main model's argmax at the
  same position. Output stream is identical to `TokenIterator`.
- **Metrics exposed**: `ngramProposedCount`, `ngramAcceptedCount`,
  `ngramAcceptanceRate` on the iterator.
- **Disabled by default** — `ngramSize=0` remains the
  `GenerateParameters` default; the iterator precondition-fails if
  constructed without both knobs set, pointing callers back at
  `TokenIterator` for the non-speculative path.

## Implementation

- `NGramLookup`: rolling Swift-side hash table. FNV-1a over last
  `ngramSize` tokens → list of token-positions where that n-gram
  ends. `extend(with:)` amortises O(k) work per appended token
  rather than rescanning the whole history.
- `NGramSpeculativeTokenIterator`: prefill the main model, then per
  round (a) look up a draft of up to `maxNgramDraftTokens`; (b) run
  `[y, draft_1 ... draft_k]` through the main model in ONE forward
  pass; (c) accept drafts until the first rejection, always emit the
  main model's bonus/correction token at position `accepted`; (d)
  trim the KV cache by `numDraft - accepted`; (e) extend the lookup
  with the committed tokens.

## Scope (v1)

- Single ngramSize (spec'd multi-size 2-5 fallback is a follow-up).
- Fixed draft length (dynamic-length-per-acceptance-rate is a follow-up).
- Greedy only; temperature > 0 path uses the same argmax verification,
  but for full parity with sampling that differs per position we'd
  need a resample loop — tracked as follow-up.

## Tests

`Tests/MLXLMTests/NGramSpeculativeTests.swift`:

1. **Greedy parity** — spec iterator emits the same token count as
   `TokenIterator` at temperature=0. Token-equality under tiny
   random-weight models is unstable (argmax ties flip), so this is
   the stable assertion at unit-test scale; real-model end-to-end
   parity is the acceptance test.
2. **Metrics sanity** — `proposed >= 0`, `accepted <= proposed`,
   rate in `[0, 1]`.
3. **Config contract** — precondition on `ngramSize >= 1` documented.

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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>
TurboFlash kernels only instantiated for specific (kb,vb) combos:
(4,4), (4,2), (4,3), (3,2), (3,3), (8,4), (8,2), (8,8).

turbo2 symmetric (2,2) and other combos now fall through to the
separated score+softmax+value path instead of crashing with
"Unable to load kernel".

Also reverted Qwen3 newCache — Qwen3 head_dim=80 isn't validated
for TurboQuant yet. Only Qwen3.5 uses TurboQuantKVCache.

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

ekryski commented Apr 24, 2026

Copy link
Copy Markdown
Owner

I think this supersedes #57. Going to merge this and close that one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants