Skip to content

feat: optimize unsloth quantization recipe and switch to mmap model loading - #32

Merged
Brooooooklyn merged 10 commits into
mainfrom
feat/unsloth-recipe-v2-mmap-loading
Mar 20, 2026
Merged

Brooooooklyn merged 10 commits into
mainfrom
feat/unsloth-recipe-v2-mmap-loading

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Note

Medium Risk
Medium risk due to changes in model loading/materialization, quantized weight handling (including new embedding/lm_head paths), and token decode loop scheduling plus new FFI surface (mlx_eval).

Overview
Model loading is switched to mmap-backed lazy SafeTensors reads via load_safetensors_lazy for Qwen3/Qwen3.5 (incl. sharded and vision weights), then explicitly materializes weights with new chunked materialize_weights() to avoid first-inference disk I/O spikes and Metal timeouts.

Quantization support is expanded and the unsloth recipe is updated: it now snaps to supported bit widths, defaults to a 3-bit base (with higher-bit embed_tokens/lm_head), and normalizes MoE checkpoints that provide pre-stacked fused expert tensors so expert weights don’t get skipped during quantization.

Inference performance is improved by pipelining Qwen3.5 dense and MoE decode loops (submit step N+1 before eval N) and by adding quantized execution paths for Linear (runtime quantized_matmul) and quantized loading for embeddings/lm_head in Qwen3.5 persistence. CLI convert also applies the unsloth default bits when --q-bits is omitted, and an unused example script is removed.

Written by Cursor Bugbot for commit 16afd2c. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

  • New Features

    • Quantized embeddings and LM head support; "unsloth" recipe now defaults to a 3‑bit base with per‑component bitwidths and clearer CLI help.
  • Performance Improvements

    • Lazy mmap-backed weight loading with explicit materialization to avoid delayed first inference.
    • Pipelined token decode for faster generation.
  • Bug Fixes

    • MoE checkpoint sanitization accepts multiple expert formats and warns on mixed inputs.
  • Refactor

    • Consolidated example imports and removed an unused example script.

Brooooooklyn and others added 5 commits March 19, 2026 17:55
…oading

Unsloth recipe improvements based on per-tensor KLD analysis from
https://unsloth.ai/docs/models/qwen3.5/gguf-benchmarks:

