Skip to content

feat(models): load the Raon-1 mini MLX and ModelOpt NVFP4 exports - #3453

Merged
inureyes merged 6 commits into
mainfrom
feature/issue-3437-raon-nvfp4-exports
Nov 26, 2026
Merged

inureyes merged 6 commits into
mainfrom
feature/issue-3437-raon-nvfp4-exports

Conversation

@inureyes

@inureyes inureyes commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Loads both KRAFTON NVFP4 exports of Raon-1 mini (about 16 GB on disk against the original's 30 GB) and removes the named refusal #3225 added.

  • Vendor MLX export (KRAFTON/Raon-1-mini-mlx): per-expert global_scale planes go through the existing config-flag resolution into gather_qmm's native NVFP4 tensor scale. The per-tensor global_scale of each raon_global_scaled_linears entry is the UnifiedLinear output multiplier (bf16(f32(y) * g), the vendor's GlobalScaledLinear); sanitize cross-checks the list against the tensors. Vendor runtime switches, head_stage1_* and dflash2/ are ignored.
  • ModelOpt export (KRAFTON/Raon-1-mini-nvfp4): modelopt_fp4 + MIXED_PRECISION now counts as ModelOpt NVFP4 when each quantized_layers entry is NVFP4, W4A16_NVFP4 or MXFP8 (src/models/modelopt_mixed_precision.rs). An all-NVFP4 mixed-precision export loads for every text family. MXFP8 layers become MLX mxfp8 planes byte for byte only for Raon (MXFP8_LAYER_FAMILIES), whose loader reads layouts from shapes; another family's MXFP8 layer fails by name and its weights are left unchanged. Raon stacks the repacked per-expert planes. Any other per-layer algorithm, an MLX quantization entry other than NVFP4 g16 / MXFP8 g32, or a kv_cache_scheme fails by name.
  • Raon dense linears, the head and the expert planes take their layout from tensor shapes, so the MXFP8 head is not misread as NVFP4 or MXFP4. Steering vectors stay f32.

Shared Raon files touched (small, local): raon1_mini.rs (spec layout, head loader, test module line), raon1_mini_moe.rs (inferred expert layout), raon1_mini_sanitize.rs (one call), raon1_mini_config.rs (refusal replaced by delegation). New logic lives in raon1_mini_quant.rs.

Validation (M3 Ultra)

Full numbers in docs/benchmark_results/raon-nvfp4-m3ultra-2026-11-26.md.

  • --reasoning-effort none on the arithmetic prompt: 42 on both exports; default effort gives coherent thinking then 42.
  • Teacher-forced vs the original (mlxcel trace): top-1 agreement 88.7% / 86.9% at 512 tokens and 89.8% / 89.9% at 4096 (MLX / ModelOpt), perplexity +2.5% to +3.6%, every disagreement at a reference top-two gap of 2.375 or less. The two exports agree with each other on every decided position.
  • Resident 16.34 / 16.39 GB vs 30.56 GB; decode 39.9 / 38.8 vs 33.4 tok/s. ModelOpt load is about 70 s (the shared CPU NVFP4 repack), MLX export 0.7 s.
  • Vendor runtime (--no-dflash, RAON_EXACT_KERNELS=0), greedy 64 tokens: identical at the default effort; thinking off diverges at token 50 on a 0.25 logit tie (34.25 vs 34.0) where a wider mlxcel forward agrees with the vendor.
  • Tests: tiny model quantized into each layout, written to disk and loaded through Raon1MiniModel::load, matches its dequantized twin; global-scaled linear vs dequantize-matmul times the scale; detector accept/reject; MXFP8 byte view; f32 steering. Raon, sanitize, switch-layer and modelopt suites pass; clippy --lib --tests clean.

Changes during review

  • MXFP8 layers in a mixed-precision ModelOpt export are converted only for Raon; other families get a named load error instead of a plane their loader would misread (474d6fe).
  • Load-time validation of untrusted planes: every Raon quantized plane (dense, routed experts, RDA, MLA, head) must have scales (and biases) matching weight on every axis but the last, which prevents GPU reads past the scales buffer (f198964, f6ad29e). Dense per-tensor global_scale must be one float element, and a "global_scale": true flag on a dense linear outside raon_global_scaled_linears is refused instead of silently dropped (f6ad29e). The same row check in the shared UnifiedLinear constructors is left for a follow-up.

Closes #3437

#3225 refused both KRAFTON NVFP4 exports of Raon-1 mini at load. This replaces the named refusal with support for both layouts.

- Vendor MLX export: per-expert global_scale planes go through the existing flag resolution into gather_qmm's native NVFP4 tensor scale; the per-tensor global_scale of the raon_global_scaled_linears is the UnifiedLinear output multiplier, and the list is cross-checked against the tensors at sanitize. Runtime switches and the optional head and drafter files are ignored.
- ModelOpt export: modelopt_fp4 + MIXED_PRECISION is now ModelOpt NVFP4 for every text family when each quantized_layers entry is NVFP4, W4A16_NVFP4 or MXFP8 (new modelopt_mixed_precision module). MXFP8 layers become MLX mxfp8 planes byte for byte; Raon stacks the repacked per-expert planes with drain_numbered_expert_planes.
- Raon linears, the head and the expert planes take their layout from the tensor shapes, so the MXFP8 head is not misread as NVFP4 or MXFP4.
- Any other per-layer algorithm, MLX quantization entry, or a ModelOpt kv_cache_scheme fails by name.

Tests: the tiny model quantized into each layout, written to disk and loaded through Raon1MiniModel::load, matches its dequantized twin at the default and none efforts with f32 steering; a global-scaled linear equals dequantize-matmul times the scale; detector accept/reject; MXFP8 byte view.

Refs #3437
supported-models.md and the changelog now describe both NVFP4 exports in place of the #3225 refusal. The new benchmark doc records teacher-forced traces of each export against the original at 512 and 4096 tokens (top-1 agreement 87 to 90%, perplexity +2.5% to +3.6%, the two exports agree with each other on every decided position), ABAB load time, resident memory and decode tok/s for all three checkpoints, the arithmetic and thinking checks, and the vendor-runtime greedy comparison with its one explained near-tie divergence.

Also fixes a clippy lint in the export test writer.

Refs #3437
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata labels Nov 26, 2026
@inureyes inureyes added modelsize:medium 4-bit checkpoint 10-50GB; comfortable on a 128GB dev box modeltype:text Text-only language model arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) labels Nov 26, 2026
The modelopt_fp4 MIXED_PRECISION detector applies to every text family, and the shared repack turned an MXFP8 layer into an mxfp8 plane for all of them. Only Raon's loader reads a linear's layout from its tensor shapes. Any other family passes its NVFP4 16 / 4 to UnifiedLinear::from_weights, which reconciles the plane's widths to MXFP4 at group size 64. MLX cannot run that layout, so a checkpoint that used to fail at load by name would fail at the first forward instead.

The MXFP8 repack now runs only for families in MXFP8_LAYER_FAMILIES (raon1_mini). Another family's MXFP8 layer fails the load with a named error, and the weight map is left unchanged. The repack test covers both cases. The raon, modelopt and sanitize lib tests pass (340), and clippy --lib --tests is clean.

Refs #3437
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Load the Raon-1 mini vendor MLX and ModelOpt NVFP4 exports, replacing the named refusal from #3225 (closes #3437).

Findings Addressed

  • The modelopt_fp4 MIXED_PRECISION detector applies to every text family, and the shared repack turned any family's MXFP8 layer into an mxfp8 plane. Only Raon reads layouts from shapes; another family's UnifiedLinear::from_weights(16, 4) reconciles that plane to MXFP4 g64, which MLX cannot run. A checkpoint that used to fail at load by name would instead fail at the first forward. The MXFP8 repack is now limited to raon1_mini, and other families get a named load error. Fixed in 474d6fe, with a test (HIGH)

Remaining Items

  • ModelOpt export load takes about 70 s because of the shared CPU NVFP4 repack. This is shared with every ModelOpt family and out of scope (LOW)
  • is_modelopt_nvfp4's Used by names Raon1Mini without the path it takes (through load_text_weights) (LOW)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (raon, modelopt and sanitize lib tests: 340 pass; clippy --lib --tests clean)

Raon-1 mini loads quantized planes straight from checkpoint files, and neither UnifiedLinear, SwitchLinear nor MLX's validate_quantized_input compares weight and scales on the output-row or expert axis. A malformed export with scales shaped [out', groups] (or [E', out', groups] for routed experts) shorter than the weight reached qmv / gather_qmm, which index scales by row with raw pointers: an out-of-bounds GPU read, or an uncatchable abort at the first routed forward when a per-expert scales leaf was missing.

Add check_scales_match_weight in raon1_mini_quant.rs: when a scales plane exists it requires the weight, equal rank of at least 2, equality on every axis but the last, and biases shaped like the scales. linear() calls it before layout inference (dense MLP, shared experts, lm_head), and RaonMoe::from_weights calls it for each switch_mlp leaf, covering the MXFP8 checkpoint and both NVFP4 exports. Two load-time unit tests cover a dense linear with short scale rows and an expert stack with a short expert axis.

Validated with cargo check, the scoped raon1_mini and modelopt lib tests, and clippy -D warnings.

Refs #3437
The scales/weight row check from the previous commit ran only where Raon builds a linear through raon1_mini_quant::linear or RaonMoe, so the RDA projections (raon_rda.rs checks weight rows only) and the MLA projections loaded through kimi_k3 still reached qmv with a short scales plane. sanitize_export now runs check_scales_match_weight over every `.scales` key once the expert planes are stacked, covering every quantized plane of both exports. The calls in linear() and RaonMoe stay: they guard direct from_weights callers and the original checkpoint's MXFP8 experts, which are stacked after sanitize_export.

Per-tensor global_scale tensors outside switch_mlp must now be one float32, float16 or bfloat16 element; a vector would broadcast across the output and an integer would truncate it. A `"global_scale": true` flag on a dense entry of the vendor quantization block is refused by name at config parse, and a resolved native_global_scale on a dense path, which UnifiedLinear never reads, is refused at sanitize. check_global_scaled_linears uses a HashSet for the listed paths.

Three load-time tests cover a short-row RDA and MLA scales plane, malformed and valid per-tensor scales, and the dense flag. Scoped raon, modelopt and sanitize lib tests, clippy -D warnings and fmt pass; both real exports answer 42 through mlxcel generate.

Refs #3437
@inureyes

Copy link
Copy Markdown
Member Author

Security review outcome for this PR.

  • HIGH: a scales row count that disagreed with the weight could read out of bounds. Fixed in f198964 and f6ad29e, which check every quantized plane (dense, expert, RDA and MLA).
  • MEDIUM: global_scale shape and dtype were not validated. Fixed in f6ad29e.
  • LOW findings: fixed.
  • Left for a follow-up issue: the shared row check in UnifiedLinear::from_weights_with_mode and from_stacked_parts, which other model families also use.
  • Left as a shared follow-up: the ModelOpt CPU repack takes about 70 s at load.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 26, 2026
@inureyes
inureyes marked this pull request as ready for review November 26, 2026 12:43
@inureyes
inureyes merged commit f74dd84 into main Nov 26, 2026
34 checks passed
@inureyes
inureyes deleted the feature/issue-3437-raon-nvfp4-exports branch November 26, 2026 12:44
inureyes added a commit that referenced this pull request Nov 26, 2026
## Summary

Adds KRAFTON's DFlash2 speculator for Raon-1 mini (`KRAFTON/Raon-1-mini-dflash2`) on `mlxcel generate` and the server, through the existing `--draft-model` / `--model-draft` flags (auto-detected as `--draft-kind dflash`).

- **Drafter** (`mlxcel-core::drafter::raon_dflash2`): config with named errors (a mismatched `target_layer_ids` or stream count fails at load; dimension products that overflow i32 are rejected), sanitize that refuses the vendor NVFP4 key format, the grouped block conv, the 2048-position context window, non-causal attention over grouped KV heads, and the candidate selector chain. It borrows the target's embedding and head. A feature-width mismatch at run time is a `DraftFailed` error, not a panic.
- **Target** (`models/raon1_mini_speculative.rs`): captures the four mHC streams after layers 1, 6, 11, 16 and 21 (`[n, 51200]`, layer then stream). The verify forward is byte-identical to decode: RDA conv and recurrence and MLA run per position, and the dense products (RDA projections, mHC selector, router, SiTU MLPs, head) go through `row_invariant`. The request's reasoning-effort alpha is carried in the burst caches, and rollback restores the recorded RDA state and trims the MLA cache. Gated by `mtp_exactness_gate`.
- **Prefill window**: prefill captures tap features only for the drafter's window (new `Drafter::context_window`, `Drafter::skip_context`, `Raon1MiniModel::limit_prefill_capture`, a no-op `DFlashTargetModel` hook for other targets), so a long prompt no longer materializes `[L, 51200]` features for every row. Context positions, drafts and target logits are unchanged.
- **Sampling**: the draft is deterministic, so the round loop samples each verify row with plain decode's sampler and history and accepts while the sample equals the draft (`drafter::dflash::sampled_verify`, opt-in per drafter through `Drafter::supports_sampled_verify`). That is the speculative rule, so the output keeps plain sampling's distribution, and logprobs come from the sampler-adjusted logits as in plain decode. Samplers that carry feedback state (Mirostat, adaptive-p) fall back to classic decode on the server and are refused offline.
- **Width**: defaults to 5 (four drafts); widths above the trained 8 are refused. `MLXCEL_RAON_ROW_INVARIANT=1` uses the row-invariant matvec kernel for every forward (faster drafting, but plain greedy text changes), so it stays off by default.

Shared Raon files touched with small local edits: `raon_rda.rs` (`forward_recording`, `RdaStep`), `raon_mhc.rs`, `raon1_mini_moe.rs`, `raon1_mini.rs`, `raon1_mini_lm.rs`. Merged with main after #3453 (NVFP4 exports); both sides' behavior is kept.

## Results (M3 Ultra)

Greedy drafted text equals plain decode at widths 3, 5 and 7 on three prompts, including a 3137-token prompt past the context window, and on the server at reasoning effort high and low. After the prefill-window change, width 5 was re-checked on a short prompt and a 3284-token prompt and is still identical. Width 5 runs at 1.30x to 1.76x plain decode and width 3 at 1.39x to 1.76x; sampled width 5 runs at 1.51x. Numbers are in `docs/benchmark_results/raon-dflash2-m3ultra-2026-11-26.md`. Drafting is on whenever a drafter is passed, because the exactness gate passes and every width is faster than plain decode.

Known limits: concurrent batches decode classically (no batched DFlash for this target); the drafter is not yet checked against the NVFP4 exports from #3453, where the exactness gate decides at startup.

## Changes during review

- Adaptive-p joined Mirostat in the sampled-verify decline, since a per-row sampler call reset its running average.
- Sampled-row logprobs now come from the penalty-adjusted logits.
- Prefill captures only the drafter window (above); config size overflow and the `add_context` panic were fixed.

## Test plan

- [x] `raon_dflash2` unit tests: block-boundary conv, hand-computed 3-step selector chain, named `target_layer_ids` error, sanitize, trained-block cap, feature-width error, dimension overflow, skipped context rows
- [x] `raon1_mini::speculative` tests: capture order, verify equal to decode steered and unsteered, probe at widths 3/5/7, rollback after a partial accept equal to a fresh decode, limited prefill capture
- [x] `sampled_verify` tests: Markov joint distribution at widths 2 and 4; a presence penalty sees accepted drafts; feedback samplers never take the sampled rows; adjusted-logit logprobs
- [x] Real checkpoint: greedy equality offline and on the server, server sampled burst
- [x] Narrow clippy (`--lib --tests`, both crates), workspace fmt and clippy, env-var docs and Used-by checks

Closes #3436
inureyes added a commit that referenced this pull request Nov 26, 2026
## Summary

Closes the nine correctness and validation gaps the Raon-1 mini PRs (#3441, #3445, #3453, #3455) left open, in one change.

- **1. presence_penalty (server only).** `GenerationConfigDefaults` reads `presence_penalty`; `resolve_generation_sampling_defaults` overlays it when `--presence-penalty` was not passed (new `presence_penalty_was_set`), logging the source. A request's own value still wins; `mlxcel generate` keeps 0.0. Negative or non-numeric values are ignored with a warning. The llama-server manifest entry moves to `by_design`, like `--top-p`.
- **2. Input widths at load.** New `UnifiedLinear::check_input_width` and `SwitchLinear::check_input_width` (quantized planes through `validate_quantized_packing` with the loaded layout, dense ones by the last axis), called for every RDA, MLA, dense MLP, routed and shared expert projection and `lm_head`. Errors name `{prefix}.weight` and both widths. `KimiK3MLAAttention::check_input_widths` exists but Kimi K3 does not call it yet.
- **3. Scales leading axes.** `check_scales_leading_axes` runs in `UnifiedLinear::from_weights_with_mode` and `SwitchLinear::from_stacked_parts` before reconciliation, for every quantized family. `validate_quantized_packing` and Raon's `check_scales_match_weight` delegate to it.
- **4. KV estimate.** With `rda_config`, `total_bytes` adds `rda_layers * (H*D*D*4 + (K-1)*3*H*D*2)` per sequence (48.8 MB on Raon-1 mini); `marginal_bytes_per_token` is unchanged and the detail line names the state.
- **5. Oracle digests.** `PINNED_CODE_DIGESTS` for revision `6691a076` (verified against the local files' HF etags), checked before the checkpoint code is imported; `--allow-unpinned-code` warns and writes `code_pin unpinned` into the header.
- **6. RMSNorm double rounding.** `rms_norm_round_once` added and measured; Raon keeps `fast_rms_norm` (table below).
- **7. Bounded gate.** `compute_g_lower_bounded` casts `a` to f32 before adding `dt_bias`.
- **8. Steering on unsupported paths.** Startup fails, naming the path and the model, when a `reasoning_effort_steering` model is served pipeline-parallel (in-process, remote, or as a stage peer), as a disaggregated prefill or decode node, or on XLA. The guard is `src/server/reasoning_steering_startup_guard.rs`; its tests live next to it rather than in `startup_tests.rs`, because `start_server` cannot be unit-tested per path.
- **9. Bounded echo.** The invalid-level error echoes at most 32 characters, Debug-escaped, plus `... (N bytes)`.

### Item 1: affected families under `models/`

Only Raon checkpoints set `presence_penalty`: `raon-1-mini`, `raon-1-mini-mlx`, `raon-1-mini-nvfp4` (1.5) and `raon-1-nano` (1.5, not loadable yet, #3438). The other checkpoints under `models/` are unaffected.

Side effect on DFlash2 serving: a nonzero presence penalty makes `needs_token_history()` true, and `sampling_config_eq` (`src/server/batch/speculative_burst.rs`) keeps such requests out of batched speculative windows. Concurrent Raon requests that name no penalty therefore draft as single-request bursts under the new 1.5 default (output unchanged); `--presence-penalty 0` or a per-request value restores batching. Lifting this needs per-row token history in the batched window, a separate follow-up. The docs note this next to the presence_penalty default.

### Item 6: measurement and decision

Teacher-forced traces against the existing Transformers reference (bf16, CPU, `--effort max`), `compare_logit_traces.py --decided 1`. Arms differ only in Raon's decoder and final norms (input, post-attention, final); the MLA latent norms and the f32 RDA `o_norm` were left as they are. Decode is `mlxcel generate`, 256 tokens, temp 0, ABAB in one lock hold on M3 Ultra (load average 13.7 to 8.3, the sibling unit was building).

| Arm | 4 x 256 decided disagree | 4 x 256 ppl delta | 871-token decided disagree | 871-token ppl delta | Decode tok/s (r1 / r2) |
|---|---|---|---|---|---|
| `fast_rms_norm` | 0 / 578 | +0.186% | 1 / 549 | +0.337% | 33.30 / 33.31 |
| `rms_norm_round_once` | 0 / 578 | +0.225% | 0 / 549 | +0.607% | 32.26 / 32.26 |

Decision: keep `fast_rms_norm`. Round-once removes the one decided disagreement (row 866, which #3441 traced to reference-side bf16 noise) but slows single-stream decode 3.1%, above the 2% bar, and raises perplexity delta on the long prompt. No family's norm changes in this PR.

### Item 7: CUDA and ROCm coverage

No CUDA or ROCm host was reachable from this run (no local GPU tools, `spark-101` / `spark-102` do not resolve, no SSH keys). The fix and its test ran on Metal only, where the test passes before and after as designed. `make test-fast-cuda FILTER=gated_delta` and the Raon tiny-model suites on CUDA and ROCm remain to be run.

## Test plan

- [x] New tests fail on main (pre-fix binary): `a_projection_with_the_wrong_input_width_fails_the_load_by_name`, `unified_linear_refuses_scales_with_fewer_rows_than_the_weight`, `stacked_switch_linear_refuses_scales_with_fewer_rows_than_the_weight`, `raon1_mini_counts_its_rda_state_once_per_sequence`, `an_oversized_level_is_echoed_truncated`, and the digest tests against main's oracle script. Items 1 and 8 add new API, so their tests do not compile on main. `bounded_gate_upcasts_a_bf16_input_before_adding_dt_bias` passes on Metal before and after.
- [x] Targeted suites pass: raon, generation_config, kv_arch, reasoning_steering, gated_delta, switch_layers, server startup and cli_input, kimi_k3, core layers and rms_norm.
- [x] All three Raon checkpoints and two other quantized families load and generate with the new checks.
- [x] `make verify-llama-compat`, `make verify-python-tooling`, and `make verify` locally.
- [ ] `make test-fast-cuda FILTER=gated_delta` and the Raon tiny-model suites on CUDA and ROCm (no host available).

Closes #3457
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) area:models Model architectures, weights, loading, metadata modelsize:medium 4-bit checkpoint 10-50GB; comfortable on a 128GB dev box modeltype:text Text-only language model priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): load the Raon-1 mini MLX and ModelOpt NVFP4 exports

1 participant