Repository navigation
feat(calibrate): mlx calibrate — native modelopt FP8-activation parity (attn/GDN) - #92
Conversation
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]>
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_d38d7837-d590-460c-8cf9-d75b62de2523) |
|
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 Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
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: 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".
| write_amax_into_config(config_path, amax)?; | ||
| Ok(amax.len() as u32) |
There was a problem hiding this comment.
Return only amax entries actually written
When calibration records keys but config.json has no matching per-layer object entries (for example an older/top-level-only mxfp8 quantization block or missing quantization aliases), write_amax_into_config can write zero input_amax fields because it only mutates existing entries. Returning amax.len() still makes native/CLI report success, so the model remains uncalibrated while users proceed as if it was written. Track actual insertions from apply_amax_to_block (or fail when none are written) and return that count.
Useful? React with 👍 / 👎.
|
|
||
| /** | ||
| * Read the first `count` `{"text": ...}` rows from a JSONL calibration file. | ||
| * Blank lines and rows without a string `text` field are skipped. |
There was a problem hiding this comment.
Stream calibration rows instead of loading the whole file
When --dataset points at a large JSONL dump, this reads the entire file into memory even though the command only needs the first calibSize valid rows. With the default 1024-row calibration over a multi-GB dataset, the CLI can spend a long time or OOM before native calibration starts. Read line-by-line with a stream/readline and stop once count rows have been collected.
Useful? React with 👍 / 👎.
What
Adds
mlx calibrate— mlx-node natively reproduces NVIDIA modelopt's static W8A8 FP8-activation quantization for the attention + GDN projections, calibrated from the cnn/Nemotron mix, as Metal fake-quant (numeric parity, not speed — Apple has no FP8 matmul hardware).This is the calibrated half of the modelopt recipe that the data-free
--q-recipe nvidiaport (#90) intentionally skipped. Weights stay MXFP4/MXFP8 as before; this branch adds the calibrated per-tensor activationinput_amaxand the runtime that consumes it.The graph-level insight
modelopt's activation quant is just elementwise fake-quant, reproducible with MLX's existing
to_fp8/from_fp8— no new Metal kernel, never touches a quantized matmul:E4M3 (max 448, RNE, saturate);
xupcast to f32 before the pre-scale for bit-exactness;amax <= 0⇒ passthrough. A calibration pass records the runningmax|x|per attn/GDN projection (modeloptMaxCalibrator) and writes it into the model config.How it fits together
to_fp8FFI (mlx-sys)from_fp8wrapperfp8_fake_quant(x, amax)input_amaxparse + threadQuantizedLinearin both denseqwen3_5and MoEqwen3_5_moeloadersQuantizedLinear::forwardinput_amax > 0,mode == mxfp8, and the projection is an activation-FP8 site (symmetric with the calibration tap)ActivationAmaxCollectorMaxCalibratorrunning max, thread-local calibrating flag scoped to the model thread;write_amax_into_configwritesinput_amaxinto bothquantizationaliases with mergedin_proj_qkvz→ splitin_proj_qkv/in_proj_zfanoutmlx calibrateCLIcalib_seq-token truncation) → drain → atomic config writeCorrectness properties (all test-backed)
forwardsuppresses fake-quant, so the pass measures raw activations regardless of any existinginput_amax. Re-calibration is idempotent (verified bit-identical, 78/78 amax).config.jsonbyte-untouched; a successful write is atomic (temp +rename).try_lockserialization + clear-at-start); the arm flag is thread-local so concurrent inference on another model can't contaminate it; the former unguardedstart/finish/discardexports were removed.input_amaxis consumed only on the attn/GDN activation sites at both the writer and loader sides; MXFP4 FFN, affine gates,lm_head,in_proj_baare byte-identical to pre-branch. A non-calibrated model (noinput_amax) is unchanged.encode_sync(add_special_tokens=false)+truncate(calib_seq)is the only truncation boundary (no tokenizer-blind char slicing).model_typedispatch routesqwen3_5→ dense andqwen3_5_moe→ MoECalibratePrefillRaw; anything else is a clear error.Usage
Validation
-D warnings+fmtclean.mlx calibratesmoke 4/4; typecheck clean.0/186 → 78/186 input_amaxon attn/GDN (both aliases, qkv/z fanout), coherent decode that differs from the uncalibrated baseline; forced tiny amax degenerates output — proving the runtime consumesinput_amax. Re-calibrate amax bit-identical.Every review finding (8 rounds) was verified against real code before fixing; the divergent-alias concern was adjudicated non-reachable because convert emits equal-clone aliases (
convert.rs:2726).🤖 Generated with Claude Code
Note
High Risk
Touches quantized forward paths, in-place
config.jsonwrites, and model-thread calibration with process-global state; incorrect amax or site gating would change inference numerics on production checkpoints.Overview
Adds
mlx calibrateand native end-to-end FP8 (E4M3) activationinput_amaxcalibration for--q-recipe nvidiacheckpoints, matching NVIDIA modelopt MaxCalibrator / W8A8 on mxfp8 attention and GDN projections (fake-quant on Metal for numeric parity, not speed).The CLI reads JSONL
{"text": ...}rows and callscalibrateActivationAmaxRawwith full row strings—no tokenizer-blind JS char pre-truncation; native raw tokenize (add_special_tokens=false) and truncate tocalib_seqtokens is the only window boundary. Native code loadsqwen3_5/qwen3_5_moe, runs prefill-only per row with a thread-local collector, then atomically writesinput_amaxinto bothquantizationandquantization_config(merged GDNin_proj_qkvzfans out to splitin_proj_qkv/in_proj_z). Failed, zero-row, or no activation-fp8-site runs leaveconfig.jsonunchanged.Runtime changes thread
PerLayerQuant::input_amaxonly onto attn/GDN mxfp8 sites in dense and MoE loaders;QuantizedLinear::forwardrecords rawmax|x|while calibrating, otherwise appliesfp8_fake_quantwheninput_amax > 0and mode is mxfp8. Newto_fp8FFI andfp8_activationmodule support the E4M3 round-trip. Docs and tests cover CLI smoke, char-slice regression, and loader site gating.Reviewed by Cursor Bugbot for commit dd22613. Bugbot is set up for automated code reviews on this repo. Configure here.