Skip to content

feat: NVIDIA modelopt recipe for mlx — --q-recipe nvidia (MXFP4 weights) + mlx calibrate (FP8 activations) - #90

Merged
Brooooooklyn merged 29 commits into
mainfrom
nvidia-recipe
Jul 9, 2026
Merged

Brooooooklyn merged 29 commits into
mainfrom
nvidia-recipe

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Ports the whole NVIDIA modelopt w4a16_nvfp4-fp8_attn-kv_fp8_cast recipe to mlx-node, in two halves that compose: (A) the data-free MXFP4 weight quantization at convert time, and (B) mlx calibrate, which reproduces modelopt's static FP8 activation quantization (attn/GDN) as Metal fake-quant. Covers both dense qwen3_5 and MoE qwen3_5_moe.

Validated end-to-end on the real 27B: bf16 qwen3.6-27b → mlx convert --q-recipe nvidia (52G→21G, 497 overrides) → mlx calibrate (208 attn/GDN input_amax, both aliases) → coherent decode; runtime provably consumes input_amax (crushing it to 0.05 degenerates output).


Part A — mlx convert --q-recipe nvidia (data-free MXFP4)

A faithful, data-free port of the recipe's weight quantization with MXFP4 in place of NVFP4.

Why data-free: modelopt's MXFP4 weight quant == MLX's mlx_quantize(mode="mxfp4") (dynamic per-block absmax, E2M1, block 32, E8M0, uncalibrated — modelopt doesn't calibrate weight quantizers). Calibration only sets FP8 activation amax, which Part B handles. No imatrix, no AWQ prescaling.

Tensor class Format
FFN gate/up/down (dense .mlp.*, MoE switch_mlp.*, shared_expert.*) + lm_head mxfp4 4/32
self_attn.{q,k,v,o} + GDN linear_attn.in_proj_qkv/in_proj_z/out_proj mxfp8 8/32
GDN in_proj_a/in_proj_b affine 8/64
router gates (.mlp.gate, .shared_expert_gate, .router.proj, .feed_forward.gate) affine 8/64
embeddings, norms, conv1d, A_log/dt_bias, vision, MTP, in_proj_ba bf16

Two conservative deviations from NVIDIA's bf16 (documented in the builder): a/b → affine 8/64 (T=0 MTP↔AR bit-exactness) and router gates → affine 8/64 (mxfp8's coarse E8M0 scales flip top-K). Shared validate_nvidia_recipe_options rejects --imatrix-path / --q-mxfp / explicit --q-bits!=4 / --q-group-size!=32 on both the SafeTensors and GGUF entry points.

mlx convert -m qwen3_5     -q --q-recipe nvidia -i <bf16> -o <out>   # dense
mlx convert -m qwen3_5_moe -q --q-recipe nvidia -i <bf16> -o <out>   # MoE

Part B — mlx calibrate (native FP8-activation parity)

Makes mlx-node natively reproduce modelopt's static W8A8 FP8-activation math for the attn/GDN projections, as Metal fake-quant — numeric parity, not speed (Apple has no FP8 matmul HW). This is the calibrated half Part A intentionally skipped.

Graph-level insight (no new Metal kernel, never touches a quantized matmul):

xq = from_fp8( to_fp8( x · 448/amax ), f32 ) · amax/448     # E4M3 max 448, RNE, saturate; x upcast f32; amax<=0 => passthrough

A calibration pass records the running max|x| per attn/GDN projection (modelopt MaxCalibrator) and writes input_amax into the model config; the runtime then fake-quants those activations.

mlx calibrate -i <nvidia-mxfp4-model> --dataset <calib.jsonl> [--calib-size 1024] [--calib-seq 512]

Correctness properties (all test-backed):

  • Raw-bf16 measurement — a thread-local flag scopes calibration to the model thread and suppresses fake-quant during the pass, so it measures raw activations; re-calibration is idempotent (78/78 amax bit-identical).
  • Non-destructive — a failed / zero-row / empty-collection run leaves config.json byte-untouched; success writes atomically (temp + rename).
  • Not corruptible — one guarded public entry (calibrateActivationAmaxRaw); process-wide try_lock serialization + clear-at-start; the arm flag is thread-local so concurrent inference can't contaminate it.
  • Non-sites untouched — input_amax is consumed only on attn/GDN activation sites at both the writer and loader sides (symmetric is_activation_fp8_site gate); MXFP4 FFN, affine gates, lm_head, in_proj_ba are byte-identical to pre-branch, and a non-calibrated model is unchanged.
  • Token-window fidelity — full rows go to native; encode_sync(add_special_tokens=false) + truncate(calib_seq) is the only truncation boundary (no tokenizer-blind char slicing).
  • Both families — model_type dispatch routes qwen3_5 → dense and qwen3_5_moe → MoE CalibratePrefillRaw.

