Skip to content

Muse Glimmer 30B: port production-safe challenge inference optimizations (4a28444e) - #580

Open
GumbiiDigital wants to merge 10 commits into
mainfrom
muse-glimmer/challenge-optimizations
Open

GumbiiDigital wants to merge 10 commits into
mainfrom
muse-glimmer/challenge-optimizations

Conversation

@GumbiiDigital

@GumbiiDigital GumbiiDigital commented Dec 3, 2026 •

Copy link
Copy Markdown

PR on branch muse-glimmer/challenge-optimizations (head 3152d2cf3acb4319e09bdf469d7e903723477a8a, 10 SSH-signed verified commits) targeting main @ 5d4d485d7afa23a45bc546596e3d9e25764a0513 (synced cleanly with origin/main including #578 and #579 via merge commit 59350d9b; related to #579 and #430 — neither prior PR nor any of Jonathan's branches are modified or closed).

Disposition of @jonathan308 Review (6196865119) & Codex Comments

  • Blocking Sendable GenerationBatchResponse #1 — Codex P1 (DARKBLOOM_CBV2_PAGED_PTOK_TARGET > 0 + dynamic tree verify):
    • Fixed in 3152d2cf: gated pagedTreeReady (EngineLoopV2+MTPExecution.swift) and the additive tree depth slot (CBv2MTPRoundDriver.swift) on PagedAttentionKernel.partitionTargetThreadgroups == 0, and added a fail-closed precondition(CBv2DraftRegime.activeDynamicTreeMeta == nil, ...) before PagedLayerCache.swift's linear per-column decode fallback loop.
    • Added unit-test coverage in MuseGlimmerChallengeOptimizationsTests.dynamicTreeVerifyMatchesSerialGreedyAndHonorsKillSwitch() (PagedAttentionKernel.partitionTargetOverrideForTesting = 64 -> asserts dynTreeCalls == 0, treeRounds == 0, and exact serial greedy token parity).
    • Verified on real 30B weights on M5 Max with DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64 (benchmarks/muse-glimmer-30b/m5-max-128g-results/killswitch-ptok64.log: code, math, and math-greedy all exact_parity: true, first_diff_idx: -1, tree_rounds: 0, tree_branch_hits: 0).
  • Blocking Layr/make batched cache #2 — M5 Ultra hardware availability:
    • M5 Max (128 GiB) is the only M5 hardware we have locally right now (no M5 Ultra on hand yet). Agreed to treat the bare-metal M5 Ultra rerun of the real-30B parity suite and c=1/2/4/8 sweep as an explicit pre-promotion / rollout gate rather than a merge gate.
  • Before merge Sendable GenerationBatchResponse #1 — Sync branch with main (#578):
    • Cleanly merged origin/main (5d4d485d, including #578 70183a70 and #579) into muse-glimmer/challenge-optimizations in SSH-signed commit 59350d9b (0 conflicts, 0 diff lines on #430's 3 *RowExact* files).
  • Before merge Layr/make batched cache #2 — Codex P2 (CBv2ParameterResidency cap when mlock fails):
    • Fixed in 3152d2cf: tracked committed MTLResidencySet bytes independently of mlock success (Registration.residentBytes + CBv2ParameterResidency.residentByteCount), enforced CBV2_PARAMETER_RESIDENCY_MAX_BYTES against residentByteCount both during buffer selection and under lock on registration commit, and added parameterResidencyCapEnforcedWhenMlockFails() proving that failed-mlock resident allocations (lockedByteCount == 0, residentByteCount > 0) still cap subsequent acquisitions and release cleanly to 0.
  • Before merge Layr/promptpadding #3 — Reproducible real-30B parity harness + tree branch acceptance evidence:
    • Checked in the standalone SwiftPM target 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/).
    • Added dynamicTreeVerificationRounds and dynamicTreeBranchHits to CBv2MTPMetrics.
    • Added MuseGlimmerChallengeOptimizationsTests.dynamicTreeVerifyAcceptsNonChainBranchAndMatchesSerialGreedy() proving real non-chain tree branch acceptance (dynamicTreeBranchHits > 0) + paged KV slot compaction + exact serial greedy parity in unit tests.
    • Re-ran real-30B parity on M5 Max on the merged branch (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), all exact_parity: true (first_diff_idx: -1), and tree_rounds: 0 on sampled t=0.6 and t=1.0.
  • Before merge Validate BatchGenerator inputs #4 — PR description cleanups:
    • Removed stale "Keeping in Draft" banner (PR is Ready for Review).
    • Corrected DARKBLOOM_DFLASH_REQUANT_4BIT description below: opt-in via DARKBLOOM_DFLASH_REQUANT_4BIT=1 (default OFF since 788a4c03), not a =0 kill switch.
    • Confirmed defersPendingCommits is intentionally default-on and whoever lands second between #580 and #428 owns 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) onto main, 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-request B > 1 batching, dynamic-tree capability gating + adaptive-PTOK guard + kill-switch, thread-local per-round regime context, opt-in resident-byte-capped parameter residency with MTLResidencySet capability probing, full-logits sampling/logprobs/bias/penalty fallbacks, and clean engine teardown).

Response to Earlier @jonathan308 Review Items

  1. Default-on verify kernels vs #430 row-exact path — PROVEN BYTE-EXACT ON REAL 30B WEIGHTS:
    • Root-caused and fixed two real-30B exactness divergences found on M5 Max (muse-glimmer-30b-nvfp4, commit 40f59be0):
      • Metal compiler bfloat16_t(constant_float_buf[1]) bug in all 4 fused readout kernels (CBv2TopTwo.swift, CBv2VerifyScales.swift, MuseGlimmerTextModel+CBv2.swift, MuseGlimmerDFlashDrafter.swift): Reading bfloat16_t(params[1]) from a const constant float* buffer inside a loop was miscompiled by Apple's Metal compiler as an fp16 (half) conversion (20.0 -> 0x4d00 -> 134,217,728 as bf16), silently disabling final_logit_softcapping=20.0 and flipping argmax on BF16 saturation ties. Fixed via host-side BF16 pre-rounding in cbv2CachedReadoutParams ([bf16_mult, bf16_cap, has_cap]) and explicit float-register arithmetic (bfloat16_t(float(a) op b)). Exhaustively tested across all 65,536 BF16 bit patterns + 202,048-vocab saturation ties (0 differing bits).
      • Cross-generation G16/G17 AGX rope.metal FMA order in VerifyFusedQK (VerifyFusedNorms.swift): MLX's rope.metal lowers rx2 = x1 * sintheta + x2 * costheta with opposite FMA operand order on M4 Max (G16) vs M5 Max (G17). Added compile-time RX2_FMA_X1_ calibrated once per process (~1 ms) against live MLXFast.RoPE across offsets [64, 70, 512, 1025], failing closed (VerifyFusedQK.isEnabled == false) to #430's reference path if neither order achieves 0 differing bits.
    • Real-30B SHA-256 parity vs #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 both 580-fixed-stock and 580-fixed-nax (full table and checked-in JSONL logs below).
    • Real-30B DARKBLOOM_MUSE_GLIMMER_VERIFY_PROJ_SELFTEST=1 (extended to cover nvfp4.lm_head.fused_top2 directly vs outputLogits + cbv2TopTwoRows): Verified 22,000+ kernel outputs / 1,576,918,304 (1.58B) real 30B elements across all 52 layers + lm_head with differing=0 and exact_parity=true.
  2. Tree verify kill-switch, adaptive-PTOK guard, & branch acceptance tests:
    • Added CBV2_TREE_LOW=0 and CBV2_DYN_TREE=0 (along with CBV2_FUSED_LMHEAD=0 and DARKBLOOM_MUSE_GLIMMER_GROUPED_VERIFY=0) to the kill-switch list below, and gated dynamic tree verify on PagedAttentionKernel.partitionTargetThreadgroups == 0.
    • MuseGlimmerChallengeOptimizationsTests verifies serial greedy parity, CBV2_TREE_LOW=0, DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64, and non-chain branch acceptance (dynamicTreeBranchHits > 0 + KV slot compaction).
    • Verified CBV2_TREE_LOW=0, DARKBLOOM_MUSE_GLIMMER_VERIFY_PROJ=0, and DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64 on real 30B weights on M5 Max (exact_parity=true, first_diff_idx=-1, 0 crashes).
  3. Standalone #579 vs #579+#580 speeds (c=1/2/4/8 + 4-arm ABBA c=1):
    • Captured thermally-controlled (ProcessInfo.thermalState == .nominal start) standalone numbers on M5 Max (128 GiB, stock pinned mlx-swift) below: +31.9% on concurrency_dflash c=1 (52.6 -> 69.4 tok/s), +32.6% on DFlash code (59.5 -> 78.9 tok/s), +16.1% on DFlash math (84.3 -> 97.9 tok/s), zero regression across c=1/2/4/8 target decode, and -2.0 to -8.3 GiB lower memory footprint.

Summary

Included optimizations

  1. CBv2 verify kernels & paged attention (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, with CBv2FusedVerifyForwarding.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 with cbv2CachedReadoutParams; shared cbv2TopTwoRows untouched).
    • PagedOnePassAttention (MUSE_PAGED_ONEPASS, default on in PagedSegmentAttention.decode when eligible(...) and load-time threadgroup probes pass; kill switch MUSE_PAGED_ONEPASS=0).
    • PagedSegmentTransfers.copySlotsInPlace (batched same- and cross-segment KV slot compaction; write/copy launch caches bounded at 256 entries).
    • CBv2ParameterResidency (opt-in CBV2_PARAMETER_RESIDENCY=1, bounded by CBV2_PARAMETER_RESIDENCY_MAX_BYTES enforced against total committed resident bytes even when mlock fails, one-time supportsMetalResidencySets probe so paravirtualized macOS VM GPUs fail closed cleanly without mlock/munlock churn, ref-counted across engines with EngineV2.shutdown() and model deinit teardown).
    • CBv2WorkInterval (os_workgroup_interval pacing, opt-in via CBV2_ENGINE_WORK_INTERVAL=1).
    • CBv2DraftRegime.RoundContext (thread-local per-round regime/tree metadata scoped via withRoundContext(_:_:), eliminating process-global mutable statics) + CBv2MTPMetrics.dynamicTreeVerificationRounds / dynamicTreeBranchHits.
  2. Muse Glimmer target & DFlash drafter (Libraries/MLXLLM/Models/MuseGlimmer/):
    • Fused verify trunk (MuseGlimmerTextModel+CBv2.swift), fused top-two verify readout (CBv2FusedVerifyReadoutForwarding), and supportsDynamicTreeVerify(rows:) enforcement.
    • DFlash drafter optimizations (MuseGlimmerDFlashDrafter.swift), including opt-in in-memory 8-bit -> 4-bit layer requantization (default OFF, opt-in via DARKBLOOM_DFLASH_REQUANT_4BIT=1) and production low-acceptance regime drafting adaptation (retaining CBv2DraftRegime.RoundContext, fixedDepthAcceptanceWindow, and low-regime drafter paths without imposing any high-acceptance ceiling).
  3. Production-safety tests, parity harness, & receipts (Tests/MLXLMTests/, benchmarks/muse-glimmer-30b/, changelog.d/):
    • MuseGlimmerChallengeOptimizationsTests (18 tests: dynamic-tree capability gating, dynamic-tree vs serial greedy parity + CBV2_TREE_LOW=0 kill-switch + DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64 adaptive-PTOK guard, non-chain tree branch acceptance & KV slot compaction parity, concurrent RoundContext isolation, sampling/bias/penalty/topLogprobs full-logits fallback, B = 3 batched speculative verify parity, opt-in capped EngineV2 residency lifecycle & teardown, failed-mlock resident-byte cap enforcement, one-pass vs two-pass bit-exact paged attention parity, direct copySlotsInPlace parity, uncapped acceptance-state depth, full-width fused verify greedy parity, VerifyFusedQK bit-exactness at qk_scale_factor=3.87, VerifyFusedNorms bit-exactness at 30B width=6656, exhaustive 65,536-BF16 softcap-tie readout bit-exactness, fusedVerifyScoredNilFallback KV-cache immutability, and memory hygiene defaults).
    • CBv2PagedSegmentTests updated to assert both the 28-binding non-tree and 29-binding dynamic-tree Metal buffer budgets (<= 31).
    • Standalone SwiftPM target MuseGlimmerParityBench (benchmarks/muse-glimmer-30b/MuseGlimmerParityBench.swift, README.md, and raw M5 Max JSONL receipts under benchmarks/muse-glimmer-30b/m5-max-128g-results/).
    • changelog.d/muse-glimmer-challenge-optimizations.md registered in fork.yaml.

Omitted / dropped items

Omitted item Reason
Contest acceptanceCeiling (5x ceiling cap) Contest-only throttling; stripped so high-acceptance requests keep full declared depth.
_rec / Record duplicated slow kernels Contest-only diagnostic/telemetry kernel duplicates; stripped to keep single production Metal kernels.
Partial promptArithmeticLayers / promptAttentionLayers (2x cap) Contest-only partial-layer skip hooks; stripped for exact prompt semantics.
CBv2PacingFloors Contest-only artificial pacing floor; stripped.
#430's 3 row-exact kernel files (MuseGlimmerRowExact.swift, ModelOptWeightOnlyNVFP4RowExactKernels.swift, ModelOptRowExactKernels.swift) Left completely untouched (0 diff lines against main @ 5d4d485d) to avoid any conflict with #430.

Placeholders / pending rollout items

Deferred / Pending Item Owner / Target Notes
Bare-metal M5 Ultra c=1/2/4/8 & real-30B parity confirmation Pre-promotion / rollout gate M5 Max (128 GiB) is the only M5 hardware on hand locally right now (no M5 Ultra on hand yet). CI test shards run on Apple M5 Ultra (Virtual).
Companion NAX C++/Metal kernels (9 Vendor/mlx-swift/ files) Layr-Labs/mlx-swift#79 + Layr-Labs/mlx#73 Out of scope here; #580 delivers +31.9% to +32.6% DFlash speedup and -2.0 to -8.3 GiB memory reduction standalone on stock pinned mlx-swift.
Per-model gating or expanded multi-partition / D=256/512 parity for PagedOnePassAttention (PagedSegmentAttention.swift:327) Follow-up PR (if desired before multi-model co-hosting) Currently geometry-qualified in a process-global set (see Blast Radius below).
Wire #578 opt-in DARKBLOOM_CBV2_LAYER_SUBMIT into prepareSingleRowDirectVerifyWrite / attendColumnsPreWrittenWithGate Follow-up PR Performance-only for opt-in DARKBLOOM_CBV2_LAYER_SUBMIT; off by default.
RoPE calibration hardening (L in {1, 8} x B in {1, 2} + write kernel + stderr log on failure) & boolean kill-switch spellings Optional follow-up Current calibration covers M4 Max (G16) & M5 Max / M5 Ultra Virtual (G17) and fails closed to #430.

Blast Radius / What This Could Affect

Shared seams touched

File(s) Symbol / Behavior Changed Affected Models / Subsystems Gating / Isolation
MTP/EngineLoopV2+MTP.swift, EngineLoopV2+MTPPlanning.swift, EngineLoopV2+MTPExecution.swift, EngineLoopV2+MTPTargetVerification.swift, EngineLoopV2+MTPFinalize.swift, MTPContractsV2.swift Per-round thread-local CBv2DraftRegime.RoundContext, dynamic-tree verification routing (gated on PagedAttentionKernel.partitionTargetThreadgroups == 0) + fail-closed precondition, dynamicTreeVerificationRounds/dynamicTreeBranchHits metrics, fused top-two readout dispatch, defersPendingCommits (intentionally default-on; whoever lands second between #580 and #428 owns any conflict), and usesFixedDepthAcceptanceWindow. All CBv2 MTP / speculative-decoding engines. supportsDynamicTreeVerify(rows:) defaults false; PagedAttentionKernel.partitionTargetThreadgroups == 0 required; supportsFusedTopTwoReadout falls back to full logits on temperature > 0, logitBias, penalties, or topLogprobs > 0; usesFixedDepthAcceptanceWindow is strictly limited to fixed-depth, request-stateful, advisory-history drafters.
MTP/CBv2MTPRoundDriver.swift, MTP/CBv2MTPDepthController.swift Thread-local CBv2DraftRegime.RoundContext, low-acceptance regime adaptation (CBV2_TREE_LOW, CBV2_DYN_TREE, gated on partitionTargetThreadgroups == 0), and depth/window bookkeeping. All CBv2 MTP speculative-decoding loops. Tree verify gated on supportsDynamicTreeVerify(rows:) + partitionTargetThreadgroups == 0 + CBV2_TREE_LOW=0 / CBV2_DYN_TREE=0; contest acceptanceCeiling stripped.
Paged/PagedSegmentAttention.swift, Paged/PagedOnePassAttention.swift One-pass paged decode kernel (MUSE_PAGED_ONEPASS, default on) in decode / decodeWithOutputGate when newKeys == nil, sinks == nil, dispatchCache != nil, single bucket, eligible(...) != nil, and load-time threadgroup probe succeeds. Process-global geometry scope: PagedOnePassAttention.isQualified checks a process-global warmedConfigs set 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. Kill switch: MUSE_PAGED_ONEPASS=0 forces two-pass split-K + merge; bit-identical to two-pass (MUSE_PAGED_ONEPASS_CHECK=1).
Paged/PagedLayerCache.swift, Paged/PagedSequenceKV.swift Lazy materialization of devicePositionOffsets, advanceGLM5NextOffsets, prepareSingleRowDirectVerifyWrite / attendColumnsPreWrittenWithGate, tree-row dispatch gated by thread-local activeDynamicTreeK > 0 && activeDynamicTreeMeta != nil, fail-closed precondition forbidding linear column decode fallback when activeDynamicTreeMeta != nil, and removed un-zeroed columnsAsRowsScratch reuse in 2-pass verify fallback (788a4c03). All paged-KV models (including GLM5-Next position offset tracking). Note: #578's opt-in DARKBLOOM_CBV2_LAYER_SUBMIT boundary hooks are not called in the direct-write verify path (off by default; performance-only). Lazy offsets preserve identical tensor values; direct-write and tree paths activate only for Muse fused verify / supportsDynamicTreeVerify(rows:).
Paged/pagedattention.metal, Paged/PagedAttentionKernel.swift, Paged/PagedSegmentDispatchPlan.swift, Paged/PagedSegmentDispatchCache.swift Extended SeqInfoRow with slots 6–7 (treeMask/treeSlot), widened work-record stride 42 -> 44, updated paged-attention kernel signatures, added isDynamicTree to PagedSegmentDispatchCache key (29 Metal bindings for tree vs 28 non-tree, both <= 31), and added locked test override for partitionTargetThreadgroups. All paged-KV attention dispatches using PagedKVBackend. Non-tree dispatches pass zeroed slots 6–7 and compile DYN_TREE = false; tree dispatches activate only when supportsDynamicTreeVerify(rows:) returns true and partitionTargetThreadgroups == 0.
Paged/PagedSegmentTransfers.swift Added batched copySlotsInPlace Metal compaction kernel and bounded writeLaunches / copyLaunches caches (maxCachedLaunches = 256). All paged-KV write and in-place compaction paths. Bounded cache prevents unbounded memory growth; copySlotsInPlace parity unit-tested.
SteppableAdapterV2.swift, CBv2DecodeCommandBuffers.swift, EngineLoopV2.swift, EngineV2.swift, CBv2ParameterResidency.swift Added opt-in CBv2LastPositionLogitsForwardable, decode command-buffer work-interval hook (CBV2_ENGINE_WORK_INTERVAL), verify cache eviction hygiene, and ref-counted CBv2ParameterResidency with resident-byte cap enforcement independent of mlock, one-time supportsMetalResidencySets probe, and EngineV2.shutdown() / deinit teardown. All CBv2 engines (residency/work-interval only when opted in; verify cache hygiene applies to CBv2 verify steps). CBV2_PARAMETER_RESIDENCY and CBV2_ENGINE_WORK_INTERVAL are off by default; CBv2LastPositionLogitsForwardable is opt-in; residency fails closed on unsupported/paravirtual Metal devices.
CBv2TopTwo.swift Added cbv2CachedReadoutParams and fused BF16 softcap readout kernels. Muse Glimmer only; shared cbv2TopTwoRows (used by Qwen3.5, Nemotron, GLM5, Inkling 2, MiMo) is byte-identical to main. CBV2_FUSED_LMHEAD=0 disables fused LM-head top-two readout.
MuseGlimmerTextModel+CBv2.swift, MuseGlimmerDFlashDrafter.swift, MuseGlimmerTextModel.swift, MuseGlimmerDFlashDraftModel.swift Fused verify trunk, fused top-two readout, dynamic tree verify, and opt-in DFlash drafter 8-bit -> 4-bit requantization (DARKBLOOM_DFLASH_REQUANT_4BIT=1, default OFF). Muse Glimmer 30B text target and DFlash drafter only. Kill switches below fall back cleanly to #430 row-exact path; 8-bit drafter weights are default.

Non-interference guarantees

  • Sibling architectures (Inkling 2 / Inkling 2 Mini, Gemma 4, GLM5-Next, Nemotron, Qwen, GPT-OSS, MiMo) do not conform to CBv2FusedVerifyReadoutForwarding or override supportsDynamicTreeVerify(rows:) (defaults to false), and continue using the unchanged cbv2TopTwoRows. (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 warms PagedOnePassAttention, it can share the bit-exact one-pass decode path unless MUSE_PAGED_ONEPASS=0.)
  • #430's 3 row-exact files (MuseGlimmerRowExact.swift, ModelOptWeightOnlyNVFP4RowExactKernels.swift, ModelOptRowExactKernels.swift) have 0 diff lines vs main @ 5d4d485d.
  • Multimodal vision/video paths (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/#430 projections.
  • 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=0 or DARKBLOOM_VERIFY_FUSED_QK=0 -> disables fused verify norms/QK and automatically disables dynamic-tree verification (falling back cleanly to #430 + linear draft/verify). VerifyFusedQK also fails closed automatically if live MLXFast.RoPE calibration cannot match 0 differing 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 since 788a4c03; keeps original 8-bit drafter weights when unset).
  • CBV2_PARAMETER_RESIDENCY=1 -> opts in to mlock / MTLResidencySet parameter pinning, capped by CBV2_PARAMETER_RESIDENCY_MAX_BYTES against total committed resident bytes (and automatically fails closed via supportsMetalResidencySets on unsupported/paravirtual Metal devices).
  • CBV2_ENGINE_WORK_INTERVAL=1 -> opts in to os_workgroup_interval host-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]
Loading

Before any rollout

  1. M5 Ultra bare-metal pre-promotion gate: Re-run MuseGlimmerParityBench parity-suite and concurrency-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).
  2. Optional companion NAX pin: Land and pin Layr-Labs/mlx-swift#79 + Layr-Labs/mlx#73 if targeting the combined NAX stack; #580 is already self-contained and delivers +31.9% to +32.6% DFlash speedup standalone on stock pinned mlx-swift.
  3. Residency opt-in policy: Keep CBV2_PARAMETER_RESIDENCY unset on shared multi-model hosts; only opt in (CBV2_PARAMETER_RESIDENCY=1, optionally tuned with CBV2_PARAMETER_RESIDENCY_MAX_BYTES) on dedicated single-model serving nodes after checking RLIMIT_MEMLOCK and 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 (see benchmarks/muse-glimmer-30b/README.md; raw JSONL receipts checked in under benchmarks/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).

Case Mode #579 (579-stock) SHA-256 (prefix) #580 Stock vs #579 #580 NAX vs #579 Tree Rounds / Branch Hits (3152d2cf) First Diff #579 -> #580 Stock DFlash tok/s #579 -> #580 Stock Footprint
code (greedy) adaptive 8d76b106fc510478 EXACT MATCH EXACT MATCH 0 / 0 -1 60.8 -> 85.1 (+40.0%) 28.66 -> 26.67 GiB
code (greedy) fixed7 8d76b106fc510478 EXACT MATCH EXACT MATCH 45 / 7 -1 60.9 -> 87.2 (+43.2%) 28.66 -> 26.47 GiB
math (greedy) adaptive a4f1cb48b5acc967 EXACT MATCH EXACT MATCH 0 / 0 -1 74.2 -> 93.3 (+25.7%) 29.79 -> 24.08 GiB
math (greedy) fixed7 a4f1cb48b5acc967 EXACT MATCH EXACT MATCH 23 / 3 -1 82.2 -> 97.7 (+18.9%) 29.79 -> 23.99 GiB
math-greedy adaptive 0a0e491c12f1740c EXACT MATCH EXACT MATCH 0 / 0 -1 56.9 -> 69.1 (+21.4%) 30.39 -> 26.33 GiB
math-greedy fixed7 0a0e491c12f1740c EXACT MATCH EXACT MATCH 25 / 5 -1 64.5 -> 79.7 (+23.6%) 30.39 -> 26.23 GiB
prose (greedy) adaptive 2a74a11f66c9a174 EXACT MATCH EXACT MATCH 0 / 0 -1 29.8 -> 33.9 (+13.8%) 31.69 -> 23.82 GiB
prose (greedy) fixed7 2a74a11f66c9a174 EXACT MATCH EXACT MATCH 75 / 33 -1 30.5 -> 40.4 (+32.5%) 31.69 -> 23.65 GiB
sampled-t06 (t=0.6) seeded 35c365b3573146e9 EXACT MATCH EXACT MATCH 0 / 0 -1 — 33.16 -> 23.64 GiB
sampled-t10 (t=1.0) seeded 37ce2e1ec3a64b0d EXACT MATCH EXACT MATCH 0 / 0 -1 — 34.69 -> 24.02 GiB
prefix_cache cold A 1048 tok bfd0168d8d98410c EXACT MATCH EXACT MATCH — -1 — —
prefix_cache warm A 1048 tok bfd0168d8d98410c EXACT MATCH EXACT MATCH — -1 — —
prefix_cache branch B 1044 tok bfb699356502143e EXACT MATCH EXACT MATCH — -1 — —
  • Total real-30B dynamic tree coverage (3152d2cf, parity-580-postreview-stock.log): 168 dynamic-tree verify rounds and 48 accepted non-chain tree branches (all exact_parity: true, first_diff_idx: -1).
  • DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64 real-30B check (3152d2cf, killswitch-ptok64.log): code, math, and math-greedy all exact_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,304 elements (including nvfp4.lm_head.fused_top2@8=156, nvfp4/fp8/dense QKVG/gate_up/down/o, silu_prod), differing=0, exact_parity=true.
  • Kill-switch real-30B verification (code): DARKBLOOM_MUSE_GLIMMER_VERIFY_PROJ=0 (exact_parity=true, 53 rounds) and CBV2_TREE_LOW=0 (exact_parity=true, 58 rounds, tree verify cleanly disabled).

2. Standalone Concurrency Sweep c=1/2/4/8 (#579 vs #579+#580 on Stock Pinned mlx-swift, M5 Max 128 GiB)

Both binaries cooled to thermalState == .nominal (+20 s stabilization) before sweeping c=1,2,4,8 (192 tokens/request; identical thermal trajectory nominal at c=1,2 and fair at c=4,8):

Workload c #579 Agg Decode (tok/s) #579+#580 Agg Decode (tok/s) Delta #579 /req #580 /req #579 Footprint #580 Footprint Footprint Delta
Target decode 1 21.9 22.0 +0.5% 21.9 22.0 25.94 GiB 23.76 GiB -2.18 GiB
Target decode 2 38.6 38.8 +0.5% 19.3 19.4 27.16 GiB 25.12 GiB -2.04 GiB
Target decode 4 71.5 71.1 -0.6% 17.9 17.8 29.90 GiB 27.81 GiB -2.09 GiB
Target decode 8 118.9 119.3 +0.3% 14.9 14.9 34.09 GiB 31.43 GiB -2.66 GiB
DFlash speculative 1 52.6 69.4 +31.9% 52.6 69.4 26.01 GiB 24.03 GiB -1.98 GiB
DFlash (c>1 target fallback) 2 34.9 33.9 -2.9% (+0.3% wall) 17.4 17.3 27.20 GiB 24.84 GiB -2.36 GiB
DFlash (c>1 target fallback) 4 64.2 64.6 +0.6% 16.1 16.1 29.99 GiB 27.73 GiB -2.26 GiB
DFlash (c>1 target fallback) 8 101.1 101.9 +0.8% 12.6 12.7 34.29 GiB 32.14 GiB -2.15 GiB

3. Clean 4-Arm ABBA c=1 Isolation (bench-single, M5 Max 128 GiB)

Mean of 2 reverse-ordered thermal-controlled rounds (nominal + 15 s before every arm; MLX_NAX_KSPLIT=unset):

Arm Target Decode (r1/r2) 4096 Prefill (r1/r2) DFlash code (r1/r2) code Delta code Footprint DFlash math (r1/r2) math Delta math Footprint Exact Parity
579-stock 20.5 (20.4/20.6) 728.4 (727.2/729.6) 59.5 (59.7/59.3) baseline 31.17 GiB 84.3 (84.8/83.8) baseline 32.30 GiB True
580-fixed-stock 20.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) True
579-nax 20.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) True
580-fixed-nax 20.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) True

