Repository navigation
feat(nemotron_h): NVIDIA Nemotron 3.5 Lightning 30B-A3B NVFP4 support - #120
Conversation
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_23c0a7d8-aa11-4896-be0e-c27df96a5465) |
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f7ea70a44d
ℹ️ 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_4f0d07be-c474-40bf-84b7-3e103e0bec59) |
|
Thanks for the review — verified all three P2 findings against the code and fixed them in b80aeb3:\n\n1. MTP pre-norm residual (mtp.rs) — confirmed: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b80aeb3394
ℹ️ 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_8ad4eea3-97dc-4137-95c5-f34cb25d6864) |
|
Follow-up on the MTP findings from the re-validation — root-caused and fixed in c867d0c:\n\nRoot cause (deeper than the residual bug): |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c867d0cd3f
ℹ️ 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".
|
Final state of the MTP work (c867d0c + docs commit): the strict sequential verify is confirmed bit-identical to the flat-path greedy stream on the real checkpoint (PAGED-MTP rawText == FLAT-AR rawText exactly; real_mtp_t0_lossless_gate passes over 60 tokens). The residual MTP-vs-paged-AR text difference on this checkpoint is the documented flat/paged recurrence divergence (flat path is loop-prone on NVFP4, paged answers crisply) — tracked as the open follow-up in docs/models.md. |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_197774a4-f1ed-4d28-af92-0e096eb7decc) |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_b8819a83-7147-40e5-92cd-12f315f3c99d) |
|
Addressed the remaining reviewer findings (#4-#7) and the 'yarn build:ts && yarn test' CI failure in 9bc95c8, each verified against the engine conventions first:\n\n- MTP extra EOS — unioned |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9bc95c80b5
ℹ️ 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".
|
Addressed #8 and #9 in 9be4d64, verified before applying:\n\n- #8 (P1) — the recipe dispatch matched the caller's omitted |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9be4d649cd
ℹ️ 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_7904c5a1-379f-42c8-b7a6-a6620985108a) |
|
All 10 review threads addressed and resolved. The last one ("Apply the architecture probe in native conversion", P2) is fixed in 32e867b: the config-driven predicate now mirrors the native parser and TS registry (model_type OR NemotronHForCausalLM architecture is authoritative), extracted as is_nemotron_h_config() with a five-case unit test. A direct convertModel caller with an architecture-only config now runs the ingest sanitizer instead of saving un-repacked U8/F8 tensors.\n\nLocal gates: fmt, clippy --all-targets -D warnings, nemotron 37/37, convert 213 — all clean. CI re-running on the new head. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 32e867bbb0
ℹ️ 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_c17da584-bc0a-4511-a39d-463ac6c8f1ff) |
|
Both new findings verified and fixed in 564640d, threads resolved:\n\n- P1 (MTP desync latch) — confirmed: the mid-cycle-stop latch was stored on the inner but the ChatBackend trait methods defaulted to false/no-op, so cache recovery could reuse advanced flat caches after a partial verified cycle. Now overrides flat_caches_desynced / clear_flat_caches_desynced (the qwen3_5/qwen3_5_moe contract) with a wiring test.\n- P2 (effective-type dtype ownership) — confirmed: has_custom_sanitizer consulted the caller's raw model_type; with -m omitted and an f16/bf16 target the generic cast pre-rounded the F32 weight_scale_2 / input_scale sidecars before the ingest fold. Now derives ownership from the effective recipe_model_type via a shared helper with a contract test.\n\nLocal gates: fmt, clippy --all-targets -D warnings, nemotron suite, convert suite (214) — all clean. CI re-running. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 564640d98a
ℹ️ 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_15caeed9-4da8-425c-a797-ccf55d583437) |
|
The two newest findings are verified and fixed in 570a8b5, threads resolved:\n\n- Architecture-aware ingest guard (convert.rs) — confirmed: validate_nemotron_h_ingest_options checked only config.model_type, so quant flags with an architecture-only Nemotron config bypassed the rejection while the driver (architecture-aware) ran the ingest sanitizer and then the generic quantize block — packing dense tensors the loader requires dense. The guard now uses the shared is_nemotron_h_config predicate (tests: arch-only reject + clean accept).\n- CLI probe-first detection (convert.ts) — confirmed: the Nemotron architecture check sat after the recognized model_type branches, so a stale model_type (e.g. qwen3_5) with the Nemotron architecture routed to another family's sanitizer. The probe now runs FIRST (authoritative architecture, matching the native parser + registry); new CLI tests for architecture-only and architecture-beats-stale-model_type.\n\nGates: fmt, clippy --all-targets -D warnings, convert 214, CLI convert-cmd 33, typecheck — clean. CI re-running. |
…\n\n- Convert ingest (-m nemotron_h) for the modelopt checkpoint: NVFP4 U8 fp4\n codes repacked bit-exact into MLX nvfp4 u32 storage with weight_scale_2\n folded into per-group E4M3 scales; FP8 Mamba-2 projections mapped to\n mxfp8 8/32 with the checkpoint's input_scale threaded as a static\n input_amax; 128 experts fused into [E,N,K] switch-linear pairs; lm_head\n dequantized to bf16; mtp.* retained verbatim; re-quantization flags\n rejected (ingest-only).\n- Native nemotron_h model: 52-layer hybrid (23 Mamba-2 SSM + 23 MoE-FFN +\n 6 GQA attention layers), chunk-128 chunk-scan prefill + recurrent\n decode, sigmoid top-6 router with e_score_correction_bias, relu2\n experts + shared expert, native MTP (eh_proj fusion, depth-1\n draft+verify), flat and paged caches, ChatSession surface.\n- Concurrent inference: default-on scheduled lane; paged K/V for the six\n GQA layers via the generic batched route; per-request Mamba-2 conv/SSM\n rows stacked/scattered around batched [N,1] decode; chunk-128-aligned\n prefill break-sets; per-row exact decode for quantized checkpoints\n (bit-identical to serial).\n- Tokenizer: omit absent context keys so HF 'is defined' templates\n (Nemotron) render correctly.\n- TS wiring: registry entry, stream wrapper, exports, detection tests;\n curated-catalog entry (hidden); docs updated.\n\nValidated on the real checkpoint: deterministic 21 GB conversion,\nAR decode 48-53 tok/s, MTP drafts accepted (verified commits), 4-way\nconcurrency, paged-vs-flat and batched-vs-serial parity gates green.
…g, architecture authority, clippy - mtp.rs: fix MTP draft residual math — the skip connection now carries the PRE-norm hidden (NemotronHBlock contract: residual = h; h = norm(h); h = mixer(h); return residual + h). The previous post-norm residual replaced the residual stream with its normalized self and corrupted the draft logits (reviewer P2; likely the main cause of the low MTP acceptance). - persistence.rs: fail closed on missing required tensors — embeddings, final_norm, per-layer norms, mamba in/out projections + conv1d weight/ bias + dt_bias/A_log/D/mixer-norm, attention q/k/v/o, MoE gate + e_score_correction_bias + both expert stacks + both shared experts now error instead of silently keeping the randomly-initialized tensors (reviewer P2). Also single_match clippy conversions. - config.rs: the NemotronHForCausalLM architecture is now authoritative for the native parser, matching the TS registry probe (a config that detects as nemotron_h must load as nemotron_h; reviewer P2). Tests updated: wrong model_type + architecture present -> accepted; wrong model_type without the architecture -> rejected. - clippy -D warnings clean (CI Rust Lint): needless_range_loop, manual_is_multiple_of, single_match x3, let_unit_value, identity_op x2, field_reassign_with_default x2, collapsible_if. - Verified: cargo clippy --all-targets -- -D warnings green; nemotron (35+), tokenizer (80+), and convert (212) test suites green; cargo fmt clean.
…forwards verify_step batched the verify window [anchor, drafts] as ONE [1, depth+1] forward, so every Mamba-2 layer took the chunk-scan path whose padded-chunk arithmetic differs from the recurrent decode path in f32 rounding (measured 0.66-1.5 logits of drift on the real checkpoint). The drift flips the near-tie argmaxes (gaps 0.09-2.5) the model produces everywhere, so the verify's argmax stopped being the true AR greedy token and the commit path could commit a non-target token at T=0 — breaking the lossless contract (identical first-53 committed tokens followed by a divergent commit) and derailing continuations into loops. Fix: verify_step now forwards each verify token SEQUENTIALLY (one [1,1] decode forward each, stacked via concatenate_many), so the verify is bit-identical to the plain AR greedy computation and the accept test always compares against the true target greedy. Tests: hardened mtp_turn_runs_draft_verify_cycles with an explicit strictness assertion against the plain-AR oracle; new env-gated real_mtp_t0_lossless_gate (real checkpoint, MTP == AR over 60 tokens). Local: nemotron suite 37/37, clippy --all-targets -D warnings clean, fmt clean. Real checkpoint: lossless gate PASS, acceptance 0.78 drafts/cycle.
…t-identical to flat greedy Reflects the c867d0c verification result: the MTP committed stream is now bit-identical to the flat-path greedy stream (real-checkpoint lossless gate), and the remaining cross-path T=0 difference vs paged-AR is the documented flat/paged recurrence divergence (open follow-up).
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 570a8b5986
ℹ️ 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".
…ction + TS mock Reviewer findings #4-#7 and the 'yarn test' CI failure, each verified against the engine conventions before applying: - model.rs run_mtp_whole_turn: union the checkpoint's extra_eos_ids (2, 11) into the MTP turn params (engine contract: the executor populates ChatParams::extra_eos_ids — engine/params.rs:115), so MTP turns stop on the alternate terminators like the paged executor. - model.rs: seed the MTP penalty history with the FULL rendered prompt (tokens.clone()) instead of cached_token_history (empty on fresh turns), matching the flat/paged executors and the decode.rs penalty contract. - model.rs: initialize the MTP finish_reason to "length" (matches paged_turn.rs:233); run_mtp_turn overrides it on a real EOS stop. Runtime-verified: a budget-exhausted MTP run reports finish="length". - convert.ts: auto-detect architecture-only Nemotron checkpoints (architectures: ['NemotronHForCausalLM']) and canonicalize to the nemotron_h ingest recipe, mirroring model-loader.ts and the native parser's authoritative-architecture policy. - packages/lm/__test__/stream-template-policy.test.ts: add NemotronHModel to the @mlx-node/core vi.mock (the new wrapper export) — fixes the CI 'yarn build:ts && yarn test' failure. Verified: cargo clippy --all-targets -D warnings clean; nemotron suite 37/37 (incl. real_mtp_t0_lossless_gate); yarn test 177 files passed / 2 environment-dependent failures (gemma4 audio continuation + agent provider-live — reproduced on base by reverting the shared tokenizer change; pass on main's CI; no PR code touches either path).
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_3684c68c-3878-43cd-b82e-62e2ddef6e2f) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4e9410893d
ℹ️ 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".
… MTP its own KV Deep review of this branch against vLLM and HF transformers found one P0 and five P1 defects, all outside the areas the branch had been iterating on. P0 — attention was NoPE all along. Every reference (HF modeling_nemotron_h.py, vLLM nemotron_h.py, mlx-lm nemotron_h.py) runs the GQA layers with no positional encoding; Mamba-2 carries the sequence modelling. HF defines apply_rotary_pos_emb and never calls it, and no reference config class reads rope_theta. We applied RoPE in all four attention paths, corrupting the 6 backbone GQA layers on every one. Rotation is identity at offset 0 and grows with position, so short prompts stayed fluent and hid it — the visible symptom was the "loops inside <think>" limitation, which this branch had attributed to 4-bit expert noise. Removing RoPE makes the loops disappear. rope_theta stays parsed but optional. P1 — NVFP4 scales are no longer folded. modelopt ships a per-group E4M3 weight_scale plus a per-tensor f32 weight_scale_2. Folding the two (to_fp8(from_fp8(ws) * ws2)) pushes 99.77% of the 243,210,240 group scales below E4M3's smallest normal, into the subnormal band where the grid step is a fixed 2^-9: mean 8.15% / median 6.67% relative error per group scale, one multiplicative factor shared by all 16 elements of a group, so it does not average out in a dot product. Counting only the 0.16% that fold fully to zero is how this reads as harmless. Dequantize-and-requantize measured worse (10.26% vs 8.99% Frobenius). We now do what vLLM does: emit weight_scale verbatim as .scales, carry weight_scale_2 as a separate f32 .global_scale, and apply it on the projection output, which is exact because the matmul is linear in the weight. weight_scale_2 varies per expert, so the stacked switch-linear carries an [E] gather, not a scalar. Existing converted checkpoints must be regenerated; the loader is fail-closed and names the command. P1 — the MTP head now owns its KV. It previously read the target's padded key/value buffers unsliced with mask None, so it attended to uninitialised padding. It now has its own k_proj/v_proj cache, prompt-seeded with the vLLM EAGLE left-shift, and rewound by cursor trim rather than snapshot. forward_read_only is deleted. P1 — row-exact batched decode no longer needs an unwind. Reordered to record-all-then-forward: phase 1 reserves every block (the only fallible step), phase 2 forwards (the only step touching non-invertible Mamba state). A mid-wave failure can no longer leave 23 recurrent states half-advanced. P1 — activate_paged_seq no longer clobbers the recurrent-survival flag on its early return, so the scheduler's double call cannot fake a surviving state. P1 — streaming MTP falls back to AR instead of hard-erroring. P1 — the Mamba dt clamp is now the optional time_step_limit, default (0.0, inf). The in-file CPU oracles hard-coded the same .max(0.001), so no test could observe the divergence. P2 — truncate_history_thinking pinned false; mid-cycle length-stop keeps the I4 frontier aligned. New gates: mid-cycle-stop + warm-continue, lane crossing, MTP mid-cycle state, and a nemotron leg on the model-e2e CI job. Scratch e2e probes under experiments/nemotron-e2e/ removed. Verified on the real 30B checkpoint (reconverted): - .scales byte-identical to source for 128/128 experts; .global_scale bit-identical 128/128 - reasoning loops gone: 833 tokens, finish=stop, closed <think>, correct answer - MTP acceptance 0.888/cycle, up from ~0.4 (depth-1 max is 2.0) - cargo test -p mlx-core --lib 3134 passed / 0 failed / 101 ignored (baseline 3058 / 0 / 99); --tests 3239 / 0 / 224; mlx-paged-attn 327 / 0 / 16 - clippy --all --all-targets clean; typecheck clean Still open, unchanged by this commit: MTP is a net throughput loss at 0.557x AR on this checkpoint. The cycle costs 66.5 ms against a 19.4 ms AR step, so the depth-1 ceiling is 2.0/3.43 = 0.583x — it would need 3.43 accepted tokens per cycle against a maximum of 2.0. The cause is a 2.487 GiB BF16 MTP head on an NVFP4 backbone, byte-identical in the pre-fix checkpoint and therefore pre-existing. Quantizing the head or moving to depth >= 2 is the only route. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JozSaYNtse9xLhvBZ2iSA7
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_628bba4e-6d49-46df-8861-7350c2569fc5) |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Pushed The headline: attention should never have had RoPE. We applied it in all four paths. It survived because only 6 of 52 layers are attention and rotation is identity at offset 0, so short prompts stayed fluent. The "loops inside Second: the NVFP4 scale fold was not harmless. I first measured only underflow-to-zero (0.16%) and concluded it was fine. That is the wrong measurement. One multiplicative factor shared by all 16 elements of a group, so it does not average out in a dot product. Dequant→requant was measured worse (10.26% vs 8.99% Frobenius). Fix is what vLLM does: Remaining P1s: MTP head read the target's padded K/V unsliced with MTP acceptance 0.4 → 0.888/cycle. Gates: lib 3134/0/101 (baseline 3058/0/99), tests 3239/0/224, paged-attn 327/0/16, clippy Not fixed, and I want it on the record: MTP is a net throughput loss at 0.557× AR here and cannot break even at depth 1. The cycle costs 66.5 ms against a 19.4 ms AR step, so the ceiling is |
… router, MTP off by default A deep review against vLLM and HF transformers, then two alignment passes. Every defect below was found and fixed on this branch. THE RESIDUAL STREAM RAN f32. `gated_rmsnorm` never cast back to the mixer's I/O dtype, and the MoE routed-weight multiply re-promoted from the deliberately-f32 router. Layer 0 is a Mamba layer, so the whole 52-layer residual went f32 — and with it every dense projection. The bf16 lm_head was copied to f32 on every forward (2.11 GB vs 0.71 GB peak, 6.99 ms vs 1.53 ms). Both references cast back: vLLM mamba_mixer2.py:148, HF modeling_zamba2.py:69. Closing both escapes at their source is what turned MTP from a 0.56x throughput loss into a wash, and it makes the flat KV cache bf16 so the paged path's astype is the no-op its comment already claimed. MAMBA FP8 PROJECTIONS WERE RE-GRIDDED. fp8_to_mxfp8 dequantized the checkpoint's E4M3 weights and requantized them onto MLX's mxfp8 E8M0 grid, whose power-of-two shared exponent saturates above 448. Measured against the exact from_fp8(w)*weight_scale reconstruction: 4.66-7.94% rel-RMS on top of the source's own 2.65%, with the largest weight clipped in 30% of groups (mean 13.6%). That is 890M params, the entire sequence-mixing backbone, feeding a recurrence this codebase notes amplifies ULP into token flips. vLLM never re-grids FP8 weights. Now affine 8-bit group-32: 0.62-0.72%, 9.83x better. The shipped test could not see it — it used a smooth linear ramp; realistic Gaussian weights blow the same budget. THE F32 ROUTER WAS ROUNDED TO bf16. NemotronAction::Passthrough cast every non-quantized float to bf16, but gate.weight and gate.e_score_correction_bias are the model's only F32 weights and sit on modelopt's ignore list precisely to stay full precision. Rounding them is a DISCRETE error: top-6-of-128 selection flips near ties. The tell that it was accidental — mtp.* short- circuits before the cast, so the MTP router bias kept F32 while the backbone's 23 did not. vLLM builds GateLinear without quant_config. THE SHARED-EXPERT GLOBAL SCALE WAS ROUNDED TO bf16 AT THE POINT OF USE. mul_scalar(f64) builds the scalar in the array's dtype, so 8.646647e-5 truncated by 0.184% on a bf16 activation, and relu^2 squared it to 0.367% every MoE layer. The loader rejects a bf16 .global_scale with a message about exactly this error, and the runtime then committed it. Now an f32 MxArray and .mul(), mirroring the routed arm. A PREEMPTED RESUME RAN AN UNBOUNDED RECONSTRUCTION. The previous pass made the recurrent-survival flag honest, which routed preempted resumes into run_mamba_only_prefill: the whole cached prefix in one unsliced forward through all 52 layers, no cancel check (397 KiB/token/layer => 12.4 GiB at 32k against a 2048-capped normal path). It also performed the very reconstruction prime_prefix_state bans elsewhere for a documented output-quality reason. State survival now gates prefix reuse, so the resume takes the ordinary sliced, cancel-checked cold prefill. mtpAdaptiveDepth ESCAPED THE DEPTH CLAMP. `depth: p.mtp_depth.min(1)` is only a SEED; with the adaptive flag set the Throughput policy explores 2..=5, and depth > 1 routes the replay through chunk_scan — the path whose own comment says it derails the continuation into loops. Reachable from a public NAPI knob with no family gate. Now clamped explicitly, plus a fail-closed error in verify_step if a depth != 1 ever arrives. MTP WAS ON BY DEFAULT. hasMtpWeights() is unconditionally true on the shipped checkpoint, and enable_mtp forces chat_requires_barrier, taking the turn out of continuous batching entirely. Now off by default for this family; MLX_NEMOTRON_MTP_DEFAULT=1 opts back in. Note the throughput half of the original rationale is retracted — MTP is now a wash — so the batching loss is the whole justification. THE MTP DESYNC LATCH. Narrowed from `unemitted > 0` to `unemitted > 1`. This was disputed and settled by measurement, not argument: at depth 1 the bonus token is an argmax of an already-computed verify row and is never forwarded through the 52 layers, so on a mid-cycle stop kv_offset == history length (measured 109/82/51, delta 0 on all 10 probes; an injected 1-token skew moved Mamba state distance 35-150x, proving the probe was sensitive). The real gate was keying off the latch — a detector of the guard, not of the skew — and is retargeted to read rollback_unemitted directly. It is mutation-tested and still fails when the behavior it protects is broken. Also: calibration tap narrowed back to MXFP8_MODE (widening it would have flipped `mlx calibrate` behavior for qwen3_5 under --q-recipe unsloth, which yields affine-8/32 on five activation-fp8 sites); gated-norm epsilon now reads config.layer_norm_epsilon; dead accessors removed; docs, CI comments and CLI help corrected where they described the old layout. Verified on the real 30B checkpoint (reconverted, 72.5 s, 21 GiB, 947 tensors), fidelity checked by an independent raw-safetensors reader rather than through the loader: - .scales byte-identical to source for all 5,888 routed (layer,proj,expert) triples and all 46 shared projections; .global_scale bit-identical - reasoning loops gone: 1,485 tokens, finish=stop, closed <think>, correct answer with a self-check - MTP vs flat AR 1.004x / 1.042x, vs paged AR 0.994x (was ~0.56x) - acceptance 0.9539 — this gauge is accepted_drafts/depth, so its depth-1 MAXIMUM IS 1.0, not 2.0; committed tokens per cycle is 1.9539 - flat AR and flat MTP are BIT-IDENTICAL (max |delta logit| 0.000). The T=0 fork this PR documented as an MTP limitation is not MTP: it is flat vs paged, now at generated token #320 (was #117), ~1 bf16 ULP per position from block-wise paged accumulation order. - lib 3157/0/101, tests 3263/0/224, mlx-paged-attn 327/0/16, clippy zero warnings, cargo build --release clean, typecheck clean Checkpoints converted before this commit must be regenerated; the loader is fail-closed and names the command. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JozSaYNtse9xLhvBZ2iSA7
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_5b7b8378-13be-47f3-aac1-9c20a7dabbfa) |
|
Pushed The headline: MTP is no longer a throughput loss, and the cause was not the BF16 head. Both escapes closed at source:
Quantization: two silent accuracy losses, both measured against the exact reconstruction, not reasoned about. The shipped test could not see it — it used a smooth linear ramp; realistic Gaussian weights blow the same budget. Second: Three defects the earlier fix pass introduced, now closed: a preempted resume ran an unbounded, uncancellable Mamba reconstruction (397 KiB/token/layer ⇒ 12.4 GiB at 32k, against a 2048-capped normal path) — state survival now gates prefix reuse; the shared-expert global scale was rounded to bf16 by MTP is now off by default here. One correction to a limitation this PR previously claimed. The T=0 fork was documented as an MTP-vs-AR difference. A controlled 3-arm experiment shows flat AR and flat MTP are bit-identical (max |Δ logit| = 0.000 across all compared positions). The fork is flat-vs-paged, now at generated token #320 (was #117), a ~1 bf16 ULP residual from block-wise paged accumulation order. Anyone triaging a future divergence should look at the lane, not at MTP. The desync latch was disputed and settled by measurement. Narrowing to Gates: lib 3159 / 0 / 101 (baseline 3134), |
CI pins `toolchain: stable` with no rust-toolchain.toml, so it moved to Rust
1.98, which adds `clippy::chunks_exact_to_as_chunks`. With `-D warnings` that
reds the whole repo, not just this branch: 35 sites across 14 files, of which
exactly one (convert.rs, the NVFP4 u32 repack) came from this branch. Clippy
fail-fasts, so the first run only reported mlx-paged-attn's 2 errors and never
linted mlx-core's 33 — fixing what CI printed would have moved the failure,
not cleared it.
`as_chunks::<N>()` returns `(&[[T; N]], &[T])`, so the element type sharpens
from `&[T]` to `&[T; N]`. That deletes work rather than adding it: about 30
sites drop a `[c[0], c[1], c[2], c[3]]` re-index in favour of `*c`, and
engine/cache.rs sheds a real `try_into().expect("SHA-256 word is 8 bytes")`
panic path that is now statically impossible.
The lint CONST-EVALUATES its argument rather than matching literals, so a
grep for `chunks_exact([0-9]` misses four live sites — two spelled
`size_of::<u16>()`, one `size_of::<f32>()`, one `TENSORS_PER_LAYER as usize`.
Those need the braced turbofish, `as_chunks::<{ size_of::<u16>() }>()`.
Leaving them would have kept CI red.
`qianfan_ocr/processing.rs:221` is deliberately untouched: its `channels` is a
local `let`, not a const, and clippy resolves const items but not `Res::Local`,
so the lint stays silent there. Verified against a real clippy build carrying
the lint rather than assumed.
No behavior change anywhere — `chunks_exact` and `as_chunks().0` both drop the
remainder, and no call site used `.remainder()` or `chunks_exact_mut`.
cargo clippy --all --all-targets: 0 warnings. mlx-paged-attn 327/0/16 and
mlx-core --lib 3159/0/101, both exactly matching the pre-change counts.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JozSaYNtse9xLhvBZ2iSA7
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_d7b8a777-d3c5-4528-a90e-614132e55419) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 45216ee09f
ℹ️ 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".
… slim comments Behaviour change (not cleanup — calling it out so it is not missed in the diff): a cooperatively cancelled prefill used to route into mtp_seed_failed_fallback, which clears mtp_weights_loaded. Nothing outside the loader ever sets it back and every session shares one inner, so a single Ctrl-C permanently disarmed MTP for the whole loaded model. Cancellation is now a distinguished error (PREFILL_CANCELLED) that resets caches and propagates without touching the head. Gated by cancelled_prefill_seed_propagates_without_disarming_the_mtp_head. Paged-KV flags. Six env-var names governed one pair of toggles across overlapping subsets of families, and nemotron_h reached into models::lfm2::attention to read two of them: MLX_QWEN3_NATIVE_KV_WRITE, MLX_GEMMA4_NATIVE_KV_WRITE, MLX_LFM2_NATIVE_KV_WRITE, MLX_QWEN35_NATIVE_KV_WRITE and its undocumented MLX_NATIVE_KV_WRITE alias -> MLX_PAGED_NATIVE_KV_WRITE MLX_LFM2_GRAPH_DECODE_GATHER -> MLX_PAGED_GRAPH_DECODE_GATHER Setting MLX_LFM2_NATIVE_KV_WRITE=0 silently steered Nemotron-H too. One implementation now lives in transformer/paged_flags.rs. All six old names are deleted with no alias. Every one defaulted true and qwen3_5's hand-rolled parse was verified identical to the shared helper on unset, empty, truthy, non-truthy and non-UTF-8 input, so with the vars unset behaviour is bit-identical. The docs claimed the switch falls back to the synchronous path. That holds only for whole-turn decode: all five batched/ragged lanes hard-error, so turning it off turns continuous batching off everywhere. perf.md, the flag docs and `mlx launch claude --help` now say so. Legacy deletion. rope_theta (attention is NoPE) and num_logits_to_keep were parsed and never read; tie_word_embeddings kept only its fail-closed reject and lost the dead stored field. All three leave the public NemotronHConfig typing. Config parsing reads named keys off a serde_json::Value, so the real checkpoint's rope_theta and num_logits_to_keep are simply ignored. The two stale-checkpoint regenerate guards collapse into one; the rejections themselves stay, since a fail-closed guard is the opposite of a compat shim. convert no longer writes the duplicate quantization_config alias — the reader still accepts it, because that is NVIDIA modelopt's on-disk format. Comments. Added-comment ratio 24.6% -> 13.8% (4200 -> 2080 lines) with zero non-comment changes in the slimmed files. Benchmark figures, cross-file line citations and pass-history narrative are gone; the traps stay. Muse companion configs. `prepare_muse_secondary_config` seeded a MISSING quantization alias from the COMPANION's block. Now that convert emits one alias, a single-alias target came out with two DISAGREEING aliases and `select_quantization_block` rejects those, so the model would not load at all. The missing alias is now seeded from its sibling. Latent — no shipped CLI command reaches it — but this branch created the route. Gated by single_alias_target_does_not_produce_disagreeing_companion_aliases, verified to fail under the original seeding. The separate phantom-override bug in the same loop is pre-existing and CLI-reachable: issue #123. CI comments. The nemotron_h matrix entry carried 75 lines of comment for 20 lines of YAML; now 24. Kept: the `-mlx-bf16` misnomer, that BOTH env vars are required (wiring one makes the others early-return, which libtest counts as PASSED), the rejected convert flags, that the leg has never run green, and its disk/memory bill. Verified on the real 30B-A3B NVFP4 checkpoint: paged-vs-flat greedy parity across 3 prompts and two-turn dialog parity. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JozSaYNtse9xLhvBZ2iSA7
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_a531c184-64d2-48c1-b200-9ffb5286bad7) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fd8285e369
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
The leg skipped only when the event was not `pull_request` — but a PR carrying `model-e2e` is exactly the case that runs it. macos-26 has neither the ~38 GB disk nor the ~42 GB memory it needs, so it downloaded the 30B checkpoint and failed. `model-e2e` runs the whole matrix, so that failure landed on every other family's PR too, not just nemotron ones. Skips on every event now. The entry stays as wiring for a self-hosted runner. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JozSaYNtse9xLhvBZ2iSA7
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_58975653-6230-45be-9247-33c4c515379c) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f5c60f1cc2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
The affine-8/32 config override for an FP8 projection is derived from its `.input_scale` sidecar. The collection arm keyed only on `.weight_scale` rank, so a group without the sidecar was repacked as affine while the config kept the top-level nvfp4 mode — convert succeeded and the checkpoint then failed to load. Refused at collection, where the reason is still legible. No stock modelopt preset emits a scalar `weight_scale` without an `input_scale` (the other weight-only shapes are already rejected by the rank classifier), and the real 30B source carries one for all 46 FP8 groups, so this changes nothing that converts today. Gated by nemotron_h_fp8_group_without_input_scale_is_rejected_at_ingest, whose control arm proves the same fixture ingests cleanly with the sidecar present. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JozSaYNtse9xLhvBZ2iSA7
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_d5c0e47a-a436-4100-9671-27040f2c6f15) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7840782987
ℹ️ 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".
…se changed PR #120 landed `nemotron_h` against APIs this branch had already rewritten, so the rebase left the crate non-compiling. Each call site is re-pointed at the surviving shape, with no behavior change: - `MtpStepper::frontier` is now required; implement it. The stepper is a FLAT hybrid, so `attn_tokens` reads the first attention layer's offset through a new ungated `NemotronHLayerCache::attention_offset` (`as_kv_cache` is `cfg(any(test, debug_assertions))` and is gone from a release build). `recurrent_tokens` is `None`: `Mamba2State` carries no consumed-token counter, and the family rewinds the recurrent side by whole-snapshot restore rather than a replayed step count, so there is no bookkeeping to publish. - `MtpVerifyOutput` lost `target_argmax` / `target_sparse` and its `logits` stopped being optional with the dead verify fast paths; construct it through `logits_only`, as every other family does. - `MtpTurnArgs` / `MtpTurnSetup` lost `prompt_hidden_position_base`; the eight sites all passed `0`, which is what the field's removal made unconditional. - `MtpTurnSetup` gained `lookahead_rows`; the five test sites take it off the model's own `SpeculativePlan` the way `run_mtp_turn` does, instead of pinning a literal. - `RenderContextOptions` gained `preserve_thinking`; the Nemotron template test states the one-shot default, which is the caller its pin has to hold for. Also escape the two `|` inside the `MLX_NEMOTRON_MTP_DEFAULT` code span in docs/perf.md: they split the row into seven cells, which the conflict resolution's five-column delimiter then truncated on render. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MCBk7iwMve89ru8c116kki
…125) When the target `config.json` carries no quantization block, `prepare_muse_secondary_config` seeded both aliases from the **companion's** block and then ran the target rescope over that seed. The companion's per-tensor keys are already spelled in the draft namespace, so the rescope invented a target override that was never asked for. ``` GGUF blk.0.attn_q ─normalize_override_key─► language_model.model.layers.0.self_attn.q_proj ─rescope─► language_model.model.language_model.layers.0.self_attn.q_proj ◄─ PHANTOM ─normalize_per_layer_key─► language_model.layers.0.self_attn.q_proj == quant_lookup_prefix(target layer 0 q_proj) muse_projection_quant tries the scoped key FIRST ─► the target inherits the draft's q4k geometry ``` ## Severity: latent today, loud tomorrow The seeding branch is reachable only when the target has **no** quantization block at all, which means an entirely float target. `build_projection` computes the per-layer quant but only consumes it inside `if params.contains_key("{prefix}.scales")`, and a float target has no scales — so the override is discarded. Today the user gets a bogus key in `config.json` and nothing else. Two ways it stops being harmless, both verified rather than assumed: - **Repeating the companion pass hard-errors.** The second pass rescopes the re-inserted draft key onto the phantom already present and hits *"companion quantization collides with existing scoped target override"*. This is wider than `--config-dir`: the function reads `output_dir/config.json`, so any repeat against an already-converted output dir reaches it. - **It disables a safety refusal.** With the block seeded, `top_mode` becomes `Some`, so the *"packed weights but config.json has no quantization mode"* check no longer fires. A quantized target with no alias would go from a loud refusal to a silent mis-decode. ## The fix Build the merged block once and assign it to both aliases, and rescope **only** a block that came from a target alias. When no target block exists, the companion's block is used as-is — its per-tensor entries are restated verbatim by the profiles loop immediately after, so not rescoping them loses nothing. This subsumes #120's sibling fix; `single_alias_target_does_not_produce_disagreeing_companion_aliases` still passes. **One deliberate behavior change.** Two aliases that are both present and disagree now error instead of each being transformed independently. That input is already unloadable — `select_quantization_block` rejects it — so the alternative was silently picking one half, possibly the wrong one. This function runs before the destructive save, so the failure simply moves earlier. ## Gate `companion_seed_does_not_rescope_draft_keys_into_the_target_namespace`, on the same fixture as the existing test — which is the point, since that test produces the phantom and never notices. It asserts anti-vacuity first (the fixture really has neither alias, or the seeding branch never runs and the test proves nothing), then that the draft's own override survives, the literal phantom is absent, and — writing the config out and reading it back through the real loader — that no key resolves onto any target projection across 52 layers × 8 projections plus `embed_tokens`. Mutation-checked in two stages: restoring the old shared-seed rescope makes it fail; then, still mutated, disabling the literal-phantom assertion leaves it failing at the resolver loop. So the spelling-independent half is not carried by the literal one. `clippy --all-targets` 0 warnings. `utils::gguf::` 73, `convert` 220, `models::muse_glimmer::` 216, `models::quant_dispatch::` 41 — 0 failures. ## Repeated companion merges: refused, not silently merged A reviewer raised that a repeated companion pass re-creates the phantom, because `target_block` then holds the draft profiles the previous pass wrote and the rescope cannot tell them from genuine target overrides. **Correcting this PR's earlier claim.** An earlier revision of this description said the fix "turned a loud failure into a silent one" on the second pass. That is **wrong**, and it was checked by running `prepare_muse_secondary_config` from both `main` and this branch over three chained passes. For a target that carries a quantization alias — uniform, single-alias, or with an explicit per-layer override — the two revisions are **bit-identical at every pass**: `main`'s rescope loop moves the previous pass's draft keys exactly as this one does. The repeated-pass phantom is pre-existing and unchanged in kind. The only shape whose pass index moved is a target with **no** quantization block, and that shape *is* issue #123: on `main` the companion seed put the phantom there on pass 1, so `main`'s pass-2 error was `main` tripping over its own corruption rather than a guard worth preserving. That shape is also inert — no quantization block means a float target, and `build_projection` consumes the resolved override only inside `if params.contains_key("{prefix}.scales")`. **The obvious discriminator does not exist.** Excluding entries whose key is also a companion profile key looks like it would work, and does not: the SafeTensors target converter writes genuine target overrides at the *same* spelling the draft uses — that is the only reason the rescope loop exists — and `companion_quantization_keeps_target_and_dflash_layers_distinct` pins a real target q6k override at exactly the key the draft owns as q4k. Key-identity would delete a real target pin, and value-identity fails whenever a Q4_K target meets a Q4_K draft. Separating the two provenances needs the companion to write under its own on-disk namespace, which is a format decision with migration consequences. **So the ambiguous input is refused instead** — keyed on the ambiguity itself, not on a marker. A first attempt keyed the refusal on `dflash_config` alone, on the premise that this function is the only on-disk writer of it. A reviewer showed that premise is false: when `--config-dir` points at an already converted Muse directory, the primary conversion copies that config forward, marker included, so the draft pass would always refuse — and the suggested remedy, a fresh output directory, is what the CLI already does. The obvious repair, clearing the marker in the primary, is **strictly worse**, and the reason is the decisive fact here: the primary does not always rebuild the quantization block. When the source is neither quantized by this run nor carries preserved source quantization, the copied block passes through verbatim, previous draft entries and all. Clearing the marker there would remove the signal and keep the ambiguous data, so the phantom would come back silently. Verified by probe rather than argued. The refusal therefore requires **both** conditions: | non-null `dflash_config` | bare-prefix entry in the block | verdict | | --- | --- | --- | | no | — | allow: a bare entry is the target's own, and is rescoped | | yes | no | allow: the primary rebuilt the block, so nothing is ambiguous | | yes | yes | refuse: a previous draft pass wrote in the namespace a target override also uses | The marker means a **non-null** `dflash_config`. Key presence alone disagreed with the loader, whose `Option<MuseGlimmerDFlashConfig>` maps a JSON null to `None` — so an explicit null would have refused a first companion pass. No writer in the tree emits a null; the schema permits it and two copy paths preserve it, so this is marker/loader alignment rather than an observed failure. Why no further narrowing is needed, which the earlier rounds did not establish: a Muse main-GGUF primary that rebuilds the block always writes it one wrapper deeper, into `language_model.model.language_model.layers.*`. So **any** unscoped key present when the guard runs was copied from a config describing a different checkpoint, or written by a previous secondary merge. There is no input where a correct, current block reaches the guard. A dense primary is the case that makes this visible: it rebuilds nothing, the copied block survives verbatim, and disabling the guard there writes the issue-#123 phantom outright. It also binds the **block** rather than the running companion. The rescope loop walks the target block, so a vision pass over a merged config invents the same phantom; an `is_dflash` conjunct would have let it through. The error now names the offending key and gives advice the user can act on: point `--config-dir` at the base model directory rather than a converted output, or re-run the primary so it rebuilds the block. Five mutations were run and each observed failing: dropping either half of the condition, restoring the marker-only guard, re-adding the `is_dflash` conjunct, deleting the guard entirely, and — as the anti-vacuity proof — making the primary strip `dflash_config`, which fails the test's on-disk marker assertion. **Still open, deliberately.** A stale `dflash_config` is still written into an output that has no `draft.safetensors`, when `--config-dir` points at a converted output and no `--draft` is given. It is inert at load, since the loader returns early when the draft file is absent, and clearing it is the unsafe move above. Removing it properly means clearing the bare-prefix entries alongside it, in the primary path every family shares — a larger blast radius than this PR. The same pass-through arm also leaves a quantization block that is stale for the new weights independently of DFlash; that is pre-existing and untouched. Separately, `muse_projection_quant`'s bare-namespace fallback resolves a target prefix down to the draft's own key, so a target projection with no scoped override still picks up draft geometry. That is asserted as **intended** by `target_and_dflash_quantization_namespaces_stay_distinct`, so it is a design question, not this bug. Fixes #123 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01MCBk7iwMve89ru8c116kki --------- Co-authored-by: Claude Opus 5 <[email protected]>
Summary
End-to-end support for nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4 — a 30B-total / 3B-active hybrid Mamba-2 + MoE + attention reasoning model — including conversion, native chat inference, native MTP speculative decoding, and paged continuous-batching concurrency.
Important
Checkpoints converted before the quantization-accuracy pass must be regenerated. The on-disk layout changed twice on this branch (NVFP4 scale split, then Mamba FP8 → affine-8/32). The loader is fail-closed and names the regenerate command.
What's included
-m nemotron_h) for the modelopt checkpoint:weight_scaleis emitted verbatim as.scalesand the per-tensor f32weight_scale_2is carried as a separate.global_scale, applied on the projection output (exact — the matmul is linear in the weight).input_scalethreaded as a staticinput_amaxfor W8A8-parity activation fake-quant.[E,N,K]switch-linear pairs; F32 router tensors retained at F32;lm_headdequantized to bf16;mtp.*verbatim; re-quantization flags rejected (ingest-only).e_score_correction_bias+ shared expert), 6 NoPE GQA attention; native MTP (vLLM-verified EAGLE fusion, depth-1 draft + verify, own K/V cache).Review and alignment passes
This branch went through a deep review against vLLM and HF transformers, then two alignment passes. Everything below was found and fixed on this branch.
apply_rotary_pos_emband never calls it, vLLM'sforwardtakes nopositions, mlx-lm goes project → SDPA. No reference config readsrope_theta.<think>loops this PR originally documented as a limitation.weight_scale_2was folded into the E4M3 group scale, driving 99.77% of 243,210,240 group scales subnormal: mean 8.15% error per group scale, shared by all 16 elements of a group, so it does not average out..global_scale, vLLM-style. Dequant→requant measured worse (10.26% vs 8.99% Frobenius).gated_rmsnormnever cast back to the input dtype (vLLMmamba_mixer2.py:148and HFmodeling_zamba2.py:69both do), and the MoE routed-weight multiply re-promoted. Every dense projection then ran f32 — the bf16lm_headwas copied to f32 every forward (2.11 GB vs 0.71 GB peak).mask: None.trimrewound.prime_prefix_statebans elsewhere.mtpAdaptiveDepth(a public knob, no family gate) let the Throughput policy explore depth 2-5, escaping themin(1)seed clamp onto an unvalidated multi-token Mamba replay path.verify_step.mul_scalar(f64), which MLX builds in the array's dtype — truncating 8.6e-5 by 0.184%, squared by relu² to 0.367%, every MoE layer.MxArray+.mul(), mirroring the routed arm.gate.weight/e_score_correction_biaswere rounded to bf16 (a discrete error — top-6-of-128 flips near ties).GateLinear.MLX_NEMOTRON_MTP_DEFAULT=1opts back in.activate_paged_seqclobbered the recurrent-survival flag; streaming MTP hard-errored; thedtclamp was hardcoded (and so were the CPU oracles, so no test could see it).time_step_limitoptional, default(0.0, ∞).Architecture and legacy cleanup
A final pass on the branch itself, after the alignment work landed.
One behaviour change, called out so it is not lost in the diff. A cooperatively cancelled prefill routed into
mtp_seed_failed_fallback, which clearsmtp_weights_loaded. Nothing outside the loader ever sets it back and every session shares one inner, so a single Ctrl-C permanently disarmed MTP for the whole loaded model — whilehasMtpWeights()kept returningtrue. Cancellation is now a distinguished error that resets caches and propagates without touching the head. Gated bycancelled_prefill_seed_propagates_without_disarming_the_mtp_head. The reporting half is issue #122.Paged-KV flags. Six env-var names governed one pair of toggles across overlapping subsets of families, and
nemotron_hreached intomodels::lfm2::attentionto read two of them:MLX_QWEN3_NATIVE_KV_WRITE,MLX_GEMMA4_NATIVE_KV_WRITE,MLX_LFM2_NATIVE_KV_WRITE,MLX_QWEN35_NATIVE_KV_WRITE+ its undocumentedMLX_NATIVE_KV_WRITEaliasMLX_PAGED_NATIVE_KV_WRITEMLX_LFM2_GRAPH_DECODE_GATHERMLX_PAGED_GRAPH_DECODE_GATHERSetting
MLX_LFM2_NATIVE_KV_WRITE=0silently steered Nemotron-H too. One implementation now lives intransformer/paged_flags.rs; all six old names are deleted with no alias. Every one defaultedtrue, andqwen3_5's hand-rolled parse was checked expression-by-expression against the shared helper on unset, empty, truthy, non-truthy and non-UTF-8 input — so with the vars unset, behaviour is bit-identical.The docs claimed the switch "falls back to the synchronous write". That holds only for whole-turn decode: all five batched/ragged lanes hard-error, so turning it off turns continuous batching off everywhere.
docs/perf.md, the flag docs andmlx launch claude --helpnow say so.Legacy deletion.
rope_theta(attention is NoPE) andnum_logits_to_keepwere parsed and never read;tie_word_embeddingskeeps only its fail-closed reject and loses the dead stored field. All three leave the publicNemotronHConfigtyping. Config parsing reads named keys off aserde_json::Value, so the real checkpoint'srope_theta: 10000andnum_logits_to_keep: 1are simply ignored — verified by loading it. The two stale-checkpoint regenerate guards collapse into one; the rejections stay, since a fail-closed guard is the opposite of a compat shim.convertno longer writes the duplicatequantization_configalias — the reader still accepts it, because that is NVIDIA modelopt's on-disk spelling.Muse companion configs. Emitting one alias exposed a seam:
prepare_muse_secondary_configseeded a missing alias from the companion's block, so a single-alias target came out with two disagreeing aliases andselect_quantization_blockrejects those outright. The missing alias is now seeded from its sibling. Latent — no shipped CLI command reaches it — but this branch created the route. Gated bysingle_alias_target_does_not_produce_disagreeing_companion_aliases, verified to fail under the original seeding. A separate phantom-override bug in the same loop is pre-existing and CLI-reachable: issue #123.Comments. Added-comment ratio 24.6% → 13.8% (4200 → 2080 lines) with zero non-comment changes in the slimmed files. The
nemotron_hCI matrix entry alone went from 75 comment lines to 24. Benchmark figures, cross-file line citations and pass-history narrative are gone; the traps stay.Validation on the real checkpoint
Conversion 72.5 s, 21 GiB, 947 tensors. Fidelity verified by an independent raw-safetensors reader, not through the loader:
.scalesbyte-identical to source for all 5,888 routed (layer, proj, expert) triples and all 46 shared projections;.global_scalebit-identical for all.from_fp8(w)·weight_scalereconstruction (was 4.66-7.94%).Reasoning loops gone: 1,485 tokens,
finish=stop, closed<think>, correct answer with a self-check.MTP is no longer a throughput loss (two replicates, same binary, cool-down between):
MTP vs flat AR 1.004× / 1.042×; vs paged AR 0.994×. Was ~0.56× before the dtype fix. Acceptance 0.9539 — note this gauge is
accepted_drafts / depth, so its maximum at depth 1 is 1.0, not 2.0; committed tokens per cycle is1 + acceptance= 1.9539.Gates:
cargo test -p mlx-core --lib3157+ / 0 failed (baseline 3134);--tests3263 / 0;mlx-paged-attn327 / 0 / 16 (identical to baseline);clippy --all --all-targetszero warnings;cargo build --release --allclean; typecheck clean. All real-checkpoint gates pass and were confirmed to have actually run (they self-skip as pass when the env var is unset).Known limitations
mamba_cache_mode="align"); we re-derive instead, and forbid reuse when the state did not survive. Different design, documented.row_exact_decode_projectionsforces N serial single-row decodes, so the fused batched branch is not exercised by the published checkpoint.k_scale/v_scaledropped; bf16 KV), DSpark/DFlash drafts, and SSD cold-tier restore are follow-ups.Note
High Risk
New model family plus convert/quant layout, chat scheduler, MTP, and paged-KV paths. Also changes shared convert config emission (
quantizationonly) and unifies paged-KV env flags across families.Overview
Adds Nemotron 3.5 Lightning (
nemotron_h) as a first-class family: convert ingest, native chat, paged continuous batching, and optional MTP.Convert is ingest-only. NVFP4 expert codes are repacked bit-exact; E4M3 group scales stay verbatim and
weight_scale_2is a separate f32.global_scale(not folded). Mamba FP8 projections become affine-8/32 withinput_amax; routers stay F32;lm_headdequants to bf16;mtp.*is kept verbatim. Quantize flags are rejected. Convert now writes a singlequantizationblock (drops the duplicate alias).Runtime is a 52-layer hybrid: Mamba-2, relu² MoE, and NoPE GQA. Paged KV is default-on. Quantized decode is row-exact (serial per row, bit-identical to serial). MTP is off by default so sessions stay in the continuous-batching lane (
MLX_NEMOTRON_MTP_DEFAULT=1or explicitenableMtp: trueopts in).Shared cleanup: paged-KV toggles collapse to
MLX_PAGED_NATIVE_KV_WRITE/MLX_PAGED_GRAPH_DECODE_GATHER. MTPbegin_cycleno longer runs on near-tail skipped cycles. Hosted CI wires anemotron_he2e leg but always skips it (needs a ~38 GB / ~42 GB self-hosted runner).Reviewed by Cursor Bugbot for commit 7840782. Bugbot is set up for automated code reviews on this repo. Configure here.