Validation

  • Unit tests: convert recipe emits exact per-group QuantDecision (dense + MoE); calibration 18/18 · fp8/E4M3 oracle 30/30 · input_amax + site-gating 7/7 (incl. non-site drop negatives) · MoE dispatch/guard/reachability. clippy -D warnings, fmt, typecheck clean.
  • E2E dense 27B (52G→21G): histogram exactly 193 mxfp4 + 208 mxfp8 + 96 affine = 497, lm_head mxfp4; calibrate → 0→208 input_amax (both aliases, in_proj_qkvz→qkv/z fanout); coherent decode that consumes the amax.
  • E2E MoE (agentworld 35B-A3B, 65G→19G): switch_mlp/shared_expert mxfp4, gates affine; coherent.

Every review finding (8 codex rounds) was verified against real code before fixing.

🤖 Generated with Claude Code


Note

High Risk
Large change to Qwen3.5 quantization, model-thread calibration, and in-place config.json mutation on the inference forward path; mistakes could skew FP8 scales or corrupt checkpoints.

Overview
Introduces the NVIDIA modelopt-style workflow in two parts: mlx convert --q-recipe nvidia applies a fixed per-tensor map (MXFP4 FFN/lm_head, MXFP8 attn/GDN, affine gates and GDN a/b) for qwen3_5 / qwen3_5_moe, with upfront validation (model type from config.json, no imatrix/--q-mxfp, pinned bits/group size).

mlx calibrate drives native calibrateActivationAmaxRaw: raw-text tokenize (no chat template), token-only truncation to calib_seq, prefill-only forwards with a thread-local collector on mxfp8 attn/GDN sites, then atomic input_amax writes to both quantization aliases (GDN in_proj_qkvz fans to split qkv/z). Failed, empty, or incomplete homing runs leave config.json untouched.

Runtime changes thread PerLayerQuant::input_amax into QuantizedLinear: fake-quant activations when calibrated (suppressed while calibrating), record max|x| only on activation-FP8 sites, and drop amax on non-sites like lm_head. Adds MxArray::to_fp8, process-wide calibration serialization, and CLI/e2e tests including no fixed UTF-16 char cap before native truncation.

Reviewed by Cursor Bugbot for commit cc6fcf4. Bugbot is set up for automated code reviews on this repo. Configure here.

@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: db5ee21d-7938-4bbf-bf66-038c4716a2b4

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch nvidia-recipe

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cursor

cursor Bot commented Jul 8, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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_870c98a5-6b29-442d-91a5-4fbe11c18dab)

Brooooooklyn and others added 2 commits July 8, 2026 17:06
…t recipe)

Ports NVIDIA modelopt's w4a16_nvfp4-fp8_attn-kv_fp8_cast PTQ recipe with MXFP4
substituted for NVFP4. Data-free: MLX's mlx_quantize(mxfp4) reproduces modelopt's
dynamic uncalibrated weight quantization exactly, and modelopt's calibration only
sets FP8 activation amax (mlx-node keeps activations/KV bf16), so no imatrix or
calibration data is needed. Covers dense qwen3_5 and MoE qwen3_5_moe.

Per-layer map: FFN gate/up/down (dense + MoE switch_mlp experts + shared_expert)
and lm_head -> mxfp4 4/32; self_attn q/k/v/o + GDN in_proj_qkv/z/out_proj ->
mxfp8 8/32; GDN in_proj_a/b -> affine 8/64 (T=0 MTP<->AR bit-exactness);
router gates -> affine 8/64 (mxfp8 destroys top-K routing); embeddings, norms,
conv1d, A_log/dt_bias, vision, MTP, in_proj_ba -> bf16.

Recipe emits Custom{mxfp4/mxfp8} directly (no --q-mxfp wrapper); runs under
top-level --q-mode affine. Rejects --imatrix-path/--q-mxfp/explicit --q-bits!=4/
--q-group-size!=32. Also adds video_preprocessor_config.json to the aux copy list
and de-stales the is_affine_only_key lm_head doc (mode-aware LinearProj post-#85).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `--q-recipe nvidia` validation (reject --imatrix-path, --q-mxfp,
explicit --q-bits != 4, explicit --q-group-size != 32) lived only in the
safetensors path (`convert_model_inner`). The GGUF entry point
`convert_gguf_to_safetensors` had no such guard, so via the exported NAPI
`GgufConversionOptions` API those forbidden flags silently produced a
non-spec checkpoint: an imatrix triggered AWQ pre-scaling that rewrites
weights, and --q-mxfp wrapped the recipe predicate with `apply_mxfp_upgrade`,
upgrading the nvidia recipe's affine-8/64 in_proj_a/in_proj_b decisions to
mxfp8 and breaking the intended T=0 MTP<->AR bit-exactness.

Extract a shared `validate_nvidia_recipe_options` helper (same four
rejections, byte-identical messages) and call it from both entry points:
in `convert_model_inner` under the existing `recipe == "nvidia"` guard, and
early in `convert_gguf_to_safetensors` before the imatrix AWQ pre-scaling and
before the recipe predicate is built/wrapped. Add six unit tests for the
helper (each rejection + bare pass + explicit-matching-defaults pass).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cursor

cursor Bot commented Jul 8, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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_25b26172-e86f-44fb-93fd-f7ae442642f0)

Brooooooklyn and others added 19 commits July 8, 2026 19:27
Mirror the existing from_fp8 wrapper to expose MLX's to_fp8 elementwise
cast to Rust: a one-function C++ FFI (mlx_to_fp8) + extern decl + the
MxArray::to_fp8() method. Produces a uint8 array of raw E4M3 bytes that
round-trips via from_fp8. Foundation for the FP8 activation fake-quant
path (no scale applied here).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add fp8_fake_quant(x, amax) reproducing NVIDIA modelopt's per-tensor static
E4M3 quantize_dequantize on Metal (numeric parity, not speed): upcast x to f32,
scale by 448/amax, round-trip through to_fp8/from_fp8, scale back by amax/448,
downcast to the input dtype. amax <= 0 is a no-op. A pure-Rust E4M3 grid oracle
(3 exp bits bias 7, 3 mantissa bits, subnormals, RNE, saturate to +/-448) proves
the helper matches modelopt independent of MLX.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Review-driven fix. The zero early-return in the e4m3_round test oracle
returned +0.0 for -0.0 (Rust -0.0 == 0.0), violating the doc-comment's
sign-preserving contract; return v instead. Numerically inert but correct
per the stated contract. The reviewer's inf->NaN claim was refuted
empirically (e4m3_round(inf)=448 via the existing q > E4M3_MAX clamp), so
the saturation logic is untouched.

Adds e4m3_oracle_preserves_signed_zero, e4m3_oracle_saturates_above_max
(finite over-range + verified inf saturation), and
e4m3_oracle_rounds_ties_to_even (272->256, 304->320 in the step-32 binade).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add `input_amax: Option<f32>` to `PerLayerQuant`, parsed from an optional
"input_amax" field on each tensor's config.json quantization override
(None when absent), and thread it onto the qwen3_5 `QuantizedLinear` via a
`with_input_amax` builder at the load-time dispatch site in
qwen3_5/persistence.rs. Forward behaviour is unchanged — this only carries
the calibrated FP8 (E4M3) activation scale for a later task to consume.

Dropped `Eq` from `PerLayerQuant` (Option<f32> is not Eq; PartialEq suffices)
and set `input_amax: None` on every other struct literal. Adding the field
grew `QuantizedLinear`, which `LinearProj` wraps ×4 inside `Lfm2Attention`,
tipping lfm2 `OperatorType` over clippy's large_enum_variant threshold;
allowed the lint there rather than box a hot-path per-layer variant.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…dLinear in MoE loader

The dense qwen3_5 loader threads PerLayerQuant::input_amax onto each built
attention/GDN QuantizedLinear, but the MoE qwen3_5_moe try_build_ql closure
returned the raw builder result and dropped it — so a MoE (agentworld-style)
nvidia checkpoint with a calibrated activation-fp8 input_amax silently loaded
its attn/GDN projections with input_amax = None, defeating the plumbing.

Mirror the dense pattern: bind the mode dispatch to `built`, then return
`Ok(built.map(|ql| ql.with_input_amax(plq.input_amax)))`. Experts (mxfp4) and
gates (affine) carry no amax and are untouched. Added a one-line note on the
MTP module's own try_build_ql explaining it deliberately keeps amax None
(the recipe keeps the MTP head Skip/bf16, never an activation-fp8 site).

RED-first test mxfp8_attention_q_proj_threads_input_amax_through_moe_loader
drives apply_weights_moe_inner and reads the amax back off the loaded
attention block (via new #[cfg(test)] read-back seams on LinearProj /
Qwen3_5Attention). RED on the unfixed closure: left None, right Some(37.5).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…esent

Route the QuantizedLinear public forward through fp8_fake_quant when a
calibrated per-tensor input_amax is present, reproducing NVIDIA modelopt's
static W8A8 (E4M3) activation math for the attn/GDN mxfp8 projections. The
input_amax.is_some() guard is the predicate: it is Some only on the
config-marked mxfp8 attn/GDN sites (threaded by Task 3), so mxfp4 FFN /
affine gates+a/b / sym8 / lm_head keep bf16 activations and forward stays
byte-identical when None. Apple GPUs have no fp8 matmul hardware, so this is
numeric parity, not speed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Task-4 forward gate fake-quant'd activations whenever input_amax was
Some(>0), regardless of self.mode. But the Task-3 loaders thread
plq.input_amax onto EVERY built QuantizedLinear unconditionally, so a
stale/malformed/hand-edited config that put input_amax on a non-mxfp8
entry (mxfp4 FFN, affine gate/in_proj_ba, lm_head, sym8) would silently
fake-quant activations on paths that MUST stay bf16.

Enforce the "only attn/GDN mxfp8 sites get FP8 activations" invariant at
the point of use: add `&& self.mode == MXFP8_MODE` to the gate predicate
(the nvidia recipe's mxfp8 projections are exactly the attn/GDN
activation-fp8 sites) and document it. Loaders/parse_quant_block
untouched.

RED-first negative test forward_ignores_input_amax_on_non_mxfp8: a mxfp4
QuantizedLinear with .with_input_amax(Some(2.0)) must be byte-identical
(native u16 bf16 payload, 0 words differ) to the same linear with
input_amax == None. Fails on the unfixed gate (121/128 words differ),
passes with the guard. Positive mxfp8 test stays green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…librator)

Add the FP8-activation calibration instrumentation (modelopt MaxCalibrator):
a process-global ActivationAmaxCollector (AtomicBool enable flag + Mutex map of
per-key running max|activation|), a QuantizedLinear::forward tap that records
the raw bf16 activation max on mxfp8 sites when the collector is armed, the
amax_key threading at both dense + MoE loaders, and write_amax_into_config to
persist collected input_amax into the model config.json quantization block.

Unit-tested without loading a real model; collector/tap tests serialized via a
shared #[cfg(test)] CALIB_TEST_LOCK (poison-recovering) so parallel cargo test
workers don't race the process-global state. Forward is behaviorally unchanged
for normal inference (disabled collector = one atomic load then skip).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…gating

Two codex Task-5 review [high] gaps:

1. write_amax_into_config mapped nothing: collected keys are STRIPPED and the
   GDN input projection is recorded MERGED (in_proj_qkvz) with no config entry,
   while config keys are RAW/WRAPPED and stored SPLIT. Rewrite to iterate config
   quantization entries, strip each key, and fan the merged in_proj_qkvz amax to
   both split in_proj_qkv/in_proj_z entries (shared input x). Non-site/uncollected
   entries left untouched.

2. Forward tap recorded ANY mxfp8 projection: both loaders set amax_key on every
   built QuantizedLinear, so a uniform-mxfp8/hand-edited checkpoint could tap and
   later fake-quant FFN/lm_head. Add is_activation_fp8_site() and gate amax_key to
   the 6 attn/GDN sites (self_attn q/k/v/o, merged in_proj_qkvz, out_proj) only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… aliases

Converted nvidia configs mirror the per-layer quant block into BOTH
`quantization` and `quantization_config` as equal clones (convert.rs). The
writer picked only ONE alias, leaving the mirror stale — an internally
inconsistent config where a consumer reading the other alias sees uncalibrated
input_amax.

Extract the per-entry update loop verbatim into `apply_amax_to_block` (strip
wrapper prefix, in_proj_qkvz merged->split fanout, finite-only, object-only)
and apply it to EVERY present object-valued alias instead of one. Neither alias
present stays a no-op; a single alias updates just that one.

Regression test write_amax_into_config_updates_both_aliases asserts identical
calibration lands in both aliases (incl. GDN split fanout, mxfp4 untouched).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ib mix

Final task of the FP8 activation quantization plan. Adds the `mlx calibrate`
driver that reproduces NVIDIA modelopt's MaxCalibrator: it runs an
`--q-recipe nvidia` model over the cnn/Nemotron calibration mix with the
process-global ActivationAmaxCollector armed, then writes each attn/GDN mxfp8
projection's per-tensor `input_amax` into config.json (both the `quantization`
and `quantization_config` aliases) so a calibrated forward fake-quants those
activations to E4M3 for W8A8 numeric parity.

- Two thin NAPI exports (startActivationCalibration / finishActivationCalibration)
  wrapping the collector's enable/disable+take+write_amax_into_config boundary.
- CLI `calibrate.ts`: loadSession once, per-row minimal prefill via sendStream
  (maxNewTokens 1) + session.reset() between rows to keep each row a fresh
  turn-0 prefill (no KV-cache context accumulation); flags -i/--input,
  --dataset, --calib-size (1024), --calib-seq (512).
- docs/cli.md `mlx calibrate` section; hand-synced both index.d.cts artifacts.

Verified: 0.8b nvidia smoke (input_amax on attn/GDN incl. qkv/z fanout in BOTH
aliases, absent on mxfp4 FFN); e2e decode differs before vs after calibration
while staying coherent (a forced-tiny amax degenerates output, proving the
runtime fp8 path reads config input_amax).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…estructive config write

Review-driven fix of two [high]s in the `mlx calibrate` driver.

Fix 1: a failed calibration no longer mutates the live model config. The TS
catch path called finishActivationCalibration (which wrote partial amax). Now
config is written ONLY after the full loop succeeds; on any error the partial
amax is discarded. write_amax_into_config is atomic (temp file + rename), and a
new discardActivationCalibration() NAPI separates cleanup from persistence.

Fix 2: calibrate over RAW text through PREFILL ONLY (modelopt MaxCalibrator
parity), not chat-templated prompts + a generated token. New native one-shot
calibrateActivationAmaxRaw reuses the session loader (load_with_thread) and runs
a model-thread CalibratePrefillRaw command: encode_sync (no chat template, no
BOS) -> truncate to calibSeq -> prefill only -> reset caches, per row. The CLI
becomes a thin wrapper; the sendStream/loadSession chat path is removed.

Verify: cargo test -p mlx-core --lib calibration 9/9 (incl. atomic-write test);
clippy/fmt clean; typecheck+lint 0; gated CLI smoke 3/3; e2e on 0.8B nvidia
(--calib-size 16) decodes coherent-but-different vs uncalibrated baseline
(60 projections, config 0/186 -> 78/186 input_amax, first divergence char 428).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ss-global collector

Task 6 re-review found two [high]s in the native raw-text prefill calibration
driver (`mlx calibrate`).

Finding 1: `calibrate_activation_amax_raw` was hard-wired to the dense loader +
`Qwen35Cmd::CalibratePrefillRaw`, so a `qwen3_5_moe` nvidia checkpoint (agentworld
etc.) had no command to route to and could not be calibrated — even though the MoE
loader already threads `input_amax`. Now `read_model_type` reads the top-level
`model_type` and dispatches: `qwen3_5` -> dense; `qwen3_5_moe` -> MoE loader + a new
`Qwen35MoeCmd::CalibratePrefillRaw` (a faithful mirror of the dense prefill body:
raw encode, truncate, prefill-only, reset per row); anything else -> clear error.
The enable->disable->persist contract is factored into one shared helper.

Finding 2: the one-shot armed the process-global `ActivationAmaxCollector`, awaited
prefill, then drained+wrote with no mutual exclusion, so a concurrent calibration or
a `start`/`finish` pair could interleave and corrupt the persisted amax. Added a
process-wide `calib_guard` (`tokio::sync::Mutex<()>` -- Send guard held across the
async prefill; `try_lock` fails fast with "another calibration is in progress"), held
for the whole clear->enable->prefill->disable->take->write section. The collector is
cleared at the very start so a prior panicked run's residue cannot leak in. Added
concurrency doc-notes to the start/finish/discard NAPI exports (no functional change).

No NAPI signature changed; no TS change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The public NAPI exports start_activation_calibration,
finish_activation_calibration, and discard_activation_calibration mutated the
process-global ActivationAmaxCollector WITHOUT holding calib_guard, so a
concurrent call could disable/drain/partial-write an in-flight guarded
calibrate_activation_amax_raw run. These three exports were unused (the CLI and
all TS use only calibrateActivationAmaxRaw; no Rust caller references them
outside napi.rs).

Remove them so the guarded one-shot calibrate_activation_amax_raw is the sole
public calibration entry point. Keep the internal ActivationAmaxCollector
enable/disable/take methods (still driven by arm_prefill_persist) and update the
module + calib_guard docs that cross-referenced the removed exports.

Regenerated the napi-rs bindings drop the three exports from packages/core
index.cjs/index.d.cts; hand-synced crates/mlx-core/index.d.cts to match
(byte-identical). Unrelated napi-codegen version churn reverted.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ss fake-quant while calibrating

Codex review found three issues rooted in the calibration collector being an
unscoped process-global. Fix all three at the root:

- [high] visibility bypass: ActivationAmaxCollector arm/disarm/record/take,
  write_amax_into_config, and is_activation_fp8_site are now pub(crate) — no
  in-workspace crate can arm/drain the collector outside the guarded one-shot.
- [high] concurrent-inference contamination: the process-global AtomicBool
  "enabled" flag becomes a thread_local Cell. The model runs on its own OS
  thread, so the CalibratePrefillRaw command self-arms that thread (RAII
  CalibrationArmGuard, disarm on every exit path incl. panic) and record() is a
  no-op unless the CALLING thread is armed. A second model's inference on its
  own thread can no longer pollute the calibrating model's persisted input_amax.
  The running-max map stays process-global (drained off-thread), and calibration
  RUNS stay serialized by calib_guard so only one thread is ever armed.
- [medium] re-calibration parity: QuantizedLinear::forward now suppresses the
  FP8 activation fake-quant while is_calibrating() is true, so a re-calibration
  on an already-calibrated model measures raw bf16 (modelopt MaxCalibrator
  parity) instead of perturbed activations. Non-calibrating inference is
  byte-identical to before.

The NAPI one-shot no longer toggles any global flag (arm_prefill_persist ->
prefill_and_persist): it awaits the self-arming model-thread prefill, then
drains + atomically persists on success.

Tests (RED-first): new record_is_noop_unless_thread_armed and
forward_suppresses_fake_quant_while_calibrating (both shown RED before the fix:
117/128 bf16 words differ without suppression); existing tap/running-max tests
migrated to the thread-scoped API. Gated CLI e2e: re-calibrate on scratch 0.8B
nvidia is bit-identical run-to-run (78/78 amax, max rel diff 0) and decodes
coherently.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…_site in both loaders

The dense (qwen3_5) and MoE (qwen3_5_moe) per-layer try_build_ql closures
gated the recorded calibration tap (amax_key) behind is_activation_fp8_site
but threaded the consumed PerLayerQuant::input_amax unconditionally. Since
QuantizedLinear::forward fake-quants whenever input_amax > 0 && mode ==
MXFP8_MODE, a stale / hand-edited / future-recipe config placing input_amax on
a non-attn/GDN mxfp8 projection (e.g. mlp.gate_proj, lm_head) would fake-quant
that non-site's activations, violating "activation FP8 only on attn/GDN sites".

Thread input_amax under the same is_activation_fp8_site gate as amax_key in
both loaders. No change to QuantizedLinear::forward, write_amax_into_config, or
the collector; no NAPI signature change.

Adds RED-first regression coverage: negative tests assert a non-site mxfp8
lm_head drops input_amax to None (both loaders), plus a dense positive sibling
asserting a real q_proj site still threads Some(37.5).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lects nothing

prefill_and_persist wrote config.json after any successful prefill, ignoring
the prefilled-row count and drained-map size — so an empty dataset, all-empty
rows, or a non-nvidia checkpoint would rewrite/pretty-print config.json and
report a misleading success 0, contradicting the CLI's "config.json was left
unchanged" contract (and potentially churning bytes / stranding stale
input_amax).

Two guards in prefill_and_persist:
- zero prefilled rows => Error (no forward ran, nothing could be collected)
  before any persistence, so a no-op calibration fails loudly instead of
  silently succeeding with 0;
- empty drained map => new persist_amax_if_any helper returns 0 WITHOUT calling
  write_amax_into_config, leaving config.json byte-untouched.

CLI message unchanged (now genuinely accurate). Adds 3 unit tests
(empty-map skip byte-identical, non-empty writes, zero-rows Err); 17/17
calibration tests green, clippy/fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… the sole boundary

The CLI pre-sliced each calibration row to calibSeq*CHARS_PER_TOKEN*2 UTF-16
chars before handing it to the native calibrateActivationAmaxRaw, which itself
tokenizes (add_special_tokens=false) and truncates to calibSeq TOKENS. For
char-dense rows (long URLs/base64/byte-level edge cases exceeding ~2 chars/token)
the slice cut BELOW calibSeq tokens, calibrating on a shorter prefix than
modelopt's token window and biasing input_amax low while still reporting success.

Native token-truncation is now the sole boundary: rows pass through untruncated
in token terms. A coarse memory guard (calibSeq*CHARS_PER_TOKEN*16, far above any
realistic calibSeq-token char length) remains only to bound a pathological
multi-MB row's NAPI payload — documented as a memory bound, not a token guarantee.

Adds a weightless TS test (spies native to assert the full char-dense row reaches
it, RED against the old *2 slice) and a hermetic Rust test proving native encode+
truncate keeps exactly calib_seq tokens.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…truncation is the SOLE boundary

The f217371 "16× memory guard" (calibSeq*CHARS_PER_TOKEN*16) was still a
fixed UTF-16-char cap, which is tokenizer-blind. Concrete failure:
`' '.repeat(70000)` encodes to ~548 tokens under the local Qwen tokenizer
(space runs merge to ~128 chars/token) but the 16× guard slices to 8192
chars = only ~256 tokens, recreating the original under-feed bug where a row
with >=calibSeq tokens calibrates on a shorter prefix, biasing input_amax low.

Pass the full row text to `calibrateActivationAmaxRaw` untouched. The native
`CalibratePrefillRaw` already does `encode_sync(text, add_special_tokens=false)`
then `tokens.truncate(calib_seq)` — the SOLE tokenizer-correct calibration
boundary. Delete the now-unused `CHARS_PER_TOKEN` constant and `maxChars`
slice; drop the false "NEVER cut below calibSeq tokens" comment. No native
char cap added (cnn/Nemotron rows are article-sized; native truncates to
calibSeq tokens regardless, so full-text payload is correct and bounded work).

Test: rename to assert native receives a `' '.repeat(70000)` row UNSLICED
regardless of length. RED against f217371 (slices to 8192 vs 70000), GREEN
after removing the slice. Hermetic Rust truncation test kept intact.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cursor

cursor Bot commented Jul 9, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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_24f3f86e-2ca6-4313-9a99-3edc225bd017)

@Brooooooklyn Brooooooklyn changed the title feat(convert): add --q-recipe nvidia (data-free MXFP4 port of NVIDIA modelopt recipe) feat: NVIDIA modelopt recipe for mlx — --q-recipe nvidia (MXFP4 weights) + mlx calibrate (FP8 activations) Jul 9, 2026

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dd226131d5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mlx-core/src/convert.rs Resolved
The nvidia recipe is a data-free port of NVIDIA modelopt's Qwen3.5/3.6
hybrid recipe and is documented + validated only for qwen3_5 /
qwen3_5_moe. Its per-layer map (build_nvidia_recipe) is a pure
key-pattern predicate with no model-family awareness, so applying it to
any other family — or to an omitted/None model type — emitted mxfp4/mxfp8
per-layer metadata on generic substrings (lm_head, self_attn, .mlp.*)
that those loaders were never designed for, producing an unloadable or
numerically invalid checkpoint instead of failing upfront.

Both convert entry points previously only validated the auxiliary flags
(imatrix / --q-mxfp / --q-bits / --q-group-size) for nvidia and let the
predicate run regardless of model type:
  - safetensors (convert_model_inner): gemma4/lfm2 pass sanitize and a
    None model type passes through untouched, then reach the recipe map.
  - GGUF (convert_gguf_to_safetensors): no HF model_type in scope at all.

Thread model_type: Option<&str> into the shared validate_nvidia_recipe_
options and reject anything outside {qwen3_5, qwen3_5_moe} first. The
safetensors path passes its model_type; the GGUF path passes None (its
arch is inferred from GGUF metadata as e.g. qwen3, never the exact HF
model_type, and re-quantizing an already-lossy GGUF was never a supported
path), so nvidia-on-GGUF is now rejected wholesale.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Brooooooklyn and others added 2 commits July 9, 2026 18:09
…ype, not --model-type

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… + MLX FFI

The ground-truth config.json model_type gate (f712305) was placed after
`convert_mutex().lock()` and `CpuConvertGuard::enter_cpu()`. `enter_cpu` calls
MLX FFI (`mlx_set_default_device`), which can abort with a foreign C++ exception
in a headless/degraded MLX environment — so an unsupported `--q-recipe nvidia`
request would lock the process-wide mutex, mutate MLX's default device, and
create the output dir before the gate could reject it (and the regression test
only reached its assertion where MLX init happened to succeed).

Parse config.json up front (pure file I/O, no MLX) and run the nvidia gate there,
before the mutex / CpuConvertGuard / output-dir creation, reusing the parsed
config for the conversion proper. The gate now fails closed regardless of MLX
state; the regression test rejects in 0.03s without touching MLX FFI.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cursor

cursor Bot commented Jul 9, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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_2b14faec-9189-4a3e-b17c-1ee40a4e4a70)

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2b35341322

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mlx-core/src/calibration/napi.rs Resolved
Brooooooklyn and others added 5 commits July 9, 2026 19:06
…uniform-mxfp8 checkpoint)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-write

Strengthen the phantom-success guard: calibration succeeds only when the
loader-preferred `quantization` alias (quant_dispatch.rs:292 reads it first,
falling back to `quantization_config`) homes EVERY finite collected
activation-amax key — not merely one.

`write_amax_into_config` now counts the homed source keys in the first-present
(loader-preferred) alias and skips the atomic write unless that alias homes all
finite collected keys, so a partial or alias-drifted config is left
byte-untouched. `persist_amax_if_any` measures completeness against the finite
collected count and fails loudly when `written < expected` (covering zero,
partial, and fallback-only-homes cases). Non-finite maxima never home, so
completeness is measured against the finite collected count.

`write_amax_into_config_sets_input_amax` dropped its stray-`v_proj` case (now a
persist-layer failure) and two new regressions cover partial homing and alias
drift. 17 calibration:: tests pass; clippy/fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ed amax

The completeness check must count only what the loader will actually read back,
otherwise a schema-drifted config reports success while inference stays
uncalibrated. Two gaps closed against `parse_quant_block` / the loader's alias
selection (quant_dispatch.rs:242,291):

- `apply_amax_to_block` now skips (does not attach or count) an override object
  without a parseable integer `bits` — the loader DROPS such an entry, so any
  `input_amax` written there is silently discarded on load.
- `write_amax_into_config` selects the loader-preferred alias by KEY PRESENCE, not
  object-ness: the loader reads `quantization` whenever the key is present (even a
  non-object value → materializes nothing, no fallback) and only uses
  `quantization_config` when `quantization` is absent. A present-but-non-object
  `quantization` now yields zero homed even with a complete fallback.

Two regressions added (bits-less override; non-object preferred alias with a
complete fallback). 19 calibration:: tests pass; clippy/fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A non-finite collected maximum (inf/NaN) marks a numerically degenerate prefill
(corrupted weights or a runtime numerical fault). Previously the finite-filtered
`expected` let such a run report success after silently skipping the non-finite
site (which never homes) and calibrating only the rest — a partial phantom
success, and any stale `input_amax` on the skipped site was left in place.

`persist_amax_if_any` now scans for a non-finite value before touching
config.json and fails loudly, naming the offending key. With non-finite rejected
up front, `expected` is simply `amax.len()` (every collected key must home).
Regression added (mixed finite / +inf collection -> error, config byte-identical).
20 calibration:: tests pass; clippy/fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…N masking)

The persist-time non-finite guard (329c28f) inspects only the FINAL folded map,
but `ActivationAmaxCollector::record` folds samples with `f32::max`, which IGNORES
NaN (`4.0.max(NaN) == 4.0`). A row-level NaN could therefore be erased by any
finite sample for the same projection, so a numerically degenerate run's final map
looked all-finite and slipped past the guard.

The fold is now non-finite-preserving: once a key has seen an inf/NaN sample it
stays non-finite (in either sample order), so the persist guard reliably rejects
the run. Regression added recording finite+NaN in both orders.
21 calibration:: tests pass; clippy/fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cursor

cursor Bot commented Jul 9, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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_10712c37-71cb-4c17-833c-0bc2e6d92de7)

@Brooooooklyn
Brooooooklyn merged commit 3141228 into main Jul 9, 2026
7 checks passed
@Brooooooklyn
Brooooooklyn deleted the nvidia-recipe branch July 9, 2026 13:39
Brooooooklyn added a commit that referenced this pull request Jul 9, 2026
…#93)

## What

CI's rolling `stable` toolchain bumped to **rustc/clippy 1.97.0
(2026-07-07)**, which added the **"redundant reference in `format!`
argument"** lint. That trips the existing `cargo clippy --all-targets --
-D warnings` gate on a pre-existing line in
`crates/mlx-core/src/tools/mod.rs`:

```rust
error: Some(format!("Tool call missing name: {}", &raw_content)),   // &raw_content is now flagged
```

This is what turned the **Rust Lint → Clippy** job red on `main` (first
failure on #89, then the #90 merge — run `29022183758`). The code itself
dates back to #64; nothing on #90 touched it — a toolchain bump surfaced
it.

## Fix

Inline the captured identifier:

```rust
error: Some(format!("Tool call missing name: {raw_content}")),
```

`raw_content` is still moved into the struct field on the next line, so
behavior is unchanged.

## Verification

Reproduced the CI toolchain locally (`rustup update stable` → clippy
`0.1.97 (2d8144b788 2026-07-07)`) and ran the exact gate:

```
cargo clippy -p mlx-core --all-targets -- -D warnings
    Finished `dev` profile in 2m 34s   # exit 0, no redundant-reference error
```

Only remaining output is the pre-existing `block v0.1.6` future-incompat
note (present on all green runs; not a `-D warnings` failure).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> One-line formatting change in an error message path; no logic or API
changes.
> 
> **Overview**
> Unblocks **Rust Lint → Clippy** on CI after **clippy 0.1.97** started
enforcing the redundant-reference-in-`format!` lint under `-D warnings`.
> 
> In `ToolCallResult::missing_name`, the error string now uses inline
capture (`{raw_content}`) instead of `{}", &raw_content`. The message
and move semantics are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
44cc4cd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant