Skip to content

Qwen 3.5: keep the batched recurrent state between decode steps; free a paused request's batch - #422

Draft
jonathan308 wants to merge 8 commits into
mainfrom
perf/recurrent-batch-carry
Draft

jonathan308 wants to merge 8 commits into
mainfrom
perf/recurrent-batch-carry

Conversation

@jonathan308

@jonathan308 jonathan308 commented Nov 14, 2026 •

Copy link
Copy Markdown

Proposed changes

Two engine changes for hybrid recurrent models (Qwen 3.5 / 3.6 / 3.8), and the bench repairs used to measure them. No output bit changes.

1. Keep the batched recurrent state between decode steps (CBv2RecurrentBatchCarry)

Each recurrent layer of a CBv2 decode step splits its new state into one-row views, one per request, and the next step joined those views back into one batch: a copy of every request's state, per layer, per step. The Qwen 3.5 27B has 48 recurrent layers and 146.8 MiB of recurrent state per request, so at 56 streams each step copied about 8 GiB that the step before had just written.

A row state now remembers the batched step it came from (CBv2RecurrentBatchOrigin, CBv2RecurrentLayerState.batchOrigin / batchRow). When the next step's rows are exactly the rows of that batch in the same order, the layer takes the batched tensors as they are; a row that joined or left, another order, a rollback to an older generation or a state built another way joins as before. The join of the views of X is X, so the values that reach the layer are the same either way. On by default; DARKBLOOM_RECURRENT_BATCH_CARRY=0 turns it off. Nemotron, GLM and the MTP verify step keep their own joins (not changed here).

2. A paused request re-owns its recurrent rows (CBv2RecurrentRowOwnership)

When a client stops reading, EngineLoopV2 pauses the request (backpressure, up to its 120 s lease). The paused request kept one-row views of its last step's batched state, and a view keeps the whole batch allocated: one paused 27B request held the recurrent state of every request of its last step. The pause handler now has the request's recurrent state copy its committed rows into owned arrays once (setPaused), and a generation that commits while the request stays paused is owned too. Values are unchanged. DARKBLOOM_RECURRENT_REOWN_ON_PAUSE=0 turns the rule off; always copies at every commit (measurement only). Kept sessions and stored checkpoints are not affected: they are captured from prompt ranges, not from decode steps.