4. Local Unit Tests & Hosted CI (3152d2cf)

Check Command / Run Hardware Result
Local targeted suite (3152d2cf) swift test --filter "MuseGlimmerChallengeOptimizationsTests|CBv2TopTwoTests|CBv2PagedSegmentTests|CBv2LayerSubmissionDecodeOnlyTests" + CBv2LayerSubmissionQwen35EngineTests (18/18 challenge tests including PTOK=64, failed-mlock residency cap, and non-chain branch acceptance) Apple M4 Max (Mac16,5, G16) PASS
Real-30B PTOK=64 & post-merge tree-hit parity (3152d2cf) swift build -c release --product MuseGlimmerParityBench + diag-parity (PTOK=64) + parity-suite Apple M5 Max (128 GiB, G17) PASS (168 tree rounds / 48 branch hits; 0 tree rounds under PTOK=64; all exact_parity: true)
#430 row-exact untouched check (3152d2cf) git diff origin/main -- '*RowExact*' — PASS (0 diff lines)
Unit test file hygiene, fork.yaml, & formatting (3152d2cf) bash scripts/check-unit-test-files.sh + uv run --with pyyaml python3 scripts/check_forkdiff.py + swift format — PASS
Hosted CI (3152d2cf) Fork Tests 47434183649 + Lint 47434183463 + Fork Diff 47434183506 Apple M5 Ultra (Virtual) PASS (29 passed, 4 skipped, 0 failed; 33/33 green)

Skipped / Ignored

  • Live checkpoint tests gated on MUSE_GLIMMER_NVFP4_DIR / MUSE_GLIMMER_ORACLE_DIR are skipped on hosted CI VMs without model weights; real-30B parity & throughput were executed directly on M5 Max (sections 1–3 above).

Not proven

  • Apple M1–M3 hardware (G13–G15): Real-30B byte-exactness was proven on M5 Max (G17), and unit tests ran on M4 Max (G16) and Apple M5 Ultra Virtual (G17). Nothing ran on M1/M2 (where MLX may use emulated _MLX_BFloat16) or M3.
  • Bare-metal M5 Ultra throughput: M5 Max (128 GiB) is the only M5 hardware on hand locally right now (no M5 Ultra on hand yet); bare-metal M5 Ultra real-30B parity and c=1/2/4/8 sweeps remain a pre-promotion gate.
  • CBV2_DYN_TREE=0 kill-switch path: Code-verified to feed the same per-round gate, while CBV2_TREE_LOW=0 and DARKBLOOM_CBV2_PAGED_PTOK_TARGET=64 were both unit-tested and real-30B verified.
  • Opt-in DARKBLOOM_CBV2_LAYER_SUBMIT combined with fused verify: Off by default; #578's layer-submission hooks are not wired into #580's direct-write verify path.
  • Multi-hour multi-tenant soak with 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

  • I have read the CONTRIBUTING document
  • I have run swift-format and repo hygiene checks (check_forkdiff.py, check-unit-test-files.sh) prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (changelog.d/muse-glimmer-challenge-optimizations.md, benchmarks/muse-glimmer-30b/README.md, and fork.yaml)

AI usage

  • I have read this PR description in full and approve it as my own, and it accurately describes the code changes.
  • AI usage disclosure: Drafted, debugged, and validated with Cursor coding agents, including root-cause debugging of the Metal BF16 softcap readout compiler bug, G16/G17 RoPE FMA calibration on real 30B weights on M5 Max, and addressing Jonathan's and Codex's review findings.

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 == 0 dynamic-tree gate + fail-closed linear-fallback precondition (3152d2cf), thread-local CBv2DraftRegime.RoundContext, and dynamicTreeVerificationRounds/dynamicTreeBranchHits metrics.
  • Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2ParameterResidency.swift: resident-byte cap enforcement independent of mlock (residentByteCount) + EngineV2.shutdown() / deinit teardown (3152d2cf).
  • Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2TopTwo.swift, CBv2VerifyScales.swift, Libraries/MLXLLM/Models/MuseGlimmer/MuseGlimmerTextModel+CBv2.swift, MuseGlimmerDFlashDrafter.swift: cbv2CachedReadoutParams host BF16 pre-rounding & explicit float-register readout arithmetic across all 4 fused readout kernels.
  • Libraries/MLXLMCommon/ContinuousBatchingV2/VerifyFusedNorms.swift: VerifyFusedNorms width=6656 exactness and VerifyFusedQK RX2_FMA_X1_ live per-process MLXFast.RoPE calibration with fail-closed fallback to #430.
  • benchmarks/muse-glimmer-30b/: standalone MuseGlimmerParityBench target, 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.

- 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 jonathan308 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.

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:

  1. 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).
  2. 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.
  3. 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-time warm probe, 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.
  • defersPendingCommits is 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.
@GumbiiDigital
GumbiiDigital changed the base branch from muse-glimmer/text-only-baseline to main December 4, 2026 20:30
@GumbiiDigital
GumbiiDigital marked this pull request as ready for review December 4, 2026 20:43
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T20:47:05.776105Z b7f55eb Draft marked ready
ℹ️ 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: 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".

Comment on lines +823 to +827
let pagedTreeReady =
batch == 1
&& mtp.drafter.batchesVerifyColumnsAsDecodeRows
&& !rowMetadata[0].storageRows.isEmpty
&& rowMetadata[0].storageRows.allSatisfy { $0 is PagedSequenceKV }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +286 to +287
let alreadyPinnedBytes = lockedByteCount
var remainingBudget = max(0, maxTotalBytes - alreadyPinnedBytes)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 jonathan308 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.

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. b7f55eb only reformats code relative to 40f59be, so those runs cover this head.

Blocking:

  1. 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 checks PagedAttentionKernel.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 add partitionTargetThreadgroups == 0 to pagedTreeReady, 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.
  2. 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 base d625d5bd), 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.
  • defersPendingCommits is 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=0 a kill switch, but the option is opt-in with =1.

I'll approve once item 1 is fixed and item 2 is settled.

This branch has not been deployed

No deployments
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