Skip to content

Port upstream PR 607: DFlash2 block speculative decoding for Qwen3.5 and Qwen3.8 - #70

Open
ronaldmannak wants to merge 6 commits into
mainfrom
claude/issue-252-port-dflash2-607
Open

ronaldmannak wants to merge 6 commits into
mainfrom
claude/issue-252-port-dflash2-607

Conversation

@ronaldmannak

@ronaldmannak ronaldmannak commented Oct 26, 2026 •

Copy link
Copy Markdown
Owner

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 fork main with git cherry-pick -x 47ec29a. The author's authorship is kept. The upstream PR is still open and unreviewed there. The port is byte-identical to 47ec29a for all nine files; Evaluate.swift differs 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: the DFlash2DrafterModel and DFlash2TargetModel protocols, 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.swift and Libraries/MLXLLM/DFlash2Registration.swift: a factory and type registry in the MTP drafter's shape. DFlash2 checkpoints report model_type: qwen3; the dflash_config object 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: DFlash2TargetModel on Qwen35TextModel and Qwen35Model (also serving the qwen3_8 types): dflash2Prefill captures layer outputs, dflash2Verify 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. The plain decode path is unchanged apart from factoring the q/k norm into normalizedQK.
  • Libraries/MLXLMCommon/Evaluate.swift: generate(..., dflash2Drafter:) and generateTokens(..., dflash2Drafter:) overloads. Libraries/MLXLLM/Documentation.docc/using-model.md gains a DFlash2 section. Tests/MLXLMTests/DFlash2Tests.swift adds 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 in Tests/MLXLMTests/DFlash2Tests.swift that fails before the fix and passes after it. Upstream 607 still has these defects; the owner may want to carry them upstream by hand.

  • Continue DFlash2 generation after a cache the input does not repeat. The generate(dflash2Drafter:) overloads pass a caller's cache with prefilledPrefixTokens at zero, which is how a chat turn arrives: the cache holds the conversation and input is the new tokens only. Prefill appended after the cached positions, but the first verify pass started at input'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 through prefill.prefix, as TokenIterator does. Cold caches and the explicit prefilledPrefixTokens warm start are unchanged. Test: testDFlash2IteratorContinuesAfterCachedPrefix.
  • Draw DFlash2 draft samples from the seeded random state. With temperature > 0 and a seed, 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 and two runs with the same seed could emit different tokens. The proposal now runs under withRandomState(randomState). The mock target in the tests builds its captures from a private random state instead of reseeding the global one. Test: testDFlash2SeededSamplingIgnoresGlobalRandomState.
  • Sample the first DFlash2 token from the iterator's random state. 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/DFlash2Tests runs zero tests and still reports success, because the file holds top-level @Test functions with no suite of that name plus the XCTest class DFlash2MemoryTests. 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):

Test Suite 'DFlash2MemoryTests' passed at 2026-10-25 22:18:12.140.
	 Executed 1 test, with 0 failures (0 unexpected) in 0.041 (0.041) seconds
􁁛 Test run with 28 tests in 0 suites passed after 0.476 seconds.
** TEST SUCCEEDED **

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 MLXLMTests bundle on the PR head 2034ffc (-only-testing:MLXLMTests):

Test Suite 'MLXLMTests.xctest' passed at 2026-10-25 22:20:50.099.
	 Executed 843 tests, with 4 tests skipped and 0 failures (0 unexpected) in 110.632 (110.779) seconds
􁁛 Test run with 1226 tests in 105 suites passed after 28.485 seconds.
** TEST SUCCEEDED **

Whole MLXLMTests bundle on origin/main (991266a, separate worktree):

Test Suite 'MLXLMTests.xctest' passed at 2026-10-25 21:47:11.200.
	 Executed 842 tests, with 4 tests skipped and 0 failures (0 unexpected) in 112.142 (112.282) seconds
