Skip to content

feat(calibrate): mlx calibrate — native modelopt FP8-activation parity (attn/GDN) - #92

Merged
Brooooooklyn merged 19 commits into
nvidia-recipefrom
fp8-activation
Jul 9, 2026
Merged

Brooooooklyn merged 19 commits into
nvidia-recipefrom
fp8-activation

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

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 nvidia port (#90) intentionally skipped. Weights stay MXFP4/MXFP8 as before; this branch adds the calibrated per-tensor activation input_amax and the runtime that consumes it.

Stacked on #90 (nvidia-recipe). Review/merge #90 first; this PR is based on that branch so its diff is the calibration feature alone. I'll retarget to main once #90 lands.

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:

xq = from_fp8( to_fp8( x · 448/amax ) , f32 ) · amax/448

E4M3 (max 448, RNE, saturate); x upcast to f32 before the pre-scale for bit-exactness; amax <= 0 ⇒ passthrough. A calibration pass records the running max|x| per attn/GDN projection (modelopt MaxCalibrator) and writes it into the model config.

How it fits together

Piece What
to_fp8 FFI (mlx-sys) E4M3 encode, mirrors the existing from_fp8 wrapper
fp8_fake_quant(x, amax) the graph op above, with a pure-Rust E4M3 oracle test (bias-7, RNE, ±448 saturate, signed-zero)
input_amax parse + thread per-tensor amax parsed from the quant config, threaded onto attn/GDN QuantizedLinear in both dense qwen3_5 and MoE qwen3_5_moe loaders
QuantizedLinear::forward fake-quants an activation only when input_amax > 0, mode == mxfp8, and the projection is an activation-FP8 site (symmetric with the calibration tap)
ActivationAmaxCollector MaxCalibrator running max, thread-local calibrating flag scoped to the model thread; write_amax_into_config writes input_amax into both quantization aliases with merged in_proj_qkvz → split in_proj_qkv/in_proj_z fanout
mlx calibrate CLI one guarded native call: load → raw-text prefill-only (no chat template, no generation, calib_seq-token truncation) → drain → atomic config write

Correctness properties (all test-backed)

  • Raw-bf16 measurement — while a model thread is calibrating, forward suppresses fake-quant, so the pass measures raw activations regardless of any existing input_amax. Re-calibration is idempotent (verified bit-identical, 78/78 amax).
  • Non-destructive — a failed run, a zero-row run, or a run that collects nothing leaves config.json byte-untouched; a successful write is atomic (temp + rename).
  • Not corruptible — the process-global collector is armed only by the one guarded entry (try_lock serialization + clear-at-start); the arm flag is thread-local so concurrent inference on another model can't contaminate it; the former unguarded start/finish/discard exports were removed.
  • Non-sites untouched — input_amax is consumed only on the attn/GDN activation sites at both the writer and loader sides; MXFP4 FFN, affine gates, lm_head, in_proj_ba are byte-identical to pre-branch. A non-calibrated model (no input_amax) is unchanged.
  • Token-window fidelity — the CLI passes full rows to native; 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; anything else is a clear error.

Usage

mlx calibrate -i <nvidia-mxfp4-model> --dataset <calib.jsonl> [--calib-size 1024] [--calib-seq 512]
# writes input_amax into <model>/config.json; the runtime then fake-quants attn/GDN activations

Validation

  • Rust: calibration 18/18, fp8/oracle 30/30, input_amax + site-gating 7/7 (incl. non-site drop negatives), MoE reachability + dispatch + guard tests. clippy -D warnings + fmt clean.
  • CLI: mlx calibrate smoke 4/4; typecheck clean.
  • E2E (0.8B nvidia): calibrate → 0/186 → 78/186 input_amax on attn/GDN (both aliases, qkv/z fanout), coherent decode that differs from the uncalibrated baseline; forced tiny amax degenerates output — proving the runtime consumes input_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.json writes, and model-thread calibration with process-global state; incorrect amax or site gating would change inference numerics on production checkpoints.

Overview
Adds mlx calibrate and native end-to-end FP8 (E4M3) activation input_amax calibration for --q-recipe nvidia checkpoints, 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 calls calibrateActivationAmaxRaw with full row strings—no tokenizer-blind JS char pre-truncation; native raw tokenize (add_special_tokens=false) and truncate to calib_seq tokens is the only window boundary. Native code loads qwen3_5 / qwen3_5_moe, runs prefill-only per row with a thread-local collector, then atomically writes input_amax into both quantization and quantization_config (merged GDN in_proj_qkvz fans out to split in_proj_qkv / in_proj_z). Failed, zero-row, or no activation-fp8-site runs leave config.json unchanged.

Runtime changes thread PerLayerQuant::input_amax only onto attn/GDN mxfp8 sites in dense and MoE loaders; QuantizedLinear::forward records raw max|x| while calibrating, otherwise applies fp8_fake_quant when input_amax > 0 and mode is mxfp8. New to_fp8 FFI and fp8_activation module 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.

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_d38d7837-d590-460c-8cf9-d75b62de2523)

@coderabbitai

coderabbitai Bot commented Jul 9, 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: ec14f70a-2c51-4ad6-9aa5-70f24221b1b1

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 fp8-activation

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.

@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 on lines +141 to +142
write_amax_into_config(config_path, amax)?;
Ok(amax.len() as u32)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@Brooooooklyn
Brooooooklyn merged commit dd22613 into nvidia-recipe Jul 9, 2026
1 check passed
@Brooooooklyn
Brooooooklyn deleted the fp8-activation branch July 9, 2026 08:04
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