Repository navigation
perf(cbv2): chain batch-gated Qwen MTP decode and seed the first carry from prefill - #330
Merged
Merged
Conversation
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>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
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>
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The inline Qwen MTP head (
Qwen35InlineMTPAssistant) speculates for one decode row only (maximumSpeculativeBatch1). 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):executeMixed/launchChainedDecodesteps. The target forward also returns its[B, 1, H]pre-norm hidden (decodeLogits(returnsHidden:)callsmtpRecurrentForwardWithHidden, the seed steps' recurrent forward: same trunk, positions and lm_head, so logits are unchanged).finalizeMTPOrdinaryHistoryappends 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.requiresCommittedObservationFencekeeps 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=0restores the post-first-token seed step. With both set, the engine takes the pre-PR path.d489c297style(tests): format CBv2QwenMTPIntegrationTests.swiftmain534db8a3perf(cbv2): chain batch-gated Qwen MTP decode and seed the first carry from prefillCBv2MTPConfig.ordinaryDecodeHistory,.prefillCarry),EngineLoopV2+MTPOrdinaryHistory.swift, and tests8fd0e7fatest(qwen35): share one target across ordinary-history enginesbe4bc656fix(cbv2): keep MTP steps for drafters that need the observation fence22896c7erefactor(cbv2): share the recurrent hidden-returning forward with ordinary history3fd6d07etest(cbv2): cover a row joining while another row speculatesBase:
main@66f556b7(#318). The provider pin is the paired Layr-Labs/d-inference PR (branchttft/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.5pxAfter
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.5pxLegend: 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 throughdarkbloom benchmark --runtime-generation --runtime-mtp --runtime-concurrency(the provider PR adds it). "Before" is the same binary with both kill switches set to0. Measured on the pre-rebase build: the same engine change on SDK14661d9b(b0c9ba00; binariesb248bfd9…and7de052d5…,mlx.metallibfb1ba8f9…). The rebased build was tested and smoke-run but not re-measured (see Validation). Logs:qwen-mtp-decode/{m3u,m3u3}/*.jsonandqmtp-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):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):TTFT counts the client-side queue (the coordinator-like
--max-inflightwait). 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); withDARKBLOOM_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
Qwen35MTPOrdinaryHistoryTests(Integration/Engine) "batch-gated rows chain with exact tokens and contiguous history"CBv2QwenMTPIntegrationTests"batch-gated history rows chain and observe every committed input once"synchronized_seedfallbackrequiresCommittedObservationFencefinalizeMTPOrdinaryHistory, or making it twice, fails this test; the two batch-gated fixture tests above still passValidation
Run on M5 Ultra (
applegpu_g17d) in the PR clone, fromlibs/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 is6af40831;be4bc656differs 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 final3fd6d07e.nice -n 15 swift build --build-tests, with the Swift Testing plugin path and XCTest from Xcodemlx-swift81f58d79. Same onbe4bc656../../scripts/stage-test-metallib.sh .build/debugmlx.metallibbuilt from nested MLX71271f08: SHA-256fb1ba8f9…swift test --skip-build --filter 'Qwen35MTPOrdinaryHistoryTests|CBv2QwenMTPIntegrationTests|Qwen35MTPDraftTrimTests'Qwen35MTPDraftTrimTeststolerance cases, and the removed join testswift test --skip-build --filter23 MTP and engine suites in one process (list ingpu-ticket.sh)cbv2SchedCollectstops 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 2Qwen35MTPDraftTrimTestscases, andNemotronSuperMTPTextTargetTests.hiddenTargetMatchesPlainTextAndNarrowPrefill(max diff 9.0e-4 vs 1e-5; a direct model call, no engine). 1 is the removed join testxctest -XCTest14 XCTest suites, includingCBv2SchedulerLoopTests,CBv2PrefillOutputTests,CBv2LogprobsTests,CBv2MTPCaptureVerifyTestsandNemotronH35MTPTestsCBv2PrefillOutputTests.testNarrowedPathIsTokenIdenticalToFallback(narrowed vs sliced logits 1.3e-3 vs 1e-5; a test driver with no engine or MTP)--runtime-concurrency 1,2,4 --max-tokens 64, after vs both switches0swift format format --configuration .swift-format(Command Line Tools 6.4 and swift-format 604.0.0) on the 11 changed Swift filespython3 scripts/check_forkdiff.pyRefactor-pass rerun on the same machine and toolchain, after the refactor pass (
22896c7e, then3fd6d07e, whose library code is identical). GPU commands ran in five tickets on the shared queue; the broad run started at load average 1.8.swift build --build-tests(same flags), at22896c7eand at3fd6d07e22896c7eQwen35MTPDraftTrimTeststolerance cases3fd6d07e--no-parallel), at22896c7etestNarrowedPathIsTokenIdenticalToFallbackcasefinalizeMTPOrdinaryHistory(not committed): the pending carry not observed, or observed twice[3, 9, 9, 10, …]is not increasing). The two batch-gated fixture tests passed both times22896c7elibrary codeswift format format --configuration .swift-formaton the 12 changed Swift filespython3 scripts/check_forkdiff.py;scripts/check-unit-test-files.shNot run: the full SDK test plan, and Lint with the CI's Xcode 26 formatter. Logs:
logs/sdk-*.logandlogs/smoke-*.jsonin the PR preparation directory; the rerun's logs, scripts and smoke comparison are inlogs/refactor/.Compatibility
CBv2MTPRequestStatefulDrafter.supportsOrdinaryDecodeHistory(defaultfalse);CBv2MTPConfig.ordinaryDecodeHistoryand.prefillCarry(defaults from the two switches) with matchinginitparameters. Existing drafters and call sites are unchanged.Qwen35InlineMTPAssistantopts in. Gemma, Nemotron (including Nemotron Super's recurrent MTP target) and MiMo keep their schedules; native completion tracking keeps MTP steps.[B, 1, H]hidden that a seed step already kept is now kept by the ordinary step instead.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
14661d9b. Rebasing onto66f556b7merged 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.[3, 9, 10 … 15, 25, 26]. The version in3fd6d07echecks 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.DARKBLOOM_TTFT_QWEN_MTP_CARRY=0removes only the prefill carry.<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.previousTopTwoMarginis nil), so the depth policy skips its sigmoid cap for that one round. Output is unaffected (target-authoritative).Qwen35MTPDraftTrimTestscases (atol1e-5) also fail on the pristine14661d9bbundle. This PR touches neither those tests nor the code they cover.CBv2PrefillOutputTests.testNarrowedPathIsTokenIdenticalToFallbackandNemotronSuperMTPTextTargetTests.hiddenTargetMatchesPlainTextAndNarrowPrefillfail the same way on M5 Ultra (narrowed vs full GEMM shapes); neither runs code this PR changes, but neither was run onmainhere.Landing order
libs/mlx-swift-lmto the mergedmaincommit (the provider PR also moveslibs/mlx-swiftto81f58d79andlibs/mlxto71271f08, which SDKmainneeds).mainthat 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 added22896c7eand3fd6d07e. The change's logic is untouched; the reruns are under Validation.Changes in
22896c7e(no behavior change):main's row-basedmtpRecurrentForwardWithHidden(feat(nemotron-super): target-only images on the speculating owner; saturating activation overflow; public checkpoint pin #315), and this PR'smtpHistoryTargetForwardrepeated its sequence: bind each row's recurrent transaction, runforwardWithHiddenunder the Qwen4 position scope andcheckedModelForward, then evaluate.decodeLogits(returnsHidden:)now calls an ids-basedmtpRecurrentForwardWithHidden, 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.prefillCarriesand.prefillCarryTopTwoValuesare immutableinitparameters, like the seed fields, instead ofvars set after construction.CBv2MTPConfig.envEnableduses the newenvSwitchparser instead of a second copy of it.supportsOrdinaryDecodeHistory(wasordinaryDecodeHistoryTarget), and its doc comment includes the fence exclusion. The chained fast-path comment inengineStepno longer says that chained launches never capture hidden.Qwen35MTPOrdinaryHistoryTestsmoved toTests/MLXLMTests/Integration/Engine/with the.integrationtag, asCONTRIBUTING.md("Test types") requires of new tests.3fd6d07eadds the corrected join test (Limitations). In this body: the code-flow figures now name real symbols (engineStep,beginMTPPlan,mtpWantsStep,mtpRoundNeeded,finalizeMTPRound,permitsChainedSuccessor). They previously showedplanStep, which does not exist, andfinalizeRound, 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:
synchronized_seed) fail on the old path, which the off mode asserts.planCanSpeculate, an alias ofcontrollerMeasurementEligiblewhose name fits its two new call sites;dropCarry, which differs fromconsumeCarry(a launching round takes its carry); and the carry-observation construction thatmtpBuildRoundGraphandfinalizeMTPOrdinaryHistoryeach write once.DARKBLOOM_TTFT_QWEN_MTP_CHAINEDandDARKBLOOM_TTFT_QWEN_MTP_CARRYembed the program name, which the d-inferenceAGENTS.mdasks files to avoid, andCHAINEDchanges decode, not TTFT. The tree's convention for Qwen MTP switches isDARKBLOOM_QWEN_MTP_*(SERIAL,SHORTLIST,DOUBLE_FORWARD), soDARKBLOOM_QWEN_MTP_CHAINED_DECODEandDARKBLOOM_QWEN_MTP_PREFILL_CARRYwould fit. Renaming changes operator-facing names that sibling TTFT PRs share, so it was not done here.🤖 Generated with Claude Code