Repository navigation
Muse Glimmer 30B: full multimodal baseline — text, vision, video (replay #423, #427, #429, #430, #432 on main) - #579
Conversation
…ATEM/Onyx (replay #423) Replays PR #423 (feat/muse-glimmer-native, cc2be07) onto current main (5c04ce2), resolving the 5 textual/semantic conflicts: - RecurrentStateV2.swift: preserve main's requiresFixedPrefillChunkGrid alongside requiresPagedKV and prefillChunkAlignment. - EngineV2.swift: wire prefillChunkAlignment with precedence over fixedPrefillChunkGrid, and preserve main's recurrentStateSpec == nil guard alongside checkpointsRequireAssistantHistory. - SchedulerV2.swift: reconcile prefillChunkAlignment (model-forced cell alignment, decode-first fairness, deferred claim, pool check, deadline projection) with main's fixedPrefillChunkGrid (#515) and finishingPromptsMayPassPartialCap (#565). - PagedCompleteCheckpointAdoption.swift: preserve !historicalRecurrent alongside checkpointsRequireAssistantHistory. - ToolArgumentNormalizationTests.swift: keep main's combinator/literal tests alongside boundedJSONNesting, and apply nestsPastTheBound to untypedContainer.
…and finishing-prompt lane
davidtai
left a comment
There was a problem hiding this comment.
Approved by David, with these requests. Reviewed at head 9b64917fa1, read-only. CI is green.
The replay is faithful. The 95 files are exactly the files that #423, #429 and #430 change from fe9b5282. The 64 added files are byte-identical, except that CBv2PrefillChunkGridTests.swift has +37 lines from commit 4. The modified files differ from the source PRs only by the six conflict resolutions the body lists.
Before it leaves draft:
-
Medium: root-cause rule. The JSON depth bound is added one call site at a time. #423 put the 63-level guard in the ATEM scanner (
ATEMReferenceScanner.swift:351) and in typed normalization (ToolArgumentNormalization.swift:145). The conflict resolution adds a third copy at:304. These paths still read model text at up toJSONSerialization's 512 levels:JSONToolCallParser.swift:68,82, followed by a recursiveJSONValuedecode;ParserUtilities.swift:29(deserializeJSON).
I have not checked that a deep payload overflows the stack there, but those paths are unbounded. Don't add a fourth guard. Instead, make one bounded JSON reader in
ParserUtilitiesthat every parser and the normalizer must call. -
Medium: the prompt cut grid has two owners.
fixedPrefillChunkGrid(#515, Inkling 2) andprefillChunkAlignment(Muse) do the same job. Which one wins is hand-coded inEngineV2.swift:930and inSchedulerV2.swift:319and:525. The plan is copied a third time inFirstTokenDeadlineAdmissionV2.swift:902,1001, and that copy ignoresfixedPrefillChunkGrid. Use oneCBv2PrefillCutPolicy(none,fixedGrid(n),alignedCells(n)) inCBv2ModelCapabilities, read only bySchedulerV2. The projection should call the same cell function. -
Medium: wrong output in the default mode. Strict Onyx is the default (
ServerConfiguration.swift:27,MLXModelContainerEngine.swift:28). In strict mode,<|end_of_text|>reaches the client as content. The PR records this withwithKnownIssue(OnyxContainerEngineTests.swift:262-274), and the newchannelStreampath makes it visible to users. Close the open frame on a generation stop token inOnyxStreamAdapter, and turn the known issue into a plain#expect. -
Medium: real weights were never run.
MuseGlimmerRealArtifactTests,MuseGlimmerExactWindowRealTests,MuseGlimmerDFlashRealArtifactTestsandMuseGlimmerOnyxTokenizerLiveTestsare gated by environment variables and never ran. Every CI proof uses tiny random-weight fixtures. Attach box receipts, run under the GPU lock.
Before merge:
- The head is behind main.
70183a70(#578) touchesEngineV2.swiftandPagedLayerCache.swift. It merges cleanly, but CI ran on the old base. Rebase and run CI again. - Merge with a merge commit, not a squash, so the four signed replay commits keep their SHAs for d-inference to pin. Then close #423, #429 and #430 as superseded.
Also:
- Low:
MuseGlimmerDFlashStudyTests.swift(484 lines) andModelOptWeightOnlyNVFP4RowExactBenchmarkTests.swift(785 lines) are probes. They print results, run only behind environment variables, and never run in CI. Move them to a benchmark target or delete them. - Low:
MuseGlimmerTextModel.swift:351: the publicmtpHiddenLayerIDssetter callspreconditionindidSet, so a bad value kills the process. Throw instead, and check the value when the engine is built.
Checked clean:
- Config:
validate()refuses a bad config, andstageaccepts only the pinned architecture. - Shapes: GQA 32/2 with head dim 128, a gated attention output and a dense SwiGLU MLP. RoPE is applied only where theta ≠ 0. The sliding and full masks are correct, and CBv2 takes RoPE positions from a snapshot made before each step.
- Native tower: it matches the MLXVLM tower bit for bit.
- Quantization: each layer's format comes from the hash-verified headers, and coverage is checked in both directions. FP16 activations with NVFP4 weights are refused.
- Kernels: the NVFP4 and FP8 kernels are shape-specialized, and the choice between kernels was measured on GPU generations 15 and 17.
- Text-only: the vision tensors are counted but never loaded. The model is not in
LLMModelFactory. - Other models: every new CBv2 seam defaults to off.
- Commit 4's test is real.
…che (replay Layr-Labs#2149) Replays Layr-Labs#2149 onto dev (82175d9) and pins libs/mlx-swift-lm to d625d5bde2bd6f181227e858422f1d072d84c6cc (Layr-Labs/mlx-swift-lm#579, multimodal SDK baseline: Layr-Labs#423, Layr-Labs#427, Layr-Labs#429, Layr-Labs#430, Layr-Labs#432; Layr-Labs#428 omitted) so every commit in the stack compiles cleanly. Drops Layr-Labs#2149's MTPAcceptancePolicy.swift edit (superseded by Layr-Labs#2723 universal exact acceptance on dev), regenerates fixtures/prompt-contract/v1/reasoning_effort_vectors.json (475 -> 504 cases, inserting muse_glimmer at indices 380-408 via scripts/generate-reasoning-effort-vectors.py), and updates CachePromptParityTests and MuseGlimmerPolicyTests for dev parity.
…eceipts/coupled/batched) Replays Layr-Labs#2150's speculative-row switch onto dev: DARKBLOOM_MTP_MUSE_GLIMMER_ROWS defaults to 1 (.single) with opt-in 2 (.paired, [7, 3]) and wide (up to 4 rows, [7, 3, 2, 2]), forwarded by LaunchAgent and read via sanitized process environment. Drops Layr-Labs#2150's DARKBLOOM_DEBUG_MTP_RECEIPTS (GET /v1/debug/mtp-receipts), DARKBLOOM_MTP_MUSE_GLIMMER_COUPLED (measured negative), and DARKBLOOM_MTP_MUSE_GLIMMER_BATCHED (depends on SDK Layr-Labs#428, which is omitted from Layr-Labs/mlx-swift-lm#579).
davidtai
left a comment
There was a problem hiding this comment.
Approved by David at head d625d5bde2, with these requests on the two new commits (the image and video replays of #427 and #432). The earlier review's requests at 9b64917fa1 still stand. CI is green.
Both commits are faithful replays: every Swift and test file is byte-identical to #427 3702459f and #432 4b002a2f. The PR is no longer text-only, though the branch name muse-glimmer/text-only-baseline still says so.
- Medium: the platform and the engine disagree on media sizes and prices.
- Images. For an extreme sliver image (e.g. 1,048,576×1 px),
grid.goin darkbloom-platform #2464 prices 37,451 tokens and routes the request. The engine refuses any grid over 4,096 merged tokens (MuseGlimmerImageEncoder.swift:51-58), so the request fails at the provider after routing. - Video. #2464 launches video, but its
profile.goleaves Muse video unprofiled, so the generic fallback prices it. The engine adds up to 6,912 video tokens, plus timestamp and separator tokens. - Fix. The cause is the same constants and rules written once in Go and once in Swift. Give them one owner: generate the image and video vectors from this Swift code, have the Go side refuse what the engine refuses, and hold video in #2464 until it is priced.
- Images. For an extreme sliver image (e.g. 1,048,576×1 px),
- Medium: one media request turns off drafting for its batch neighbours. The adapter extension (
MuseGlimmerCBv2Adapter.swift:87) does not adoptCBv2MTPRequestScopedMediaFallback. While an image or video request is generating, every text row batched with it runs DFlash at depth 0. Decode is row-exact under the exact windows production uses, so adopt that protocol and add a test with drafting on. If this stays, David has to accept it explicitly. - Medium: there is no limit on media per request, and encoding runs before admission.
MuseGlimmerImagePrompt.expand(ImageEncoder.swift:106) andMuseGlimmerMediaPrompt.expand(Video.swift:145) accept any number of images and videos. Inkling 2 refuses more than 64 images before it decodes any.- The encoder's thread rule (
ImageEncoder.swift:142-146) tells the host to evaluate features beforesubmit, so the full encoding runs before EngineV2's cheap checks (canEverFit,maxWaiting). The validate/materialize split inMultimodalV2.swiftexists to prevent exactly that. - This is the per-call-site bound pattern again. Use one owner:
- compute the grids and the expansion on the CPU first;
- call
encoder.featuresinside theCBv2MultimodalInputprovider closure, which runs after the cheap checks; - put one per-request limit on media count or span tokens in
CBv2MultimodalPlan.validate, not one limit per model.
- Low:
MuseGlimmerImageProofTests.proofsForOneArmonly writes JSONL for an outside script, and its expectations cover setup, not answers. The Real and Proof suites skip in CI (0.001 s in shards 1 and 15), so NVFP4 vision and video parity against the HF oracle has never run. Move the proof to a script, and attach a real-weight receipt (box, GPU lock) before the PR leaves draft. - Low:
normalizedPixels(ImageEncoder.swift:289-301) copies the body of upstream'sMuseGlimmerProcessor.preprocess, guarded only by a bit-equality test. Expose that step once in the upstream file (an additive change) and call it. - Low:
Int(extent.height.rounded())atImageEncoder.swift:273andVideo.swift:211traps on an infinite or hugeCIImageextent. Check that the extent is finite and within an axis limit (the platform uses 1<<20), and refuse with.geometry.
Checked clean:
- Cut grid. Causal media spans form no blocks, so the scheduler never moves a cut to a span edge, and
prefillChunkAlignmentremains the only grid owner.spansAcrossThe1024GridEqualTheEagerSplicecovers a 250-row image across the 1,024 cut, and it runs in CI. - Positions.
.scalarCacheOffsetmatches upstream's 1-D RoPE, features skipembed_normas upstream does, and the splice casts to the embedding dtype. - Prefix cache. Media requests never read or write the prefix cache, and a test covers it.
- Prompt expansion. Expansion counts equal
featureRows, and placeholder count and kind mismatches are refused. - Video limits. Video is bounded at 96 frames, 48 groups, 144 tokens per frame and 6,912 tokens in all. The frame linspace matches torch's float32 algorithm.
- JSON depth.
crossCheckadds no recursive walk, so the JSON depth class does not repeat here.
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. |
jonathan308
left a comment
There was a problem hiding this comment.
Approving. I checked the replay against my drafts. #423, #427, #429, #430 and #432 are byte-identical to their heads, apart from the documented merges with main (grid mutual exclusion vs #515/#565, the RecurrentStateV2 param order, and main's 63-level depth guard). Every shared-engine change is opt-in or gated to Muse, so I don't see a regression path for other models. Leaving out #428 is fine for the SDK, because nothing in #579 or #580 uses its APIs.
Follow-ups (none block this merge):
- No per-request image or video count limit in the library (
MuseGlimmerImageEncoder.swift:106,MuseGlimmerVideo.swift:145). Encoding runs before the engine's fit checks, so a request with hundreds of tiny solid-colour 1792×1792 PNGs would OOM the host. In production d-inference#2902 caps Muse at 16 images before the encoder and refuses video, so we're covered there. Still, please add a library-side ceiling like Inkling 2's 64 so any other host (MLXLMServer) is safe too. This is David's #3. MuseGlimmerCBv2Adapter.swift:88doesn't adoptCBv2MTPRequestScopedMediaFallback. While any media request is live, text requests batched with it lose drafting. This hits tok/s, and OpenRouter's derank bar is going up. This is David's #2.- Media requests never use the prefix cache (
EngineV2.swift:1899). Multi-turn chats with an image re-encode and re-prefill the whole history on every turn. That's an existing engine rule, not new here, but it matters for Muse's cost and latency. Worth a ticket. - Video frame and timestamp parity (
MuseGlimmerVideo.swift:51-64vs:95-97): frames are chosen the HF way but timestamps are written the vLLM way, so 24/30 fps prompts differ from at least one reference. We need a real-weights vision/video run against the oracle before we turn video on. FirstTokenDeadlineAdmissionV2.swift:353,1023: with the grid on, a pending cell claim or an oversized cell makes deadline submit reject. Check whether d-inference uses deadline submit for Muse, because this could refuse requests under load for no good reason.
Also still open from David: <|end_of_text|> leaks into content in the server's default strict mode (MLXLMServer path only).
Please merge with a merge commit so d-inference#2902 can re-pin to the commit on main. I'll close my drafts #423, #427, #429, #430 and #432 once this lands.
…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.
Draft. Full multimodal (text + vision + video) Muse Glimmer 30B baseline on branch
muse-glimmer/text-only-baseline, signed head commitd625d5bde2bd6f181227e858422f1d072d84c6cc, based onmain(f55c0220, clean merge with currentmain70183a70), 6 SSH-signed commits (103 files changed, +20,019 / -64). Replays and consolidates Jonathan's five non-superseded Muse Glimmer PRs (#423, #429, #430, #427, #432) for review — referenced for provenance only (no closing keywords); Jonathan's original branches and PRs remain completely untouched.Summary
Proposed changes
Consolidates the complete Muse Glimmer 30B multimodal serving stack (text decoder, DFlash speculative drafter, strict ATEM/Onyx tool validation, M5 gen-17 row-exact NVFP4 + PSO warm-up, image encoder + causal image spans, and video frame sampling + temporal-group prompt expansion) onto current
main:a389719a— Replay Muse Glimmer 30B: native NVFP4 tower, exact verify windows and the DFlash drafter #423 (feat/muse-glimmer-native,cc2be070): native NVFP4/FP8/BF16 text tower (Libraries/MLXLLM/Models/MuseGlimmer/), pinned ModelOpt indexed checkpoint loader, DFlash block drafter (MuseGlimmer/DFlash/), exact verify windows,CBv2MTPAdvisoryHistoryDrafter,prefillChunkAlignment(1,024-token prompt grid) scheduler & deadline-projection seam,PagedLayerCache.attendColumnsAsDecodeRows, ATEM/Onyx tool & reasoning parsers + server wiring, andToolArgumentNormalization.maximumValueDepth = 63.3221dd8c— Replay Muse Glimmer: read ATEM invokes for a host that validates calls itself #429 (feat/muse-glimmer-atem-reference-reader,b7672434): strictATEMReferenceReaderfor host-side tool validation,ATEMReferenceReaderTests, changelog, andfork.yaml.45fe4857— Replay Muse Glimmer: row-exact NVFP4 kernel chosen from the Metal device, and verify-width warm-up #430 (feat/muse-glimmer-rowexact-m5-d5,44378936): Metal-device-only GPU generation selection (gen-15 scalar at 1 row; gen-17 matrix at every row count; gen-16/M4 falls outsidescalarKernelGenerationsand uses matrix at every row count),warmRowExactWindowsonsetRowExactWindows(true)(DARKBLOOM_MUSE_GLIMMER_ROW_EXACT_WARMUP=0to disable), andMuseGlimmerRowExactWarmupTests.9b64917f— Grid reconciliation test:CBv2PrefillChunkGridTests.testAlignmentSuppressesFixedGridAndFinishingPromptLaneverifying mutual exclusion betweenprefillChunkAlignment(#423) andfixedPrefillChunkGrid(#515) / finishing-prompt lane (#565).c60b7efa— Replay Muse Glimmer 30B: image input on the pinned NVFP4 checkpoint (stacked on #423) #427 (feat/muse-glimmer-vision,3702459f): additiveMuseGlimmerVisionFeaturesinLibraries/MLXVLM/Models/MuseGlimmer.swift, fork-onlyMuseGlimmerImageEncoder(strict 809-tensor BF16 pinned loader, upstream sRGB + LANCZOSsmart_resizepreprocessing up to 4,096 merged tokens,<|patch|>expansion), causal-onlyCBv2MultimodalSteppableModelconformance onMuseGlimmerCBv2Adapter, synthetic/real/proof test suites,docs/muse-glimmer.md, andfork.yaml.d625d5bd— Replay Muse Glimmer: video input (frames, temporal groups, prompt expansion) #432 (feat/muse-glimmer-video,4b002a2f): fork-onlyMuseGlimmerVideo.swift(2 fps reference frame sampling up to 96 frames / 48 temporal groups / 6,912<|video|>tokens, 144-token per-framesmart_resizecap, pair patchify, per-group encoding,MuseGlimmerMediaPrompt.expandwith vLLMTime: {:.1f}stimestamps and one causal span per group), sharednormalizedPixelsinMuseGlimmerImageEncoder,MuseGlimmerVideoTests, video engine & proof cases,docs/muse-glimmer.md, andfork.yaml.Omitted / dropped items
feat/muse-glimmer-speed)#550/#561onmain(and measured negative on 5/6 Muse Glimmer arms); batched request drafter overlaps#525(CBv2MTPBatchedBlockDrafter) and regressed atc=8.Layr-Labs/mlxfast-muse-glimmer-30b-engine,4a28444e)#423,#427,#429,#430,#432)Placeholders / pending rollout items
d-inferenceto this signed head SHA (d625d5bd)d-inferencePR 2 / PR 4 rebase on top of this commit.MUSE_GLIMMER_NVFP4_DIR,MUSE_GLIMMER_ASSISTANT_DIR,MUSE_GLIMMER_ORACLE_DIR, andMUSE_GLIMMER_VISION_*fixtures.4a28444e)d-inference), not inmlx-swift-lm.Investigation of
#427Test shard 1CI failure & conflict resolutions#427Test shard 1CI failure (run 44242319918/job 134595482466): Inspected the exact failure logs. It was not a vision or Muse Glimmer bug — it was a transient Metal GPU watchdog timeout (Fatal error: [METAL] Command buffer execution failed: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout)) insideModelOptGraphParityTests.fp8ExactReferenceIsBitwiseAtSuperShapes(inputs: 4096, outputs: 131072)(an unrelated Nemotron Super FP8 output-head test from#312/#317) on a virtualized CI runner. All remaining 348 tests in shard 1 passed on Attempt 2,#432(stacked on#427's identical tree) passedTest shard 1,#579's own 16-shard CI runs on both9b64917fandd625d5bdpassedTest shard 1, andModelOptGraphParityTests(including(4096, 131072)) passes locally in0.703s.main(7 total — 6 in text replay + 1 doc hunk in#427;#432applied with 0 conflicts):RecurrentStateV2.swift(vs#515): keptrequiresFixedPrefillChunkGrid = falsealongsiderequiresPagedKV = falseandprefillChunkAlignment = nil.EngineV2.swift(vs#515,#573): wiredscheduler.prefillChunkAlignmentand gatedscheduler.fixedPrefillChunkGridonprefillChunkAlignment == nil && requiresFixedPrefillChunkGrid; preserved#423'sbackendCapabilityViolationchecks,#515'srecurrentStateSpec == nil, and#573'shistoricalPrefillPolicyalongside!(mtpDriver?.checkpointsRequireAssistantHistory ?? false).SchedulerV2.swift(vs#515,#565): madefixedPrefillChunkGridandprefillChunkAlignmentmutually exclusive insideplan()(fixedGridsuppressed whenprefillChunkAlignment != nil) and gatedfinishingPromptsMayPassPartialCaponfixedPrefillChunkGrid == nil && prefillChunkAlignment == nil.PagedCompleteCheckpointAdoption.swift(vs#515): combined!staged.codec.historicalRecurrentwith!(mtp?.checkpointsRequireAssistantHistory ?? false).PagedLayerCache.swift(vs#576): placed#423's opt-inif mtpBatchesRectangularColumnsAsRowsahead of#576's opt-inif mtpBatchesRectangularAttention ... rows.count > 1/rows.count == 1.ToolArgumentNormalizationTests.swift+ToolArgumentNormalization.swift(vs#535/#537/#539): kept allmaintests alongsideboundedJSONNesting(), keptmaximumValueDepth = 63, and extended!nestsPastTheBound(trimmed)tomain'suntypedContainerJSON parse path.docs/muse-glimmer.md(in#427vs#430): kept both#430's verify-window warm-up paragraph and#427's## Imagessection.Blast Radius / What This Could Affect
All Muse Glimmer text tower, DFlash drafter, vision encoder (
MuseGlimmerImageEncoder), video processor (MuseGlimmerVideo), ATEM/Onyx parser, and weight-only NVFP4 files are fork-only additions. Four upstream (ml-explore/mlx-swift-lm) files are modified:Libraries/MLXVLM/Models/MuseGlimmer.swift,Libraries/MLXLMCommon/Tool/ToolCallFormat.swift,Libraries/MLXLMCommon/Tool/ToolCallPolicy.swift, andLibraries/MLXLMCommon/Tool/ToolArgumentNormalization.swift(all described infork.yaml). Every upstream and shared seam touched is listed below:Libraries/MLXVLM/Models/MuseGlimmer.swift(upstream file)MuseGlimmerVisionFeatures(+29 lines)MuseGlimmer,MuseGlimmerVision,MuseGlimmerLanguageModel, or VLM factory weight loading. Wraps upstream's private vision tower/adapter/projection +perception_emb_normfor the native host.Libraries/MLXLMCommon/Tool/ToolCallFormat.swift(upstream file) &ToolCallPolicy.swift(upstream file)ToolCallFormat.swiftinfers.atemfrommodel_type == "muse_glimmer"(+10 lines);ToolCallPolicy.swiftadds publiconyxParsingstored property & init parameter (+7 lines)muse_glimmer: anymuse_glimmerconfig now infers.atemtool format automatically. Other models' tool formats and defaultToolCallPolicybehavior are unchanged.Libraries/MLXLMCommon/Tool/ToolArgumentNormalization.swift(upstream file)maximumValueDepth = 63, +49 lines)JSONSerialization/JSONValue.from(both typedobject/arrayandmain'suntypedContainerpath). Matchesd-inference's 64-level bound and prevents 512 KiB cooperative-thread stack overflow. Payloads ≤63 levels are unchanged.MLXLMServer(MLXServerRunner.swift,MLXModelContainerEngine.swift,ReasoningParserFormat.onyx).atem/muse_glimmerserved viaMLXLMServer(--onyx-parsingopt-in for parsing mode)MLXLMServerbehavior for stock upstream MLXVLMMuseGlimmer: (1)MLXServerRunnerdefaults the reasoning parser to.onyxwhenever tool format is.atem(moving reasoning intoreasoning_content); (2)MLXModelContainerEngineroutes.atemmodels whose tokenizer contains Onyx control tokens throughchannelStream(parsing tool frames from token IDs instead ofModelContainer.generate); (3)channelStreamdoes not callloadOnDemandComponents, so upstreamMuseGlimmer'sOnDemandComponentvision tower loads lazily insideTokenIteratorinit on the cooperative pool rather than off-pool, andchannelStreamdrops theTaskreturned bygenerateLoopTask. Non-.atemmodels are unaffected.MuseGlimmerCBv2Adapter.swift(CBv2MultimodalSteppableModel).scalarCacheOffset); does not adoptCBv2MTPRequestScopedMediaFallback.deadlineUnreachable(.multimodalWork)). Mixed-traffic throughput impact: becauseMuseGlimmerCBv2Adapterdoes not adoptCBv2MTPRequestScopedMediaFallback, any live image or video request drops concurrent text rows in the same batch to draft depth 0 until that media request finishes generating (not just during prefill). Outputs are unchanged, but DFlash speedups pause for co-batched text while media requests are generating. Bidirectional and misshapen spans are refused at submit.MuseGlimmerImageEncoder.swift&MuseGlimmerVideo.swiftInstalled.visionSourcesconfig.jsoncross-checked only, never drives loading, bounded regular file, no symlink). Enforces hard caps: 4,096 merged image tokens; 96 video frames / 48 temporal groups / 144 merged tokens per frame / 6,912 `<RecurrentStateV2.swift(CBv2ModelCapabilities)requiresPagedKV = false,prefillChunkAlignment = nil,requiresFixedPrefillChunkGrid = falserequiresPagedKVorprefillChunkAlignment; Inkling 2 keepsrequiresFixedPrefillChunkGrid.EngineV2.swift(backendCapabilityViolation, scheduler grid wiring, historical checkpoints)CBv2ModelCapabilities&CBv2MTPAdvisoryHistoryDrafterprefillChunkAlignment == nilandrequiresPagedKV == false(Inkling 2 still getsfixedPrefillChunkGrid = prefillChunkSize). Historical attention checkpoints still requirerecurrentStateSpec == niland refuse persistent-history drafters unless explicitly advisory under.exact.SchedulerV2.swift&FirstTokenDeadlineAdmissionV2.swiftprefillChunkAlignment == nilby defaultprefillChunkAlignment == nil,stepTokenLimit,runningOrder,prefillGridCell,fixedGrid, andfinishingPromptsMayPassPartialCapbehave identically tomain. Verified byInkling2PagedEngineTests,CBv2FinishingPromptLaneTests, andCBv2PrefillChunkGridTests.PagedCompleteCheckpointAdoption.swift!historicalRecurrent+checkpointsRequireAssistantHistoryhistoricalRecurrent == true) and non-advisory stateful drafters follow the exactmainpath.PagedLayerCache.swift+MTPContractsV2.swift+EngineLoopV2+MTPTargetVerification.swiftbatchesVerifyColumnsAsDecodeRows = false,requiresExactAcceptance = falsemtpBatchesRectangularColumnsAsRows = falseand execute#576'smtpBatchesRectangularAttentionor column-loop paths untouched. Verified byQwen35MTPCohortTests,Qwen35MTPCohortRowsTests, andPagedColumnsAsDecodeRowsTests.CBv2MTPRoundDriver.swift+EngineLoopV2+MTPExecution.swift+CBv2MTPAdvisoryHistory.swiftCBv2MTPAdvisoryHistoryDrafter+.exactobserveCommittedTarget(_:requestState:)identically.ModelOptRowExactKernels.swift,ModelOptWeightOnlyNVFP4RowExactKernels.swift,ModelOptCalibratedLinear.swiftModelOptRowExact.Scheduledefaults to.standard; NVFP4 row-exact kernels are Muse Glimmer weight-only NVFP4 only.standard.ModelOptCalibratedLinearactivation quantization saturates cleanly (ModelOptActivationOverflowTests). Hardware gating note: NVFP4 row-exact scalar-vs-matrix selection (scalarKernelGenerations = [15, 17],defaultScalarRows = 1on gen-15) is gated on GPU generation only (not variant letter; measured on M3 Ultra and M5 Ultra only). M4 is gen-16 (outside both sets, so it uses the matrix kernel at every row count — self-consistent).Non-interference guarantees
requiresFixedPrefillChunkGrid = trueand DSpark drafter (prefillChunkAlignment == nil,mtpBatchesRectangularColumnsAsRows == false);Inkling2PagedEngineTestspasses unchanged.#576): KeepsmtpBatchesRectangularColumnsAsRows == falseand hits#576'smtpBatchesRectangularAttentioncohort path untouched;Qwen35MTPCohortTestsandQwen35MTPCohortRowsTestspass unchanged..standardrow-exact schedule andModelOptGraphParityTestsFP8/NVFP4 kernels;ModelOptGraphParityTests(including(4096, 131072)) passes unchanged.fixedPrefillChunkGridandprefillChunkAlignmentremainnil,#565's finishing-prompt lane remains active, and tool-calling payloads ≤63 JSON nesting levels are unchanged.MuseGlimmer: Generic VLM factory still loads upstream's MLX 4-bit checkpoint identically (MuseGlimmerTextModelis not registered in any generic factory); when served viaMLXLMServer,muse_glimmernow defaults to.atem+.onyxreasoning andchannelStreamrouting as disclosed in the Blast Radius table above.Rollback / fail-closed profile
MuseGlimmerInstallation(never auto-selected by generic factories). Reverting this PR or omitting host staging leaves all other models unaffected.config.json, non-paged KV backends,maxPrefillChunk < 1024, bidirectional media spans, deadline-submitted media, over-cap grids (>4,096 image tokens, >144 video tokens/frame, >96 frames), and placeholder/item mismatches all fail closed with typed errors before execution.DARKBLOOM_MUSE_GLIMMER_ROW_EXACT_WARMUP=0disables verify-width PSO warm-up without changing decode or K/V bytes.Before and After
flowchart LR subgraph Before["Before (main f55c0220)"] B1["Upstream MLXVLM MuseGlimmer<br/>(4-bit factory only)"] B2["CBv2 SchedulerV2<br/>fixedPrefillChunkGrid (#515) +<br/>finishing-prompt lane (#565)"] B3["PagedLayerCache MTP<br/>cohort rows (#576) / column loop"] B4["ToolArgumentNormalization<br/>unbounded JSON recursion"] end subgraph After["After (PR #579, d625d5bd)"] A1["MuseGlimmerInstallation (pinned NVFP4/FP8)<br/>+ MuseGlimmerTextModel + DFlash + M5 gen-17 NVFP4"] A2["MuseGlimmerImageEncoder (809 BF16)<br/>+ MuseGlimmerVideo (2fps / 48 groups)<br/>-> causal CBv2MultimodalSteppableModel"] A3["CBv2 SchedulerV2<br/>prefillChunkAlignment (1,024, Muse) XOR<br/>fixedPrefillChunkGrid (Inkling 2) XOR<br/>finishing-prompt lane (others)"] A4["PagedLayerCache MTP<br/>columns-as-decode-rows (Muse, opt-in) -> <br/>cohort rows (#576) -> column loop"] A5["ToolArgumentNormalization<br/>63-level JSON nesting guard + ATEM/Onyx"] end B1 -. additive MuseGlimmerVisionFeatures + server Onyx/channelStream .-> A2 B2 --> A3 B3 --> A4 B4 --> A5Before any rollout
maxPrefillChunk >= 1024): Configure the paged KV pool withmaxPrefillChunk >= 1024(required byMuseGlimmerTextModel.defaultPrefillChunkAlignment = 1024; the engine refuses at build ifmaxPrefillChunk < 1024) and keepmaxBatchedTokensPerStep >= 1024(SDK andd-inferencedefault is2,048).nvidia/Muse-Glimmer-30B-NVFP4shards (text + 809 BF16 vision tensors verified viaMuseGlimmerInstallation) and the pinned quantized DFlash drafter artifact.setRowExactWindows(true)after staging and before serving, and includenumericsProfilein the checkpoint numerics fingerprint. Note that NVFP4 row-exact kernel selection is gated on GPU generation only (measured on M3 Ultra gen-15 and M5 Ultra gen-17: gen-15 uses scalar at 1 row / matrix for multi-row; gen-17 uses matrix at every row count; M4 is gen-16 and uses matrix at every row count).MuseGlimmerCBv2Adapterdoes not adoptCBv2MTPRequestScopedMediaFallback, so any active image/video generation drops co-batched text rows to draft depth 0 until that media request finishes generating. Account for this in mixed-workload capacity planning or adoptCBv2MTPRequestScopedMediaFallbackin a follow-up.d-inferencePR 2 (and rebase PR 4) to pinmlx-swift-lmto signed commitd625d5bde2bd6f181227e858422f1d072d84c6cc.Validation
Built and tested locally on Apple Silicon (macOS 27.2.0, Xcode 27.2
27B52, Swift 6.4.2, native build system,MLX_ENABLE_TF32=0,--no-parallel) on signed headd625d5bde2bd6f181227e858422f1d072d84c6cc:d625d5bd,Fork Testsrun47209547655)fork.yaml+ Shard maps + CodeQL + Analyze + Hosted audio tests + Sandbox integrityswift-format(6.4.4)git diff -z --name-only --diff-filter=ACMR f55c0220...HEAD -- '*.swift' | xargs -0 swift format format --in-place --configuration .swift-format && git diff --exit-codefork.yamlcheckuv run --with pyyaml python3 scripts/check_forkdiff.py --upstream-ref refs/remotes/upstream/main2,357changed /2,357described)scripts/check-unit-test-files.shCC=$(xcrun -f clang) swift build --build-system native --build-tests --disable-index-store -debug-info-format none -Xswiftc -enable-incremental-file-hashingscripts/stage-test-metallib.sh /tmp/mlx-glimmer.metallib "$(swift build --build-system native --show-bin-path)"(19,433symbols,213 MiB)swift test list --build-system native --skip-build > .build/fork-tests-list.txt && python3 .github/scripts/test_shards.py check --list .build/fork-tests-list.txt8,547tests, each in 1 main run)MLX_ENABLE_TF32=0 swift test --build-system native --skip-build --no-parallel --filter 'MuseGlimmerImage|MuseGlimmerVideo'33tests in7suites:28passed,5env-gated skipped,0failed; video tower & prefillbits_equal=true max_relative=0.0)ModelOptGraphParityTests(#427shard 1 check)MLX_ENABLE_TF32=0 swift test --build-system native --skip-build --no-parallel --filter 'ModelOptGraphParityTests'16tests in2suites,0failed;fp8ExactReferenceIsBitwiseAtSuperShapes(4096, 131072)passed in0.703s)MLX_ENABLE_TF32=0 swift test --build-system native --skip-build --no-parallel --filter 'MuseGlimmer'173tests in36suites:149passed,24env-gated skipped,0failed,276.1s)MLX_ENABLE_TF32=0 swift test --build-system native --skip-build --no-parallel --filter 'ModelOptRowExact|ModelOptWeightOnlyNVFP4|ModelOptActivationOverflow|ModelOptCalibratedLinear|PagedColumnsAsDecodeRows|Onyx|ATEMReference|ToolArgumentNormalization|CBv2PrefillChunkGrid|CBv2FinishingPromptLane|CBv2RecurrentState|CBv2CompleteCheckpoint|PagedCompleteCheckpointCodec|Inkling2PagedEngine|Qwen35MTPCohort'51XCTests passed +222Swift Testing tests in26suites:211passed,11env-gated skipped,1expected known issue inOnyxContainerEngineTests,0failed)Skipped / Ignored
MuseGlimmer(MuseGlimmerRealArtifactTests,MuseGlimmerDFlashRealArtifactTests,MuseGlimmerDFlashStudyTests,MuseGlimmerExactWindowRealTests,MuseGlimmerImageRealTests,MuseGlimmerImageProofTests, andMuse Glimmer Onyx decoder with the published tokenizer) skipped because checkpoint directories (MUSE_GLIMMER_*) are unset on this machine.ModelOptWeightOnlyNVFP4RowExactBenchmarkTestsskipped (opt-in benchmark suite).withKnownIssue) inOnyxContainerEngineTests.endOfTextEndsGeneration(.strict)carried unchanged from#423(reference-parity mode passes).Not proven
#423/#427/#432against pinned checkpoints, not re-run locally without checkpoint weights).docs/muse-glimmer.md).main's#578(70183a70, CBv2 early layer submission) in CI (local test merge is textually and semantically clean; see Reviewer Notes).Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes (not--all-filessincemainis not formatted; CI'sswift format6.4.4 check passed with 0 diffs on all changed Swift files)docs/muse-glimmer.md,changelog.d/atem-reference-reader.md,fork.yaml, tool-calling docs)AI usage
accurately describes the code changes.
#423,#429,#430,#427, and#432ontomain, reconciled conflicts, verified#427's shard 1 CI failure, added the scheduler grid-reconciliation test, ran the local Swift/Metal test suites, and drafted this PR description under Dylan's direction. The box above stays unticked until Dylan/Jonathan reviews the diff and description.Reviewer Notes
Highest-signal files to inspect first:
Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift&EngineV2.swift— mutual exclusion betweenprefillChunkAlignment(#423) andfixedPrefillChunkGrid(#515), plusfinishingPromptsMayPassPartialCap(#565) gating (CBv2PrefillChunkGridTests.testAlignmentSuppressesFixedGridAndFinishingPromptLane).Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedLayerCache.swift— opt-inmtpBatchesRectangularColumnsAsRows(#423) coexisting cleanly ahead of#576'smtpBatchesRectangularAttention.Libraries/MLXVLM/Models/MuseGlimmer.swift(+29 additiveMuseGlimmerVisionFeatures),Libraries/MLXLMCommon/Tool/ToolArgumentNormalization.swift(+49,maximumValueDepth = 63active for all models across typed anduntypedContainerpaths),ToolCallFormat.swift(+10), andToolCallPolicy.swift(+7).Libraries/MLXVLM/Models/MuseGlimmerImageEncoder.swift,MuseGlimmerVideo.swift, andMuseGlimmerCBv2Adapter.swift— strict 809-tensor vision loading, 2 fps / 48-group video framing & vLLM timestamps, and causal-onlyCBv2MultimodalSteppableModelconformance.Inherited
#423invariants & merge-freshness items flagged for Jonathan before un-drafting:maxBatchedTokensPerStep < alignment(M2):EngineV2.backendCapabilityViolationenforcesmaxPrefillChunk >= alignment(1024) but does not refusemaxBatchedTokensPerStep < alignment, whileSchedulerV2raisesstepTokenLimit = max(maxBatchedTokensPerStep, alignment). Safe at the default2,048(SDK andd-inference), worth adding a fail-closed check before un-drafting.cbv2RequiresHistoricalPrefillGrid; the effective capture stride (1,024viahistoricalCheckpointStrideTokens) currently matchesdefaultPrefillChunkAlignment = 1,024coincidentally with no explicit assertion. Any customretention.strideoff-grid would break cold-vs-restored prompt parity.MLXLMServerchannelStreamon upstreammuse_glimmer(M3):channelStreamskipsloadOnDemandComponents(lazy vision-tower load on the cooperative pool) and drops theTaskreturned bygenerateLoopTask.main#578(L1): Merge-base isf55c0220(#576), one commit behindmain(70183a70,#578CBv2 early layer submission). Verified textually and semantically clean merge (Muse'supdateAndAttendhitsCBv2LayerSubmission.layerBoundarybeforeattendColumnsAsDecodeRows); merge/rebasemainand re-run CI before un-drafting.