- Default base bits changed from 4 to 3 (gate/up_proj "generally ok to
  quantize to 3-bit", IQ3_XXS is "best compromise on disk space")
- down_proj: 5-bit → 4-bit (default_bits+1, "slightly more sensitive")
- embed_tokens: bf16 → 5-bit (KLD ~0.15 at q5_k, among least sensitive)
- lm_head: bf16 → 6-bit (KLD ~0.05 at q5_k, safest tensor to quantize)
- Attention/SSM layers remain at bf16 (correctly high sensitivity)
- Estimated model size: 29 GB → ~22 GB for Qwen3.5-27B

Model loading switched from eager SafeTensors read to MLX's native
mmap-backed lazy loader (load_safetensors_lazy). The eager path read
each tensor via read_exact + bytes_to_u16 + array copy (~87 GB of data
movement for 29 GB of weights, taking 3-4 minutes). The mmap path is
near-instant. An explicit async_eval + synchronize after loading
materializes all weights before first inference so prefill TTFT metrics
are not affected.

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

The model loader's Embedding.set_weight() validates shape and rejects
packed U32 quantized tensors. Reverted embed_tokens and lm_head to bf16
in the unsloth recipe until QuantizedEmbedding support is added.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Re-enable embed_tokens (5-bit) and lm_head (6-bit) quantization in the
unsloth recipe. These are dequantized at load time via mlx_dequantize
since the model accesses them every token — savings come from smaller
file on disk (8.3 GB vs 10.7 GB for Qwen3.5-9B).

Per Unsloth's per-tensor KLD chart, embed_tokens (KLD ~0.15 at q5_k)
and lm_head (KLD ~0.05 at q5_k) are among the least sensitive tensors.

Also handles quantized key renaming in sanitize_weights (embed_tokens.*
→ embedding.* for .weight/.scales/.biases).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Instead of dequantizing embed_tokens and lm_head at load time (no memory
bandwidth savings), keep them quantized in memory:

- Embedding: stores packed weights, dequantizes full table on forward()
  (MLX dequantize + take). get_weight() returns pre-dequantized table
  for tied embeddings and compiled C++ path.
- Linear: optional quantized backend using quantized_matmul on forward().
  get_weight() returns dequantized weight for tied embeddings path.

Decode speed improvement on M3 Max (Qwen3.5-9B):
- Before (dequantize-at-load): 34.6-36.0 tok/s
- After (quantized_matmul): 39.6-41.8 tok/s (+15%)

Disk size unchanged at 8.3 GB (54% reduction from 18 GB bf16).

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

coderabbitai Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Reworks quantization and loading for Qwen3.5/Qwen3 MoE: adds quantized embedding/linear paths, refines the "unsloth" recipe (per-component bit snapping and higher-precision embeds/LM head), switches safetensors to mmap-backed lazy loading with explicit materialization, normalizes MoE expert formats, and pipelines token decode (N+1) loops.

Changes

Cohort / File(s) Summary
Quantized NN primitives
crates/mlx-core/src/nn/linear.rs, crates/mlx-core/src/nn/embedding.rs
Introduce QuantizedBackend/QuantizedWeight, load_quantized(...), is_quantized(), quantized forward paths that call dequant/quantized matmul, and clone/metadata handling.
Unsloth recipe & conversion
crates/mlx-core/src/convert.rs, packages/cli/src/commands/convert.ts
Change build_unsloth_recipe to use per-component "99.9% KLD" guidance, snap bits to supported widths, mark embeddings/LM head for higher precision pre-should_quantize(), and default CLI unsloth base to 3 bits when unspecified.
Safetensors lazy loading & materialization
crates/mlx-core/src/models/qwen3/.../persistence.rs, crates/mlx-core/src/array/memory.rs
Replace eager SafeTensors loads with load_safetensors_lazy(...) (mmap); add materialize_weights(...) and call it after weight registration to realize mmap-backed arrays.
Persistence: quantized embeddings & LM head
crates/mlx-core/src/models/qwen3_5/persistence.rs, crates/mlx-core/src/models/qwen3_5_moe/persistence.rs
Generalize embed_tokens.* → embedding.* prefix stripping (preserve metadata suffixes), drop all lm_head.* when tied, and add loading paths for quantized embeddings and quantized LM head using per-layer (bits, group_size).
MoE sanitization & stacking
crates/mlx-core/src/convert.rs (sanitize_qwen35_moe)
Detect and normalize two expert checkpoint formats: (A) per-expert experts.{i}.{proj}.weight (stack into switch_mlp.*) or (B) pre-stacked experts.gate_up_proj+/experts.down_proj (split/rename to switch_mlp.*); warn if both present and perform appropriate cleanup.
Decode pipelining (N+1 submission)
crates/mlx-core/src/models/qwen3_5/model.rs, crates/mlx-core/src/models/qwen3_5_moe/model.rs
Change generation/chat loops to build/submit step N+1 before awaiting/evaluating step N, moving repetition-penalty and cache-eval into graph construction and aligning token-history at graph-build time.
FFI & synchronous eval
crates/mlx-sys/src/lib.rs, crates/mlx-sys/src/mlx_nn_ops.cpp, crates/mlx-sys/src/mlx_qwen35_common.h, crates/mlx-sys/src/mlx_qwen35_moe.cpp
Add mlx_eval synchronous batch eval FFI + C wrapper; add infer_affine_bits(...) and switch several linear/switch calls to linear_proj(...) that infer affine bits/gs at runtime, removing hardcoded quant param passing.
Examples & CLI cleanup
examples/lm.ts, examples/measure-prompt.ts
Consolidated imports in lm.ts; removed examples/measure-prompt.ts.
Visibility tweak
crates/mlx-core/src/stream.rs
Made WiredLimitContext::parse_max_working_set_size crate-public (pub(crate)).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐇 I hopped through bytes and tiny bits,

Snapped the widths to perfect fits,
Lazy maps woke up with cheer,
Pipelines hum—next step is near,
Embeds and heads now shine like new, hop hop, hooray!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the two main changes: optimizing the unsloth quantization recipe and switching to mmap-backed model loading. Both features are central to the PR's objectives.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/unsloth-recipe-v2-mmap-loading
📝 Coding Plan
  • Generate coding plan for human review comments

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 and usage tips.

@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: 8cbd83548c

ℹ️ 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
Comment thread crates/mlx-core/src/nn/embedding.rs Resolved

@coderabbitai coderabbitai 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.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
crates/mlx-core/src/models/qwen3_5_moe/persistence.rs (1)

67-80: ⚠️ Potential issue | 🟠 Major

Sharded VLM loads still need the separate vision file merged.

The single-file branch still appends vision.safetensors, but this sharded branch returns after loading only model-*.safetensors. A directory laid out as text shards plus a separate vision file will now load as text-only because has_vision never sees those tensors.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5_moe/persistence.rs` around lines 67 - 80,
The sharded load loop populates all_params from model-*.safetensors but never
merges a separate vision.safetensors, so downstream checks (e.g., has_vision)
miss those tensors; after the for shard_path loop that calls
load_safetensors_lazy and extends all_params, check for the existence of a
vision file (named "vision.safetensors") in the same directory, and if present
call load_safetensors_lazy on it and extend/merge its returned HashMap into
all_params (ensuring naming/overwrite semantics match single-file behavior) so
vision tensors are included before returning Ok(all_params).
crates/mlx-core/src/models/qwen3_5/persistence.rs (1)

83-96: ⚠️ Potential issue | 🟠 Major

Sharded VLM directories still need the separate vision file merged.

The single-file path already appends vision.safetensors, but this new sharded branch stops after model-*.safetensors. A text-sharded VLM directory with a separate vision file will now be treated as text-only because has_vision never sees those tensors.

Suggested patch
     for shard_path in &shard_files {
         info!("  Loading shard: {} (mmap)", shard_path.display());
         let shard_params = load_safetensors_lazy(shard_path)?;
         all_params.extend(shard_params);
     }
+
+    let vision_path = dir.join("vision.safetensors");
+    if vision_path.exists() {
+        info!("Loading vision weights from: {} (mmap)", vision_path.display());
+        let vision_params = load_safetensors_lazy(&vision_path)?;
+        info!("Loaded {} vision tensors", vision_params.len());
+        all_params.extend(vision_params);
+    }
 
     Ok(all_params)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5/persistence.rs` around lines 83 - 96, The
sharded-file branch currently only loads model-*.safetensors and never merges a
separate vision.safetensors, so has_vision won't detect vision tensors; update
the loop that iterates over shard_files to also detect and load a sibling
"vision.safetensors" (e.g., check
shard_path.parent().join("vision.safetensors")) and call load_safetensors_lazy
on it (once) and extend the resulting map into all_params alongside each shard;
ensure you reference the existing variables/functions shard_files, shard_path,
all_params and load_safetensors_lazy and only load the vision file if it exists
to avoid duplicate loads.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/mlx-core/src/convert.rs`:
- Around line 845-866: The closure in crates/mlx-core/src/convert.rs returning
QuantDecision currently quantizes embed_tokens.weight which breaks qwen3_5_moe
since its persistence expects a dense embedding (embedding.set_weight); either
1) gate this branch so the embed_tokens block only runs for the dense Qwen3.5
loader (e.g., check model variant/flag before returning the Custom QuantDecision
for "embed_tokens" in the closure) or 2) implement the MoE-side quantized load
path by adding load_quantized handling in qwen3_5_moe persistence that consumes
the packed .scales/.biases and calls the appropriate embedding.load_quantized()
instead of embedding.set_weight; update either the QuantDecision emit logic or
the qwen3_5_moe persistence to keep embed_tokens compatible with MoE loading.

In `@crates/mlx-core/src/models/qwen3/persistence.rs`:
- Around line 514-526: The materialization block currently calls
MxArray::async_eval_arrays(...) and crate::array::memory::synchronize() on the
N-API completion thread, which blocks the JS event loop; move this work into the
existing spawn_blocking closure that prepares the return tuple so the
async_eval_arrays call and the blocking crate::array::memory::synchronize() run
on the blocking thread. Specifically, relocate the code that collects arrays
from param_map, calls MxArray::async_eval_arrays(&arrays), invokes
crate::array::memory::synchronize(), and logs the timing into the spawn_blocking
closure (before it returns the tuple), keeping references to param_map and using
the same info! logging.

In `@crates/mlx-core/src/nn/embedding.rs`:
- Around line 45-60: The forward(&self, indices: &MxArray) path currently calls
dequantize(...) on self.quantized every invocation and then
dequantized.take(...), causing full-table dequantization per lookup; instead,
add a cached/materialized dequantized table (e.g. a field like
cached_dequantized: Option<MxArray> on the embedding struct) and change forward
to: if cached_dequantized is None, call dequantize(...) once to populate it,
then reuse cached_dequantized.take(indices, 0) on subsequent calls; ensure the
cache is invalidated or updated whenever quantized weights change (referencing
forward, quantized, dequantize, dequantized, and take).

---

Outside diff comments:
In `@crates/mlx-core/src/models/qwen3_5_moe/persistence.rs`:
- Around line 67-80: The sharded load loop populates all_params from
model-*.safetensors but never merges a separate vision.safetensors, so
downstream checks (e.g., has_vision) miss those tensors; after the for
shard_path loop that calls load_safetensors_lazy and extends all_params, check
for the existence of a vision file (named "vision.safetensors") in the same
directory, and if present call load_safetensors_lazy on it and extend/merge its
returned HashMap into all_params (ensuring naming/overwrite semantics match
single-file behavior) so vision tensors are included before returning
Ok(all_params).

In `@crates/mlx-core/src/models/qwen3_5/persistence.rs`:
- Around line 83-96: The sharded-file branch currently only loads
model-*.safetensors and never merges a separate vision.safetensors, so
has_vision won't detect vision tensors; update the loop that iterates over
shard_files to also detect and load a sibling "vision.safetensors" (e.g., check
shard_path.parent().join("vision.safetensors")) and call load_safetensors_lazy
on it (once) and extend the resulting map into all_params alongside each shard;
ensure you reference the existing variables/functions shard_files, shard_path,
all_params and load_safetensors_lazy and only load the vision file if it exists
to avoid duplicate loads.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6e95d061-b073-4b99-aaa8-fe2ec87ea693

📥 Commits

Reviewing files that changed from the base of the PR and between 9065dc1 and 8cbd835.

📒 Files selected for processing (9)
  • crates/mlx-core/src/convert.rs
  • crates/mlx-core/src/models/qwen3/persistence.rs
  • crates/mlx-core/src/models/qwen3_5/persistence.rs
  • crates/mlx-core/src/models/qwen3_5_moe/persistence.rs
  • crates/mlx-core/src/nn/embedding.rs
  • crates/mlx-core/src/nn/linear.rs
  • examples/lm.ts
  • examples/measure-prompt.ts
  • packages/cli/src/commands/convert.ts
💤 Files with no reviewable changes (1)
  • examples/measure-prompt.ts

Comment thread crates/mlx-core/src/convert.rs Resolved
Comment thread crates/mlx-core/src/nn/embedding.rs Resolved
Brooooooklyn and others added 3 commits March 20, 2026 12:11
1. Embedding.forward(): Remove redundant dequantize branch. Since
   load_quantized() pre-dequantizes into self.weight, forward() should
   just use self.weight.take() for both quantized and non-quantized
   paths. (cursor bot, coderabbitai)

2. MoE persistence: Add quantized embedding loading support with
   load_quantized() and prefix-based key renaming (embed_tokens.* →
   embedding.*) so .scales/.biases are properly renamed. Without this,
   converting an MoE model with --q-recipe unsloth would crash on load.
   (cursor bot, coderabbitai, chatgpt-codex-connector)

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

- snap_bits: MLX quantize supports 2,3,4,5,6,8 (not 7). When
  default_bits=4, lm_head_bits was 4+3=7 which crashed. Now snaps
  7→8.
- MoE persistence: Add quantized embedding loading with load_quantized()
  and prefix-based key renaming for .scales/.biases
- Embedding.forward(): Use pre-dequantized self.weight (remove redundant
  dequantize branch per review feedback)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The C++ compiled forward paths hardcoded bits=4 for affine quantization,
breaking mixed-bit recipes like unsloth (3-bit gate/up, 4-bit down, etc).

Changes:
- mlx_qwen35_common.h: Add infer_affine_bits() helper that computes
  bits from weight_cols * 32 / (scales_cols * group_size). Update
  linear_proj() to use it instead of hardcoded bits=4.
- mlx_qwen35_moe.cpp: Update detect_quant(), dense_mlp_fn(), shared
  expert forward, and switch_linear_fwd() to infer bits per-tensor.
  Previously all MLP projections used the same bits detected from
  gate_proj, but down_proj may have different bits.

Tested: Qwen3.5-35B-A3B MoE with unsloth recipe (3-bit base)
decodes at 37.8-42.5 tok/s on M3 Max.

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

@cursor cursor 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.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Comment thread crates/mlx-sys/src/mlx_nn_ops.cpp Resolved

@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: f9b4b4cacb

ℹ️ 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-sys/src/mlx_qwen35_moe.cpp Resolved
Comment thread crates/mlx-core/src/nn/embedding.rs Resolved

@coderabbitai coderabbitai 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.

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
crates/mlx-core/src/models/qwen3_5/model.rs (2)

1085-1086: ⚠️ Potential issue | 🟡 Minor

Drop the second async kick-off for the first token.

y is already queued at Line 931, so this resubmits the same first-token graph on the chat() Rust fallback path and can inflate TTFT for no gain.

Suggested cleanup
-                // Kick off first token's async eval
-                MxArray::async_eval_arrays(&[&y]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5/model.rs` around lines 1085 - 1086, The
call to MxArray::async_eval_arrays(&[&y]) at the end of the chat() fallback
duplicates the async kick-off for the first token (variable y) which was already
queued earlier; remove this second invocation (the one referencing
MxArray::async_eval_arrays and y near the end of model.rs) so the first-token
graph is not resubmitted and TTFT is not inflated.

607-632: ⚠️ Potential issue | 🟠 Major

Don't reuse the Rust caches before the sampled token is materialized.

MxArray::async_eval_arrays() only schedules mlx_async_eval and returns immediately, but these loops call forward_inner(..., &mut caches_guard, ...) for step N+1 before y.eval() has waited for step N. That means the fallback path is reusing the same caches before the token-eval barrier has been reached, which can bring back the lazy-chain/Metal issues this PR is trying to remove. Either wait on y.eval() before reusing caches_guard, or add a synchronous/materialize helper for the Rust path.

As per coding guidelines, "crates/mlx-core/src/**/*.rs: Call token.eval() after sampling to prevent unbounded lazy graph accumulation".

Also applies to: 1088-1125, 1649-1674

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5/model.rs` around lines 607 - 632, The loop
is reusing mutable Rust caches (caches_guard) before the sampled token is
actually materialized because MxArray::async_eval_arrays() only schedules work;
fix by materializing the sampled token synchronously after sampling and before
the next call to forward_inner. Specifically, after calling sample(...) and
MxArray::async_eval_arrays(&[&next_token]) (or after the equivalent sampling
code), call next_token.eval() (or y.eval() where y represents the running token
sequence) to force evaluation/materialization so forward_inner(..., &mut
caches_guard, ...) is not invoked while the previous token is still lazy; make
the same change in the other occurrences mentioned (around the other ranges) to
ensure caches_guard is only reused after token.eval() has completed.
crates/mlx-core/src/models/qwen3_5_moe/model.rs (2)

472-495: ⚠️ Potential issue | 🟠 Major

The Rust fallback reuses caches before the previous token finishes materializing.

These loops only queue MxArray::async_eval_arrays(&[&next_token]), then immediately call forward_inner(..., &mut caches_guard, ...) for the next step. Because async_eval_arrays() is non-blocking, the fallback path is reusing the same caches before the repo's token.eval() barrier has been reached, which undercuts the lazy-graph break this change is trying to achieve.

As per coding guidelines, "crates/mlx-core/src/**/*.rs: Call token.eval() after sampling to prevent unbounded lazy graph accumulation".

Also applies to: 953-988, 1526-1548

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5_moe/model.rs` around lines 472 - 495, The
loop queues asynchronous evaluation with
MxArray::async_eval_arrays(&[&next_token]) but then immediately calls
forward_inner(..., &mut caches_guard, ...) reusing caches before the sampled
token has been materialized; fix this by calling the token evaluation barrier
(token.eval()) after sampling and async_eval_arrays and before the next
forward_inner call so the caches are not reused prematurely—apply this change
around the next_token/sample logic (reference next_token, sample,
MxArray::async_eval_arrays, forward_inner, caches_guard); repeat the same
insertion at the other occurrences mentioned (around the blocks at ~953-988 and
~1526-1548).

865-901: ⚠️ Potential issue | 🟠 Major

repetition_penalty is now one token behind the decode state.

The new pipeline samples next_y before the current token has been eval'd and appended to token_history, so step N+1 ignores step N whenever repetition penalty is enabled. The new comment calls that out, but it is still a user-visible behavior change in the sampling contract.

Also applies to: 953-993, 1437-1457, 1522-1552

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5_moe/model.rs` around lines 865 - 901, The
sampling pipeline applies apply_repetition_penalty using token_history before
the current token for this step has been appended (because
eval_token_and_moe_caches runs after sample), causing the penalty to be one
token stale; fix by ensuring the current step's token/state is included when
computing repetition penalty: update token_history (or compute a temporary
history including the current token y) or call eval_token_and_moe_caches (or a
function that appends the current token to token_history) before calling
apply_repetition_penalty and sample. Locate the pattern around next_y generation
(symbols: step, next_y, forward_moe_cpp, apply_repetition_penalty, sample,
eval_token_and_moe_caches, token_history, repetition_context_size) and apply the
same change to the other equivalent blocks with the same pattern.
crates/mlx-core/src/models/qwen3_5_moe/persistence.rs (1)

39-80: ⚠️ Potential issue | 🔴 Critical

Load vision.safetensors in the MoE loader too.

load() only enables VLM mode if raw_params already contains vision_tower / visual keys, but this helper never reads the sidecar vision file. A MoE-VL checkpoint with separate vision.safetensors will currently load as text-only.

📦 Suggested fix
     if let Some(path) = single_path {
         info!("Loading weights from: {} (mmap)", path.display());
-        return load_safetensors_lazy(&path);
+        let mut params = load_safetensors_lazy(&path)?;
+        let vision_path = dir.join("vision.safetensors");
+        if vision_path.exists() {
+            info!("Loading vision weights from: {} (mmap)", vision_path.display());
+            params.extend(load_safetensors_lazy(&vision_path)?);
+        }
+        return Ok(params);
     }
@@
     let mut all_params: HashMap<String, MxArray> = HashMap::new();
     for shard_path in &shard_files {
         info!("  Loading shard: {} (mmap)", shard_path.display());
         let shard_params = load_safetensors_lazy(shard_path)?;
         all_params.extend(shard_params);
     }
+
+    let vision_path = dir.join("vision.safetensors");
+    if vision_path.exists() {
+        info!("Loading vision weights from: {} (mmap)", vision_path.display());
+        all_params.extend(load_safetensors_lazy(&vision_path)?);
+    }

     Ok(all_params)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5_moe/persistence.rs` around lines 39 - 80,
The MoE loader currently only collects shard files and never looks for a
separate vision sidecar, so load_safetensors_lazy is never called for
vision.safetensors and VLM keys (vision_tower/visual) are missing; update the
shard discovery/loading logic in persistence.rs (the block that builds
shard_files, iterates over shard_path and calls load_safetensors_lazy) to also
check for a sibling "vision.safetensors" (or similarly named sidecar) in the
same dir and, if present, call load_safetensors_lazy on that path and extend the
same all_params HashMap with the returned params so the loader will see
vision_tower/visual keys and enable VLM mode. Ensure the vision sidecar is
loaded once and merged before returning Ok(all_params).
crates/mlx-core/src/models/qwen3_5/persistence.rs (1)

83-96: ⚠️ Potential issue | 🔴 Critical

Sharded VL checkpoints still miss vision.safetensors.

The single-file branch handles the vision sidecar, but the sharded branch returns only the text shards. A model-*.safetensors checkpoint with a separate vision.safetensors file will never populate the vision encoder.

📦 Suggested fix
     let mut all_params: HashMap<String, MxArray> = HashMap::new();
     for shard_path in &shard_files {
         info!("  Loading shard: {} (mmap)", shard_path.display());
         let shard_params = load_safetensors_lazy(shard_path)?;
         all_params.extend(shard_params);
     }
+
+    let vision_path = dir.join("vision.safetensors");
+    if vision_path.exists() {
+        info!("Loading vision weights from: {} (mmap)", vision_path.display());
+        let vision_params = load_safetensors_lazy(&vision_path)?;
+        info!("Loaded {} vision tensors", vision_params.len());
+        all_params.extend(vision_params);
+    }

     Ok(all_params)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5/persistence.rs` around lines 83 - 96, The
sharded branch currently only iterates shard_files and never loads a separate
vision sidecar, so add logic in the same function (the block using shard_files,
info!, all_params: HashMap<String, MxArray>, and load_safetensors_lazy) to
detect a "vision.safetensors" file next to the model shards and, if present,
call load_safetensors_lazy on that path and extend all_params with its contents;
place this check after the shard_files loop (or before returning Ok(all_params))
and merge the returned map into all_params (using extend) so the vision encoder
params are populated just like in the single-file branch.
♻️ Duplicate comments (1)
crates/mlx-core/src/models/qwen3/persistence.rs (1)

514-519: ⚠️ Potential issue | 🟠 Major

Keep synchronous materialization inside spawn_blocking.

materialize_weights() is synchronous now, but Lines 514-519 still run it after the blocking worker has already returned. Please move it next to the lazy load so the completion path only builds the model object.

🏗️ Suggested move
-                info!("✅ Tokenizer loaded successfully");
-
-                return Ok::<_, Error>((config, mapped_params, tokenizer));
+                info!("✅ Tokenizer loaded successfully");
+
+                let arrays: Vec<&MxArray> = mapped_params.values().collect();
+                crate::array::memory::materialize_weights(&arrays);
+
+                return Ok::<_, Error>((config, mapped_params, tokenizer));
...
-            // Materialize all mmap-backed weight arrays so the first inference
-            // prefill timing is not inflated by lazy disk reads.
-            {
-                let arrays: Vec<&MxArray> = param_map.values().collect();
-                crate::array::memory::materialize_weights(&arrays);
-            }

Run this to confirm that the synchronous materialization currently sits outside the blocking worker:

#!/bin/bash
set -euo pipefail
sed -n '209,223p;331,404p;507,520p' crates/mlx-core/src/models/qwen3/persistence.rs
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3/persistence.rs` around lines 514 - 519, The
synchronous call to crate::array::memory::materialize_weights currently runs
after the blocking worker returns; move the materialize_weights invocation
(using the arrays Vec<&MxArray> from param_map.values()) into the same
spawn_blocking / blocking-worker closure immediately after the lazy load of
weights so the blocking task performs both lazy loading and materialization, and
the completion path only constructs the model object; update references around
the blocking worker that touches param_map and MxArray to call
crate::array::memory::materialize_weights(&arrays) before returning from the
spawn_blocking closure.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/mlx-core/src/convert.rs`:
- Around line 1496-1544: The branch that handles has_individual_experts stacks
per-expert weights but leaves pre-stacked/fused tensors (e.g. keys like
".mlp.experts.gate_up_proj.weight", ".mlp.experts.up_proj.weight",
".mlp.experts.down_proj.weight" or similar fused names) in new_weights; after
stacking each layer (or after finishing stacking for all layers) remove those
fused keys from new_weights so only the stacked "switch_mlp.*.weight" remain.
Locate the has_individual_experts branch and the loop over layers (use symbols
num_hidden_layers, prefix = format!("language_model.model.layers.{}.mlp", l),
new_weights) and add code to explicitly remove any fused keys under that prefix
(e.g. keys containing ".mlp.experts." that represent fused tensors like
"gate_up_proj", "up_proj", "down_proj") before returning/continuing.

In `@crates/mlx-core/src/models/qwen3_5_moe/persistence.rs`:
- Around line 1048-1053: The code only materializes mmap-backed arrays from
params, leaving vision_params unmapped; update the block around the
materialize_weights call to also collect the vision MxArray references (e.g.,
gather values() from both params and vision_params into a Vec<&MxArray> or call
crate::array::memory::materialize_weights twice) so that vision_params are
materialized before the first image pass; reference the existing params,
vision_params, MxArray, and crate::array::memory::materialize_weights symbols
when making the change.

In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 1001-1033: The repetition_penalty is being applied too late
because next_y is sampled before the current token y is evaluated and pushed
into token_history (see next_y, repetition_penalty, token_history,
forward_compiled, apply_repetition_penalty, eval_token_and_compiled_caches); fix
by ensuring the penalty is applied using an up-to-date token_history: either
(preferred) move the apply_repetition_penalty and sample steps so they run after
eval_token_and_compiled_caches()/y.eval() and after pushing y into
token_history, or (alternative) if you must keep the async pipeline, detect
repetition_penalty != 1.0 and disable the speculative next_y pipeline so the
penalty always sees the latest token_history; apply the same change in the other
occurrences you noted (around the blocks at 1088-1128, 1562-1583, 1649-1678).

In `@crates/mlx-core/src/models/qwen3_5/persistence.rs`:
- Around line 917-922: The materialization currently only collects text model
arrays from params, so vision encoder mmap-backed tensors in vision_params are
not materialized; update the block that builds arrays (the Vec<&MxArray> named
arrays used with crate::array::memory::materialize_weights) to also include
vision_params.values() (i.e., collect both params.values() and
vision_params.values() into the arrays vector) before calling
materialize_weights so VL model image-encoder weights are eagerly materialized
too.

In `@crates/mlx-core/src/nn/embedding.rs`:
- Around line 92-95: The dequantized table assigned to self.weight is a lazy MLX
array from dequantize(weight, scales, biases, group_size, bits) so it must be
materialized immediately; change the assignment in the embedding initialization
to call eval() (or the MLX materialization method) on the result of dequantize
before storing it in self.weight so that get_weight() / forward() and the
loaders' materialize_weights() (which only inspects params.values()) see a
realized dense tensor rather than a lazy array.

In `@crates/mlx-sys/src/mlx_nn_ops.cpp`:
- Around line 48-59: Wrap the body of mlx_eval in the same try/catch
exception-guard used by mlx_array_eval and mlx_async_eval: enclose the existing
logic in try { ... } and add catch (const std::exception& e) {
mlx_set_last_error(e.what()); } catch (...) { mlx_set_last_error("unknown C++
exception"); } so no C++ exceptions cross the Rust FFI boundary; use the same
error-reporting helper (e.g., mlx_set_last_error) and return after setting the
error.

In `@crates/mlx-sys/src/mlx_qwen35_moe.cpp`:
- Around line 141-175: The quantized path in switch_linear_fwd should not depend
on is_quant; change the condition to check has_weight(prefix + ".scales")
directly, and replace the manual bits/gs inference with a call to
infer_affine_bits(...) (the same helper used by linear_proj) to determine
gs/bits/mode; then call mlx::core::gather_qmm(...) with those inferred values
(and preserve biases handling), otherwise fall back to switch_linear_forward(x,
prefix, indices, sorted). Locate switch_linear_fwd, get_weight/has_weight usage
and replace the open-coded ratio logic with infer_affine_bits(...) consistent
with linear_proj from mlx_qwen35_common.h.

---

Outside diff comments:
In `@crates/mlx-core/src/models/qwen3_5_moe/model.rs`:
- Around line 472-495: The loop queues asynchronous evaluation with
MxArray::async_eval_arrays(&[&next_token]) but then immediately calls
forward_inner(..., &mut caches_guard, ...) reusing caches before the sampled
token has been materialized; fix this by calling the token evaluation barrier
(token.eval()) after sampling and async_eval_arrays and before the next
forward_inner call so the caches are not reused prematurely—apply this change
around the next_token/sample logic (reference next_token, sample,
MxArray::async_eval_arrays, forward_inner, caches_guard); repeat the same
insertion at the other occurrences mentioned (around the blocks at ~953-988 and
~1526-1548).
- Around line 865-901: The sampling pipeline applies apply_repetition_penalty
using token_history before the current token for this step has been appended
(because eval_token_and_moe_caches runs after sample), causing the penalty to be
one token stale; fix by ensuring the current step's token/state is included when
computing repetition penalty: update token_history (or compute a temporary
history including the current token y) or call eval_token_and_moe_caches (or a
function that appends the current token to token_history) before calling
apply_repetition_penalty and sample. Locate the pattern around next_y generation
(symbols: step, next_y, forward_moe_cpp, apply_repetition_penalty, sample,
eval_token_and_moe_caches, token_history, repetition_context_size) and apply the
same change to the other equivalent blocks with the same pattern.

In `@crates/mlx-core/src/models/qwen3_5_moe/persistence.rs`:
- Around line 39-80: The MoE loader currently only collects shard files and
never looks for a separate vision sidecar, so load_safetensors_lazy is never
called for vision.safetensors and VLM keys (vision_tower/visual) are missing;
update the shard discovery/loading logic in persistence.rs (the block that
builds shard_files, iterates over shard_path and calls load_safetensors_lazy) to
also check for a sibling "vision.safetensors" (or similarly named sidecar) in
the same dir and, if present, call load_safetensors_lazy on that path and extend
the same all_params HashMap with the returned params so the loader will see
vision_tower/visual keys and enable VLM mode. Ensure the vision sidecar is
loaded once and merged before returning Ok(all_params).

In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 1085-1086: The call to MxArray::async_eval_arrays(&[&y]) at the
end of the chat() fallback duplicates the async kick-off for the first token
(variable y) which was already queued earlier; remove this second invocation
(the one referencing MxArray::async_eval_arrays and y near the end of model.rs)
so the first-token graph is not resubmitted and TTFT is not inflated.
- Around line 607-632: The loop is reusing mutable Rust caches (caches_guard)
before the sampled token is actually materialized because
MxArray::async_eval_arrays() only schedules work; fix by materializing the
sampled token synchronously after sampling and before the next call to
forward_inner. Specifically, after calling sample(...) and
MxArray::async_eval_arrays(&[&next_token]) (or after the equivalent sampling
code), call next_token.eval() (or y.eval() where y represents the running token
sequence) to force evaluation/materialization so forward_inner(..., &mut
caches_guard, ...) is not invoked while the previous token is still lazy; make
the same change in the other occurrences mentioned (around the other ranges) to
ensure caches_guard is only reused after token.eval() has completed.

In `@crates/mlx-core/src/models/qwen3_5/persistence.rs`:
- Around line 83-96: The sharded branch currently only iterates shard_files and
never loads a separate vision sidecar, so add logic in the same function (the
block using shard_files, info!, all_params: HashMap<String, MxArray>, and
load_safetensors_lazy) to detect a "vision.safetensors" file next to the model
shards and, if present, call load_safetensors_lazy on that path and extend
all_params with its contents; place this check after the shard_files loop (or
before returning Ok(all_params)) and merge the returned map into all_params
(using extend) so the vision encoder params are populated just like in the
single-file branch.

---

Duplicate comments:
In `@crates/mlx-core/src/models/qwen3/persistence.rs`:
- Around line 514-519: The synchronous call to
crate::array::memory::materialize_weights currently runs after the blocking
worker returns; move the materialize_weights invocation (using the arrays
Vec<&MxArray> from param_map.values()) into the same spawn_blocking /
blocking-worker closure immediately after the lazy load of weights so the
blocking task performs both lazy loading and materialization, and the completion
path only constructs the model object; update references around the blocking
worker that touches param_map and MxArray to call
crate::array::memory::materialize_weights(&arrays) before returning from the
spawn_blocking closure.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 383c8fa3-6944-4269-ae00-f3aac1ef0d4a

📥 Commits

Reviewing files that changed from the base of the PR and between 8cbd835 and f9b4b4c.

📒 Files selected for processing (12)
  • crates/mlx-core/src/array/memory.rs
  • crates/mlx-core/src/convert.rs
  • crates/mlx-core/src/models/qwen3/persistence.rs
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/mlx-core/src/models/qwen3_5/persistence.rs
  • crates/mlx-core/src/models/qwen3_5_moe/model.rs
  • crates/mlx-core/src/models/qwen3_5_moe/persistence.rs
  • crates/mlx-core/src/nn/embedding.rs
  • crates/mlx-sys/src/lib.rs
  • crates/mlx-sys/src/mlx_nn_ops.cpp
  • crates/mlx-sys/src/mlx_qwen35_common.h
  • crates/mlx-sys/src/mlx_qwen35_moe.cpp

Comment thread crates/mlx-core/src/convert.rs Resolved
Comment thread crates/mlx-core/src/nn/embedding.rs Resolved
Comment thread crates/mlx-sys/src/mlx_nn_ops.cpp Resolved
Comment thread crates/mlx-sys/src/mlx_qwen35_moe.cpp Resolved
…al FFI

Three performance and correctness fixes:

1. Pipeline all chat/chatStream decode loops (dense + MoE, compiled + Rust
   fallback) to submit forward(N+1) before eval(N), matching Python mlx-lm's
   double-buffered async pattern. Decode: 37.8-42.5 → 58.8 tok/s on 35B MoE.

2. Fix MoE expert weight quantization: pre-stacked fused expert tensors from
   HuggingFace (experts.gate_up_proj without .weight suffix) were silently
   skipped by should_quantize(). Split gate_up_proj → gate_proj + up_proj,
   rename to switch_mlp.{proj}.weight. Model size: 64GB → 18GB.

3. Add mlx_eval FFI (synchronous mlx::core::eval) and materialize_weights
   helper for weight materialization, replacing async_eval+synchronize which
   caused Metal command buffer timeouts on large models.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/unsloth-recipe-v2-mmap-loading branch from f9b4b4c to 5b0d41e Compare March 20, 2026 13:01

@coderabbitai coderabbitai 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.

♻️ Duplicate comments (1)
crates/mlx-core/src/convert.rs (1)

1536-1543: ⚠️ Potential issue | 🟠 Major

Pre-stacked expert tensors are not removed when both formats are present.

When a model has both individual experts and pre-stacked experts (Format A and B), the warning at line 1497 is issued and Format A is used. However, the cleanup at lines 1536-1543 only removes keys ending with .weight, so pre-stacked tensors like *.experts.gate_up_proj and *.experts.down_proj (which lack the .weight suffix) remain in new_weights and get written to the output checkpoint.

🔧 Suggested fix
         // Clean up any remaining individual expert keys
         let expert_keys: Vec<String> = new_weights
             .keys()
-            .filter(|k| k.contains(".mlp.experts.") && k.ends_with(".weight"))
+            .filter(|k| k.contains(".mlp.experts."))
             .cloned()
             .collect();
         for k in expert_keys {
             new_weights.remove(&k);
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/convert.rs` around lines 1536 - 1543, The removal logic
that builds expert_keys only targets keys ending with ".weight", so pre-stacked
expert tensors like "*.experts.gate_up_proj" and "*.experts.down_proj" remain in
new_weights; update the filter used to populate expert_keys (the Vec<String>
created from new_weights.keys()) to match all pre-stacked expert key patterns
(e.g., any key containing ".mlp.experts." and ending with ".weight" OR
containing ".mlp.experts.gate_up_proj" OR containing ".mlp.experts.down_proj",
or generally matching the known pre-stacked suffixes your model uses) and then
remove those keys from new_weights the same way as before to ensure both Format
A and Format B tensors are cleaned up.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@crates/mlx-core/src/convert.rs`:
- Around line 1536-1543: The removal logic that builds expert_keys only targets
keys ending with ".weight", so pre-stacked expert tensors like
"*.experts.gate_up_proj" and "*.experts.down_proj" remain in new_weights; update
the filter used to populate expert_keys (the Vec<String> created from
new_weights.keys()) to match all pre-stacked expert key patterns (e.g., any key
containing ".mlp.experts." and ending with ".weight" OR containing
".mlp.experts.gate_up_proj" OR containing ".mlp.experts.down_proj", or generally
matching the known pre-stacked suffixes your model uses) and then remove those
keys from new_weights the same way as before to ensure both Format A and Format
B tensors are cleaned up.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0a147292-f1b0-46b7-ad09-2c4f515d8711

📥 Commits

Reviewing files that changed from the base of the PR and between f9b4b4c and 5b0d41e.

📒 Files selected for processing (10)
  • crates/mlx-core/src/array/memory.rs
  • crates/mlx-core/src/convert.rs
  • crates/mlx-core/src/models/qwen3/persistence.rs
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/mlx-core/src/models/qwen3_5/persistence.rs
  • crates/mlx-core/src/models/qwen3_5_moe/model.rs
  • crates/mlx-core/src/models/qwen3_5_moe/persistence.rs
  • crates/mlx-core/src/stream.rs
  • crates/mlx-sys/src/lib.rs
  • crates/mlx-sys/src/mlx_nn_ops.cpp
🚧 Files skipped from review as they are similar to previous changes (6)
  • crates/mlx-sys/src/mlx_nn_ops.cpp
  • crates/mlx-sys/src/lib.rs
  • crates/mlx-core/src/array/memory.rs
  • crates/mlx-core/src/models/qwen3_5_moe/persistence.rs
  • crates/mlx-core/src/models/qwen3_5_moe/model.rs
  • crates/mlx-core/src/models/qwen3_5/model.rs

@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: 5b0d41e577

ℹ️ 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/array/memory.rs Resolved

@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: 16afd2caa1

ℹ️ 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/nn/embedding.rs Resolved
@Brooooooklyn
Brooooooklyn merged commit 08354f8 into main Mar 20, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/unsloth-recipe-v2-mmap-loading branch March 20, 2026 13:41
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
…oading (#32)

<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Medium Risk**
> Medium risk due to changes in model loading/materialization, quantized
weight handling (including new embedding/lm_head paths), and token
decode loop scheduling plus new FFI surface (`mlx_eval`).
> 
> **Overview**
> **Model loading is switched to mmap-backed lazy SafeTensors reads**
via `load_safetensors_lazy` for Qwen3/Qwen3.5 (incl. sharded and vision
weights), then explicitly materializes weights with new chunked
`materialize_weights()` to avoid first-inference disk I/O spikes and
Metal timeouts.
> 
> **Quantization support is expanded and the `unsloth` recipe is
updated**: it now snaps to supported bit widths, defaults to a 3-bit
base (with higher-bit `embed_tokens`/`lm_head`), and normalizes MoE
checkpoints that provide pre-stacked fused expert tensors so expert
weights don’t get skipped during quantization.
> 
> **Inference performance is improved** by pipelining Qwen3.5 dense and
MoE decode loops (submit step N+1 before eval N) and by adding quantized
execution paths for `Linear` (runtime `quantized_matmul`) and quantized
loading for embeddings/lm_head in Qwen3.5 persistence. CLI `convert`
also applies the `unsloth` default bits when `--q-bits` is omitted, and
an unused example script is removed.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
16afd2c. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Quantized embeddings and LM head support; "unsloth" recipe now
defaults to a 3‑bit base with per‑component bitwidths and clearer CLI
help.

* **Performance Improvements**
* Lazy mmap-backed weight loading with explicit materialization to avoid
delayed first inference.
  * Pipelined token decode for faster generation.

* **Bug Fixes**
* MoE checkpoint sanitization accepts multiple expert formats and warns
on mixed inputs.

* **Refactor**
  * Consolidated example imports and removed an unused example script.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 5, 2026
…fc via LinearProj (#85)

## Problem

The qwen3.5 dense `lm_head` and MTP `fc` could only load an **affine**
quantized head. `Linear::load_quantized` / `Linear::forward`
(`crates/mlx-core/src/nn/linear.rs`) hardcode `c"affine"` (dequant +
`mlx_quantized_matmul` mode) and require biases. A micro-scaled head
(nvfp4 / mxfp8 — scales only, no biases) crashed at load:

```
Biases must be provided for affine quantization
```

This is an unfinished early path (commit `08354f84`, PR #32, when affine
was the only mode). It forced NVIDIA-NVFP4 → MLX transcodes to fall back
to an affine-int4 `lm_head` instead of keeping the intended per-layer
bit allocation.

## Fix

Migrate the qwen3.5 dense `lm_head` and both MTP `fc` fields (dense +
moe) from `Linear` / `Option<Linear>` onto the mode-aware `LinearProj`
(`quantized_linear.rs`) and install them via the existing `try_build_ql`
dispatch on `plq.mode` — exactly as **gemma4** and **qwen3_5_moe**
already do for their heads. `Linear::load_quantized` is left untouched
(other families still use it).

```
                       old (affine-only)            new (mode-aware)
lm_head / mtp.fc  ──▶  Linear::load_quantized  ──▶  LinearProj  ─┬─ bf16    → Standard(Linear)
                       (c"affine", needs biases)                 ├─ affine  → Quantized("affine")
                                                                 ├─ mxfp8   → Quantized("mxfp8")   ← was a crash
                                                                 └─ nvfp4   → Quantized("nvfp4")   ← was a crash
```

- **Task 1** `d08372b6` — dense `lm_head: Option<Linear>` →
`Option<LinearProj>`; install in `persistence.rs`; threaded through
every `model.rs` + `paged_forward.rs` forward call site.
- **Task 2** `96e3e450` — MTP `fc: Linear` → `LinearProj` in
`models/qwen3_5/mtp.rs` and `models/qwen3_5_moe/mtp.rs`; removed a stale
"falls through to `set_weight`" comment.
- **Tidy** `293482fb` — two cosmetic follow-ups from the final review
(literal `"affine"` test assertion; `"quantized"` debug label).

No checkpoint or `convert` change — this removes a **loader** constraint
only. Existing checkpoints keep bf16/affine heads unchanged.

## Behavior preservation

- bf16 head/fc → `LinearProj::Standard` → identical
`input.matmul(weight_t)` (heads are bias-free).
- affine head/fc → `LinearProj::Quantized` mode `"affine"` → identical
`mlx_quantized_matmul(x, weight, scales, biases, true, gs, bits,
"affine")` operands.
- tied-embeddings path unchanged (`lm_head` is `None` when tied).

## Validation

3 new install-type unit tests assert the mode dispatch (affine →
`Quantized("affine")`, mxfp8 → `Quantized("mxfp8")`, bf16 → `Standard`)
for the dense head and both MTP fc. `cargo clippy -D warnings` + `cargo
fmt` clean.

E2E runtime (a hand-built qwen3.5-9B checkpoint with an mxfp8 `lm_head`
— scales, no biases):

| Head mode | Result |
|---|---|
| bf16 (0.8b tied, 9B-bf16) | ✅ coherent — unchanged path |
| affine (9B-unsloth) | ✅ coherent — behavior preserved |
| **mxfp8 (9B-mxfp8head)** | ✅ **loads (was a crash) + generates correct
text** — the fix |

> The authoritative GPU parity suite (`qwen3_5_paged_vs_flat_parity`,
`qwen3_5_session`) runs in CI.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core inference and weight-loading paths for lm_head and MTP
fc; behavior is intended to be parity-preserving for bf16/affine, with
new support for mxfp8/nvfp4.
> 
> **Overview**
> **Fixes quantized checkpoint loading** for dense `lm_head` and MTP
`fc` (dense + MoE): those layers no longer go through affine-only
`Linear::load_quantized`, which failed on mxfp8/nvfp4 heads missing
affine biases.
> 
> They now use **`LinearProj`** with the same **`try_build_ql`** path as
other projections, so affine, mxfp8, mxfp4, and nvfp4 install correctly;
bf16 stays **`LinearProj::Standard`**. **`set_weight`** calls take a
name label (e.g. `"lm_head"`, `"mtp.fc"`). Forward/prefill/paged paths
only change types to **`Option<LinearProj>`**; tied embeddings still
leave **`lm_head`** as **`None`**.
> 
> **Tests** cover install dispatch for dense **`lm_head`** (mxfp8,
affine, bf16, tied) and both MTP **`fc`** modules.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
293482f. 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