Repository navigation
Port upstream PR 607: DFlash2 block speculative decoding for Qwen3.5 and Qwen3.8 - #70
ronaldmannak wants to merge 6 commits into
Conversation
Adds DFlash2 speculative decoding: a drafter model (DFlash2DraftModel), the iterator that drives it (DFlash2SpeculativeTokenIterator), a factory and registry in the MTP drafter's shape, generate/generateTokens overloads, and the target side on Qwen35TextModel/Qwen35Model, which also serve the qwen3_8 model types. The drafter embeds [anchor, MASK x 7], attends over a sliding window of the target's captured hidden states and walks the top-16 candidates per position with its selector; the target verifies the block in one pass. The next round is built while that pass runs, from lazy accept-dependent arrays, and the host syncs once per round. Greedy rounds compare argmaxes; sampled rounds rejection-sample against the selector's candidate distribution. A verify pass sums in a different order than a one-token step, so greedy output can differ from TokenIterator where the top two logits nearly tie. The iterator follows the token-loop contracts the MTP iterator follows: - the logit processor comes from logitProcessor(parameters:model:), and the drafter masks the same suppressed ids before it picks candidates; - recordEmittedToken reaches the processor's didEmit, reasoningTokenCount is reported, and finalizeGeneration reaches the processor; - prefill runs through PrefillParameters.forEachChunk, after reporting the reused prefix through prefill.prefix; - a KV cache plan that compresses or bounds the cache is rejected before prefill, since the verify pass writes plain attention rows; - the MLX buffer cache is cleared on the first token and every 256, as TokenIterator does; - generate takes tool schemas and passes the tool-call policy. The drafter reads both published config layouts (layer_types with sliding_window, and mlx-community's dflash_config.use_swa with a top-level block_size) and is checked against the target's depth, hidden size and vocabulary before prefill. The factory passes excludedComponents. Qwen3.5: the verify pass reuses the compiled decode segments with S rows, writes attention rows at a lazy position without moving the cache offset, and returns gated-delta captures so the iterator can replay the recurrent state to the accepted prefix. Its traces declare the fused GDN projection as compile state, as the decode traces do, and live in a keyed cache that invalidateCompiledTraces() reaches. The plain decode path is unchanged. (cherry picked from commit 47ec29a)
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6059057b8f
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
The generate(dflash2Drafter:) overloads pass a caller's cache with prefilledPrefixTokens left at zero, which is how a chat turn arrives: the cache holds the conversation so far and `input` is only the new tokens. Prefill appended the new tokens after the cached positions, but the first verify pass then started at `input`'s length instead of the cache's absolute position, so it wrote attention rows over cached ones, applied RoPE at the wrong positions, and told the drafter its context rows sat at position zero. Derive the absolute positions from the cache's offset before prefill: `origin` is where `input`'s first token sits, the anchor and the drafter's context position follow from it, and the reused prefix reported through `prefill.prefix` is the cache's position count, as TokenIterator reports it. A cold cache and the explicit `prefilledPrefixTokens` warm start are unchanged. Found by the Codex review of #70. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
With `temperature > 0` and `GenerateParameters.seed` set, the first token and the rejection sampling drew from the iterator's seeded state, but `drafter.propose` ran outside it, so the selector's `categorical` consumed the global random state. Different proposals change which drafts are accepted, so two runs with the same seed could emit different tokens. Run the proposal under `withRandomState(randomState)` as the acceptance already does. The mock target in the tests now builds its captures from a private random state instead of reseeding the global one. Found by the Codex review of #70. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3ae9aeeb77
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
With `temperature > 0` and a seed, `parameters.sampler()` and the iterator each built a random state from the same seed, so both started on the same key: the sampler spent it on the first token and the iterator spent it again on the first drafts, which correlated the drafts with the anchor and broke the independence rejection sampling assumes. Upstream 607 had the same overlap between the first token and the first acceptance draw. Sampled rounds now draw the first token from the iterator's own state, through the same filtered distribution `speculativeSamplingProbabilities` builds for acceptance, so one advancing stream serves the first token, the drafts and the acceptance and no key is drawn twice. Greedy rounds still use the argmax sampler. The mock drafter's first sampled draft now has the shape of the target's first-token sample, and the mock target can emit flat logits, so the test can show that a shared key would repeat the first token as the first draft. Found by the Codex review of #70. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Brings in the 32 commits main gained since 991266a, among them mlx-swift 0.33.0, the MLXFast gated delta kernel and LFM2.5 DSpark. One conflict: main and this branch each added a speculative decoding section to using-model.md at the same place. Both are kept, main's LFM2.5 DSpark section first, then the DFlash2 section unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 799f75f7d2
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Main's reasoning streaming (ml-explore#563) passes the model's reasoning configuration to the text handler in the plain and MTP generate overloads, so thinking text arrives as `.reasoning` events. The DFlash2 overload from PR 607 predates it and passed none, so a Qwen 3.5 or 3.8 target's thinking arrived as ordinary `.chunk` output, delimiters included. Read whether the prompt already opens a thought before the iterator queues its prefill, and pass the configuration and that seed to the handler, as the MTP overload does. The new test streams a prompt that ends in a prefilled `<think>` and expects the thought as reasoning and the rest as the answer. Found by the Codex review of #70. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Closes PicoMLX/picocore#252
This is upstream PR
ml-explore/mlx-swift-lm#607("DFlash2 block speculative decoding for Qwen3.5 and Qwen3.8") by @spokvulcan, cherry-picked onto forkmainwithgit cherry-pick -x 47ec29a. The author's authorship is kept. The upstream PR is still open and unreviewed there. The port is byte-identical to47ec29afor all nine files;Evaluate.swiftdiffers only by the 17 lines main itself added in ml-explore#714, which the cherry-pick merged around. No adaptation commit was needed: the branch compiles and tests against current main as is. Three further commits fix defects the Codex review found in the ported iterator (see below); the port commit itself is untouched.What changed
Libraries/MLXLMCommon/DFlash2DrafterModel.swift: theDFlash2DrafterModelandDFlash2TargetModelprotocols,DFlash2Geometry, drafter state, and the proposal / verify request and result types.Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift: a block speculative iterator. Each round verifies[anchor, draft × (blockSize − 1)]in one target pass, builds the next round from lazy accept-dependent arrays, and syncs the host once per round. Greedy rounds compare argmaxes; sampled rounds rejection-sample against the drafter's candidate distribution. It follows the MTP iterator's token-loop contracts (logit processor,didEmit,finalizeGeneration,PrefillParameters.forEachChunk, buffer-cache clearing, tool schemas) and rejects compressed or bounded KV cache plans before prefill.Libraries/MLXLMCommon/DFlash2DrafterModelFactory.swiftandLibraries/MLXLLM/DFlash2Registration.swift: a factory and type registry in the MTP drafter's shape. DFlash2 checkpoints reportmodel_type: qwen3; thedflash_configobject tells them apart.Libraries/MLXLLM/Models/DFlash2.swift: the drafter (DFlash2DraftModel) with its dynamic convolution, sliding-window context cache over the target's captured hidden states, and the top-16 candidate selector. Reads both published config layouts.Libraries/MLXLLM/Models/Qwen35.swift:DFlash2TargetModelonQwen35TextModelandQwen35Model(also serving theqwen3_8types):dflash2Prefillcaptures layer outputs,dflash2Verifyreuses the compiled decode segments with S rows, writes attention rows at a lazy position without moving the cache offset, and returns gated-delta captures so the iterator can replay the recurrent state to the accepted prefix. The plain decode path is unchanged apart from factoring the q/k norm intonormalizedQK.Libraries/MLXLMCommon/Evaluate.swift:generate(..., dflash2Drafter:)andgenerateTokens(..., dflash2Drafter:)overloads.Libraries/MLXLLM/Documentation.docc/using-model.mdgains a DFlash2 section.Tests/MLXLMTests/DFlash2Tests.swiftadds 25 Swift Testing tests and one XCTest class.Fork-side fixes after Codex review
All are in
Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift, each with a regression test inTests/MLXLMTests/DFlash2Tests.swiftthat fails before the fix and passes after it. Upstream 607 still has these defects; the owner may want to carry them upstream by hand.generate(dflash2Drafter:)overloads pass a caller's cache withprefilledPrefixTokensat zero, which is how a chat turn arrives: the cache holds the conversation andinputis the new tokens only. Prefill appended after the cached positions, but the first verify pass started atinput's length, so it overwrote cached attention rows, applied RoPE at the wrong positions, and told the drafter its context started at zero. The iterator now derives absolute positions from the cache's offset before prefill and reports the cache's position count throughprefill.prefix, asTokenIteratordoes. Cold caches and the explicitprefilledPrefixTokenswarm start are unchanged. Test:testDFlash2IteratorContinuesAfterCachedPrefix.temperature > 0and aseed, the first token and the rejection sampling drew from the iterator's seeded state butdrafter.proposeran outside it, so the selector'scategoricalconsumed the global random state and two runs with the same seed could emit different tokens. The proposal now runs underwithRandomState(randomState). The mock target in the tests builds its captures from a private random state instead of reseeding the global one. Test:testDFlash2SeededSamplingIgnoresGlobalRandomState.parameters.sampler()and the iterator each built a random state from the same seed, so both started on the same key: the sampler spent it on the first token and the iterator spent it again (on the first acceptance draw in upstream 607, and on the first drafts after the previous fix), correlating the drafts with the anchor. Sampled rounds now draw the first token from the iterator's own state through the same filtered distribution the acceptance uses, so one advancing stream serves everything and no key is drawn twice. Greedy rounds still use the argmax sampler. Test:testDFlash2FirstTokenAndDraftsDrawDifferentKeys.Evidence
All runs on this machine (Xcode 27.1, macOS, Debug) via
DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' -skipPackagePluginValidation.Note on the selector:
-only-testing:MLXLMTests/DFlash2Testsruns zero tests and still reports success, because the file holds top-level@Testfunctions with no suite of that name plus the XCTest classDFlash2MemoryTests. The run below selected each of the 25 functions by name (-only-testing:'MLXLMTests/testDFlash2…()') plus-only-testing:MLXLMTests/DFlash2MemoryTests.DFlash2 tests on the PR head 2034ffc (28 Swift Testing functions plus
DFlash2MemoryTests):The 28 passing functions (the last three are this PR's regression tests): testDFlash2ConfigurationDecodesReleaseCheckpoint, testDFlash2ConfigurationRejectsUnsupportedShapes, testDFlash2ConfigurationReadsTheMLXCommunityLayout, testDFlash2GeometryChecksWidthVocabularyAndDepth, testDFlash2ContextCachePlaceholdersResolve, testDFlash2ContextCacheCompactionKeepsNewestValidRows, testDFlash2VisibilityMaskWindowsAndHidesPlaceholders, testDFlash2DynamicConvMatchesNaive, testDFlash2SelectorGreedyPrefersCoherentPath, testDFlash2CompiledProposalMatchesEager, testDFlash2DrafterSkipsSuppressedTokens, testSpeculativeSamplingProbabilitiesMatchTopPSampler, testDFlash2IteratorAcceptsPrefixAndTakesBonus, testDFlash2IteratorMatchesTokenIteratorWithPenalties, testDFlash2IteratorWarmStartMatchesColdStream, testDFlash2IteratorFinalizeRewindsUndrainedDrafts, testDFlash2IteratorRejectsUnsupportedInputs, testDFlash2IteratorNeverEmitsSuppressedTokens, testDFlash2IteratorForwardsEmitAndFinalizeToTheProcessor, testDFlash2IteratorReportsPrefixAndProgress, testGatedDeltaCaptureReplayMatchesPrefix, testDFlash2RejectionSampleFullAgreementAcceptsAll, testDFlash2RejectionSampleZeroProbabilityRejectsFirst, testQwen35VerifyMatchesOneForwardAndCommitsAnyPrefix, testQwen35VerifySeesReplacedProjectionsAfterInvalidation, testDFlash2IteratorContinuesAfterCachedPrefix, testDFlash2SeededSamplingIgnoresGlobalRandomState, testDFlash2FirstTokenAndDraftsDrawDifferentKeys.
Whole
MLXLMTestsbundle on the PR head 2034ffc (-only-testing:MLXLMTests):Whole
MLXLMTestsbundle onorigin/main(991266a, separate worktree):The deltas are exactly this PR's tests: +1 XCTest (
DFlash2MemoryTests) and +28 Swift Testing functions (25 from upstream 607, 3 regression tests from the fixes above). The same bundle on the port commit 6059057 alone was 843 / 1223 with 0 failures. The 4 skipped tests are the same local-checkpoint benchmarks on both (Gemma4FusionTests.testFusionLatency,Qwen35FusedGDNProjectionTests.testRealCheckpointBenchmark,Qwen35PrefillLogitsTests.testLocalCheckpointTextAndVisionParity,Qwen3PrefillLogitsTests.testLocalCheckpointPreservesLogitsCacheAndContinuation). Upstream 607's description saystargetLoaderExcludesConvertedMTPComponent(vision: true)fails on main; that is stale here. It passes on both current main and the PR head (Test targetLoaderExcludesConvertedMTPComponent(vision:) with 2 test cases passed).pre-commit run --all-fileswith swift-format 603.0.0 (the version.github/workflows/pull_request.ymlpins; built from the 603.0.0 tag, since Homebrew ships 604.0.0):No files changed after the run.
scripts/verify-docs.sh: MLXLLM and MLXLMCommon (the two library targets this PR touches) build their documentation with no warnings, as do BenchmarkHelpers, IntegrationTestHelpers, MLXEmbedders, MLXRerankers, MLXScriptedLM and MLXVLM. The script exits 1 because MLXGuidedGeneration and MLXHuggingFace fail inclang -extract-apion the vendored xgrammar header:The same two targets fail identically on
origin/main991266a with this Xcode 27.1 toolchain, so it is a local environment issue and not something this PR introduces.Xcode Cloud "PicoMLXSwiftIntegrationTesting | Default | Build - macOS" fails on this head with:
(and the same line for
swift-syntax). The same check fails with the same two errors onorigin/main991266a, so it is pre-existing and not caused by this PR. Cause: the fork's Xcode Cloud setup relies onci_scripts/ci_post_clone.sh(plusIntegrationTesting/ci_scripts/ci_post_clone.shandci_override.xcconfig), which exist onpico/0.32.4-jacclbut not onmain. That script runsdefaults write com.apple.dt.Xcode IDEDisableAutomaticPackageResolution -bool NOandIDEPackageOnlyUseVersionsFromResolvedFile -bool NO, so PRs against the jaccl branch resolve packages while anything againstmainrequires aPackage.resolved, which this repository gitignores. Porting those scripts tomainis a CI change and belongs to PicoMLX/picocore#259. This PR touches no package dependency.Merge with main (799f75f) and reasoning routing (6494db9)
Fork
mainmoved to 4ab2679 (32 commits, including mlx-swift 0.33.0, the MLXFast gated delta kernel and reasoning streaming), and this PR conflicted with it. 799f75f mergesmainwithout a rebase or force-push. The only conflict was inLibraries/MLXLLM/Documentation.docc/using-model.md, where both sides added a speculative decoding section at the same place. Both are kept: main's LFM2.5 DSpark section, then the DFlash2 section unchanged.6494db9 fixes the Codex finding on the merge. Main's reasoning streaming (ml-explore#563) passes the reasoning configuration to the text handler in the plain and MTP
generateoverloads, but the DFlash2 overload from 607 did not. A Qwen 3.5 or 3.8 thought therefore arrived as.chunktext. The overload now reads whether the prompt opens a thought, then passesreasoningConfigand that seed, as the MTP overload does.testDFlash2GenerateRoutesReasoningcovers it: it fails on 799f75f, with no reasoning andweigh it</think>Answeras chunks, and passes on 6494db9.DFlash2 tests on 6494db9:
Whole
MLXLMTestsbundle on 6494db9:The same bundle on
main4ab2679:The two Swift Testing failures are identical on both. They are
EmbeddingGemmaMaskTests"G7: a left-padded batch matches the texts run one at a time" (relNorm about 1e-3 against a 1e-5 bound) andLFM2DSparkMetalTests.rotatingHybridCacheMatchesGreedyAcrossWindowwithpromptLength 3(a difference above 1e-4). Both suites arrived withmain, so they are pre-existing on this machine and not from this PR. The deltas, +1 XCTest and +29 Swift Testing, are exactly this PR's tests. On 6494db9,pre-commit run --all-fileswith swift-format 603.0.0 reportsswift-format....Passed.Not done on purpose
DFlash2prefix. The code stays as upstream wrote it so the owner can submit it upstream by hand.🤖 Generated with Claude Code