􁁛 Test run with 1198 tests in 105 suites passed after 25.919 seconds.
** TEST EXECUTE SUCCEEDED **

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 says targetLoaderExcludesConvertedMTPComponent(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-files with swift-format 603.0.0 (the version .github/workflows/pull_request.yml pins; built from the 603.0.0 tag, since Homebrew ships 604.0.0):

swift-format.............................................................Passed

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 in clang -extract-api on the vendored xgrammar header:

Libraries/MLXCXGrammar/xgrammar/3rdparty/picojson/picojson.h:44:10: fatal error: 'algorithm' file not found

The same two targets fail identically on origin/main 991266a 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:

Could not resolve package dependencies:
  a resolved file is required when automatic dependency resolution is disabled and should be placed at /Volumes/workspace/repository/IntegrationTesting/IntegrationTesting.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved. Running resolver because the following dependencies were added: 'swift-transformers' (https://github.com/huggingface/swift-transformers)

(and the same line for swift-syntax). The same check fails with the same two errors on origin/main 991266a, so it is pre-existing and not caused by this PR. Cause: the fork's Xcode Cloud setup relies on ci_scripts/ci_post_clone.sh (plus IntegrationTesting/ci_scripts/ci_post_clone.sh and ci_override.xcconfig), which exist on pico/0.32.4-jaccl but not on main. That script runs defaults write com.apple.dt.Xcode IDEDisableAutomaticPackageResolution -bool NO and IDEPackageOnlyUseVersionsFromResolvedFile -bool NO, so PRs against the jaccl branch resolve packages while anything against main requires a Package.resolved, which this repository gitignores. Porting those scripts to main is a CI change and belongs to PicoMLX/picocore#259. This PR touches no package dependency.

Merge with main (799f75f) and reasoning routing (6494db9)

Fork main moved 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 merges main without a rebase or force-push. The only conflict was in Libraries/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 generate overloads, but the DFlash2 overload from 607 did not. A Qwen 3.5 or 3.8 thought therefore arrived as .chunk text. The overload now reads whether the prompt opens a thought, then passes reasoningConfig and that seed, as the MTP overload does. testDFlash2GenerateRoutesReasoning covers it: it fails on 799f75f, with no reasoning and weigh it</think>Answer as chunks, and passes on 6494db9.

DFlash2 tests on 6494db9:

Test Suite 'DFlash2MemoryTests' passed at 2026-11-06 17:11:07.101.
	 Executed 1 test, with 0 failures (0 unexpected) in 0.047 (0.048) seconds
􁁛 Test run with 29 tests in 0 suites passed after 0.425 seconds.
** TEST SUCCEEDED **

Whole MLXLMTests bundle on 6494db9:

Test Suite 'MLXLMTests.xctest' passed at 2026-11-06 17:14:42.332.
	 Executed 975 tests, with 8 tests skipped and 0 failures (0 unexpected) in 116.736 (116.893) seconds
􀢄 Test run with 1478 tests in 122 suites failed after 25.253 seconds with 6 issues (including 2 known issues).

The same bundle on main 4ab2679:

Test Suite 'MLXLMTests.xctest' passed at 2026-11-06 17:04:23.424.
	 Executed 974 tests, with 8 tests skipped and 0 failures (0 unexpected) in 120.939 (121.111) seconds
􀢄 Test run with 1449 tests in 122 suites failed after 23.393 seconds with 6 issues (including 2 known issues).

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) and LFM2DSparkMetalTests.rotatingHybridCacheMatchesGreedyAcrossWindow with promptLength 3 (a difference above 1e-4). Both suites arrived with main, 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-files with swift-format 603.0.0 reports swift-format....Passed.

Not done on purpose

  • DFlash v1 (z-lab) drafter support. That is PicoMLX/picocore#253 and stacks on this PR.
  • Renames away from the DFlash2 prefix. The code stays as upstream wrote it so the owner can submit it upstream by hand.
  • Any PicoCore change, the MTP iterator, and upstream PR 724.
  • Any workflow or CI change.

🤖 Generated with Claude Code

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)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T05:24:24.740926Z 2034ffc 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

ronaldmannak and others added 2 commits October 25, 2026 22:05
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>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread Libraries/MLXLMCommon/Evaluate.swift Resolved
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>
@ronaldmannak

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 6494db9b8d

ℹ️ 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".

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants