Repository navigation
Muse Glimmer 30B: port production-safe challenge inference optimizations (4a28444e) - #580
GumbiiDigital wants to merge 10 commits into
Conversation
… parameter residency
…arget and DFlash drafter
- Gate dynamic-tree verification via CBv2FusedVerifyForwarding.supportsDynamicTreeVerify(rows:) so DARKBLOOM_VERIFY_FUSED_NORMS=0, DARKBLOOM_VERIFY_FUSED_QK=0, non-exact numerics, or unsupported target models cleanly disable tree verification instead of mis-masking; add precondition guard before non-fused fallback. - Replace process-global nonisolated(unsafe) mutable static state in CBv2DraftRegime with thread-local per-round RoundContext scoped via withRoundContext(_:_:) so concurrent engines and parallel test suites cannot race or leak MLXArray metadata. - Make CBv2ParameterResidency opt-in by default (CBV2_PARAMETER_RESIDENCY=1) with a hard cumulative byte cap (CBV2_PARAMETER_RESIDENCY_MAX_BYTES, default 50% of recommendedMaxWorkingSetSize), safe failure logging, and removal of dead dlsym(cbv2_array_backing). - Cap PagedSegmentTransfers write/copy launch caches at 256 entries, add DARKBLOOM_DFLASH_REQUANT_4BIT=0 kill switch for drafter 8-bit->4-bit requantization, remove dead static-tree/unused-variable code and unnecessary nonisolated(unsafe) warnings, document SteppableAdapterV2 [B,1,V] contract, and add changelog.d fragment. - Strengthen MuseGlimmerChallengeOptimizationsTests and CBv2PagedSegmentTests to cover fused-norm/QK dynamic-tree gating, concurrent RoundContext isolation, opt-in capped EngineV2 residency lifecycle without skippable guards, B>1 batched verify proof, one-pass vs two-pass bit-exact parity, non-tautological acceptance-state depth, and 29-binding tree Metal budget.
…PUs in residency test - Add CBv2ParameterResidency.supportsMetalResidencySets one-time Metal probe (bytesNoCopy shared buffer + MTLResidencySet creation/commit) so paravirtualized macOS VM GPUs fail closed cleanly in O(1) without mlock/munlock churn. - Update MuseGlimmerChallengeOptimizationsTests.parameterResidencyIsOptInCappedAndTeardownCleanAcrossEngineLifecycle to assert supportsMetalResidencySets == true unconditionally on physical Apple Silicon GPUs while verifying fail-closed zero-leak behavior on paravirtualized macOS CI VMs (matching NemotronSuperChunkedScanGate).
jonathan308
left a comment
There was a problem hiding this comment.
Commenting rather than approving, since it's a draft. The structure looks right: prefix caching and paged attention are still the path used (supportsPrefixReuse and requiresNativePagedKV are unchanged, with no side contiguous cache). Exact rectangular verify from my #423 is kept, and the coupled proposals from #428 that I measured as a loss aren't re-enabled. What's missing is proof that it's production-safe, and that's the bar for this one ("validate speeds, no compromise").
Before this can come out of draft:
- Default-on verify kernels with no bit-exact evidence on the production path (
MuseGlimmerTextModel+CBv2.swift:765,827). By default, verify projections route around my #430 row-exact path and run about 5k lines of new kernels: fused norms, fused Q/K-norm + RoPE, FP8/NVFP4 projections, and the top-two readout. The only bit-check is an opt-in self-test that turns off the FP8 path prod runs (:266-267). It never checks the fused norms or the RoPE/KV write. The readout test uses a stand-in model (MuseGlimmerChallengeOptimizationsTests.swift:68-87). One flipped greedy token is an OpenRouter derank. Either default these off, or add a real-weights byte-exact run against #579's baseline (greedy + sampled, several prompts, prefix-cache hits). - Tree verify is on by default but missing from the kill-switch list (
CBv2MTPRoundDriver.swift:1895,1899;CBV2_TREE_LOW=1,CBV2_DYN_TREE). The mask design looks exact, and KV is compacted before prefix publication, but no test compares a tree round with serial greedy decode. Please add that test and document the switch. - No speed numbers for this PR on its own. The 70.1 tok/s figure needs mlx-swift#79 + mlx#73. Please post the tok/s for #579 vs #579+#580 at c=1/2/4/8 on an M5 Ultra.
Minor:
PagedSegmentAttention.swift:327: the one-pass kernel is default-on in shared paged code, so other models can reach it (KV-shared layers, other models' verify windows). Only Muse runs the load-timewarmprobe, and parity covers just D=128 with one partition. Gate it to Muse, or extend parity to multiple partitions, D=256/512, and tree/append.PagedLayerCache.swift:154: the verify merge scratch is reused without re-zeroing. Base code (:1087) zero-fills it because uninitialized scratch made batched rows diverge on CI's virtual GPU.- 84 new env-flag reads, mostly default-on (
CBV2_DRAFTER_XNOR_HEAD,CBV2_FAST_REGIME_V2, …). Please trim this to the switches we actually want in prod. The lossy drafter weights (8→4, 3-bit MLP, 1-bit head) only affect acceptance, so they're fine as long as exact verify holds. defersPendingCommitsis on by default (MuseGlimmerDFlashDrafter.swift:99). It's close to #428's held-row commits and touches 6 of its 9 files, so expect conflicts. It also needs a rebase onto the base branch after #578.
…d review items Fixes all four M5 Max 30B E2E issues and addresses review feedback on #580: - Fix VerifyFusedQK RoPE FMA contraction order in both `source` and `writeSource` (`metal::fma(x1, cos, -(x2 * sin))` / `metal::fma(x2, cos, x1 * sin)`) to match MLX `rope.metal` bit-for-bit on both halves, eliminating 1-ULP upper-half BF16 diffs that caused greedy DFlash parity divergence. Also gate `allowPreCastFP8` on `VerifyFusedQK.isEnabled`. - Fix `fusedVerifyForwardScoredWithMTPHidden` SIGTRAP under `DARKBLOOM_MUSE_GLIMMER_VERIFY_PROJ=0` by checking preconditions before `fusedVerifyTrunk` mutates KV caches and never returning `nil` after trunk execution. - Restore target prefill/decode speed and memory footprint to #579 baseline by removing the 1 TiB `prefillCommandBufferLimits` override, moving verify kernel warmup out of `cbv2Capabilities` into on-demand `warmVerifyFastPaths()`, evaluating warmup logits row-by-row with `Memory.clearCache()`, evicting static verify plan caches on `MuseGlimmerTextModel.deinit`, guarding small-window warmup lengths, and making lossy/duplicate shadow drafter weight transforms (`DARKBLOOM_DFLASH_REQUANT_4BIT`, `CBV2_DRAFTER_NVFP4`, `CBV2_DRAFTER_LOW_MLP_BITS`, `CBV2_DRAFTER_XNOR_HEAD`) opt-in. - Gate `PagedOnePassAttention` to explicitly warmed geometries (`isQualified`) and non-KV-sharing layers, remove un-zeroed `columnsAsRowsScratch` reuse in 2-pass verify fallback, and trim contest-sweep env reads from 84 down to documented production switches. - Add regression tests for `VerifyFusedQK` (`apply` + `applyAndWrite`) bit exactness, full-width 20-layer greedy parity, non-mutating scored verify fallback, memory hygiene defaults + cache eviction, multi-partition one-pass parity + qualification gating, and dynamic-tree verify parity + `CBV2_TREE_LOW=0` kill-switch.
… RoPE Root-caused and fixed two subtle Metal GPU codegen/FMA discrepancies exposed by real-weights Muse Glimmer 30B parity verification on M5 Max against #579: - Fix BF16 softcap miscompilation across all four fused readout Metal kernels (`CBv2TopTwo`, `CBv2VerifyScales.nvfp4ReadoutTopTwo`, `MuseGlimmerTextModel` `readoutKernel`, and `MuseGlimmerDFlashDrafter` `argMaxConfStage1`): Apple's Metal compiler miscompiled `bfloat16_t(constant_float_buf[1])` inside loops as an fp16 conversion (`0x4d00` for `20.0` -> `134217728` as bf16), disabling softcapping and flipping argmax on BF16 softcap saturation ties. Pre-round `[outputMultiplier, softcap]` to BF16->FP32 once on host in `cbv2CachedReadoutParams` and keep `mult`/`cap` in `float` registers with explicit `bfloat16_t(...)` step rounding; also check `nvfp4ReadoutTopTwo` directly against `outputLogits` + `cbv2TopTwoRows` under `selfTest`. - Auto-calibrate `VerifyFusedQK`'s upper-half RoPE FMA order (`RX2_FMA_X1_`) once against live `MLXFast.RoPE` (`rope.metal` lowers `rx2 = x1*sin + x2*cos` as `fma(x2, cos, x1*sin)` on M4/G16 and `fma(x1, sin, x2*cos)` on M5/G17), failing closed to `#430`'s reference path if neither variant is bit-exact. - Add regression unit tests covering all 65,536 BF16 bit patterns + 202,048-vocab softcap saturation ties, 30B width=6656 `VerifyFusedNorms` bit-exactness, and 30B `qk_scale_factor=3.87` normal-distributed `VerifyFusedQK` bit-exactness.
Codex Review Summary: ✅ CompletedThis 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: b7f55ebde2
ℹ️ 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".
| let pagedTreeReady = | ||
| batch == 1 | ||
| && mtp.drafter.batchesVerifyColumnsAsDecodeRows | ||
| && !rowMetadata[0].storageRows.isEmpty | ||
| && rowMetadata[0].storageRows.allSatisfy { $0 is PagedSequenceKV } |
There was a problem hiding this comment.
Gate tree verification on the actual attention dispatch capability
For low-acceptance Muse Glimmer rounds with DARKBLOOM_CBV2_PAGED_PTOK_TARGET set to a positive value, this check still enables dynamic-tree drafting, but both prepareSingleRowDirectVerifyWrite and attendColumnsAsDecodeRows reject that configuration because they require partitionTargetThreadgroups == 0. Verification consequently falls back to linear attention in attendRectangularColumns, which never consumes the tree metadata, while fused QK uses tree positions and finalization accepts a tree path. Branch rows therefore attend unrelated sibling slots and can commit incorrect tokens. Require the actual layer-cache tree-attention capability before enabling tree drafting, or fail closed whenever either attention path would fall back.
Useful? React with 👍 / 👎.
| let alreadyPinnedBytes = lockedByteCount | ||
| var remainingBudget = max(0, maxTotalBytes - alreadyPinnedBytes) |
There was a problem hiding this comment.
Count resident allocations independently of successful memory locks
With parameter residency enabled, an mlock failure leaves the buffer in an active residency set but excludes it from Registration.lockedBytes. Subtracting only lockedByteCount therefore restores that buffer's entire budget for the next provider or engine, allowing cumulative resident allocations to exceed CBV2_PARAMETER_RESIDENCY_MAX_BYTES even during sequential acquisitions. This defeats the advertised shared-host memory bound precisely when memory locking is refused. Track all retained residency-buffer bytes separately from successfully locked ranges and use that total for cap accounting.
Useful? React with 👍 / 👎.
jonathan308
left a comment
There was a problem hiding this comment.
Not approving yet at b7f55eb, but it's close. Most of my last review is done:
- Tree verify: the kill switches are documented (
CBv2MTPRoundDriver.swift:1908-1920), and there's a tree-vs-serial-greedy test that passed in CI. - Verify merge scratch: gone, so every call gets fresh zeros.
- Env flags: down from about 84 to 18, and the lossy drafter options now default off.
- One-pass kernel: gated to geometry that Muse has warmed, and off for KV-shared layers.
- Byte-exactness: the real-30B results (13/13 SHA match vs #579 across greedy, sampled and cold/warm/branch prefix-cache cases) are the evidence I asked for.
b7f55ebonly reformats code relative to40f59be, so those runs cover this head.
Blocking:
- Codex P1 is real: tree verify can commit wrong tokens when
DARKBLOOM_CBV2_PAGED_PTOK_TARGET> 0. The tree gate (EngineLoopV2+MTPExecution.swift:821-842,supportsDynamicTreeVerify) never checksPagedAttentionKernel.partitionTargetThreadgroups. Both tree-aware attention paths refuse to run when it's non-zero (PagedLayerCache.swift:1320,prepareSingleRowDirectVerifyWrite;:1450,attendColumnsAsDecodeRows). The layer then falls back to the per-column decode loop (:1286-1305), which ignores the tree layout, while fused QK still applies tree RoPE positions. Branch rows attend sibling slots, so an accepted branch can commit the wrong token and compacted KV. The default is 0, so only an operator's override reaches it, but that knob is documented as the way to turn partition adaptation back on. Please addpartitionTargetThreadgroups == 0topagedTreeReady, or fail closed whenever tree metadata is present and the linear fallback is taken. Please also add a test that sets PTOK and asserts tree verify is off. - Speed: there are no M5 Ultra numbers yet, and the gain is only at c=1. The M5 Max sweep is useful: +31.9% at c=1 with DFlash, flat at c=2/4/8. My ask was M5 Ultra, which is still listed as pending. If M5 Ultra isn't available, say so explicitly and we'll treat the M5 Ultra rerun of the parity suite and c=1/2/4/8 sweep as a gate on rollout rather than on merge.
Before merge, not blocking:
- Rebase onto main. The branch is 8 ahead and 6 behind
main(merge based625d5bd), so #578 (70183a70) isn't in it. CI ran on the merge ref, so the combination has been tested, but the body's claim that the branch "already includes #578" is wrong. defersPendingCommitsis still on by default (MuseGlimmerDFlashDrafter.swift:99) and overlaps #428's held-row commits. That's fine if intentional, but please confirm whoever lands second owns the conflict.- Make the real-30B parity run reproducible. Check in or link the harness and raw logs, and say whether any tree rounds were accepted in those cases. The in-repo tree test uses a stand-in model and doesn't assert that a branch was ever accepted.
- Codex P2 (residency cap): real, but residency is off by default. The cap should count every byte held in the residency set, not only the locked bytes.
- One-pass parity is still only at D=128. D=256/512 and tree/append can be follow-ups now that it's gated.
- Body: it says the PR is being kept in Draft, but it's marked ready. It also calls
DARKBLOOM_DFLASH_REQUANT_4BIT=0a kill switch, but the option is opt-in with=1.
I'll approve once item 1 is fixed and item 2 is settled.
…enge-optimizations
…byte cap, add branch-hit tests & parity harness
PR on branch
muse-glimmer/challenge-optimizations(head3152d2cf3acb4319e09bdf469d7e903723477a8a, 10 SSH-signed verified commits) targetingmain@5d4d485d7afa23a45bc546596e3d9e25764a0513(synced cleanly withorigin/mainincluding#578and#579via merge commit59350d9b; related to#579and#430— neither prior PR nor any of Jonathan's branches are modified or closed).Disposition of
@jonathan308Review (6196865119) & Codex CommentsDARKBLOOM_CBV2_PAGED_PTOK_TARGET > 0+ dynamic tree verify):3152d2cf: gatedpagedTreeReady(EngineLoopV2+MTPExecution.swift) and the additive tree depth slot (CBv2MTPRoundDriver.swift) onPagedAttentionKernel.partitionTargetThreadgroups == 0, and added a fail-closedprecondition(CBv2DraftRegime.activeDynamicTreeMeta == nil, ...)beforePagedLayerCache.swift's linear per-column decode fallback loop.MuseGlimmerChallengeOptimizationsTests.dynamicTreeVerifyMatchesSerialGreedyAndHonorsKillSwitch()(PagedAttentionKernel.partitionTargetOverrideForTesting = 64-> assertsdynTreeCalls == 0,treeRounds == 0, and exact serial greedy token parity).DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64(benchmarks/muse-glimmer-30b/m5-max-128g-results/killswitch-ptok64.log:code,math, andmath-greedyallexact_parity: true,first_diff_idx: -1,tree_rounds: 0,tree_branch_hits: 0).c=1/2/4/8sweep as an explicit pre-promotion / rollout gate rather than a merge gate.main(#578):origin/main(5d4d485d, including#57870183a70and#579) intomuse-glimmer/challenge-optimizationsin SSH-signed commit59350d9b(0 conflicts,0diff lines on#430's 3*RowExact*files).CBv2ParameterResidencycap whenmlockfails):3152d2cf: tracked committedMTLResidencySetbytes independently ofmlocksuccess (Registration.residentBytes+CBv2ParameterResidency.residentByteCount), enforcedCBV2_PARAMETER_RESIDENCY_MAX_BYTESagainstresidentByteCountboth during buffer selection and under lock on registration commit, and addedparameterResidencyCapEnforcedWhenMlockFails()proving that failed-mlockresident allocations (lockedByteCount == 0,residentByteCount > 0) still cap subsequent acquisitions and release cleanly to0.MuseGlimmerParityBench(benchmarks/muse-glimmer-30b/MuseGlimmerParityBench.swift+benchmarks/muse-glimmer-30b/README.md) and raw M5 Max JSONL receipts (benchmarks/muse-glimmer-30b/m5-max-128g-results/).dynamicTreeVerificationRoundsanddynamicTreeBranchHitstoCBv2MTPMetrics.MuseGlimmerChallengeOptimizationsTests.dynamicTreeVerifyAcceptsNonChainBranchAndMatchesSerialGreedy()proving real non-chain tree branch acceptance (dynamicTreeBranchHits > 0) + paged KV slot compaction + exact serial greedy parity in unit tests.benchmarks/muse-glimmer-30b/m5-max-128g-results/parity-580-postreview-stock.log): 168 dynamic-tree verify rounds and 48 accepted non-chain tree branches (code: 45 rounds / 7 hits;math: 23 / 3;math-greedy: 25 / 5;prose: 75 / 33), allexact_parity: true(first_diff_idx: -1), andtree_rounds: 0on sampledt=0.6andt=1.0."Keeping in Draft"banner (PR is Ready for Review).DARKBLOOM_DFLASH_REQUANT_4BITdescription below: opt-in viaDARKBLOOM_DFLASH_REQUANT_4BIT=1(default OFF since788a4c03), not a=0kill switch.defersPendingCommitsis intentionally default-on and whoever lands second between#580and#428owns any conflict.Proposed changes
Ports the production-safe Muse Glimmer 30B speculative-verify and paged-attention inference optimizations from the challenge optimization line (
772ed549..4a28444e) ontomain, while stripping contest-only throttles/slow-path artifacts, fixing real-30B byte-exactness bugs uncovered on M5 Max hardware, and hardening production safety invariants (multi-requestB > 1batching, dynamic-tree capability gating + adaptive-PTOK guard + kill-switch, thread-local per-round regime context, opt-in resident-byte-capped parameter residency withMTLResidencySetcapability probing, full-logits sampling/logprobs/bias/penalty fallbacks, and clean engine teardown).Response to Earlier
@jonathan308Review Items#430row-exact path — PROVEN BYTE-EXACT ON REAL 30B WEIGHTS:muse-glimmer-30b-nvfp4, commit40f59be0):bfloat16_t(constant_float_buf[1])bug in all 4 fused readout kernels (CBv2TopTwo.swift,CBv2VerifyScales.swift,MuseGlimmerTextModel+CBv2.swift,MuseGlimmerDFlashDrafter.swift): Readingbfloat16_t(params[1])from aconst constant float*buffer inside a loop was miscompiled by Apple's Metal compiler as anfp16(half) conversion (20.0 -> 0x4d00 -> 134,217,728as bf16), silently disablingfinal_logit_softcapping=20.0and flipping argmax on BF16 saturation ties. Fixed via host-side BF16 pre-rounding incbv2CachedReadoutParams([bf16_mult, bf16_cap, has_cap]) and explicitfloat-register arithmetic (bfloat16_t(float(a) op b)). Exhaustively tested across all 65,536 BF16 bit patterns + 202,048-vocab saturation ties (0differing bits).rope.metalFMA order inVerifyFusedQK(VerifyFusedNorms.swift): MLX'srope.metallowersrx2 = x1 * sintheta + x2 * costhetawith opposite FMA operand order on M4 Max (G16) vs M5 Max (G17). Added compile-timeRX2_FMA_X1_calibrated once per process (~1 ms) against liveMLXFast.RoPEacross offsets[64, 70, 512, 1025], failing closed (VerifyFusedQK.isEnabled == false) to#430's reference path if neither order achieves0differing bits.#579(579-stock): 13/13 SHA-256 byte-exact match across 4 greedy prompts (adaptive&fixed7), 2 sampled prompts (t=0.6,t=1.0), and prefix-cache (cold/warm/branch) on both580-fixed-stockand580-fixed-nax(full table and checked-in JSONL logs below).DARKBLOOM_MUSE_GLIMMER_VERIFY_PROJ_SELFTEST=1(extended to covernvfp4.lm_head.fused_top2directly vsoutputLogits+cbv2TopTwoRows): Verified22,000+kernel outputs /1,576,918,304(1.58B) real 30B elements across all 52 layers +lm_headwithdiffering=0andexact_parity=true.CBV2_TREE_LOW=0andCBV2_DYN_TREE=0(along withCBV2_FUSED_LMHEAD=0andDARKBLOOM_MUSE_GLIMMER_GROUPED_VERIFY=0) to the kill-switch list below, and gated dynamic tree verify onPagedAttentionKernel.partitionTargetThreadgroups == 0.MuseGlimmerChallengeOptimizationsTestsverifies serial greedy parity,CBV2_TREE_LOW=0,DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64, and non-chain branch acceptance (dynamicTreeBranchHits > 0+ KV slot compaction).CBV2_TREE_LOW=0,DARKBLOOM_MUSE_GLIMMER_VERIFY_PROJ=0, andDARKBLOOM_CBV2_PAGED_PTOK_TARGET=64on real 30B weights on M5 Max (exact_parity=true, first_diff_idx=-1,0crashes).#579vs#579+#580speeds (c=1/2/4/8+ 4-arm ABBAc=1):ProcessInfo.thermalState == .nominalstart) standalone numbers on M5 Max (128 GiB, stock pinnedmlx-swift) below:+31.9%onconcurrency_dflash c=1(52.6 -> 69.4 tok/s),+32.6%on DFlashcode(59.5 -> 78.9 tok/s),+16.1%on DFlashmath(84.3 -> 97.9 tok/s), zero regression acrossc=1/2/4/8target decode, and-2.0 to -8.3 GiBlower memory footprint.Summary
Included optimizations
Libraries/MLXLMCommon/ContinuousBatchingV2/):VerifyFusedNorms+VerifyFusedQK(bf16 fused RMSNorm/residual at 30B width=6656 and live-calibrated QK-norm/RoPE for verify windows of 1–31 rows, withCBv2FusedVerifyForwarding.supportsDynamicTreeVerify(rows:)capability gating).CBv2SmallProjection,CBv2GroupedProjection,CBv2VerifyNVFP4(row-exact NVFP4/FP8 small and grouped verify projections).CBv2TopTwo+CBv2VerifyScales(exact BF16 softcapped fused top-two readout withcbv2CachedReadoutParams; sharedcbv2TopTwoRowsuntouched).PagedOnePassAttention(MUSE_PAGED_ONEPASS, default on inPagedSegmentAttention.decodewheneligible(...)and load-time threadgroup probes pass; kill switchMUSE_PAGED_ONEPASS=0).PagedSegmentTransfers.copySlotsInPlace(batched same- and cross-segment KV slot compaction; write/copy launch caches bounded at 256 entries).CBv2ParameterResidency(opt-inCBV2_PARAMETER_RESIDENCY=1, bounded byCBV2_PARAMETER_RESIDENCY_MAX_BYTESenforced against total committed resident bytes even whenmlockfails, one-timesupportsMetalResidencySetsprobe so paravirtualized macOS VM GPUs fail closed cleanly withoutmlock/munlockchurn, ref-counted across engines withEngineV2.shutdown()and modeldeinitteardown).CBv2WorkInterval(os_workgroup_intervalpacing, opt-in viaCBV2_ENGINE_WORK_INTERVAL=1).CBv2DraftRegime.RoundContext(thread-local per-round regime/tree metadata scoped viawithRoundContext(_:_:), eliminating process-global mutable statics) +CBv2MTPMetrics.dynamicTreeVerificationRounds/dynamicTreeBranchHits.Libraries/MLXLLM/Models/MuseGlimmer/):MuseGlimmerTextModel+CBv2.swift), fused top-two verify readout (CBv2FusedVerifyReadoutForwarding), andsupportsDynamicTreeVerify(rows:)enforcement.MuseGlimmerDFlashDrafter.swift), including opt-in in-memory 8-bit -> 4-bit layer requantization (default OFF, opt-in viaDARKBLOOM_DFLASH_REQUANT_4BIT=1) and production low-acceptance regime drafting adaptation (retainingCBv2DraftRegime.RoundContext,fixedDepthAcceptanceWindow, and low-regime drafter paths without imposing any high-acceptance ceiling).Tests/MLXLMTests/,benchmarks/muse-glimmer-30b/,changelog.d/):MuseGlimmerChallengeOptimizationsTests(18 tests: dynamic-tree capability gating, dynamic-tree vs serial greedy parity +CBV2_TREE_LOW=0kill-switch +DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64adaptive-PTOK guard, non-chain tree branch acceptance & KV slot compaction parity, concurrentRoundContextisolation, sampling/bias/penalty/topLogprobsfull-logits fallback,B = 3batched speculative verify parity, opt-in cappedEngineV2residency lifecycle & teardown, failed-mlockresident-byte cap enforcement, one-pass vs two-pass bit-exact paged attention parity, directcopySlotsInPlaceparity, uncapped acceptance-state depth, full-width fused verify greedy parity,VerifyFusedQKbit-exactness atqk_scale_factor=3.87,VerifyFusedNormsbit-exactness at 30Bwidth=6656, exhaustive 65,536-BF16 softcap-tie readout bit-exactness,fusedVerifyScoredNilFallbackKV-cache immutability, and memory hygiene defaults).CBv2PagedSegmentTestsupdated to assert both the 28-binding non-tree and 29-binding dynamic-tree Metal buffer budgets (<= 31).MuseGlimmerParityBench(benchmarks/muse-glimmer-30b/MuseGlimmerParityBench.swift,README.md, and raw M5 Max JSONL receipts underbenchmarks/muse-glimmer-30b/m5-max-128g-results/).changelog.d/muse-glimmer-challenge-optimizations.mdregistered infork.yaml.Omitted / dropped items
acceptanceCeiling(5x ceiling cap)_rec/Recordduplicated slow kernelspromptArithmeticLayers/promptAttentionLayers(2x cap)CBv2PacingFloors#430's 3 row-exact kernel files (MuseGlimmerRowExact.swift,ModelOptWeightOnlyNVFP4RowExactKernels.swift,ModelOptRowExactKernels.swift)0diff lines againstmain @ 5d4d485d) to avoid any conflict with#430.Placeholders / pending rollout items
c=1/2/4/8& real-30B parity confirmationVendor/mlx-swift/files)Layr-Labs/mlx-swift#79+Layr-Labs/mlx#73#580delivers+31.9%to+32.6%DFlash speedup and-2.0 to -8.3 GiBmemory reduction standalone on stock pinnedmlx-swift.D=256/512parity forPagedOnePassAttention(PagedSegmentAttention.swift:327)#578opt-inDARKBLOOM_CBV2_LAYER_SUBMITintoprepareSingleRowDirectVerifyWrite/attendColumnsPreWrittenWithGateDARKBLOOM_CBV2_LAYER_SUBMIT; off by default.L in {1, 8} x B in {1, 2}+ write kernel + stderr log on failure) & boolean kill-switch spellings#430.Blast Radius / What This Could Affect
Shared seams touched
MTP/EngineLoopV2+MTP.swift,EngineLoopV2+MTPPlanning.swift,EngineLoopV2+MTPExecution.swift,EngineLoopV2+MTPTargetVerification.swift,EngineLoopV2+MTPFinalize.swift,MTPContractsV2.swiftCBv2DraftRegime.RoundContext, dynamic-tree verification routing (gated onPagedAttentionKernel.partitionTargetThreadgroups == 0) + fail-closedprecondition,dynamicTreeVerificationRounds/dynamicTreeBranchHitsmetrics, fused top-two readout dispatch,defersPendingCommits(intentionally default-on; whoever lands second between#580and#428owns any conflict), andusesFixedDepthAcceptanceWindow.supportsDynamicTreeVerify(rows:)defaultsfalse;PagedAttentionKernel.partitionTargetThreadgroups == 0required;supportsFusedTopTwoReadoutfalls back to full logits ontemperature > 0,logitBias, penalties, ortopLogprobs > 0;usesFixedDepthAcceptanceWindowis strictly limited to fixed-depth, request-stateful, advisory-history drafters.MTP/CBv2MTPRoundDriver.swift,MTP/CBv2MTPDepthController.swiftCBv2DraftRegime.RoundContext, low-acceptance regime adaptation (CBV2_TREE_LOW,CBV2_DYN_TREE, gated onpartitionTargetThreadgroups == 0), and depth/window bookkeeping.supportsDynamicTreeVerify(rows:)+partitionTargetThreadgroups == 0+CBV2_TREE_LOW=0/CBV2_DYN_TREE=0; contestacceptanceCeilingstripped.Paged/PagedSegmentAttention.swift,Paged/PagedOnePassAttention.swiftMUSE_PAGED_ONEPASS, default on) indecode/decodeWithOutputGatewhennewKeys == nil,sinks == nil,dispatchCache != nil, single bucket,eligible(...) != nil, and load-time threadgroup probe succeeds.PagedOnePassAttention.isQualifiedchecks a process-globalwarmedConfigsset keyed by(dtype, queryHeads, kvHeads, headDim, pageSize, softcap)— not per model. Once Muse Glimmer warms a geometry, any sibling model in the same process with identical geometry also takes the one-pass decode path.MUSE_PAGED_ONEPASS=0forces two-pass split-K + merge; bit-identical to two-pass (MUSE_PAGED_ONEPASS_CHECK=1).Paged/PagedLayerCache.swift,Paged/PagedSequenceKV.swiftdevicePositionOffsets,advanceGLM5NextOffsets,prepareSingleRowDirectVerifyWrite/attendColumnsPreWrittenWithGate, tree-row dispatch gated by thread-localactiveDynamicTreeK > 0 && activeDynamicTreeMeta != nil, fail-closedpreconditionforbidding linear column decode fallback whenactiveDynamicTreeMeta != nil, and removed un-zeroedcolumnsAsRowsScratchreuse in 2-pass verify fallback (788a4c03).#578's opt-inDARKBLOOM_CBV2_LAYER_SUBMITboundary hooks are not called in the direct-write verify path (off by default; performance-only).supportsDynamicTreeVerify(rows:).Paged/pagedattention.metal,Paged/PagedAttentionKernel.swift,Paged/PagedSegmentDispatchPlan.swift,Paged/PagedSegmentDispatchCache.swiftSeqInfoRowwith slots 6–7 (treeMask/treeSlot), widened work-record stride42 -> 44, updated paged-attention kernel signatures, addedisDynamicTreetoPagedSegmentDispatchCachekey (29 Metal bindings for tree vs 28 non-tree, both<= 31), and added locked test override forpartitionTargetThreadgroups.PagedKVBackend.DYN_TREE = false; tree dispatches activate only whensupportsDynamicTreeVerify(rows:)returnstrueandpartitionTargetThreadgroups == 0.Paged/PagedSegmentTransfers.swiftcopySlotsInPlaceMetal compaction kernel and boundedwriteLaunches/copyLaunchescaches (maxCachedLaunches = 256).copySlotsInPlaceparity unit-tested.SteppableAdapterV2.swift,CBv2DecodeCommandBuffers.swift,EngineLoopV2.swift,EngineV2.swift,CBv2ParameterResidency.swiftCBv2LastPositionLogitsForwardable, decode command-buffer work-interval hook (CBV2_ENGINE_WORK_INTERVAL), verify cache eviction hygiene, and ref-countedCBv2ParameterResidencywith resident-byte cap enforcement independent ofmlock, one-timesupportsMetalResidencySetsprobe, andEngineV2.shutdown()/deinitteardown.CBV2_PARAMETER_RESIDENCYandCBV2_ENGINE_WORK_INTERVALare off by default;CBv2LastPositionLogitsForwardableis opt-in; residency fails closed on unsupported/paravirtual Metal devices.CBv2TopTwo.swiftcbv2CachedReadoutParamsand fused BF16 softcap readout kernels.cbv2TopTwoRows(used by Qwen3.5, Nemotron, GLM5, Inkling 2, MiMo) is byte-identical tomain.CBV2_FUSED_LMHEAD=0disables fused LM-head top-two readout.MuseGlimmerTextModel+CBv2.swift,MuseGlimmerDFlashDrafter.swift,MuseGlimmerTextModel.swift,MuseGlimmerDFlashDraftModel.swiftDARKBLOOM_DFLASH_REQUANT_4BIT=1, default OFF).#430row-exact path; 8-bit drafter weights are default.Non-interference guarantees
CBv2FusedVerifyReadoutForwardingor overridesupportsDynamicTreeVerify(rows:)(defaults tofalse), and continue using the unchangedcbv2TopTwoRows. (Exception: if a sibling model is loaded in the same process as Muse Glimmer with the exact same(dtype, queryHeads, kvHeads, headDim, pageSize, softcap)geometry after Muse warmsPagedOnePassAttention, it can share the bit-exact one-pass decode path unlessMUSE_PAGED_ONEPASS=0.)#430's 3 row-exact files (MuseGlimmerRowExact.swift,ModelOptWeightOnlyNVFP4RowExactKernels.swift,ModelOptRowExactKernels.swift) have 0 diff lines vsmain @ 5d4d485d.MuseGlimmer.swift,MuseGlimmerImageEncoder.swift,MuseGlimmerVideo.swift) are untouched and verified by tests.Rollback / fail-closed profile (kill switches & opt-ins)
Every default-on optimization has an explicit runtime kill switch without code rollback (note: switches parse exact
"0"rather than boolean words like"false"/"off"):CBV2_TREE_LOW=0-> disables dynamic tree verification cleanly (unit-tested via test override & M5 Max real-30B verified).CBV2_DYN_TREE=0-> disables dynamic tree verification at the round/drafter gate.DARKBLOOM_CBV2_PAGED_PTOK_TARGET > 0-> automatically disables dynamic tree verification (unit-tested & M5 Max real-30B verified).CBV2_FUSED_LMHEAD=0-> disables fused NVFP4 LM-head top-two readout (nvfp4ReadoutTopTwo), falling back to full logits +cbv2TopTwoRows.DARKBLOOM_MUSE_GLIMMER_GROUPED_VERIFY=0-> disables grouped NVFP4/FP8 verify projections (CBv2GroupedProjection), falling back to ungrouped/#430projections.DARKBLOOM_MUSE_GLIMMER_VERIFY_PROJ=0-> disables fused verify projections and falls back to#430's row-exact path (M5 Max real-30B verified).DARKBLOOM_VERIFY_FUSED_NORMS=0orDARKBLOOM_VERIFY_FUSED_QK=0-> disables fused verify norms/QK and automatically disables dynamic-tree verification (falling back cleanly to#430+ linear draft/verify).VerifyFusedQKalso fails closed automatically if liveMLXFast.RoPEcalibration cannot match0differing bits.MUSE_PAGED_ONEPASS=0-> forces two-pass split-K + merge paged attention.Opt-in flags (OFF by default):
DARKBLOOM_DFLASH_REQUANT_4BIT=1-> opts in to in-memory 8-bit -> 4-bit DFlash drafter layer requantization (default OFF since788a4c03; keeps original 8-bit drafter weights when unset).CBV2_PARAMETER_RESIDENCY=1-> opts in tomlock/MTLResidencySetparameter pinning, capped byCBV2_PARAMETER_RESIDENCY_MAX_BYTESagainst total committed resident bytes (and automatically fails closed viasupportsMetalResidencySetson unsupported/paravirtual Metal devices).CBV2_ENGINE_WORK_INTERVAL=1-> opts in toos_workgroup_intervalhost-thread pacing.Before and After
flowchart TD A[Speculative Verify Round] --> B{supportsDynamicTreeVerify & PTOK==0 & CBV2_TREE_LOW/CBV2_DYN_TREE != 0?} B -- "Yes: Muse bf16 + exact + FusedNorms + calibrated FusedQK + PTOK==0 + rows 1..31" --> C[Scoped Thread-Local RoundContext with Dynamic Tree Meta] B -- "No: kill switch / PTOK>0 / calibration fail / B>1 / non-exact / other model" --> D[Linear Draft & Verify] C --> E{supportsFusedTopTwoReadout & CBV2_FUSED_LMHEAD != 0?} D --> E E -- "Greedy, no bias/penalties/logprobs" --> F[Fused BF16-Softcap Top-Two Verify Readout] E -- "Temp>0, bias, penalties, or topLogprobs>0" --> G[Full-Logits Target Verification] F --> H{MUSE_PAGED_ONEPASS & geometry qualified?} G --> H H -- "Yes" --> I[PagedOnePassAttention] H -- "No / MUSE_PAGED_ONEPASS=0" --> J[Two-Pass Split-K + Merge Paged Attention]Before any rollout
MuseGlimmerParityBench parity-suiteandconcurrency-suite(c=1/2/4/8) on bare-metal M5 Ultra once hardware is available (M5 Max 128 GiB is the only M5 hardware on hand locally right now; CI unit tests run on Apple M5 Ultra Virtual).Layr-Labs/mlx-swift#79+Layr-Labs/mlx#73if targeting the combined NAX stack;#580is already self-contained and delivers+31.9%to+32.6%DFlash speedup standalone on stock pinnedmlx-swift.CBV2_PARAMETER_RESIDENCYunset on shared multi-model hosts; only opt in (CBV2_PARAMETER_RESIDENCY=1, optionally tuned withCBV2_PARAMETER_RESIDENCY_MAX_BYTES) on dedicated single-model serving nodes after checkingRLIMIT_MEMLOCKand wired memory headroom.Validation
1. Real-Weights 30B Byte-Exact Parity & Tree Branch Acceptance (M5 Max 128 GiB,
applegpu_g17s)Reproducible via
swift build -c release --product MuseGlimmerParityBench(seebenchmarks/muse-glimmer-30b/README.md; raw JSONL receipts checked in underbenchmarks/muse-glimmer-30b/m5-max-128g-results/). Models:muse-glimmer-30b-nvfp4+muse-glimmer-30b-assistant-quantized(256 tokens/case;1048/1044-token prefix-cache prompts).#579(579-stock) SHA-256 (prefix)#580Stock vs#579#580NAX vs#5793152d2cf)#579->#580Stock DFlash tok/s#579->#580Stock Footprintcode(greedy)adaptive8d76b106fc5104780 / 0-160.8 -> 85.1(+40.0%)28.66 -> 26.67 GiBcode(greedy)fixed78d76b106fc51047845 / 7-160.9 -> 87.2(+43.2%)28.66 -> 26.47 GiBmath(greedy)adaptivea4f1cb48b5acc9670 / 0-174.2 -> 93.3(+25.7%)29.79 -> 24.08 GiBmath(greedy)fixed7a4f1cb48b5acc96723 / 3-182.2 -> 97.7(+18.9%)29.79 -> 23.99 GiBmath-greedyadaptive0a0e491c12f1740c0 / 0-156.9 -> 69.1(+21.4%)30.39 -> 26.33 GiBmath-greedyfixed70a0e491c12f1740c25 / 5-164.5 -> 79.7(+23.6%)30.39 -> 26.23 GiBprose(greedy)adaptive2a74a11f66c9a1740 / 0-129.8 -> 33.9(+13.8%)31.69 -> 23.82 GiBprose(greedy)fixed72a74a11f66c9a17475 / 33-130.5 -> 40.4(+32.5%)31.69 -> 23.65 GiBsampled-t06(t=0.6)35c365b3573146e90 / 0-133.16 -> 23.64 GiBsampled-t10(t=1.0)37ce2e1ec3a64b0d0 / 0-134.69 -> 24.02 GiBprefix_cachecold Abfd0168d8d98410c-1prefix_cachewarm Abfd0168d8d98410c-1prefix_cachebranch Bbfb699356502143e-13152d2cf,parity-580-postreview-stock.log):168dynamic-tree verify rounds and48accepted non-chain tree branches (allexact_parity: true,first_diff_idx: -1).DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64real-30B check (3152d2cf,killswitch-ptok64.log):code,math, andmath-greedyallexact_parity: true,first_diff_idx: -1,tree_rounds: 0,tree_branch_hits: 0.DARKBLOOM_MUSE_GLIMMER_VERIFY_PROJ_SELFTEST=1(real 30B weights,code):22,000+kernel outputs,1,576,918,304elements (includingnvfp4.lm_head.fused_top2@8=156,nvfp4/fp8/denseQKVG/gate_up/down/o,silu_prod),differing=0,exact_parity=true.code):DARKBLOOM_MUSE_GLIMMER_VERIFY_PROJ=0(exact_parity=true, 53 rounds) andCBV2_TREE_LOW=0(exact_parity=true, 58 rounds, tree verify cleanly disabled).2. Standalone Concurrency Sweep
c=1/2/4/8(#579vs#579+#580on Stock Pinnedmlx-swift, M5 Max 128 GiB)Both binaries cooled to
thermalState == .nominal(+20 s stabilization) before sweepingc=1,2,4,8(192tokens/request; identical thermal trajectorynominalatc=1,2andfairatc=4,8):c#579Agg Decode (tok/s)#579+#580Agg Decode (tok/s)#579/req#580/req#579Footprint#580Footprint121.922.0+0.5%21.922.025.94 GiB23.76 GiB-2.18 GiB238.638.8+0.5%19.319.427.16 GiB25.12 GiB-2.04 GiB471.571.1-0.6%17.917.829.90 GiB27.81 GiB-2.09 GiB8118.9119.3+0.3%14.914.934.09 GiB31.43 GiB-2.66 GiB152.669.4+31.9%52.669.426.01 GiB24.03 GiB-1.98 GiBc>1target fallback)234.933.9-2.9%(+0.3%wall)17.417.327.20 GiB24.84 GiB-2.36 GiBc>1target fallback)464.264.6+0.6%16.116.129.99 GiB27.73 GiB-2.26 GiBc>1target fallback)8101.1101.9+0.8%12.612.734.29 GiB32.14 GiB-2.15 GiB3. Clean 4-Arm ABBA
c=1Isolation (bench-single, M5 Max 128 GiB)Mean of 2 reverse-ordered thermal-controlled rounds (
nominal+ 15 s before every arm;MLX_NAX_KSPLIT=unset):code(r1/r2)codeDeltacodeFootprintmath(r1/r2)mathDeltamathFootprint579-stock20.5(20.4/20.6)728.4(727.2/729.6)59.5(59.7/59.3)31.17 GiB84.3(84.8/83.8)32.30 GiB580-fixed-stock20.6(20.6/20.5)726.9(723.5/730.3)78.9(79.2/78.6)+32.6%26.47 GiB(-4.70)97.9(96.3/99.5)+16.1%23.98 GiB(-8.32)579-nax20.6(20.5/20.6)722.8(723.2/722.3)59.6(59.7/59.4)+0.2%31.17 GiB(+0.00)84.2(84.2/84.3)-0.1%32.30 GiB(+0.00)580-fixed-nax20.5(20.5/20.5)718.1(716.3/719.8)77.7(77.7/77.7)+30.6%26.47 GiB(-4.70)99.7(99.8/99.6)+18.3%23.98 GiB(-8.32)4. Local Unit Tests & Hosted CI (
3152d2cf)3152d2cf)swift test --filter "MuseGlimmerChallengeOptimizationsTests|CBv2TopTwoTests|CBv2PagedSegmentTests|CBv2LayerSubmissionDecodeOnlyTests"+CBv2LayerSubmissionQwen35EngineTests(18/18challenge tests including PTOK=64, failed-mlockresidency cap, and non-chain branch acceptance)Mac16,5, G16)3152d2cf)swift build -c release --product MuseGlimmerParityBench+diag-parity(PTOK=64) +parity-suite168tree rounds /48branch hits;0tree rounds underPTOK=64; allexact_parity: true)#430row-exact untouched check (3152d2cf)git diff origin/main -- '*RowExact*'0diff lines)fork.yaml, & formatting (3152d2cf)bash scripts/check-unit-test-files.sh+uv run --with pyyaml python3 scripts/check_forkdiff.py+swift format3152d2cf)47434183649+ Lint47434183463+ Fork Diff4743418350629passed,4skipped,0failed;33/33green)Skipped / Ignored
MUSE_GLIMMER_NVFP4_DIR/MUSE_GLIMMER_ORACLE_DIRare skipped on hosted CI VMs without model weights; real-30B parity & throughput were executed directly on M5 Max (sections 1–3 above).Not proven
_MLX_BFloat16) or M3.c=1/2/4/8sweeps remain a pre-promotion gate.CBV2_DYN_TREE=0kill-switch path: Code-verified to feed the same per-round gate, whileCBV2_TREE_LOW=0andDARKBLOOM_CBV2_PAGED_PTOK_TARGET=64were both unit-tested and real-30B verified.DARKBLOOM_CBV2_LAYER_SUBMITcombined with fused verify: Off by default;#578's layer-submission hooks are not wired into#580's direct-write verify path.CBV2_PARAMETER_RESIDENCY=1: Residency is off by default; lifecycle/cap/failed-mlock/teardown is unit-tested on physical M4 Max and fail-closed on paravirtual CI VMs, not soak-tested for hours under multi-model churn.Checklist
swift-formatand repo hygiene checks (check_forkdiff.py,check-unit-test-files.sh) prior to committing changeschangelog.d/muse-glimmer-challenge-optimizations.md,benchmarks/muse-glimmer-30b/README.md, andfork.yaml)AI usage
Reviewer Notes
Start with the hardening, exactness, and review-disposition commits (
788a4c03,40f59be0,b7f55ebd,59350d9b,3152d2cf):Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift,CBv2MTPRoundDriver.swift,Paged/PagedAttentionKernel.swift,Paged/PagedLayerCache.swift:partitionTargetThreadgroups == 0dynamic-tree gate + fail-closed linear-fallback precondition (3152d2cf), thread-localCBv2DraftRegime.RoundContext, anddynamicTreeVerificationRounds/dynamicTreeBranchHitsmetrics.Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2ParameterResidency.swift: resident-byte cap enforcement independent ofmlock(residentByteCount) +EngineV2.shutdown()/deinitteardown (3152d2cf).Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2TopTwo.swift,CBv2VerifyScales.swift,Libraries/MLXLLM/Models/MuseGlimmer/MuseGlimmerTextModel+CBv2.swift,MuseGlimmerDFlashDrafter.swift:cbv2CachedReadoutParamshost BF16 pre-rounding & explicit float-register readout arithmetic across all 4 fused readout kernels.Libraries/MLXLMCommon/ContinuousBatchingV2/VerifyFusedNorms.swift:VerifyFusedNormswidth=6656 exactness andVerifyFusedQKRX2_FMA_X1_live per-processMLXFast.RoPEcalibration with fail-closed fallback to#430.benchmarks/muse-glimmer-30b/: standaloneMuseGlimmerParityBenchtarget,README.md, and raw M5 Max JSONL receipts.Tests/MLXLMTests/Integration/MuseGlimmer/MuseGlimmerChallengeOptimizationsTests.swift: all 18 production-safety, bit-exactness, adaptive-PTOK, branch-acceptance, and kill-switch tests.