Skip to content

perf(cbv2): chain batch-gated Qwen MTP decode and seed the first carry from prefill - #330

Merged
Gajesh2007 merged 7 commits into
mainfrom
ttft/qwen-mtp-decode
Oct 22, 2026
Merged

Gajesh2007 merged 7 commits into
mainfrom
ttft/qwen-mtp-decode

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Paired provider PR: Layr-Labs/d-inference#1543. Replayed onto current main for publication; the tests below ran on the base named in Validation.

Update for publication (2026-10-21, evening): replayed onto 19634dd8 (adds #318 and #314), the SDK commit d-inference master now pins; it merges cleanly into current main. Validation below ran on 66f556b7.

Summary

The inline Qwen MTP head (Qwen35InlineMTPAssistant) speculates for one decode row only (maximumSpeculativeBatch 1). With two or more requests decoding, no row can speculate, yet every step still ran as an MTP seed step: a hidden-returning forward, a vocabulary-wide policy top-two, an extra host readback, per-row lazy history bookkeeping, and no chained successor while the GPU worked. Every request also ran one target-only seed step after its first token, although prefill had already produced that exact token/hidden pair.

This PR lets a request-stateful drafter opt in with supportsOrdinaryDecodeHistory (only the Qwen inline head does):

  • Batch-gated decode chains. While no row can speculate, decode-only plans run as ordinary executeMixed / launchChainedDecode steps. The target forward also returns its [B, 1, H] pre-norm hidden (decodeLogits(returnsHidden:) calls mtpRecurrentForwardWithHidden, the seed steps' recurrent forward: same trunk, positions and lm_head, so logits are unchanged). finalizeMTPOrdinaryHistory appends each row's committed input and hidden to the head history in launch order. It stores the carry when no successor is in flight and otherwise drops the stale one, so a pending verify carry is observed exactly once. Preempted, cancelled and finished rows are skipped.
  • Prefill seeds the first carry. The final prompt chunk's last hidden row becomes the first carry once the first token is confirmed (with its policy margin when the prompt finished with no other row), so a round can follow token 1 without a seed step.
  • Prompt rows keep the hidden-returning MTP prefill path, so history still starts at position 0. Native completion tracking keeps its MTP-step schedule. A drafter that requiresCommittedObservationFence keeps MTP steps, because ordinary steps never run that fence.

Kill switches, read once per process: DARKBLOOM_TTFT_QWEN_MTP_CHAINED=0 (false, no, off) restores the seed steps at B >= 2; DARKBLOOM_TTFT_QWEN_MTP_CARRY=0 restores the post-first-token seed step. With both set, the engine takes the pre-PR path.

Commit Content
d489c297 style(tests): format CBv2QwenMTPIntegrationTests.swift Format-only. The Lint job formats every Swift file a PR touches, and this file is unformatted on main
534db8a3 perf(cbv2): chain batch-gated Qwen MTP decode and seed the first carry from prefill The change above, its contracts (CBv2MTPConfig.ordinaryDecodeHistory, .prefillCarry), EngineLoopV2+MTPOrdinaryHistory.swift, and tests
8fd0e7fa test(qwen35): share one target across ordinary-history engines Test fix: parallel suites consumed the global random stream between seeding and initialization
be4bc656 fix(cbv2): keep MTP steps for drafters that need the observation fence Enforces the fence exclusion, with a round-driver test
22896c7e refactor(cbv2): share the recurrent hidden-returning forward with ordinary history Refactor pass, no behavior change (see Refactor pass)
3fd6d07e test(cbv2): cover a row joining while another row speculates The corrected join test (see Limitations)

Base: main @ 66f556b7 (#318). The provider pin is the paired Layr-Labs/d-inference PR (branch ttft/qwen-mtp-decode).

Before

flowchart TB
  subgraph SB["Behavior: Qwen inline MTP head, two or more decoding requests"]
    direction LR
    rb["B >= 2 decode rows<br/>head speculates for 1 row only"]:::input --> sb["MTP seed step every plan<br/>(no row can speculate)"]:::slow
    sb --> cb["hidden-returning forward<br/>+ vocabulary-wide policy top-two<br/>+ extra host readback"]:::slow
    cb --> nb["step is never chained:<br/>next step built after readback"]:::slow
    nb --> ob["M3 Ultra, Qwen3.5-9B, B=2:<br/>161.2 tok/s (MTP off: 192.3)"]:::metric
    fb["Prompt done, first token"]:::input --> tb["one target-only seed step"]:::slow
    tb --> ub["first speculative round<br/>after token 2"]:::state
  end
  subgraph CB["Code flow: one engine step"]
    direction LR
    pb["engineStep:<br/>beginMTPPlan, scheduler.plan()"]:::code --> qb{"MTP step needed?<br/>mtpWantsStep, mtpRoundNeeded"}:::decision
    qb -- "yes for Qwen:<br/>tracksPersistentHistory" --> eb["executeMTPRound<br/>seed rows"]:::slow
    eb --> zb["finalizeMTPRound:<br/>storeCarry per seed row"]:::state
    zb --> kb["permitsChainedSuccessor:<br/>mtpRound != nil, so no successor"]:::code
  end
  SB ~~~ CB
  style SB fill:#f8fafc,stroke:#64748b,color:#0f172a
  style CB fill:#f8fafc,stroke:#64748b,color:#0f172a
  classDef input fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a
  classDef slow fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d
  classDef state fill:#ede9fe,stroke:#6d28d9,color:#3b0764
  classDef code fill:#e0e7ff,stroke:#4338ca,color:#1e1b4b
  classDef decision fill:#fef3c7,stroke:#b45309,color:#78350f
  classDef metric fill:#e5e7eb,stroke:#4b5563,color:#111827
  linkStyle 0,1,2,3,4,5,6,7,8,9 stroke:#64748b,stroke-width:1.5px
Loading

After

flowchart TB
  subgraph SA["Behavior: Qwen inline MTP head, two or more decoding requests"]
    direction LR
    ra["B >= 2 decode rows<br/>no row can speculate"]:::input --> sa["ordinary decode step,<br/>chained like MTP off"]:::new
    sa --> ca["same target forward also returns<br/>its [B, 1, H] pre-norm hidden"]:::new
    ca --> ha["finalize: append each row's input + hidden<br/>to the head history, in launch order"]:::state
    ha --> oa["M3 Ultra, Qwen3.5-9B, B=2:<br/>191.6 tok/s (MTP off: 192.3)"]:::metric
    ha --> la["one row left: a round starts<br/>from the stored carry, no seed step"]:::state
    fa["Prompt done, first token"]:::input --> ta["final prompt row's hidden<br/>is the first carry"]:::new
    ta --> ua["first speculative round<br/>right after token 1"]:::state
  end
  subgraph CA["Code flow: one engine step"]
    direction LR
    pa["engineStep:<br/>beginMTPPlan, scheduler.plan()"]:::code --> qa{"MTP step needed?<br/>mtpWantsStep, mtpRoundNeeded"}:::decision
    qa -- "no: no row can speculate,<br/>every history row decodes" --> ea["launchChainedDecode or executeMixed<br/>decodeLogits(returnsHidden: true)"]:::new
    ea --> fz["finalizeMTPOrdinaryHistory:<br/>pending carry once, then the row;<br/>storeCarry if no successor, else dropCarry"]:::new
    qa -- "yes: a row can speculate,<br/>or a prompt row owns history" --> ma["executeMTPRound<br/>(prompt rows record prefillCarries)"]:::code
    ma --> za["finalizeMTPRound: prefill carry<br/>(policy margin if the prompt<br/>finished with no other row)"]:::state
    ka["Kill switches<br/>DARKBLOOM_TTFT_QWEN_MTP_CHAINED=0: yes, seed steps as before<br/>DARKBLOOM_TTFT_QWEN_MTP_CARRY=0: no prefill carry"]:::decision
    ka -.-> qa
  end
  SA ~~~ CA
  style SA fill:#f8fafc,stroke:#64748b,color:#0f172a
  style CA fill:#f8fafc,stroke:#64748b,color:#0f172a
  classDef input fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a
  classDef new fill:#dcfce7,stroke:#15803d,color:#14532d
  classDef state fill:#ede9fe,stroke:#6d28d9,color:#3b0764
  classDef code fill:#e0e7ff,stroke:#4338ca,color:#1e1b4b
  classDef decision fill:#fef3c7,stroke:#b45309,color:#78350f
  classDef metric fill:#e5e7eb,stroke:#4b5563,color:#111827
  linkStyle 0,1,2,3,4,5,6,7,8,9,10,11,12 stroke:#64748b,stroke-width:1.5px
Loading

Legend: blue is input, red is the per-step cost this PR removes, green is new code, purple is assistant history and carries, amber is a decision or switch, indigo is unchanged code, grey is a measured result.

Measured effect (M3 Ultra, Qwen3.5-9B)

All rows: M3 Ultra (Mac15,14, fleet-representative, non-NAX), exclusive GPU lock, production slot through darkbloom benchmark --runtime-generation --runtime-mtp --runtime-concurrency (the provider PR adds it). "Before" is the same binary with both kill switches set to 0. Measured on the pre-rebase build: the same engine change on SDK 14661d9b (b0c9ba00; binaries b248bfd9… and 7de052d5…, mlx.metallib fb1ba8f9…). The rebased build was tested and smoke-run but not re-measured (see Validation). Logs: qwen-mtp-decode/{m3u,m3u3}/*.json and qmtp-final/load/* in the program scratchpad (originals on the M3 Ultra under ~/ttft-bench/runs/qmtp/ and ~/ttft-bench/agents/qwen-mtp-decode/).

Concurrent greedy decode, 256 tokens, distinct 25-token prompts, all-rows decode tok/s, median of 2 interleaved repeats (m3u/p256-{off,old,new}*.json):

B MTP off Before After After vs before First token ms (before / after)
1 105.5 139.5 146.9 +5.3% 36.6 / 36.6
2 192.3 161.2 191.6 +18.9% 81.3 / 82.6
4 313.6 268.3 313.1 +16.7% 185.6 / 186.2
8 381.5 342.1 381.1 +11.4% 312.5 / 312.9

At B >= 2 the after column matches MTP off; the first-token time does not change. Splitting the switches (m3u/split-*.json): chaining alone gives all of the B >= 2 gain (B2 190.8, B4 312.8 tok/s); the prefill carry alone gives the B=1 gain (time to token 3: 53.8 ms vs 68.7 ms).

Load, HTTP through run_load.sh (Poisson arrivals, T = 0.7, width 4, same seed per arm; qmtp-final/load/L{1,2}-*.json, paired per request):

Run Arm TTFT p50 / p90 / p99 s Decode p50 tok/s Paired vs before
L1: 0.15 req/s, 37 requests MTP off 1.05 / 4.28 / 6.15 84.2
Before 1.57 / 4.60 / 7.14 75.8
After 1.56 / 4.65 / 7.00 90.3 TTFT median diff +0.000 s; summed request time 232.0 s vs 261.5 s
L2: 0.25 req/s, 62 requests (saturated) Before 64.60 / 101.59 / 116.38 31.4
After 56.93 / 89.66 / 104.41 33.4 TTFT lower for 55 of 62, 54 of them by more than 10 ms (median -6.69 s); output 112.79 vs 110.42 tok/s

TTFT counts the client-side queue (the coordinator-like --max-inflight wait). Excluding that queue, the provider-side TTFT paired median difference is +0.002 s in both runs.

Speculation resuming (m3u3/stag4-*.json): 4 rows stop after 256/192/128/64 tokens. Last-token times: before 3344 / 2823 / 1994 / 1127 ms; after 2912 / 2383 / 1703 / 980 ms; MTP off 2934 / 2298 / 1617 / 894 ms.

B = 1 over 7 prompts of 75-1,892 tokens (m3u3/b1-*.json, 256 tokens, 2 repeats except one): per-row decode rate geomean +0.08%, range -2.55% (1,892-token prompt, one repeat) to +4.27%. The 1,892-token prompt at 64 tokens (m3u/t3k-*.json, 3 repeats each) was -1.5% (156.1 vs 158.4 tok/s).

Token timing. Token 1 (TTFT) is unchanged: within 1.3 ms at every B above, and 494.4 vs 493.5 ms (650-token prompt) and 1383.4 vs 1383.6 ms (1,892-token prompt) at B = 1 (m3u/t3{c,k}-*.json). Later tokens shift. At B = 1 the first round now follows token 1 and returns tokens 2 and 3 together: measured from token 1, token 2 is 8-13 ms later and token 3 is 9-20 ms earlier (m3u3/b1-*.json). At B = 2 and 4, tokens 2-4 arrive 1-9 ms later and later tokens earlier (B = 2, token 8: 159.7 vs 168.0 ms; m3u3/early-*.json).

Tokens. At B >= 2, after is token-identical to before on every row and repeat (B2 2/2, B4 4/4, B8 8/8 over 256 tokens; also on M5 Ultra, m5/p256-*.json). At B = 1, rectangular verification diverges from before at token 198 (before also diverges from MTP off at token 198); with DARKBLOOM_QWEN_MTP_SERIAL=1, after, before and MTP off are identical at B = 1 (m3u/serial-*.json). Every arm repeats token for token.

Correctness tests

Test Checks
Qwen35MTPOrdinaryHistoryTests (Integration/Engine) "batch-gated rows chain with exact tokens and contiguous history" The production Qwen3.5 inline head on a tiny target, B = 2 then B = 1, both modes: tokens equal MTP off (serial verification), every stored carry finds exactly the committed history before it, all assistant and recurrent state is released
CBv2QwenMTPIntegrationTests "batch-gated history rows chain and observe every committed input once" Chained steps > 0, no seed steps, no policy top-two; history = prompt + committed tokens with matching hidden positions; with the switch off, the old seed path
"a batch-gated row resumes speculation from its finalized carry" B = 2 then B = 1: rounds resume from the last chained finalize's carry with no synchronized_seed fallback
"the final prompt row seeds the first carry" Tokens equal MTP off; the first carry is stored at the prompt length right after token 1, and one position later (by a seed step) with the switch off
"ordinary-decode history requires a drafter without the observation fence" The opt-in is ignored for a drafter with requiresCommittedObservationFence
"a speculating row's verify carry primes history once when a row joins" A second row joins while the first row's verify carry is pending (B = 1 rounds, then B = 2, then B = 1 rounds), both modes: tokens equal MTP off; the first row's history holds that carry once, then the steps after it from that token, and never repeats or reorders an entry. Skipping the carry observation in finalizeMTPOrdinaryHistory, or making it twice, fails this test; the two batch-gated fixture tests above still pass

Validation

Run on M5 Ultra (applegpu_g17d) in the PR clone, from libs/mlx-swift-lm. Toolchain: Apple Swift 6.4 (Command Line Tools) with XCTest from Xcode 27.1, macOS SDK 27.0. All GPU commands ran in one ticket on the shared GPU queue, alongside other jobs (load average 74-100). The tested tree is 6af40831; be4bc656 differs only by removing one new test that failed (see Limitations), with identical library code, and its test bundle was rebuilt without errors. The refactor-pass rerun below covers the final 3fd6d07e.

Command Outcome
nice -n 15 swift build --build-tests, with the Swift Testing plugin path and XCTest from Xcode Build complete, 0 errors. SwiftPM resolved mlx-swift 81f58d79. Same on be4bc656
../../scripts/stage-test-metallib.sh .build/debug mlx.metallib built from nested MLX 71271f08: SHA-256 fb1ba8f9…
swift test --skip-build --filter 'Qwen35MTPOrdinaryHistoryTests|CBv2QwenMTPIntegrationTests|Qwen35MTPDraftTrimTests' 57 tests: 54 passed, including every test listed above. Failed: the 2 known Qwen35MTPDraftTrimTests tolerance cases, and the removed join test
swift test --skip-build --filter 23 MTP and engine suites in one process (list in gpu-ticket.sh) 261 tests in 39 suites, 12 failed. 8 timed out (21-97 s per test): cbv2SchedCollect stops waiting after 20 s, and every failed check shows that signature, a missing (nil) finish reason or tokens that are an exact prefix of the expected sequence. All 8 passed in the pre-rebase run of 22 of these suites (2.6-13.9 s each), and one of them, the real-head test above, passed in 2.6 s in the focused run. 3 are tolerance cases on GEMM-shape differences: the 2 Qwen35MTPDraftTrimTests cases, and NemotronSuperMTPTextTargetTests.hiddenTargetMatchesPlainTextAndNarrowPrefill (max diff 9.0e-4 vs 1e-5; a direct model call, no engine). 1 is the removed join test
xctest -XCTest 14 XCTest suites, including CBv2SchedulerLoopTests, CBv2PrefillOutputTests, CBv2LogprobsTests, CBv2MTPCaptureVerifyTests and NemotronH35MTPTests 111 tests, 4 skipped, 1 failed: CBv2PrefillOutputTests.testNarrowedPathIsTokenIdenticalToFallback (narrowed vs sliced logits 1.3e-3 vs 1e-5; a test driver with no engine or MTP)
Real-model smoke: the paired provider's debug build, Qwen3.5-9B, --runtime-concurrency 1,2,4 --max-tokens 64, after vs both switches 0 Tokens identical at B = 1, 2 and 4. After: 63 chained steps (measured batch) and 0 seed rows at B = 2 and B = 4; before: 0 chained, 188 and 376 seed rows. B = 1: 26 vs 31 rounds, 2 vs 4 seed rows. The MTP counters include the 32-token warmup batch (188 = 2 rows x (63 + 31) seed steps). Every row finished by length
swift format format --configuration .swift-format (Command Line Tools 6.4 and swift-format 604.0.0) on the 11 changed Swift files No changes
python3 scripts/check_forkdiff.py 1,696 changed files, all described

Refactor-pass rerun on the same machine and toolchain, after the refactor pass (22896c7e, then 3fd6d07e, whose library code is identical). GPU commands ran in five tickets on the shared queue; the broad run started at load average 1.8.

Command Outcome
swift build --build-tests (same flags), at 22896c7e and at 3fd6d07e Build complete, 0 errors
Focused filter as above, at 22896c7e 56 tests: 54 passed. Failed: the 2 Qwen35MTPDraftTrimTests tolerance cases
Focused filter as above, at 3fd6d07e 57 tests: 55 passed, including the join test. Failed: the same 2 tolerance cases
The 23-suite broad filter, serialized (--no-parallel), at 22896c7e 260 tests in 39 suites, 3 failed: the 3 GEMM-shape tolerance cases above. All 8 tests that timed out in the parallel run passed (0.4-2.3 s each)
The 14 XCTest suites as above 111 tests, 4 skipped, 1 failed: the same testNarrowedPathIsTokenIdenticalToFallback case
Join test against two temporary mutations of finalizeMTPOrdinaryHistory (not committed): the pending carry not observed, or observed twice The join test failed both times (the carry entry's token; then [3, 9, 9, 10, …] is not increasing). The two batch-gated fixture tests passed both times
Real-model smoke as above, provider debug build with the 22896c7e library code Tokens identical to the earlier smoke in every row of both arms, and new identical to old at B = 1, 2 and 4. Counters identical at B = 2 and 4 (63 chained steps and 0 seed rows; 0 chained and 188 / 376 seed rows). The old arm's B = 1 adaptive-controller counters differ (26 rounds here, 31 in the earlier smoke) because depth selection reads measured step costs; two repeats of one binary in the M3 Ultra evidence also differ (98 vs 99 rounds) with identical tokens
swift format format --configuration .swift-format on the 12 changed Swift files No changes
python3 scripts/check_forkdiff.py; scripts/check-unit-test-files.sh 1,696 changed files, all described; OK

Not run: the full SDK test plan, and Lint with the CI's Xcode 26 formatter. Logs: logs/sdk-*.log and logs/smoke-*.json in the PR preparation directory; the rerun's logs, scripts and smoke comparison are in logs/refactor/.

Compatibility

  • Public API additions: CBv2MTPRequestStatefulDrafter.supportsOrdinaryDecodeHistory (default false); CBv2MTPConfig.ordinaryDecodeHistory and .prefillCarry (defaults from the two switches) with matching init parameters. Existing drafters and call sites are unchanged.
  • Only Qwen35InlineMTPAssistant opts in. Gemma, Nemotron (including Nemotron Super's recurrent MTP target) and MiMo keep their schedules; native completion tracking keeps MTP steps.
  • No KV, memory-quotation, wire or telemetry change. The [B, 1, H] hidden that a seed step already kept is now kept by the ordinary step instead.
  • An ineligible prompt row (stop strings, logprobs) planned with history-owning decode rows now runs through executeMixed, as with MTP off. Equal-length chunks may then pack, which disarms that prompt's recurrent checkpoint capture, again as with MTP off.

Limitations

  • Pre-rebase measurements. The M3 Ultra numbers come from the same engine change on SDK 14661d9b. Rebasing onto 66f556b7 merged three conflicts (non-finite readback in chained decode, the recurrent media-fallback refactor, the prefill loop's recurrent target-only branch) without changing this PR's logic. The rebased build passed this PR's tests and a real-model smoke but has no new rate measurement.
  • The join test checks order, not contiguity, after rounds resume. The first version (written after the code review) failed because its loop required every entry to be contiguous, while the fixture records committed-target observations and not round commits: in ordinary mode the first row's history is [3, 9, 10 … 15, 25, 26]. The version in 3fd6d07e checks that the pending carry is observed once, that the following entries continue from it, and that no entry repeats or moves back; it passes in both modes and fails on the two mutations in Validation.
  • Tolerance failures remain in the broad and XCTest runs, in code this PR does not run (below). The 8 collector timeouts of the parallel run under load passed in the serialized rerun on a quiet GPU (Validation).
  • Only Qwen3.5-9B was measured (the M3 Ultra has no 27B or 35B-A3B). M4 Max and M5 Max are unmeasured. M5 Ultra runs shared the GPU with other jobs, so their rates are not reported.
  • At B = 1 with long prompts the rate was -1.5% (1,892 tokens, 64 generated, 3 repeats) and -2.55% (one 256-token repeat); across 7 prompts the geomean is +0.08%. DARKBLOOM_TTFT_QWEN_MTP_CARRY=0 removes only the prefill carry.
  • Token 2 arrives 6-13 ms later (see Token timing). Per the implementation notes, the Qwen MTP chat templates pre-open or pre-close <think>, so token 1 is already content. The L1 load run agrees: its client TTFT counts the first content or reasoning text, and its paired median moved by +0.000 s. A client that waits for a second token sees the delay.
  • The first round after B >= 2 drops to B = 1 has no policy margin (previousTopTwoMargin is nil), so the depth policy skips its sigmoid cap for that one round. Output is unaffected (target-authoritative).
  • Two Qwen35MTPDraftTrimTests cases (atol 1e-5) also fail on the pristine 14661d9b bundle. This PR touches neither those tests nor the code they cover. CBv2PrefillOutputTests.testNarrowedPathIsTokenIdenticalToFallback and NemotronSuperMTPTextTargetTests.hiddenTargetMatchesPlainTextAndNarrowPrefill fail the same way on M5 Ultra (narrowed vs full GEMM shapes); neither runs code this PR changes, but neither was run on main here.

Landing order

  1. This SDK PR first.
  2. After its squash merge, re-pin the provider PR's libs/mlx-swift-lm to the merged main commit (the provider PR also moves libs/mlx-swift to 81f58d79 and libs/mlx to 71271f08, which SDK main needs).
  3. Sibling TTFT PRs that pin other SDK commits conflict with the provider PR only on these gitlinks; resolve by pinning the newest SDK main that contains both changes.

Refactor pass

A dedicated refactor subagent reviewed both PRs after the rebase: names, comment accuracy and density, dead code and duplication, test placement and coverage, docs and changelog against the code, the figures (rendered with mmdc), and this body against the evidence logs. It added 22896c7e and 3fd6d07e. The change's logic is untouched; the reruns are under Validation.

Changes in 22896c7e (no behavior change):

  • Duplication removed. The rebase brought main's row-based mtpRecurrentForwardWithHidden (feat(nemotron-super): target-only images on the speculating owner; saturating activation overflow; public checkpoint pin #315), and this PR's mtpHistoryTargetForward repeated its sequence: bind each row's recurrent transaction, run forwardWithHidden under the Qwen4 position scope and checkedModelForward, then evaluate. decodeLogits(returnsHidden:) now calls an ids-based mtpRecurrentForwardWithHidden, and the row-based seed-step variant wraps it. The same arrays are bound, evaluated and retained in the same order; only that sequence's precondition messages changed.
  • CBv2MTPRoundInFlight.prefillCarries and .prefillCarryTopTwoValues are immutable init parameters, like the seed fields, instead of vars set after construction.
  • CBv2MTPConfig.envEnabled uses the new envSwitch parser instead of a second copy of it.
  • The round driver's private flag is supportsOrdinaryDecodeHistory (was ordinaryDecodeHistoryTarget), and its doc comment includes the fence exclusion. The chained fast-path comment in engineStep no longer says that chained launches never capture hidden.
  • Qwen35MTPOrdinaryHistoryTests moved to Tests/MLXLMTests/Integration/Engine/ with the .integration tag, as CONTRIBUTING.md ("Test types") requires of new tests.

3fd6d07e adds the corrected join test (Limitations). In this body: the code-flow figures now name real symbols (engineStep, beginMTPPlan, mtpWantsStep, mtpRoundNeeded, finalizeMTPRound, permitsChainedSuccessor). They previously showed planStep, which does not exist, and finalizeRound, which is the drafter's round commit. The smoke row now says that the MTP counters include the warmup batch. L2 is lower for 55 of 62 requests, not 54 (one was 1 ms lower). The rerun results replace the open serialized-rerun gate.

Checked without a change:

  • Every new engine test runs both modes. Its new-mode expectations (chained steps, no seed step or policy top-two, a first carry at the prompt length, no synchronized_seed) fail on the old path, which the off mode asserts.
  • The body's numbers were re-derived from the evidence JSON: concurrent rates and first-token times, the L1 and L2 summaries and paired differences, the stagger, switch-split, B = 1 and long-prompt runs, and the earlier focused, broad and XCTest counts. All match, apart from the 54-of-62 count above.
  • Kept as they are: planCanSpeculate, an alias of controllerMeasurementEligible whose name fits its two new call sites; dropCarry, which differs from consumeCarry (a launching round takes its carry); and the carry-observation construction that mtpBuildRoundGraph and finalizeMTPOrdinaryHistory each write once.
  • Left for the lead: the names DARKBLOOM_TTFT_QWEN_MTP_CHAINED and DARKBLOOM_TTFT_QWEN_MTP_CARRY embed the program name, which the d-inference AGENTS.md asks files to avoid, and CHAINED changes decode, not TTFT. The tree's convention for Qwen MTP switches is DARKBLOOM_QWEN_MTP_* (SERIAL, SHORTLIST, DOUBLE_FORWARD), so DARKBLOOM_QWEN_MTP_CHAINED_DECODE and DARKBLOOM_QWEN_MTP_PREFILL_CARRY would fit. Renaming changes operator-facing names that sibling TTFT PRs share, so it was not done here.

🤖 Generated with Claude Code

Gajesh2007 and others added 6 commits October 21, 2026 17:11
The pull-request Lint job formats every Swift file a pull request
touches, and this file is not formatted on main. Formatting only
(swift format with the repository .swift-format); no code change.

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

The inline Qwen MTP head speculates for one decode row only, yet every
eligible row of a two-or-more-row batch ran as a non-chained MTP seed step:
a hidden-returning forward, a vocabulary-wide policy top-two reduction, an
extra host readback and per-row lazy history bookkeeping, with no successor
built while the GPU worked. Every request also ran one target-only seed step
after its first token, although prefill already produced that exact pair.

Drafters can now opt in with `supportsOrdinaryDecodeHistory` (the inline
Qwen head does). While no row can speculate, decode rows take the ordinary
`executeMixed` / chained path: the target forward also returns its [B, 1, H]
pre-norm hidden (same trunk and lm_head, so logits are unchanged), and
finalize feeds each row's committed input and hidden to the assistant
history in launch order. A row with no successor in flight receives the
carry a seed step would have stored; otherwise any older carry is dropped,
so a verify carry's pending transition is observed exactly once. A
preempted, cancelled or finished row is skipped (its history was released).
Prompt rows keep the hidden-returning MTP prefill path so history still
starts at position zero, and mixed seed steps skip the policy top-two when
the plan cannot speculate.

The final prompt chunk's last hidden row becomes the first carry once the
first token is confirmed, with its policy margin when the prompt finishes
alone, so a round can follow the first token without a seed step.

Native completion tracking keeps its MTP-step schedule. Kill switches:
DARKBLOOM_TTFT_QWEN_MTP_CHAINED=0 restores seed steps for batch-gated
rows; DARKBLOOM_TTFT_QWEN_MTP_CARRY=0 restores the post-first-token seed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Parallel suites consume the global random stream between seeding and
initialization, so building the tiny target per engine produced different
weights for the reference and candidate engines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ordinary decode steps carry no `mtpRound`, so they never run the
committed-observation fence (`finishStatefulMTPEvaluation`). A drafter
that sets `requiresCommittedObservationFence` therefore keeps MTP steps
even when it also opts into `supportsOrdinaryDecodeHistory`. Only the
Qwen inline head opts in today and it needs no fence, so serving is
unchanged; the contract is now enforced instead of documented.

The new test checks that the round driver ignores the opt-in for a
drafter that requires the fence.

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

`decodeLogits(returnsHidden:)` now calls an ids-based
`mtpRecurrentForwardWithHidden`, which the row-based seed-step variant
wraps, instead of a second copy of the bind, forward and evaluate
sequence. The same arrays are bound, evaluated and retained in the same
order; only that sequence's precondition messages change.

Prefill carries become immutable round data passed through
`CBv2MTPRoundInFlight.init`, like the seed fields. `CBv2MTPConfig.envEnabled`
uses the parser of the two new switches. The round driver's flag is
named `supportsOrdinaryDecodeHistory` and documents the fence exclusion,
and the chained fast-path comment now says which chained rows capture
hidden.

The new Qwen3.5 engine suite moves to Tests/MLXLMTests/Integration/Engine
with the `.integration` tag, as CONTRIBUTING.md asks of new tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The first row prefills and runs two rounds alone; a second row joins
while the first row's verify carry is pending, so the first row decodes
beside it and then speculates alone again. In both modes the tokens
equal MTP off, state is released, and the first row's history holds the
pending carry once, then the steps after it from that token, and never
repeats or reorders an entry.

The fixture records committed-target observations but not round
commits, so entries after rounds resume skip positions; the test checks
only that they increase. Skipping the carry observation in
`finalizeMTPOrdinaryHistory`, or making it twice, fails this test while
the other ordinary-history tests still pass.

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

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T00:32:43.453896Z c66869e New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Refresh before review: d-inference master now pins SDK 0351444.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Gajesh2007
Gajesh2007 merged commit fa63c27 into main Oct 22, 2026
6 checks passed
@Gajesh2007
Gajesh2007 deleted the ttft/qwen-mtp-decode branch October 22, 2026 00:36
Gajesh2007 added a commit to Layr-Labs/d-inference that referenced this pull request Oct 22, 2026
Layr-Labs/mlx-swift-lm#330 squash-merged as fa63c27, and d-inference master
already pins SDK main 889fe3cc, which contains it (and #322). Pin that commit
instead of the PR branch head, so this PR no longer moves the SDK pin and
carries only its provider-side changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 added a commit that referenced this pull request Oct 22, 2026
Refresh before review: d-inference master pins SDK main 889fe3c, which adds
#322 (Flint tool protocol) and #326-#330. Resolved ToolCallProcessor.swift by
keeping Flint's tool protocol handling alongside the streamed tool_calls
fragments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 22, 2026
Brings #322 (Flint), #324, #326-#330 (CBv2 paged/MTP/SDPA, GPT-OSS), #325 and the
Nemotron Super fused MTP verify window: SDK main up to the commit d-inference
master pins (889fe3c). Main's later #331/#332 are left out until the provider
adopts #332's streamed tool-call type. Package.swift pins the cluster
mlx-swift 9fe34405 instead of main's 67dc7528; that was the only conflict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 added a commit to Layr-Labs/d-inference that referenced this pull request Oct 22, 2026
…time benchmark (#1543)

* perf(provider): chain batch-gated Qwen MTP decode; add concurrent runtime benchmark

Pins libs/mlx-swift-lm to the ttft/qwen-mtp-decode commits on SDK main:
while the inline Qwen MTP head cannot speculate (more than one decode
row), its rows run ordinary chained decode that feeds the head history
at finalize, with no policy top-two or extra readback, and the final
prompt row seeds the first carry so a round can follow the first token
without a seed step. Rollbacks: DARKBLOOM_TTFT_QWEN_MTP_CHAINED=0 and
DARKBLOOM_TTFT_QWEN_MTP_CARRY=0.

SDK main needs libs/mlx-swift 81f58d79 (GPU.CommandBufferLimits); its
nested MLX is 71271f08, and libs/mlx moves to the same commit.

`darkbloom benchmark --runtime-generation [--runtime-mtp]
--runtime-concurrency 1,2,4,8` drives distinct greedy rows through one
production slot per batch size (the artifact's MTP policy, prefix caches
off), warmed by an identical batch, and reports per-row tokens, first and
third token times, decode rates, the all-rows decode window, chained steps
and MTP metrics as JSON. CBV2_STEP_PROFILE=1 adds a per-batch phase table
on stderr.

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

* feat(provider): staggered rows and early token times for --runtime-concurrency

`--runtime-stagger` stops row i of a B-row batch after
max-tokens*(B-i)/B tokens (at least 3), so the decode cohort shrinks to
one row and the report shows speculation resuming as concurrency drops.
Each row now also reports `earlyTokenMs`, the submit-to-arrival times of
its first eight tokens.

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

* refactor(provider): pin the SDK refactor pass; tighten docs and the benchmark report

Pins libs/mlx-swift-lm to 3fd6d07e: 22896c7e shares one recurrent
hidden-returning forward between seed steps and ordinary-history decode
and moves the new Qwen3.5 engine suite to Integration/Engine (no
behavior change), and 3fd6d07e adds a test for a row joining while
another row speculates.

The concurrency benchmark now documents that each cell's MTP metrics
include the warmup batch, while chained steps count the measured batch
only. The CLI reference lists the first-eight token times and the
three-token stagger floor. The configuration rows cite the full path.
The inference paragraph names the rollback switches and links their
reference, as docs/AGENTS.md asks, and the changelog says LaunchAgents
do not forward the switches.

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

* Re-pin libs/mlx-swift-lm to SDK main 889fe3cc

Layr-Labs/mlx-swift-lm#330 squash-merged as fa63c27, and d-inference master
already pins SDK main 889fe3cc, which contains it (and #322). Pin that commit
instead of the PR branch head, so this PR no longer moves the SDK pin and
carries only its provider-side changes.

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

* refactor(benchmark): share verified target loading between runtime benchmarks

Move RuntimeGenerationBenchmark's model-type refusal, Metal check, pre- and
post-load weight hash, container load, tokenizer handle, prompt rendering,
prefix-cache-off environment and SHA-256 hex into loadVerifiedTarget,
preparedPrompt, prefixCacheDisabledEnvironment and sha256Hex so the
runtime-concurrency mode can use the same verified load. A post-load hash
mismatch still releases the container and throws modelHashMismatch.
Behavior of the runtime-generation report is unchanged.

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

* fix(benchmark): make runtime-concurrency cells verifiable measurements

Address the review findings in the opt-in --runtime-concurrency mode:

- Parse batch sizes with RuntimeConcurrencyBenchmark.batchSizes: an empty,
  non-numeric or out-of-range entry refuses the whole list (the CLI reports
  it before any model work) instead of being dropped.
- Staggered quotas are maxTokens*(B-i)/B without a floor; rowMaxTokens
  refuses maxTokens < 3B, so quotas stay distinct and at least 3 rather
  than collapsing onto a shared 3-token floor.
- Load through loadVerifiedTarget, which rehashes the weights after the
  container load before any session is built.
- Refuse a cell whose session.effectiveMaxConcurrentRequests differs from
  its batch size before warmup; it is listed in refusedCells.
- Validate each row's terminal (rowFailure): length exactly at its quota,
  or a configured stop token within it, and in stagger mode the full
  quota. Failures and refused cells make the run unsuccessful (exit 2).
- Use the two-sided median for medianRowDecodeTokensPerSecond.
- Start draining each row's stream as soon as its submit returns, so
  arrivals are not timed after the remaining submissions.
- Record the verified model hash, prompt hash, render date and per-row
  prompt-token hashes, plus per-cell backend, KV precisions, MTP state
  and assistant identity.
- Tear each cell down with shutdownReportingCompletion and propagate a
  native retirement failure (keeping the container) instead of the
  error-swallowing shutdown(); a measurement error still takes priority.

The pure helpers and the report summary move to
RuntimeConcurrencyBenchmarkReport.swift with unit tests, including a
scripted submit that only returns once the previous row is being drained.

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

* docs: describe runtime-concurrency validation, refusals and provenance

cli-reference documents the 1-64 size range and malformed-list refusal,
the 3xB stagger requirement, refusedCells, the provenance fields and the
exit-2 conditions; test.md's focused filter now includes the new suite.
The changelog fragment gains the benchmark mode entry.

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

* refactor(benchmark): tidy runtime-concurrency refusal and doc citations

Behavior-preserving cleanup from the independent refactor pass:

- Read the slot's effective width once when deciding whether a cell is
  measured or refused.
- cli-reference cites rowFailure with its source file
  (RuntimeConcurrencyBenchmarkReport.swift) and qualifies rowMaxTokens.
- The changelog entry states the actual stagger refusal (--max-tokens
  below 3xB, not only equal quotas) and lists a stop without a configured
  stop token among the exit-2 conditions.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
javiech1 pushed a commit to javiech1/mlx-swift-lm that referenced this pull request Oct 24, 2026
…rs (Layr-Labs#330)

Mirrors the LLM-side sanitize drop merged in Layr-Labs#342 to the MLXVLM Gemma4
text backbone: KV-shared layers (the last `num_kv_shared_layers`) reuse an
earlier layer's K/V and own no `k_proj`/`v_proj`/`k_norm`. After Layr-Labs#327,
those module slots are optional and not built for shared layers. QAT
checkpoints already omit the redundant tensors; some PTQ checkpoints still
ship them and would fail to load against the smaller tree.

Scope the drop to the text backbone only — `vision_tower` / `audio_tower`
share the `layers.N.self_attn.{k,v}_proj` naming, so an unguarded
predicate would amputate tower layers >= firstKVSharedLayer.
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