3. BenchCBv2

  • Formatted with swift-format (main's copy of the file was not, and CI formats every changed Swift file in full). No code change in that commit.
  • The paged arm builds its pool as the serving factory does (CBv2NativeKVTypeProbe + PagedKVBackend.segmented): before, the 27B trapped on EngineV2's capability precondition and Gemma 4 QAT's bfloat16 writes were refused. A cell's waiting queue is max(16, batch): before, requests past the 16th were refused and printed as zeros.
  • One SHA-256 per request over its token ids, and with BENCH_OUTPUT_DIGEST=1 over its log-probability bits, to compare runs without printing ids or text.
  • A scripted slow consumer (BENCH_SLOW_CONSUMER=k:N: request k stops reading after N tokens) and the re-own counters.
  • Serving's MLX memory limits (the provider's MLXMemoryGuard: ceiling = physical - 6 GiB, cache = min(0.75 x ceiling, 8 GiB); same override variables; BENCH_MLX_LIMITS=0 keeps MLX's defaults). Without a cache limit a many-stream cell used far more memory than its printed GPU peak.

Results

All with the 27B (Qwen 3.8 27B 4-bit MTP checkpoint), the paged engine arm of BenchCBv2, 256-token synthetic prompts, greedy decode.

Same output. M5 Ultra (previous base, guarded, 8 streams at most): per-request output digests equal with the carry off and on at 2, 4, 5 and 8 streams, including steps where requests join and leave. M5 Max (this code): with a fixed batch composition (16-token prompts, every request admitted at once, 64 tokens each), the per-request digests over token ids and log-probability bits are identical in all four runs (on, off, on, off) at 32, 48 and 56 streams (136 requests per run). With 256-token prompts, where requests join the decode batch at timing-dependent steps, outputs are equal in every run at 16 and 24 streams; at 32 to 56 streams one to three requests differ between runs, also between two runs with the same setting. Which rows share a step decides the kernel route at large batches, and the composition depends on timing; that variation is in today's engine and does not come from this change.

Speed, M5 Ultra (2026-11-12, previous library main 44ab17555f40, guarded, 8 streams at most): step 1.042x faster at 4 streams and 1.039x at 8 (three alternating off/on pairs; the host was shared with a standing service).

Speed, M5 Max (this code, fixed composition, step time = median inter-token latency, runs alternating on, off, on, off): every run with the carry was faster than both runs without it. Off/on over the least and the most favourable pairing: 1.24x to 1.58x at 32 streams (75.3 / 75.7 ms against 94.2 / 118.9 ms), 1.08x to 1.31x at 48 (130.0 / 138.3 against 149.9 / 170.1), 1.07x to 1.12x at 56 (175.3 / 177.6 against 190.7 / 196.1). The Mac (a laptop) was under other load, load average 10 to 23, so the size is uncertain; the direction held in every pairing. With 256-token prompts the same setting varied up to 1.9x between runs (heat and other load), and no figure is taken from those.

Speed, Python path for reference (byte-equal scores, M5 Ultra): removing the per-step rejoin gave 1.11x at 16 rows, 1.16x at 24, 1.23x at 32 and 1.25x at 56.

Memory, re-own rule: M5 Ultra, this head's bench (8 streams, 400 tokens per request, one scripted slow client): 15,355,199,824 bytes held during the pause with the rule against 16,425,140,816 without, 1.00 GiB freed, all 8 outputs identical on and off. Earlier on the previous base, six off/on pairs: 1,034 to 1,048 MiB freed at 8 streams, 429 MiB at 4, 591 MiB at 5 mixed lengths; no measurable cost when nothing is paused (copying at every commit instead costs 3.5 to 8.5 ms a step and is not proposed). M5 Max, 32 streams (27B, 400 tokens per request, one scripted slow client): with the rule, the paused request copied its 96 recurrent arrays out (reowned=96, pauses=1) and the process held 15,355,418,616 bytes during the pause; without it, 20,664,689,588 bytes: 4.94 GiB freed by one paused request (32 x 146.8 MiB of recurrent state is 4.6 GiB). Every request was served in both runs, with no swap. The paused request's output is the same in both runs; 30 of 32 outputs are equal, and the two that differ are other requests, as runs of the same setting differ at 32 streams. (The first attempt used 200 tokens, which never fills the stream's 256-event buffer, so it never paused; a later rule-on attempt was stopped by the host-memory guard during warm-up, before any pause, when the shared Mac started swapping.)

Tests

  • New: Kernel/Engine/CBv2RecurrentBatchCarryTests (Swift Testing, kernel): the carry takes the previous batch only for the same rows in the same order; the carry counters; a paused request owns its row with the same bits, and a generation that commits while it stays paused is owned too; a paused request no longer keeps its last batch allocated (three attempts, because MLX's active memory is global to the process and other suites may run at the same time). Passes in this PR's Fork Tests (whole package, run 43544875119), and on the M5 Max GPU: 4 of 4 with the default switches; with both switches off it is skipped, as designed. (The same checks as XCTest passed 4 of 4 on the M5 Ultra on 2026-11-12.)
  • Library tests around the change, debug build, M5 Max: XCTest, 19 classes (CBv2RecurrentStateTests, Qwen35PagedExecutionTests, the scheduler, MTP and stream classes and others): 171 run, 0 failures with both switches on (167 pass, 4 skipped by the library's exclusive-lane gate) and off (163 pass, 8 skipped). Swift Testing, 37 suites that use the recurrent state (283 tests): 261 pass, 18 fail, 4 skip with the switches on and off, the same as unmodified main test by test (this change on the M5 Max, unmodified main on the M5 Ultra). On this head's code (test bundle of aab89b1d), the same suites plus the new one (290 tests): M5 Ultra, default switches: 268 pass, 18 fail, 4 skip; M5 Max, both switches off: 264 pass, 18 fail, 8 skip. Against the unmodified-main baseline the only differences are the 4 new tests (pass with the switches on, skipped off) and 3 tests that main added since (pass); the 18 failing tests and their 223 issues are the same. This PR's CI passes the whole package, including those 18 checks, on its runners. The 18 are GLM-5 Next and Nemotron tolerance checks that fail on M5 GPUs without this change; every Qwen 3.5 suite passes.
  • scripts/check-unit-test-files.sh passes.

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes (pre-commit is not installed here; the changed Swift files were formatted with the swift-format of Xcode 27.2, the command .pre-commit-config.yaml runs)
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed) (changelog.d/recurrent-batch-carry.md, fork.yaml)

Security

No encryption, attestation, signing, key or weight-hash code changes. The diff touches the Qwen 3.5 model file, the batching engine's recurrent state and pause handler, a test and the bench; the only hash added is the bench's output digest.

Freshness

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: Claude Code (Claude Opus 5.5) wrote the code, the tests and this description, and ran the measurements, at the request of the repository's maintainer. The box above is left for the maintainer. The PR stays a draft until the maintainer reviews it.

🤖 Generated with Claude Code

jonathan308 and others added 8 commits November 13, 2026 18:10
CI formats every Swift file a pull request changes, and main's copy of
this file was not formatted. Formatting only; no code change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cell

The paged arm built one unsegmented float16 pool with the plain
PagedKVBackend initializer. A model that needs the native segmented
layout (Qwen 3.5 / 3.6 / 3.8) then failed EngineV2's capability
precondition, and a checkpoint with bfloat16 keys and values (Gemma 4
26b QAT) had its first write refused. The arm now probes the model's
native KV types (CBv2NativeKVTypeProbe) and builds the pool with
PagedKVBackend.segmented, the call the serving factory makes.

A cell submits all its requests at once, and the waiting queue was fixed
at 16, so requests past the 16th were refused and reported as zero
tokens. The queue is now max(16, batch).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each cell prints one SHA-256 per request over its token ids, and with
BENCH_OUTPUT_DIGEST=1 over the bit patterns of its log-probabilities too,
so two runs or two switch settings can be compared for equal output
without printing ids or text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each recurrent layer split its new state into one-row views, and the next
step joined those views back into a batch: a copy of every row's state,
per layer, per step (48 layers and 146.8 MiB per request on the 27B).
A row state now remembers the batched step it came from
(CBv2RecurrentBatchOrigin). When the next step's rows are exactly that
step's rows in the same order, the layer takes the batched tensors as
they are (CBv2RecurrentBatchCarry); any other mix joins the rows as
before. The values that reach the layer are the same either way.
DARKBLOOM_RECURRENT_BATCH_CARRY=0 turns the carry off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A request paused because its client stopped reading kept one-row views
of its last step's batched recurrent state, and a view keeps the whole
batch allocated for as long as the pause lasts. The engine's pause
handler now has the request's recurrent state copy its committed rows
into owned arrays once (CBv2RecurrentRowOwnership), so the batch can be
freed; a generation that commits while the request stays paused is owned
too. Values are unchanged. DARKBLOOM_RECURRENT_REOWN_ON_PAUSE=0 turns the
rule off; =always copies at every commit (measurement only).

BenchCBv2 gains a scripted slow consumer (BENCH_SLOW_CONSUMER=k:N) that
stops reading one request the way a slow client does, and prints the
rule's counters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Kernel/Engine/CBv2RecurrentBatchCarryTests checks that a step takes the
previous batch only for the same rows in the same order, that the carry
counters count carried and joined calls, that a paused request owns its
row with the same bits, and that a paused request no longer keeps its last
batch allocated. MLX's active memory is global to the process and other
suites may run at the same time, so that last check gets three attempts.
Test batches are built from host data: a broadcast plus a scalar keeps
MLX's compact broadcast storage and would hold a few bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The bench set no MLX buffer-cache limit, so MLX kept freed buffers up to
its default ceiling and a many-stream cell used far more memory than its
printed GPU peak (on a 256 GB Mac a 27B cell at 64 streams ran the host
into low swap). The bench now applies serving's limits before loading the
model (the provider's MLXMemoryGuard): ceiling = physical memory - 6 GiB,
cache = min(0.75 x ceiling, 8 GiB). DARKBLOOM_MLX_MEMORY_RESERVE_GB and
DARKBLOOM_MLX_CACHE_LIMIT_GB override as in serving; BENCH_MLX_LIMITS=0
keeps MLX's defaults. The report prints the limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

1 participant