Repository navigation
feat: model-agnostic training support for Qwen3 and Qwen 3.5 - #30
Conversation
…wen3.5 MoE The training system (GRPO + SFT) was hardcoded to Qwen3Model. This makes all three model families trainable through a unified internal trait. Architecture: - TrainableModel trait + TrainableModelEnum for engine-level polymorphism - ModelType enum for autograd dispatch to correct functional forward pass - Per-model training methods (get_parameters, apply_gradients, generate) - Functional forward passes for Qwen3.5 Dense (GDN + partial-RoPE attention) and MoE (gather_mm-based sparse expert routing) Key changes: - training_model.rs: TrainableModel trait, TrainableModelEnum, ModelType, compute_sgd_updates helper, dispatch macros - training_generate.rs: shared generation loop parameterized by forward closure - functional.rs: Qwen3.5 Dense/MoE functional forwards, gather_mm-based MoE (~16x fewer expert FLOPs vs per-expert loop), unified dispatch - gated_delta.rs: use_kernel flag for ops-based differentiable GDN path - Engine factories: GrpoTrainingEngine.fromQwen35/fromQwen35Moe, SftTrainingEngine.fromQwen35/fromQwen35Moe - TypeScript trainers accept Qwen3 | Qwen35 | Qwen35Moe union type - stop_gradient FFI binding for MoE routing index detachment Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Remove 4 trait methods that were never called through the trait:
- model_type(): engines store ModelType as a field, never call through trait
- clone_for_training(): engines clone concrete types before wrapping in enum
- calculate_memory_size(): never called by any engine
- save_model_sync(): checkpoint saving never implemented in engines
Also remove:
- Qwen3Model::save_model_sync() — only existed for the dead trait method
- Qwen3_5Model::{calculate_memory_size, save_model_sync} — same reason
- Qwen3_5MoeModel::{calculate_memory_size, save_model_sync} — same reason
- compute_sft_loss_only() — validation loop never implemented
Qwen3Model::calculate_memory_size() is kept — used by inference (WiredLimitContext).
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…haustive dispatch Critical fixes: - Use silu_for_autograd in all Qwen3.5 functional forward paths to prevent NaN gradients from exp overflow during backpropagation - Add warning log for unmatched parameter names in apply_layer_gradient to surface silently dropped gradients Important fixes: - Make instanceof dispatch exhaustive in TS trainers — explicit Qwen3 check with throw for unknown model types - Replace .expect() with .map_err() in get_parameters_for_training, change TrainableModel::get_parameters to return Result - Replace "Lock" error messages with descriptive lock identification - Fix .unwrap() in functional_gather_sort with ok_or_else Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…rror handling The functional depthwise conv1d implementation used a manual sliding-window loop that assumed weight shape [C,1,K] but MLX Conv1d stores weights as [C,K,1]. This caused a C++ exception during Qwen3.5 training autograd. Replace with mlx_conv1d FFI call which: - Has correct weight format handling - Has proper VJP support for autograd - Is faster (single Metal kernel vs K iterations) Also: - Remove `called` guard in autograd callback (MLX may call multiple times) - Add try/catch around loss callback in C++ wrapper to surface exceptions - Add eprintln for autograd errors to aid debugging - Remove debug prints from functional forward Tested: Both Qwen3 (0.6B) and Qwen3.5 (0.8B) complete training steps. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…int persistence Root cause: MLX's eval() inside vjp tracing context doesn't call detach(), so h.eval() between checkpointed layers materialized ALL intermediates simultaneously without freeing. Additionally, the default mlx::core::checkpoint uses a DFS topological sort that evaluates all layers' recomputed intermediates before any VJPs, causing 24× memory amplification during backward. Memory fixes: - Remove h.eval() from checkpointed layer loops (lazy graph during tracing) - Replace mlx::core::checkpoint with custom_vjp that adds cotangent dependency, forcing sequential layer-by-layer backward eval (104GB → 22GB peak) - Fix gradient accumulation leak: eval after each add to break lazy chain (+1.5GB/chunk leaked → stable 3.2GB) - Checkpoint all layers including last (was skipping final layer) Checkpoint persistence: - Add save_model NAPI to Qwen3.5 Dense and MoE (was Qwen3-only) - Include vision encoder weights in save for VL models - Add save/load_optimizer_state for AdamW moment tensors + step counter - Add hasOptimizerState flag to TrainingState for resume - Fix detectModelType to throw on missing config.json (was silent fallback) - Widen ModelLoader.saveModel to accept all model types Cleanup: - Remove all debug logging (eprintln!, std::cerr) - Remove dead LossFunctionContext.called field - Replace Box::into_raw leak with CheckpointContexts collector (passed through call chain via Rc<RefCell<>>), reclaimed after each value_and_grad - Rename forward_hidden_states_dispatch_impl → forward_hidden_states_dispatch Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Replace `new Array(n)` with `Array.from({ length: n })` (unicorn/no-new-array)
- Remove unused catch parameter `e` (no-unused-vars)
- Wrap `unknown` catch values with `String(e)` (restrict-template-expressions)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… save SFT checkpointing: - Add gradient_checkpointing field to SftEngineConfig (default: true) - Add gradient_checkpointing to SFTTrainerConfig - Thread use_checkpointing through compute_sft_loss_and_gradients - SFT training now benefits from the same memory-ordered checkpoint as GRPO (was hardcoded to false) SFT checkpoint save: - Replace stale Qwen3-only saveModel with model-agnostic call - Remove TODO about Qwen3.5 saveModel (already implemented) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
📝 WalkthroughWalkthroughThis PR adds gradient checkpointing infrastructure for memory optimization, introduces a unified ModelType abstraction to support multiple Qwen model variants (3, 3.5 Dense, 3.5 MoE), expands GRPO and SFT training engines with multi-model support and optimizer state management, and adds new MLX array operations (gather_mm, stop_gradient) for advanced training scenarios. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
📝 Coding Plan
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment Tip CodeRabbit can enforce grammar and style rules using `languagetool`.Configure the |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 533fd55ea6
ℹ️ 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".
There was a problem hiding this comment.
Actionable comments posted: 11
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
crates/mlx-core/src/grpo/engine.rs (1)
65-176:⚠️ Potential issue | 🟠 Major
topEntropyQuantileis still missing from GRPO config/plumbing.The new GRPO config surface adds several training controls but still omits entropy-filter configuration, so selective high-uncertainty token training cannot be enabled.
As per coding guidelines
Support entropy filtering via topEntropyQuantile configuration to selectively train on high-uncertainty tokens.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/grpo/engine.rs` around lines 65 - 176, Add the missing entropy-filter config to GRPO by adding a new Option<f64> field named top_entropy_quantile to the GRPOEngineConfig struct (e.g., pub top_entropy_quantile: Option<f64>) with a doc comment like "Selects the top fraction of high-entropy tokens to include in training (default: None) — corresponds to topEntropyQuantile"; then wire this field through the config parsing and plumbing where GRPO training masking/selection is applied (look for places/methods that compute token selection or entropy masks such as GRPOTrainer, compute_entropy_mask, or apply_config) so the runtime uses GRPOEngineConfig::top_entropy_quantile to enable selective high-uncertainty token training.
🧹 Nitpick comments (2)
crates/mlx-core/src/models/qwen3_5/model.rs (1)
1866-1883: Consider GPU-native NaN/Inf validation for large models.The current validation transfers all parameters to CPU via
to_float32()(Line 1867-1868), which can be slow for large models. TheMxArrayalready hashas_nan_or_inf()method (defined earlier in ops.rs) that uses GPU reduction.♻️ Suggested optimization using GPU-native check
// Validate all parameters for NaN/Inf before saving for (name, param) in params.iter() { - let data = param.to_float32()?; - let invalid_count = data - .iter() - .filter(|v| v.is_nan() || v.is_infinite()) - .count(); - if invalid_count > 0 { + if param.has_nan_or_inf()? { return Err(napi::Error::new( Status::GenericFailure, format!( - "Cannot save model: parameter '{}' contains {} NaN/Inf values. \ + "Cannot save model: parameter '{}' contains NaN/Inf values. \ Model weights are corrupted, likely due to training instability. \ Consider reducing learning rate or using an earlier checkpoint.", - name, invalid_count + name ), )); } }🤖 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 1866 - 1883, The loop over params currently calls param.to_float32() which forces GPU->CPU transfer and is slow for large models; replace this with the GPU-native check provided by MxArray::has_nan_or_inf() (call e.g. param.has_nan_or_inf()) to detect NaN/Inf on-device and only fall back to to_float32() if that method is unavailable or returns an indeterminate result; update the error message logic in the same block that currently uses params.iter(), to_float32(), and invalid_count so it uses the boolean/device count from has_nan_or_inf() (or computes a CPU-side count only on fallback).crates/mlx-core/src/utils/functional.rs (1)
417-417: Avoid panic paths when extracting checkpoint outputs.Using
unwrap()here can crash the training process if a checkpoint callback ever returns an empty output vector. Return a typed error instead.♻️ Suggested change
- hidden_states = outputs.into_iter().next().unwrap(); + hidden_states = outputs + .into_iter() + .next() + .ok_or_else(|| Error::from_reason("checkpoint_apply returned no outputs"))?;Apply the same pattern at Line 1241 and Line 1576.
Also applies to: 1241-1241, 1576-1576
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/utils/functional.rs` at line 417, The code currently calls outputs.into_iter().next().unwrap() to extract hidden_states which panics on empty vectors; change this to safely handle the empty case by using outputs.into_iter().next().ok_or_else(...) and return a typed error (e.g., a CheckpointEmpty or a crate Error variant) instead of panicking, update the surrounding function signature to return Result if necessary and propagate the error upward, and apply the identical replacement at the other occurrences where unwrap() is used (the similar lines at 1241 and 1576) so all empty-output cases return a typed error rather than calling unwrap().
🤖 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/autograd.rs`:
- Around line 341-348: param_arrays currently holds MxArray wrappers around
C++-owned handles and early returns (after setting context_ref.error) will drop
those wrappers and double-free the handles; change param_arrays to hold
ManuallyDrop<MxArray> (e.g., Vec<ManuallyDrop<MxArray>>) and when you push the
Ok(arr) use ManuallyDrop::new(arr) so that early-return paths do not run
MxArray::drop, and keep the existing forget/cleanup logic at the normal exit to
explicitly release or forget the inner handles; apply the same
ManuallyDrop-based fix to the other similar block that constructs param_arrays
around MxArray::from_handle and input_slice.
In `@crates/mlx-core/src/grpo/engine.rs`:
- Around line 409-415: The code in the grad accumulation path uses unwrap() on
MxArray::from_float32 and grad.mul which can panic; update the grad-accumulation
branch (symbols: grad_acc_steps, scale, scale_arr, MxArray::from_float32,
grads_to_use, scaled_grads, and the closure using grad.mul) to propagate errors
instead of unwrapping—return a Result from the surrounding function (or convert
to ?-compatible error) and replace .unwrap() calls with ? so failures in
creating scale_arr or multiplying gradients bubble up rather than aborting;
apply the same change to the other occurrence around lines 436-437 where
grad.mul and/or related unwraps appear.
- Around line 462-486: The current logic silently treats any non-"adamw"
optimizer_type as SGD, which can hide typos; change this by implementing an
explicit create_optimizer(&config) that matches opt_type (e.g., "adamw" =>
construct crate::optimizers::AdamW, "sgd" => construct the SGD optimizer) and
return a Result<Option<Arc<Mutex<...>>>, Error> (or Result<...>) that returns an
Err for any unknown optimizer_type instead of falling back to SGD; update
callers/constructors to call create_optimizer(&config)? so unknown values
propagate as errors.
- Around line 2596-2621: Before applying the checkpoint tensors you must clear
any existing optimizer buffers so stale moment entries don't persist: add a
reset step on opt (e.g. call opt.clear_state() or
opt.reset_moments()/opt.clear_moments() before reading from st_file) or, if such
a method doesn't exist, implement one that clears all first/second moment maps
and resets step, then restore the step via opt.set_step(...) and repopulate
moments using opt.set_first_moment(...) and opt.set_second_moment(...) based on
the tensors map; alternatively, after loading tensors, remove any existing
optimizer keys not present in tensors to ensure exact replacement.
In `@crates/mlx-core/src/models/qwen3_5_moe/model.rs`:
- Around line 1747-1754: The current NaN/Inf validation materializes each
parameter to host via param.to_float32() inside the for (name, param) in
params.iter() loop, which can OOM on MoE-sized tensors; change the check to
perform a device-side finite test and scalar reduction (e.g., compute something
like tensor.is_finite().logical_not().sum() or equivalent device-side count) and
only copy that single scalar count to the host for the if invalid_count > 0
branch. Update the code that references param.to_float32() and invalid_count so
it uses the device-side reduction API on the tensor (keeping the loop over
params and preserving the name for error messages) and only transfers the
reduced scalar to host for logging/early-exit.
In `@crates/mlx-core/src/models/training_generate.rs`:
- Around line 91-101: The repetition cutoff is currently checking all_tokens
(which includes the prompt) and is skipped in the branch where return_logprobs
== false; change the logic to run check_repetition_cutoff against
generated_tokens (not all_tokens) and ensure the same check is executed in both
branches (the branch that sets finish_reason = "repetition" and the other branch
currently missing the check). Update the two occurrences that call
check_repetition_cutoff (the block with finish_reason = "repetition" and the
similar block around the return_logprobs == false branch) to use
generated_tokens and to set finish_reason accordingly when Some is returned.
- Around line 25-47: The code currently casts config.max_new_tokens (i32) to
usize when reserving capacity for generated_tokens and logprobs, which can
overflow if negative; add an explicit check on max_new_tokens after you read it
(e.g. let max_new_tokens = config.max_new_tokens.unwrap_or(100);) to reject or
clamp non-positive values: if max_new_tokens <= 0 { return Err(...) } or set it
to 0/DEFAULT, then safely convert to usize for Vec::with_capacity; update any
early-return behavior in the function that depends on max_new_tokens and
reference the variables max_new_tokens, generated_tokens, logprobs (and the
SamplingConfig block) so the validation occurs before creating those vectors.
In `@crates/mlx-core/src/utils/functional.rs`:
- Around line 824-1677: Add baseline unit tests that cover the new Qwen3.5 Dense
and MoE functional entry points and dispatcher variants: call
qwen3_5_forward_functional, qwen3_5_moe_forward_functional,
forward_functional_dispatch and forward_hidden_states_dispatch with small
synthetic inputs and minimal params to assert output shapes match expectations
and that outputs are equal with use_checkpointing true/false; include tests for
tied vs untied lm_head behavior and for dispatching each ModelType variant to
ensure the correct path runs (Qwen35Dense/Qwen35Moe), and ensure checkpointed
helpers qwen3_5_block_checkpointed / qwen3_5_moe_block_checkpointed are
exercised indirectly via the use_checkpointing flag. Ensure tests are minimal
smoke tests (shape + checkpoint equivalence) and placed alongside existing
functional tests.
In `@crates/mlx-sys/src/mlx_misc_ops.cpp`:
- Around line 591-601: Add FFI hardening to mlx_stop_gradient: first check the
incoming mlx_array* a for nullptr and return nullptr immediately if null; when
logging errors use the "[MLX]" prefix in the std::cerr message; catch both
std::exception (logging e.what() with "[MLX]" prefix) and a catch(...) fallback
that logs a generic "[MLX] unknown error" and returns nullptr; keep existing use
of reinterpret_cast and mlx::core::stop_gradient/result creation but ensure all
exceptions are handled and no exceptions cross the FFI boundary.
In `@packages/lm/src/models/model-loader.ts`:
- Around line 77-84: The catch block in detectModelType incorrectly always
throws "config.json not found", hiding JSON parse or permission errors; change
it to differentiate ENOENT (file missing) from other errors by inspecting the
caught error (e.g., error.code === 'ENOENT') and throw a specific "config.json
not found in <modelPath>" for that case, but for other errors include the
original error message (or rethrow) so parse/permission errors are visible; keep
the original behavior of reading join(modelPath, 'config.json') and parsing JSON
and returning config.model_type ?? 'qwen3'.
In `@packages/trl/src/trainers/sft-trainer.ts`:
- Around line 556-557: The checkpoint save is using this.model which can be
stale for Qwen3; change the save to use the authoritative model returned by
getModel() (or engine.getModel() if that is the canonical accessor) so that
saveModel(checkpointPath) is invoked on getModel() instead of this.model; update
any other saves in the same area (around the block referenced at lines 636-643)
to call getModel().saveModel(...) (or engine.getModel().saveModel(...)) to
ensure Qwen3 weights are current.
---
Outside diff comments:
In `@crates/mlx-core/src/grpo/engine.rs`:
- Around line 65-176: Add the missing entropy-filter config to GRPO by adding a
new Option<f64> field named top_entropy_quantile to the GRPOEngineConfig struct
(e.g., pub top_entropy_quantile: Option<f64>) with a doc comment like "Selects
the top fraction of high-entropy tokens to include in training (default: None) —
corresponds to topEntropyQuantile"; then wire this field through the config
parsing and plumbing where GRPO training masking/selection is applied (look for
places/methods that compute token selection or entropy masks such as
GRPOTrainer, compute_entropy_mask, or apply_config) so the runtime uses
GRPOEngineConfig::top_entropy_quantile to enable selective high-uncertainty
token training.
---
Nitpick comments:
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 1866-1883: The loop over params currently calls param.to_float32()
which forces GPU->CPU transfer and is slow for large models; replace this with
the GPU-native check provided by MxArray::has_nan_or_inf() (call e.g.
param.has_nan_or_inf()) to detect NaN/Inf on-device and only fall back to
to_float32() if that method is unavailable or returns an indeterminate result;
update the error message logic in the same block that currently uses
params.iter(), to_float32(), and invalid_count so it uses the boolean/device
count from has_nan_or_inf() (or computes a CPU-side count only on fallback).
In `@crates/mlx-core/src/utils/functional.rs`:
- Line 417: The code currently calls outputs.into_iter().next().unwrap() to
extract hidden_states which panics on empty vectors; change this to safely
handle the empty case by using outputs.into_iter().next().ok_or_else(...) and
return a typed error (e.g., a CheckpointEmpty or a crate Error variant) instead
of panicking, update the surrounding function signature to return Result if
necessary and propagate the error upward, and apply the identical replacement at
the other occurrences where unwrap() is used (the similar lines at 1241 and
1576) so all empty-output cases return a typed error rather than calling
unwrap().
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: cacda4cb-8353-4979-afa0-abefcf26f49f
📒 Files selected for processing (39)
crates/mlx-core/src/array/ops.rscrates/mlx-core/src/autograd.rscrates/mlx-core/src/grpo/autograd.rscrates/mlx-core/src/grpo/engine.rscrates/mlx-core/src/grpo/mod.rscrates/mlx-core/src/lib.rscrates/mlx-core/src/models/mod.rscrates/mlx-core/src/models/qwen3/model.rscrates/mlx-core/src/models/qwen3_5/attention.rscrates/mlx-core/src/models/qwen3_5/decoder_layer.rscrates/mlx-core/src/models/qwen3_5/gated_delta.rscrates/mlx-core/src/models/qwen3_5/gated_delta_net.rscrates/mlx-core/src/models/qwen3_5/model.rscrates/mlx-core/src/models/qwen3_5/quantized_linear.rscrates/mlx-core/src/models/qwen3_5/vision.rscrates/mlx-core/src/models/qwen3_5_moe/decoder_layer.rscrates/mlx-core/src/models/qwen3_5_moe/model.rscrates/mlx-core/src/models/qwen3_5_moe/sparse_moe.rscrates/mlx-core/src/models/training_generate.rscrates/mlx-core/src/nn/normalization.rscrates/mlx-core/src/sft/autograd.rscrates/mlx-core/src/sft/engine.rscrates/mlx-core/src/sft/mod.rscrates/mlx-core/src/training_model.rscrates/mlx-core/src/utils/functional.rscrates/mlx-core/src/vision/encoder.rscrates/mlx-core/src/vision/projector.rscrates/mlx-sys/src/lib.rscrates/mlx-sys/src/mlx_autograd.cppcrates/mlx-sys/src/mlx_misc_ops.cppcrates/mlx-sys/src/mlx_qwen35.cppcrates/mlx-sys/src/mlx_qwen35_moe.cppexamples/measure-prompt.tspackages/core/index.d.ctspackages/lm/src/index.tspackages/lm/src/models/model-loader.tspackages/trl/src/trainers/grpo-trainer.tspackages/trl/src/trainers/sft-config.tspackages/trl/src/trainers/sft-trainer.ts
| let mut param_arrays = Vec::with_capacity(input_count); | ||
| for &handle in input_slice { | ||
| match MxArray::from_handle(handle, "checkpoint_input") { | ||
| Ok(arr) => param_arrays.push(arr), | ||
| Err(e) => { | ||
| context_ref.error = Some(format!("Failed to create array: {:?}", e)); | ||
| return 0; | ||
| } |
There was a problem hiding this comment.
Don't drop borrowed callback inputs on these early exits.
param_arrays wraps handles that C++ still owns. Returning from either branch before the forget at Line 361 drops any wrappers collected so far, and C++ will then delete the same handles again after the callback returns. Use ManuallyDrop or a borrowed-handle wrapper here so every exit path preserves C++ ownership.
Also applies to: 353-361
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@crates/mlx-core/src/autograd.rs` around lines 341 - 348, param_arrays
currently holds MxArray wrappers around C++-owned handles and early returns
(after setting context_ref.error) will drop those wrappers and double-free the
handles; change param_arrays to hold ManuallyDrop<MxArray> (e.g.,
Vec<ManuallyDrop<MxArray>>) and when you push the Ok(arr) use
ManuallyDrop::new(arr) so that early-return paths do not run MxArray::drop, and
keep the existing forget/cleanup logic at the normal exit to explicitly release
or forget the inner handles; apply the same ManuallyDrop-based fix to the other
similar block that constructs param_arrays around MxArray::from_handle and
input_slice.
| let grads_to_use = if grad_acc_steps > 1 { | ||
| let scale = 1.0 / grad_acc_steps as f32; | ||
| let scale_arr = MxArray::from_float32(&[scale], &[]).unwrap(); | ||
| scaled_grads = grads | ||
| .iter() | ||
| .map(|(name, grad)| (name.clone(), grad.mul(&scale_arr).unwrap())) | ||
| .collect(); |
There was a problem hiding this comment.
Remove unwrap() in optimizer-step math paths.
These unwrap() calls can panic and abort training on runtime tensor errors. Propagate errors with ? instead.
🐛 Suggested change
- let scale_arr = MxArray::from_float32(&[scale], &[]).unwrap();
- scaled_grads = grads
- .iter()
- .map(|(name, grad)| (name.clone(), grad.mul(&scale_arr).unwrap()))
- .collect();
+ let scale_arr = MxArray::from_float32(&[scale], &[])?;
+ scaled_grads = grads
+ .iter()
+ .map(|(name, grad)| Ok((name.clone(), grad.mul(&scale_arr)?)))
+ .collect::<Result<HashMap<_, _>>>()?;
@@
- let deltas: HashMap<String, MxArray> = param_names_vec
- .iter()
- .enumerate()
- .map(|(i, name)| {
- let delta = param_refs[i].sub(&updated[i]).unwrap();
- (name.clone(), delta)
- })
- .collect();
+ let deltas: HashMap<String, MxArray> = param_names_vec
+ .iter()
+ .enumerate()
+ .map(|(i, name)| Ok((name.clone(), param_refs[i].sub(&updated[i])?)))
+ .collect::<Result<HashMap<_, _>>>()?;Also applies to: 436-437
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@crates/mlx-core/src/grpo/engine.rs` around lines 409 - 415, The code in the
grad accumulation path uses unwrap() on MxArray::from_float32 and grad.mul which
can panic; update the grad-accumulation branch (symbols: grad_acc_steps, scale,
scale_arr, MxArray::from_float32, grads_to_use, scaled_grads, and the closure
using grad.mul) to propagate errors instead of unwrapping—return a Result from
the surrounding function (or convert to ?-compatible error) and replace
.unwrap() calls with ? so failures in creating scale_arr or multiplying
gradients bubble up rather than aborting; apply the same change to the other
occurrence around lines 436-437 where grad.mul and/or related unwraps appear.
| let opt_type = config.optimizer_type.as_deref().unwrap_or("adamw"); | ||
| if opt_type == "adamw" { | ||
| let optimizer = crate::optimizers::AdamW::new( | ||
| config.learning_rate, | ||
| config.adamw_beta1, | ||
| config.adamw_beta2, | ||
| config.adamw_eps, | ||
| config.weight_decay, | ||
| Some(true), // bias correction | ||
| ); | ||
| info!( | ||
| "Using AdamW optimizer (lr={}, beta1={}, beta2={}, wd={})", | ||
| config.learning_rate.unwrap_or(1e-6), | ||
| config.adamw_beta1.unwrap_or(0.9), | ||
| config.adamw_beta2.unwrap_or(0.999), | ||
| config.weight_decay.unwrap_or(0.01), | ||
| ); | ||
| Some(Arc::new(std::sync::Mutex::new(optimizer))) | ||
| } else { | ||
| info!( | ||
| "Using SGD optimizer (lr={})", | ||
| config.learning_rate.unwrap_or(1e-6) | ||
| ); | ||
| None | ||
| } |
There was a problem hiding this comment.
Reject unknown optimizer_type values instead of silently downgrading to SGD.
A typo in config currently changes optimizer behavior without error, which is high-risk for training correctness and reproducibility.
♻️ Suggested change
-fn create_optimizer(
- config: &GRPOEngineConfig,
-) -> Option<Arc<std::sync::Mutex<crate::optimizers::AdamW>>> {
+fn create_optimizer(
+ config: &GRPOEngineConfig,
+) -> Result<Option<Arc<std::sync::Mutex<crate::optimizers::AdamW>>>> {
let opt_type = config.optimizer_type.as_deref().unwrap_or("adamw");
- if opt_type == "adamw" {
+ if opt_type == "adamw" {
let optimizer = crate::optimizers::AdamW::new(
@@
- Some(Arc::new(std::sync::Mutex::new(optimizer)))
- } else {
+ Ok(Some(Arc::new(std::sync::Mutex::new(optimizer))))
+ } else if opt_type == "sgd" {
info!(
"Using SGD optimizer (lr={})",
config.learning_rate.unwrap_or(1e-6)
);
- None
+ Ok(None)
+ } else {
+ Err(Error::new(
+ Status::InvalidArg,
+ format!("Unsupported optimizer_type '{}'. Expected 'adamw' or 'sgd'.", opt_type),
+ ))
}
}(Constructors should then call create_optimizer(&config)?.)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@crates/mlx-core/src/grpo/engine.rs` around lines 462 - 486, The current logic
silently treats any non-"adamw" optimizer_type as SGD, which can hide typos;
change this by implementing an explicit create_optimizer(&config) that matches
opt_type (e.g., "adamw" => construct crate::optimizers::AdamW, "sgd" =>
construct the SGD optimizer) and return a Result<Option<Arc<Mutex<...>>>, Error>
(or Result<...>) that returns an Err for any unknown optimizer_type instead of
falling back to SGD; update callers/constructors to call
create_optimizer(&config)? so unknown values propagate as errors.
| let mut opt = opt_arc | ||
| .lock() | ||
| .map_err(|_| Error::new(Status::GenericFailure, "Failed to acquire optimizer lock"))?; | ||
|
|
||
| // Load SafeTensors file | ||
| let st_file = crate::utils::safetensors::SafeTensorsFile::load(&path)?; | ||
|
|
||
| // Restore step from metadata | ||
| if let Some(metadata) = &st_file.metadata | ||
| && let Some(step_str) = metadata.get("step").and_then(|v| v.as_str()) | ||
| && let Ok(step) = step_str.parse::<i64>() | ||
| { | ||
| opt.set_step(step); | ||
| } | ||
|
|
||
| // Load all tensors | ||
| let tensors = st_file.load_tensors(&path)?; | ||
|
|
||
| // Restore moment tensors: keys are "{param_name}.m" and "{param_name}.v" | ||
| for (tensor_key, array) in &tensors { | ||
| if let Some(param_name) = tensor_key.strip_suffix(".m") { | ||
| opt.set_first_moment(param_name.to_string(), array)?; | ||
| } else if let Some(param_name) = tensor_key.strip_suffix(".v") { | ||
| opt.set_second_moment(param_name.to_string(), array)?; | ||
| } | ||
| } |
There was a problem hiding this comment.
Reset optimizer state before restoring from checkpoint tensors.
load_optimizer_state currently overlays loaded moments onto any existing in-memory AdamW buffers. Stale keys can persist and affect future updates.
♻️ Suggested change
let mut opt = opt_arc
.lock()
.map_err(|_| Error::new(Status::GenericFailure, "Failed to acquire optimizer lock"))?;
+ // Ensure no stale moments survive from prior runs before restore.
+ opt.reset();
+
// Load SafeTensors file
let st_file = crate::utils::safetensors::SafeTensorsFile::load(&path)?;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| let mut opt = opt_arc | |
| .lock() | |
| .map_err(|_| Error::new(Status::GenericFailure, "Failed to acquire optimizer lock"))?; | |
| // Load SafeTensors file | |
| let st_file = crate::utils::safetensors::SafeTensorsFile::load(&path)?; | |
| // Restore step from metadata | |
| if let Some(metadata) = &st_file.metadata | |
| && let Some(step_str) = metadata.get("step").and_then(|v| v.as_str()) | |
| && let Ok(step) = step_str.parse::<i64>() | |
| { | |
| opt.set_step(step); | |
| } | |
| // Load all tensors | |
| let tensors = st_file.load_tensors(&path)?; | |
| // Restore moment tensors: keys are "{param_name}.m" and "{param_name}.v" | |
| for (tensor_key, array) in &tensors { | |
| if let Some(param_name) = tensor_key.strip_suffix(".m") { | |
| opt.set_first_moment(param_name.to_string(), array)?; | |
| } else if let Some(param_name) = tensor_key.strip_suffix(".v") { | |
| opt.set_second_moment(param_name.to_string(), array)?; | |
| } | |
| } | |
| let mut opt = opt_arc | |
| .lock() | |
| .map_err(|_| Error::new(Status::GenericFailure, "Failed to acquire optimizer lock"))?; | |
| // Ensure no stale moments survive from prior runs before restore. | |
| opt.reset(); | |
| // Load SafeTensors file | |
| let st_file = crate::utils::safetensors::SafeTensorsFile::load(&path)?; | |
| // Restore step from metadata | |
| if let Some(metadata) = &st_file.metadata | |
| && let Some(step_str) = metadata.get("step").and_then(|v| v.as_str()) | |
| && let Ok(step) = step_str.parse::<i64>() | |
| { | |
| opt.set_step(step); | |
| } | |
| // Load all tensors | |
| let tensors = st_file.load_tensors(&path)?; | |
| // Restore moment tensors: keys are "{param_name}.m" and "{param_name}.v" | |
| for (tensor_key, array) in &tensors { | |
| if let Some(param_name) = tensor_key.strip_suffix(".m") { | |
| opt.set_first_moment(param_name.to_string(), array)?; | |
| } else if let Some(param_name) = tensor_key.strip_suffix(".v") { | |
| opt.set_second_moment(param_name.to_string(), array)?; | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@crates/mlx-core/src/grpo/engine.rs` around lines 2596 - 2621, Before applying
the checkpoint tensors you must clear any existing optimizer buffers so stale
moment entries don't persist: add a reset step on opt (e.g. call
opt.clear_state() or opt.reset_moments()/opt.clear_moments() before reading from
st_file) or, if such a method doesn't exist, implement one that clears all
first/second moment maps and resets step, then restore the step via
opt.set_step(...) and repopulate moments using opt.set_first_moment(...) and
opt.set_second_moment(...) based on the tensors map; alternatively, after
loading tensors, remove any existing optimizer keys not present in tensors to
ensure exact replacement.
| // Validate all parameters for NaN/Inf before saving | ||
| for (name, param) in params.iter() { | ||
| let data = param.to_float32()?; | ||
| let invalid_count = data | ||
| .iter() | ||
| .filter(|v| v.is_nan() || v.is_infinite()) | ||
| .count(); | ||
| if invalid_count > 0 { |
There was a problem hiding this comment.
Avoid full host materialization during NaN/Inf checks.
Line 1749 converts each parameter to host f32 before scanning. On MoE-sized tensors, this can spike RAM and make checkpoint saves fail under memory pressure. Prefer device-side finite checks with scalar reduction, then copy only the count to host.
🤖 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 1747 - 1754,
The current NaN/Inf validation materializes each parameter to host via
param.to_float32() inside the for (name, param) in params.iter() loop, which can
OOM on MoE-sized tensors; change the check to perform a device-side finite test
and scalar reduction (e.g., compute something like
tensor.is_finite().logical_not().sum() or equivalent device-side count) and only
copy that single scalar count to the host for the if invalid_count > 0 branch.
Update the code that references param.to_float32() and invalid_count so it uses
the device-side reduction API on the tensor (keeping the loop over params and
preserving the name for error messages) and only transfers the reduced scalar to
host for logging/early-exit.
| if check_repetition_cutoff( | ||
| &all_tokens, | ||
| max_consecutive_tokens, | ||
| max_ngram_repeats, | ||
| ngram_size, | ||
| ) | ||
| .is_some() | ||
| { | ||
| finish_reason = "repetition".to_string(); | ||
| break; | ||
| } |
There was a problem hiding this comment.
Repetition cutoff is checking the wrong stream and is skipped in one branch.
Line 91 checks all_tokens (includes prompt), so prompt repetition can stop generation early. Also, the return_logprobs = false branch never runs repetition cutoff at all. Use generated_tokens and apply the same check in both branches.
💡 Proposed fix
- if check_repetition_cutoff(
- &all_tokens,
- max_consecutive_tokens,
- max_ngram_repeats,
- ngram_size,
- )
- .is_some()
- {
- finish_reason = "repetition".to_string();
- break;
- }
-
generated_tokens.push(token_id);
all_tokens.push(token_id);
+ if check_repetition_cutoff(
+ &generated_tokens,
+ max_consecutive_tokens,
+ max_ngram_repeats,
+ ngram_size,
+ )
+ .is_some()
+ {
+ finish_reason = "repetition".to_string();
+ break;
+ }
@@
generated_tokens.push(token_id);
all_tokens.push(token_id);
+ if check_repetition_cutoff(
+ &generated_tokens,
+ max_consecutive_tokens,
+ max_ngram_repeats,
+ ngram_size,
+ )
+ .is_some()
+ {
+ finish_reason = "repetition".to_string();
+ break;
+ }Also applies to: 117-133
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@crates/mlx-core/src/models/training_generate.rs` around lines 91 - 101, The
repetition cutoff is currently checking all_tokens (which includes the prompt)
and is skipped in the branch where return_logprobs == false; change the logic to
run check_repetition_cutoff against generated_tokens (not all_tokens) and ensure
the same check is executed in both branches (the branch that sets finish_reason
= "repetition" and the other branch currently missing the check). Update the two
occurrences that call check_repetition_cutoff (the block with finish_reason =
"repetition" and the similar block around the return_logprobs == false branch)
to use generated_tokens and to set finish_reason accordingly when Some is
returned.
| // ============================================ | ||
| // Qwen3.5 Dense Model Forward (Functional) | ||
| // ============================================ | ||
|
|
||
| /// RMS normalization without learnable weight (functional version). | ||
| fn rms_norm_no_weight_functional(x: &MxArray, eps: f64) -> Result<MxArray> { | ||
| let original_dtype = x.dtype()?; | ||
| let x_f32 = x.astype(crate::array::DType::Float32)?; | ||
| let squared = x_f32.square()?; | ||
| let mean_squared = squared.mean(Some(&[-1]), Some(true))?; | ||
| let variance_plus_eps = mean_squared.add_scalar(eps)?; | ||
| let sqrt_var = variance_plus_eps.sqrt()?; | ||
| let normalized = x_f32.div(&sqrt_var)?; | ||
| normalized.astype(original_dtype) | ||
| } | ||
|
|
||
| /// RMSNormGated functional: swiglu(z, rms_norm(y, weight)) | ||
| /// Implements: silu(z) * rms_norm(y) * weight | ||
| fn rms_norm_gated_functional( | ||
| y: &MxArray, | ||
| z: &MxArray, | ||
| weight: &MxArray, | ||
| eps: f64, | ||
| ) -> Result<MxArray> { | ||
| let y_normed = rms_norm_functional(y, weight, eps)?; | ||
| let z_activated = Activations::silu_for_autograd(z)?; | ||
| y_normed.mul(&z_activated) | ||
| } | ||
|
|
||
| /// Functional depthwise conv1d using MLX's native conv1d (has VJP support). | ||
| /// weight: [channels, kernel_size, 1] (MLX Conv1d format for depthwise) | ||
| /// input: [B, T, channels] | ||
| /// groups = channels (depthwise convolution) | ||
| fn functional_depthwise_conv1d( | ||
| input: &MxArray, | ||
| weight: &MxArray, | ||
| channels: i64, | ||
| _kernel_size: i64, | ||
| ) -> Result<MxArray> { | ||
| // Use MLX's native conv1d which has proper VJP for autograd. | ||
| // Parameters: stride=1, padding=0, dilation=1, groups=channels (depthwise) | ||
| let handle = unsafe { | ||
| mlx_sys::mlx_conv1d( | ||
| input.as_raw_ptr(), | ||
| weight.as_raw_ptr(), | ||
| 1, // stride | ||
| 0, // padding (we prepend zeros manually) | ||
| 1, // dilation | ||
| channels as i32, // groups = channels for depthwise | ||
| ) | ||
| }; | ||
| MxArray::from_handle(handle, "functional_conv1d") | ||
| } | ||
|
|
||
| /// GatedDeltaNet functional forward (linear attention layer). | ||
| /// | ||
| /// Implements the full GDN pipeline: project -> conv1d -> gated_delta_update -> norm -> out_proj | ||
| /// Uses `use_kernel=false` to ensure full differentiability for training. | ||
| fn gated_delta_net_functional( | ||
| params: &HashMap<String, MxArray>, | ||
| x: &MxArray, | ||
| prefix: &str, | ||
| config: &Qwen3_5Config, | ||
| ) -> Result<MxArray> { | ||
| let batch = x.shape_at(0)?; | ||
| let seq_len = x.shape_at(1)?; | ||
|
|
||
| let num_k_heads = config.linear_num_key_heads; | ||
| let num_v_heads = config.linear_num_value_heads; | ||
| let key_head_dim = config.linear_key_head_dim; | ||
| let value_head_dim = config.linear_value_head_dim; | ||
| let key_dim = num_k_heads * key_head_dim; | ||
| let value_dim = num_v_heads * value_head_dim; | ||
| let conv_dim = key_dim * 2 + value_dim; | ||
| let conv_kernel_dim = config.linear_conv_kernel_dim; | ||
|
|
||
| // Project to qkvz | ||
| let qkvz_weight = params | ||
| .get(&format!("{}.in_proj_qkvz.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.in_proj_qkvz.weight", prefix)))?; | ||
| let qkvz = linear_functional(x, qkvz_weight, None)?; | ||
|
|
||
| // Project to ba | ||
| let ba_weight = params | ||
| .get(&format!("{}.in_proj_ba.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.in_proj_ba.weight", prefix)))?; | ||
| let ba = linear_functional(x, ba_weight, None)?; | ||
|
|
||
| // Split ba into b and a | ||
| let b = ba.slice_axis(2, 0, num_v_heads as i64)?; | ||
| let a = ba.slice_axis(2, num_v_heads as i64, (num_v_heads * 2) as i64)?; | ||
|
|
||
| // Split qkvz: qkv through conv, z bypasses | ||
| let qkv = qkvz.slice_axis(2, 0, conv_dim as i64)?; | ||
| let z = qkvz.slice_axis(2, conv_dim as i64, (key_dim * 2 + value_dim * 2) as i64)?; | ||
|
|
||
| // Conv1d: prepend zeros (no cache for training - full sequence) | ||
| let conv_weight = params | ||
| .get(&format!("{}.conv1d.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.conv1d.weight", prefix)))?; | ||
| let pad_len = (conv_kernel_dim - 1) as i64; | ||
| let zeros = MxArray::zeros(&[batch, pad_len, conv_dim as i64], Some(qkv.dtype()?))?; | ||
| let conv_input = MxArray::concatenate(&zeros, &qkv, 1)?; | ||
|
|
||
| // Depthwise conv1d: use functional matmul-based implementation | ||
| let conv_out = functional_depthwise_conv1d( | ||
| &conv_input, | ||
| conv_weight, | ||
| conv_dim as i64, | ||
| conv_kernel_dim as i64, | ||
| )?; | ||
|
|
||
| // Take last seq_len timesteps | ||
| let conv_out_len = conv_out.shape_at(1)?; | ||
| let conv_out = if conv_out_len > seq_len { | ||
| conv_out.slice_axis(1, conv_out_len - seq_len, conv_out_len)? | ||
| } else { | ||
| conv_out | ||
| }; | ||
|
|
||
| // SiLU activation (autograd-safe: tanh-based, avoids NaN gradients) | ||
| let conv_out = Activations::silu_for_autograd(&conv_out)?; | ||
|
|
||
| // Split into q, k, v | ||
| let q_flat = conv_out.slice_axis(2, 0, key_dim as i64)?; | ||
| let k_flat = conv_out.slice_axis(2, key_dim as i64, (key_dim * 2) as i64)?; | ||
| let v_flat = conv_out.slice_axis(2, (key_dim * 2) as i64, conv_dim as i64)?; | ||
|
|
||
| // Reshape to head format | ||
| let q = q_flat.reshape(&[batch, seq_len, num_k_heads as i64, key_head_dim as i64])?; | ||
| let k = k_flat.reshape(&[batch, seq_len, num_k_heads as i64, key_head_dim as i64])?; | ||
| let v = v_flat.reshape(&[batch, seq_len, num_v_heads as i64, value_head_dim as i64])?; | ||
|
|
||
| // RMS norm scaling (no learnable weight) | ||
| let inv_scale = (key_head_dim as f64).powf(-0.5); | ||
| let q_normed = rms_norm_no_weight_functional(&q, 1e-6)?; | ||
| let k_normed = rms_norm_no_weight_functional(&k, 1e-6)?; | ||
| let q = q_normed.mul_scalar(inv_scale * inv_scale)?; | ||
| let k = k_normed.mul_scalar(inv_scale)?; | ||
|
|
||
| // Gated delta update (use_kernel=false for differentiability) | ||
| let a_log = params | ||
| .get(&format!("{}.a_log", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.a_log", prefix)))?; | ||
| let dt_bias = params | ||
| .get(&format!("{}.dt_bias", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.dt_bias", prefix)))?; | ||
|
|
||
| use crate::models::qwen3_5::gated_delta::gated_delta_update; | ||
| let (y, _state) = gated_delta_update(&q, &k, &v, &a, &b, a_log, dt_bias, None, None, false)?; | ||
|
|
||
| // Reshape z to per-head format | ||
| let z = z.reshape(&[batch, seq_len, num_v_heads as i64, value_head_dim as i64])?; | ||
|
|
||
| // RMSNormGated: applies swiglu(z, rms_norm(y)) | ||
| let norm_weight = params | ||
| .get(&format!("{}.norm.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.norm.weight", prefix)))?; | ||
| let y_normed = rms_norm_gated_functional(&y, &z, norm_weight, config.rms_norm_eps)?; | ||
|
|
||
| // Flatten heads and output projection | ||
| let y_flat = y_normed.reshape(&[batch, seq_len, value_dim as i64])?; | ||
| let out_proj_weight = params | ||
| .get(&format!("{}.out_proj.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.out_proj.weight", prefix)))?; | ||
| linear_functional(&y_flat, out_proj_weight, None) | ||
| } | ||
|
|
||
| /// Qwen3.5 full attention with gating and partial RoPE (functional). | ||
| fn qwen3_5_attention_functional( | ||
| params: &HashMap<String, MxArray>, | ||
| x: &MxArray, | ||
| prefix: &str, | ||
| config: &Qwen3_5Config, | ||
| ) -> Result<MxArray> { | ||
| let batch = x.shape_at(0)?; | ||
| let seq_len = x.shape_at(1)?; | ||
| let num_heads = config.num_heads; | ||
| let num_kv_heads = config.num_kv_heads; | ||
| let head_dim = config.head_dim; | ||
| let scale = (head_dim as f64).powf(-0.5); | ||
|
|
||
| // Q projection (2x width for gating) | ||
| let q_weight = params | ||
| .get(&format!("{}.q_proj.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.q_proj.weight", prefix)))?; | ||
| let q_proj_out = linear_functional(x, q_weight, None)?; | ||
|
|
||
| // Split into queries + gate per-head | ||
| let q_per_head = | ||
| q_proj_out.reshape(&[batch, seq_len, num_heads as i64, (head_dim * 2) as i64])?; | ||
| let queries = q_per_head.slice_axis(3, 0, head_dim as i64)?; | ||
| let gate = q_per_head.slice_axis(3, head_dim as i64, (head_dim * 2) as i64)?; | ||
| let gate = gate.reshape(&[batch, seq_len, (num_heads * head_dim) as i64])?; | ||
|
|
||
| // K, V projections | ||
| let k_weight = params | ||
| .get(&format!("{}.k_proj.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.k_proj.weight", prefix)))?; | ||
| let v_weight = params | ||
| .get(&format!("{}.v_proj.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.v_proj.weight", prefix)))?; | ||
| let keys = linear_functional(x, k_weight, None)?; | ||
| let values = linear_functional(x, v_weight, None)?; | ||
|
|
||
| let keys = keys.reshape(&[batch, seq_len, num_kv_heads as i64, head_dim as i64])?; | ||
| let values = values.reshape(&[batch, seq_len, num_kv_heads as i64, head_dim as i64])?; | ||
|
|
||
| // QK normalization | ||
| let q_norm_weight = params | ||
| .get(&format!("{}.q_norm.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.q_norm.weight", prefix)))?; | ||
| let k_norm_weight = params | ||
| .get(&format!("{}.k_norm.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.k_norm.weight", prefix)))?; | ||
| let queries = rms_norm_functional(&queries, q_norm_weight, config.rms_norm_eps)?; | ||
| let keys = rms_norm_functional(&keys, k_norm_weight, config.rms_norm_eps)?; | ||
|
|
||
| // Partial RoPE: only rotate rope_dims dimensions | ||
| let rope_dims = config.rope_dims(); | ||
| let queries = apply_partial_rope(&queries, rope_dims as i64, config.rope_theta, 0)?; | ||
| let keys = apply_partial_rope(&keys, rope_dims as i64, config.rope_theta, 0)?; | ||
|
|
||
| // Transpose to [B, H, T, D] for SDPA | ||
| let queries = queries.transpose(Some(&[0, 2, 1, 3]))?; | ||
| let keys = keys.transpose(Some(&[0, 2, 1, 3]))?; | ||
| let values = values.transpose(Some(&[0, 2, 1, 3]))?; | ||
|
|
||
| // SDPA with causal mask (training: full sequence, no cache) | ||
| let output = if seq_len > 1 { | ||
| use crate::array::attention::scaled_dot_product_attention_causal; | ||
| scaled_dot_product_attention_causal(&queries, &keys, &values, scale)? | ||
| } else { | ||
| scaled_dot_product_attention(&queries, &keys, &values, scale, None)? | ||
| }; | ||
|
|
||
| // Back to [B, T, H*D] | ||
| let output = output.transpose(Some(&[0, 2, 1, 3]))?; | ||
| let output = output.reshape(&[batch, seq_len, (num_heads * head_dim) as i64])?; | ||
|
|
||
| // Gate: output * sigmoid(gate) | ||
| let gate_sigmoid = Activations::sigmoid(&gate)?; | ||
| let gated_output = output.mul(&gate_sigmoid)?; | ||
|
|
||
| // Output projection | ||
| let o_weight = params | ||
| .get(&format!("{}.o_proj.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.o_proj.weight", prefix)))?; | ||
| linear_functional(&gated_output, o_weight, None) | ||
| } | ||
|
|
||
| /// Apply partial RoPE: only rotate the first `rope_dims` dimensions. | ||
| /// Input shape: [B, T, H, D] (pre-transpose, heads in dim 2) | ||
| fn apply_partial_rope(x: &MxArray, rope_dims: i64, theta: f64, offset: i32) -> Result<MxArray> { | ||
| let head_dim = x.shape_at(3)?; | ||
| if rope_dims >= head_dim { | ||
| // Full RoPE — transpose to [B, H, T, D], apply, transpose back | ||
| let x_t = x.transpose(Some(&[0, 2, 1, 3]))?; | ||
| let x_t = apply_rope(&x_t, head_dim as u32, theta, offset)?; | ||
| return x_t.transpose(Some(&[0, 2, 1, 3])); | ||
| } | ||
|
|
||
| // Split: rotated part + pass-through part | ||
| let x_rot = x.slice_axis(3, 0, rope_dims)?; | ||
| let x_pass = x.slice_axis(3, rope_dims, head_dim)?; | ||
|
|
||
| // Apply RoPE to rotated part only (transpose to [B, H, T, D] for apply_rope) | ||
| let x_rot = x_rot.transpose(Some(&[0, 2, 1, 3]))?; | ||
| let x_rot = apply_rope(&x_rot, rope_dims as u32, theta, offset)?; | ||
| let x_rot = x_rot.transpose(Some(&[0, 2, 1, 3]))?; | ||
|
|
||
| // Concatenate back along head_dim axis | ||
| MxArray::concatenate(&x_rot, &x_pass, 3) | ||
| } | ||
|
|
||
| /// Qwen3.5 dense decoder block (functional). | ||
| fn qwen3_5_block_functional( | ||
| params: &HashMap<String, MxArray>, | ||
| x: &MxArray, | ||
| config: &Qwen3_5Config, | ||
| layer_idx: usize, | ||
| ) -> Result<MxArray> { | ||
| let prefix = format!("layers.{}", layer_idx); | ||
|
|
||
| // Pre-norm + attention | ||
| let input_norm_weight = params | ||
| .get(&format!("{}.input_layernorm.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.input_layernorm.weight", prefix)))?; | ||
| let normed = rms_norm_functional(x, input_norm_weight, config.rms_norm_eps)?; | ||
|
|
||
| let attn_out = if config.is_linear_layer(layer_idx) { | ||
| let attn_prefix = format!("{}.linear_attn", prefix); | ||
| gated_delta_net_functional(params, &normed, &attn_prefix, config)? | ||
| } else { | ||
| let attn_prefix = format!("{}.self_attn", prefix); | ||
| qwen3_5_attention_functional(params, &normed, &attn_prefix, config)? | ||
| }; | ||
|
|
||
| // Residual | ||
| let h = x.add(&attn_out)?; | ||
|
|
||
| // Pre-norm + MLP | ||
| let post_norm_weight = params | ||
| .get(&format!("{}.post_attention_layernorm.weight", prefix)) | ||
| .ok_or_else(|| { | ||
| Error::from_reason(format!( | ||
| "Missing {}.post_attention_layernorm.weight", | ||
| prefix | ||
| )) | ||
| })?; | ||
| let normed = rms_norm_functional(&h, post_norm_weight, config.rms_norm_eps)?; | ||
| let mlp_out = mlp_functional( | ||
| &normed, | ||
| params | ||
| .get(&format!("{}.mlp.gate_proj.weight", prefix)) | ||
| .ok_or_else(|| { | ||
| Error::from_reason(format!("Missing {}.mlp.gate_proj.weight", prefix)) | ||
| })?, | ||
| params | ||
| .get(&format!("{}.mlp.up_proj.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.mlp.up_proj.weight", prefix)))?, | ||
| params | ||
| .get(&format!("{}.mlp.down_proj.weight", prefix)) | ||
| .ok_or_else(|| { | ||
| Error::from_reason(format!("Missing {}.mlp.down_proj.weight", prefix)) | ||
| })?, | ||
| )?; | ||
|
|
||
| h.add(&mlp_out) | ||
| } | ||
|
|
||
| /// Apply LM head to hidden states: linear projection + logit clamping. | ||
| /// Shared by all model variants (Qwen3.5 Dense and MoE). | ||
| fn lm_head_functional( | ||
| hidden_states: &MxArray, | ||
| params: &HashMap<String, MxArray>, | ||
| tie_word_embeddings: bool, | ||
| ) -> Result<MxArray> { | ||
| let logits = if tie_word_embeddings { | ||
| let embed_weight = params | ||
| .get("embedding.weight") | ||
| .ok_or_else(|| Error::from_reason("Missing embedding.weight"))?; | ||
| linear_functional(hidden_states, embed_weight, None)? | ||
| } else { | ||
| let lm_head_weight = params | ||
| .get("lm_head.weight") | ||
| .ok_or_else(|| Error::from_reason("Missing lm_head.weight"))?; | ||
| linear_functional(hidden_states, lm_head_weight, None)? | ||
| }; | ||
| logits.clip(Some(-100.0), Some(100.0)) | ||
| } | ||
|
|
||
| /// Full Qwen3.5 Dense forward pass returning logits (functional). | ||
| pub fn qwen3_5_forward_functional( | ||
| config: &Qwen3_5Config, | ||
| params: &HashMap<String, MxArray>, | ||
| input_ids: &MxArray, | ||
| ) -> Result<MxArray> { | ||
| let hidden_states = qwen3_5_forward_hidden_states(config, params, input_ids)?; | ||
| lm_head_functional(&hidden_states, params, config.tie_word_embeddings) | ||
| } | ||
|
|
||
| /// Collect sorted parameter names that match a prefix (e.g., "layers.0.") | ||
| fn collect_layer_param_names(params: &HashMap<String, MxArray>, prefix: &str) -> Vec<String> { | ||
| let mut names: Vec<String> = params | ||
| .keys() | ||
| .filter(|k| k.starts_with(prefix)) | ||
| .cloned() | ||
| .collect(); | ||
| names.sort(); | ||
| names | ||
| } | ||
|
|
||
| /// Run a Qwen3.5 Dense block through gradient checkpointing. | ||
| /// | ||
| /// Flattens [hidden_states, layer_param1, layer_param2, ...] into a single | ||
| /// array vec for checkpoint, then reconstructs params inside the callback. | ||
| fn qwen3_5_block_checkpointed( | ||
| params: &HashMap<String, MxArray>, | ||
| h: &MxArray, | ||
| config: &Qwen3_5Config, | ||
| layer_idx: usize, | ||
| ckpt_contexts: &mut autograd::CheckpointContexts, | ||
| ) -> Result<MxArray> { | ||
| let prefix = format!("layers.{}.", layer_idx); | ||
| let layer_param_names = collect_layer_param_names(params, &prefix); | ||
|
|
||
| // Build inputs: [hidden_states, param1, param2, ...] | ||
| let mut inputs: Vec<&MxArray> = vec![h]; | ||
| for name in &layer_param_names { | ||
| inputs.push( | ||
| params | ||
| .get(name) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}", name)))?, | ||
| ); | ||
| } | ||
|
|
||
| let names_clone = layer_param_names.clone(); | ||
| let config_clone = config.clone(); | ||
| let layer = layer_idx; | ||
|
|
||
| let outputs = autograd::checkpoint_apply( | ||
| inputs, | ||
| move |arrays| { | ||
| // arrays[0] = hidden_states, arrays[1..] = layer params | ||
| let h_in = &arrays[0]; | ||
| let layer_params: HashMap<String, MxArray> = names_clone | ||
| .iter() | ||
| .enumerate() | ||
| .map(|(i, name)| (name.clone(), arrays[i + 1].clone())) | ||
| .collect(); | ||
| let h_out = qwen3_5_block_functional(&layer_params, h_in, &config_clone, layer)?; | ||
| Ok(vec![h_out]) | ||
| }, | ||
| ckpt_contexts, | ||
| )?; | ||
|
|
||
| Ok(outputs.into_iter().next().unwrap()) | ||
| } | ||
|
|
||
| /// Qwen3.5 Dense forward returning hidden states before LM head. | ||
| pub fn qwen3_5_forward_hidden_states( | ||
| config: &Qwen3_5Config, | ||
| params: &HashMap<String, MxArray>, | ||
| input_ids: &MxArray, | ||
| ) -> Result<MxArray> { | ||
| let mut ckpt = autograd::CheckpointContexts::new(); | ||
| qwen3_5_forward_hidden_states_impl(config, params, input_ids, false, &mut ckpt) | ||
| } | ||
|
|
||
| /// Qwen3.5 Dense forward with optional gradient checkpointing. | ||
| pub fn qwen3_5_forward_hidden_states_impl( | ||
| config: &Qwen3_5Config, | ||
| params: &HashMap<String, MxArray>, | ||
| input_ids: &MxArray, | ||
| use_checkpointing: bool, | ||
| ckpt_contexts: &mut autograd::CheckpointContexts, | ||
| ) -> Result<MxArray> { | ||
| // Embedding | ||
| let embed_weight = params | ||
| .get("embedding.weight") | ||
| .ok_or_else(|| Error::from_reason("Missing embedding.weight"))?; | ||
| let mut h = embedding_functional(embed_weight, input_ids)?; | ||
|
|
||
| // Transformer blocks — NO eval() between layers! | ||
| // During value_and_grad tracing, eval() would materialize data without calling | ||
| // detach() (because is_tracer() is true), preventing checkpoint from freeing | ||
| // intermediates. The lazy graph is built here; the final eval() (outside tracing) | ||
| // processes it with proper detach, freeing each layer's intermediates in turn. | ||
| for layer_idx in 0..config.num_layers as usize { | ||
| if use_checkpointing { | ||
| h = qwen3_5_block_checkpointed(params, &h, config, layer_idx, ckpt_contexts)?; | ||
| } else { | ||
| h = qwen3_5_block_functional(params, &h, config, layer_idx)?; | ||
| } | ||
| } | ||
|
|
||
| // Final norm | ||
| let final_norm_weight = params | ||
| .get("final_norm.weight") | ||
| .ok_or_else(|| Error::from_reason("Missing final_norm.weight"))?; | ||
| let result = rms_norm_functional(&h, final_norm_weight, config.rms_norm_eps)?; | ||
| Ok(result) | ||
| } | ||
|
|
||
| // ============================================ | ||
| // Qwen3.5 MoE Model Forward (Functional) | ||
| // ============================================ | ||
|
|
||
| /// Helper to get a parameter by prefix.suffix from the params map. | ||
| fn get_param<'a>( | ||
| params: &'a HashMap<String, MxArray>, | ||
| prefix: &str, | ||
| suffix: &str, | ||
| ) -> Result<&'a MxArray> { | ||
| let key = format!("{}.{}", prefix, suffix); | ||
| params | ||
| .get(&key) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}", key))) | ||
| } | ||
|
|
||
| struct GatherSortResult { | ||
| x_sorted: MxArray, | ||
| idx_sorted: MxArray, | ||
| inv_order: MxArray, | ||
| } | ||
|
|
||
| /// Sort tokens by expert assignment for efficient gather_mm. | ||
| /// Replicates Python `_gather_sort` from mlx-lm switch_layers.py. | ||
| fn functional_gather_sort(x: &MxArray, indices: &MxArray) -> Result<GatherSortResult> { | ||
| let idx_shape = indices.shape()?; | ||
| let m = *idx_shape | ||
| .last() | ||
| .ok_or_else(|| Error::from_reason("empty indices"))?; | ||
|
|
||
| let flat_indices = indices.reshape(&[-1])?; | ||
| let order = flat_indices.argsort(Some(-1))?; | ||
| let inv_order = order.argsort(Some(-1))?; | ||
| let idx_sorted = flat_indices.take(&order, 0)?; | ||
|
|
||
| let x_shape = x.shape()?; | ||
| let d = *x_shape | ||
| .last() | ||
| .ok_or_else(|| Error::from_reason("gather_sort: x has empty shape"))?; | ||
| let x_flat = x.reshape(&[-1, 1, d])?; | ||
| let m_scalar = MxArray::scalar_int(m as i32)?; | ||
| let token_indices = order.floor_divide(&m_scalar)?; | ||
| let x_sorted = x_flat.take(&token_indices, 0)?; | ||
|
|
||
| Ok(GatherSortResult { | ||
| x_sorted, | ||
| idx_sorted, | ||
| inv_order, | ||
| }) | ||
| } | ||
|
|
||
| /// Unsort gather_mm output back to original token order. | ||
| fn functional_scatter_unsort( | ||
| x: &MxArray, | ||
| inv_order: &MxArray, | ||
| orig_shape: &[i64], | ||
| ) -> Result<MxArray> { | ||
| let unsorted = x.take(inv_order, 0)?; | ||
| let x_shape = unsorted.shape()?; | ||
| let mut new_shape = orig_shape.to_vec(); | ||
| for &dim in &x_shape[1..] { | ||
| new_shape.push(dim); | ||
| } | ||
| unsorted.reshape(&new_shape) | ||
| } | ||
|
|
||
| /// Sparse MoE routing and expert computation (functional). | ||
| /// | ||
| /// Uses `gather_mm` for efficient expert-indexed matmuls instead of looping | ||
| /// over all experts. Only computes matmuls for the top-k routed experts per | ||
| /// token (~16x speedup for 128 experts, top-8). | ||
| /// | ||
| /// `gather_mm` has full VJP support in MLX, so this is fully differentiable. | ||
| fn sparse_moe_functional( | ||
| params: &HashMap<String, MxArray>, | ||
| x: &MxArray, | ||
| prefix: &str, | ||
| config: &Qwen3_5MoeConfig, | ||
| ) -> Result<MxArray> { | ||
| let batch = x.shape_at(0)?; | ||
| let seq_len = x.shape_at(1)?; | ||
| let hidden_size = config.hidden_size as i64; | ||
| let num_experts = config.num_experts; | ||
| let num_experts_per_tok = config.num_experts_per_tok; | ||
| let ne = batch * seq_len; | ||
| let k = num_experts_per_tok; | ||
| let num_exp = num_experts as i64; | ||
|
|
||
| let x_flat = x.reshape(&[ne, hidden_size])?; | ||
|
|
||
| // Router: softmax(gate(x)) -> top-k | ||
| let gate_weight = get_param(params, prefix, "gate.weight")?; | ||
| let router_logits = linear_functional(&x_flat, gate_weight, None)?; | ||
| let router_weights = Activations::softmax(&router_logits, Some(-1))?; | ||
|
|
||
| // Top-k selection via argpartition | ||
| let top_indices_full = router_weights.argpartition(-k, Some(-1))?; | ||
| let top_indices = top_indices_full.slice_axis(1, num_exp - k as i64, num_exp)?; | ||
| let scores = router_weights.take_along_axis(&top_indices, -1)?; | ||
|
|
||
| // Normalize top-k weights | ||
| let scores = if config.norm_topk_prob { | ||
| let sum = scores.sum(Some(&[-1]), Some(true))?; | ||
| scores.div(&sum)? | ||
| } else { | ||
| scores | ||
| }; | ||
|
|
||
| // Expert computation using gather_mm | ||
| let gate_proj_w = get_param(params, prefix, "switch_mlp.gate_proj.weight")?; | ||
| let up_proj_w = get_param(params, prefix, "switch_mlp.up_proj.weight")?; | ||
| let down_proj_w = get_param(params, prefix, "switch_mlp.down_proj.weight")?; | ||
|
|
||
| // Transpose weights: [E, out, in] -> [E, in, out] (gather_mm convention) | ||
| let gate_proj_t = gate_proj_w.transpose(Some(&[0, 2, 1]))?; | ||
| let up_proj_t = up_proj_w.transpose(Some(&[0, 2, 1]))?; | ||
| let down_proj_t = down_proj_w.transpose(Some(&[0, 2, 1]))?; | ||
|
|
||
| // Expand x for gather_mm: [ne, D] -> [ne, 1, 1, D] | ||
| let x_expanded = x_flat.reshape(&[ne, 1, 1, hidden_size])?; | ||
|
|
||
| // stop_gradient on indices (training: don't differentiate through discrete index selection) | ||
| let top_indices = top_indices.stop_gradient()?; | ||
|
|
||
| // Sort optimization (same threshold as stateful SwitchGLU in switch_glu.rs) | ||
| let do_sort = top_indices.size()? >= 64; | ||
|
|
||
| let y = if do_sort { | ||
| let sorted = functional_gather_sort(&x_expanded, &top_indices)?; | ||
| let idx = &sorted.idx_sorted; | ||
| let gate_out = sorted.x_sorted.gather_mm(&gate_proj_t, idx, true)?; | ||
| let up_out = sorted.x_sorted.gather_mm(&up_proj_t, idx, true)?; | ||
| let gate_act = Activations::silu_for_autograd(&gate_out)?; | ||
| let activated = gate_act.mul(&up_out)?; | ||
| let expert_out = activated.gather_mm(&down_proj_t, idx, true)?; | ||
| functional_scatter_unsort(&expert_out, &sorted.inv_order, &[ne, k as i64])? | ||
| } else { | ||
| let gate_out = x_expanded.gather_mm(&gate_proj_t, &top_indices, false)?; | ||
| let up_out = x_expanded.gather_mm(&up_proj_t, &top_indices, false)?; | ||
| let gate_act = Activations::silu_for_autograd(&gate_out)?; | ||
| let activated = gate_act.mul(&up_out)?; | ||
| activated.gather_mm(&down_proj_t, &top_indices, false)? | ||
| }; | ||
|
|
||
| // Squeeze penultimate dim, weight by routing scores, sum over top-k | ||
| let y = y.squeeze(Some(&[-2]))?; // [ne, k, D] | ||
| let scores_expanded = scores.reshape(&[ne, k as i64, 1])?; | ||
| let expert_output = y.mul(&scores_expanded)?.sum(Some(&[1]), Some(false))?; // [ne, D] | ||
|
|
||
| // Shared expert (unchanged — dense MLP, always-on) | ||
| let shared_gate = get_param(params, prefix, "shared_expert.gate_proj.weight")?; | ||
| let shared_up = get_param(params, prefix, "shared_expert.up_proj.weight")?; | ||
| let shared_down = get_param(params, prefix, "shared_expert.down_proj.weight")?; | ||
| let shared_out = mlp_functional(&x_flat, shared_gate, shared_up, shared_down)?; | ||
|
|
||
| // Shared expert gate | ||
| let shared_expert_gate_weight = get_param(params, prefix, "shared_expert_gate.weight")?; | ||
| let gate_out = linear_functional(&x_flat, shared_expert_gate_weight, None)?; | ||
| let gate_sigmoid = Activations::sigmoid(&gate_out)?; | ||
| let shared_gated = shared_out.mul(&gate_sigmoid)?; | ||
|
|
||
| // Combine expert + shared | ||
| let combined = expert_output.add(&shared_gated)?; | ||
| combined.reshape(&[batch, seq_len, hidden_size]) | ||
| } | ||
|
|
||
| /// Qwen3.5 MoE decoder block (functional). | ||
| fn qwen3_5_moe_block_functional( | ||
| params: &HashMap<String, MxArray>, | ||
| x: &MxArray, | ||
| config: &Qwen3_5MoeConfig, | ||
| dense_config: &Qwen3_5Config, | ||
| layer_idx: usize, | ||
| ) -> Result<MxArray> { | ||
| let prefix = format!("layers.{}", layer_idx); | ||
|
|
||
| // Pre-norm + attention (same as dense) | ||
| let input_norm_weight = params | ||
| .get(&format!("{}.input_layernorm.weight", prefix)) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}.input_layernorm.weight", prefix)))?; | ||
| let normed = rms_norm_functional(x, input_norm_weight, config.rms_norm_eps)?; | ||
|
|
||
| let attn_out = if config.is_linear_layer(layer_idx) { | ||
| let attn_prefix = format!("{}.linear_attn", prefix); | ||
| gated_delta_net_functional(params, &normed, &attn_prefix, dense_config)? | ||
| } else { | ||
| let attn_prefix = format!("{}.self_attn", prefix); | ||
| qwen3_5_attention_functional(params, &normed, &attn_prefix, dense_config)? | ||
| }; | ||
|
|
||
| let h = x.add(&attn_out)?; | ||
|
|
||
| // Pre-norm + MLP (MoE or dense depending on layer) | ||
| let post_norm_weight = params | ||
| .get(&format!("{}.post_attention_layernorm.weight", prefix)) | ||
| .ok_or_else(|| { | ||
| Error::from_reason(format!( | ||
| "Missing {}.post_attention_layernorm.weight", | ||
| prefix | ||
| )) | ||
| })?; | ||
| let normed = rms_norm_functional(&h, post_norm_weight, config.rms_norm_eps)?; | ||
|
|
||
| let mlp_out = if config.is_moe_layer(layer_idx) { | ||
| let mlp_prefix = format!("{}.mlp", prefix); | ||
| sparse_moe_functional(params, &normed, &mlp_prefix, config)? | ||
| } else { | ||
| mlp_functional( | ||
| &normed, | ||
| params | ||
| .get(&format!("{}.mlp.gate_proj.weight", prefix)) | ||
| .ok_or_else(|| { | ||
| Error::from_reason(format!("Missing {}.mlp.gate_proj.weight", prefix)) | ||
| })?, | ||
| params | ||
| .get(&format!("{}.mlp.up_proj.weight", prefix)) | ||
| .ok_or_else(|| { | ||
| Error::from_reason(format!("Missing {}.mlp.up_proj.weight", prefix)) | ||
| })?, | ||
| params | ||
| .get(&format!("{}.mlp.down_proj.weight", prefix)) | ||
| .ok_or_else(|| { | ||
| Error::from_reason(format!("Missing {}.mlp.down_proj.weight", prefix)) | ||
| })?, | ||
| )? | ||
| }; | ||
|
|
||
| h.add(&mlp_out) | ||
| } | ||
|
|
||
| /// Full Qwen3.5 MoE forward pass returning logits (functional). | ||
| pub fn qwen3_5_moe_forward_functional( | ||
| config: &Qwen3_5MoeConfig, | ||
| params: &HashMap<String, MxArray>, | ||
| input_ids: &MxArray, | ||
| ) -> Result<MxArray> { | ||
| let hidden_states = qwen3_5_moe_forward_hidden_states(config, params, input_ids)?; | ||
| lm_head_functional(&hidden_states, params, config.tie_word_embeddings) | ||
| } | ||
|
|
||
| /// Run a Qwen3.5 MoE block through gradient checkpointing. | ||
| fn qwen3_5_moe_block_checkpointed( | ||
| params: &HashMap<String, MxArray>, | ||
| h: &MxArray, | ||
| config: &Qwen3_5MoeConfig, | ||
| dense_config: &Qwen3_5Config, | ||
| layer_idx: usize, | ||
| ckpt_contexts: &mut autograd::CheckpointContexts, | ||
| ) -> Result<MxArray> { | ||
| let prefix = format!("layers.{}.", layer_idx); | ||
| let layer_param_names = collect_layer_param_names(params, &prefix); | ||
|
|
||
| let mut inputs: Vec<&MxArray> = vec![h]; | ||
| for name in &layer_param_names { | ||
| inputs.push( | ||
| params | ||
| .get(name) | ||
| .ok_or_else(|| Error::from_reason(format!("Missing {}", name)))?, | ||
| ); | ||
| } | ||
|
|
||
| let names_clone = layer_param_names.clone(); | ||
| let config_clone = config.clone(); | ||
| let dense_clone = dense_config.clone(); | ||
| let layer = layer_idx; | ||
|
|
||
| let outputs = autograd::checkpoint_apply( | ||
| inputs, | ||
| move |arrays| { | ||
| let h_in = &arrays[0]; | ||
| let layer_params: HashMap<String, MxArray> = names_clone | ||
| .iter() | ||
| .enumerate() | ||
| .map(|(i, name)| (name.clone(), arrays[i + 1].clone())) | ||
| .collect(); | ||
| let h_out = qwen3_5_moe_block_functional( | ||
| &layer_params, | ||
| h_in, | ||
| &config_clone, | ||
| &dense_clone, | ||
| layer, | ||
| )?; | ||
| Ok(vec![h_out]) | ||
| }, | ||
| ckpt_contexts, | ||
| )?; | ||
|
|
||
| Ok(outputs.into_iter().next().unwrap()) | ||
| } | ||
|
|
||
| /// Qwen3.5 MoE forward returning hidden states. | ||
| pub fn qwen3_5_moe_forward_hidden_states( | ||
| config: &Qwen3_5MoeConfig, | ||
| params: &HashMap<String, MxArray>, | ||
| input_ids: &MxArray, | ||
| ) -> Result<MxArray> { | ||
| let mut ckpt = autograd::CheckpointContexts::new(); | ||
| qwen3_5_moe_forward_hidden_states_impl(config, params, input_ids, false, &mut ckpt) | ||
| } | ||
|
|
||
| /// Qwen3.5 MoE forward with optional gradient checkpointing. | ||
| pub fn qwen3_5_moe_forward_hidden_states_impl( | ||
| config: &Qwen3_5MoeConfig, | ||
| params: &HashMap<String, MxArray>, | ||
| input_ids: &MxArray, | ||
| use_checkpointing: bool, | ||
| ckpt_contexts: &mut autograd::CheckpointContexts, | ||
| ) -> Result<MxArray> { | ||
| let embed_weight = params | ||
| .get("embedding.weight") | ||
| .ok_or_else(|| Error::from_reason("Missing embedding.weight"))?; | ||
| let mut h = embedding_functional(embed_weight, input_ids)?; | ||
|
|
||
| let dense_config = config.to_dense_config(); | ||
| for layer_idx in 0..config.num_layers as usize { | ||
| if use_checkpointing { | ||
| h = qwen3_5_moe_block_checkpointed( | ||
| params, | ||
| &h, | ||
| config, | ||
| &dense_config, | ||
| layer_idx, | ||
| ckpt_contexts, | ||
| )?; | ||
| } else { | ||
| h = qwen3_5_moe_block_functional(params, &h, config, &dense_config, layer_idx)?; | ||
| } | ||
| } | ||
|
|
||
| let final_norm_weight = params | ||
| .get("final_norm.weight") | ||
| .ok_or_else(|| Error::from_reason("Missing final_norm.weight"))?; | ||
| rms_norm_functional(&h, final_norm_weight, config.rms_norm_eps) | ||
| } | ||
|
|
||
| // ============================================ | ||
| // Unified Model Dispatch (for autograd) | ||
| // ============================================ | ||
|
|
||
| /// Dispatch functional forward pass based on model type. | ||
| pub(crate) fn forward_functional_dispatch( | ||
| model_type: &ModelType, | ||
| params: &HashMap<String, MxArray>, | ||
| input_ids: &MxArray, | ||
| use_checkpointing: bool, | ||
| ckpt_contexts: &mut autograd::CheckpointContexts, | ||
| ) -> Result<MxArray> { | ||
| let hidden_states = forward_hidden_states_dispatch( | ||
| model_type, | ||
| params, | ||
| input_ids, | ||
| use_checkpointing, | ||
| ckpt_contexts, | ||
| )?; | ||
| lm_head_functional(&hidden_states, params, model_type.tie_word_embeddings()) | ||
| } | ||
|
|
||
| /// Dispatch forward pass returning hidden states with optional checkpointing. | ||
| pub(crate) fn forward_hidden_states_dispatch( | ||
| model_type: &ModelType, | ||
| params: &HashMap<String, MxArray>, | ||
| input_ids: &MxArray, | ||
| use_checkpointing: bool, | ||
| ckpt_contexts: &mut autograd::CheckpointContexts, | ||
| ) -> Result<MxArray> { | ||
| match model_type { | ||
| ModelType::Qwen3(config) => qwen3_forward_hidden_states_impl( | ||
| config, | ||
| params, | ||
| input_ids, | ||
| use_checkpointing, | ||
| ckpt_contexts, | ||
| ), | ||
| ModelType::Qwen35Dense(config) => qwen3_5_forward_hidden_states_impl( | ||
| config, | ||
| params, | ||
| input_ids, | ||
| use_checkpointing, | ||
| ckpt_contexts, | ||
| ), | ||
| ModelType::Qwen35Moe(config) => qwen3_5_moe_forward_hidden_states_impl( | ||
| config, | ||
| params, | ||
| input_ids, | ||
| use_checkpointing, | ||
| ckpt_contexts, | ||
| ), | ||
| } | ||
| } |
There was a problem hiding this comment.
Add baseline tests for the new Qwen3.5 Dense/MoE functional paths.
This PR introduces substantial new forward/dispatch/checkpoint logic for Qwen3.5 Dense and MoE, but this file’s tests still validate only Qwen3 paths. Please add at least baseline shape + checkpoint on/off equivalence smoke tests for the new public entry points and dispatch variants.
Based on learnings Shape correctness and cache behavior validation are considered sufficient baseline testing for initial model ports.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@crates/mlx-core/src/utils/functional.rs` around lines 824 - 1677, Add
baseline unit tests that cover the new Qwen3.5 Dense and MoE functional entry
points and dispatcher variants: call qwen3_5_forward_functional,
qwen3_5_moe_forward_functional, forward_functional_dispatch and
forward_hidden_states_dispatch with small synthetic inputs and minimal params to
assert output shapes match expectations and that outputs are equal with
use_checkpointing true/false; include tests for tied vs untied lm_head behavior
and for dispatching each ModelType variant to ensure the correct path runs
(Qwen35Dense/Qwen35Moe), and ensure checkpointed helpers
qwen3_5_block_checkpointed / qwen3_5_moe_block_checkpointed are exercised
indirectly via the use_checkpointing flag. Ensure tests are minimal smoke tests
(shape + checkpoint equivalence) and placed alongside existing functional tests.
| // Stop gradient: detach tensor from computation graph | ||
| mlx_array* mlx_stop_gradient(mlx_array* a) { | ||
| try { | ||
| auto arr = reinterpret_cast<mlx::core::array*>(a); | ||
| auto result = mlx::core::stop_gradient(*arr); | ||
| return reinterpret_cast<mlx_array*>(new mlx::core::array(std::move(result))); | ||
| } catch (const std::exception& e) { | ||
| std::cerr << "mlx_stop_gradient error: " << e.what() << std::endl; | ||
| return nullptr; | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Step 1: Verify file existence and structure
echo "=== Checking mlx_misc_ops.cpp ==="
ls -la crates/mlx-sys/src/mlx_misc_ops.cpp 2>/dev/null || echo "File not found"
# Step 2: Get file info
if [ -f crates/mlx-sys/src/mlx_misc_ops.cpp ]; then
echo ""
echo "=== File size ==="
wc -l crates/mlx-sys/src/mlx_misc_ops.cpp
echo ""
echo "=== Lines 591-601 ==="
sed -n '591,601p' crates/mlx-sys/src/mlx_misc_ops.cpp | cat -n
fi
# Step 3: List all mlx-sys src files to understand structure
echo ""
echo "=== All mlx-sys src C++ files ==="
ls -la crates/mlx-sys/src/*.cpp 2>/dev/null | awk '{print $NF}'Repository: mlx-node/mlx-node
Length of output: 1233
🏁 Script executed:
#!/bin/bash
# Step 4: Check git history to see if mlx_misc_ops.cpp is new
echo "=== Git history for mlx_misc_ops.cpp ==="
git log --oneline --follow crates/mlx-sys/src/mlx_misc_ops.cpp 2>/dev/null | head -5
# Step 5: Find the split commit
echo ""
echo "=== Checking commit 9f60db7 ==="
git show 9f60db7 --stat 2>/dev/null | head -20Repository: mlx-node/mlx-node
Length of output: 217
🏁 Script executed:
#!/bin/bash
# Step 6: Check hardening patterns in other functions from mlx_misc_ops.cpp
echo "=== First 5 extern C functions in mlx_misc_ops.cpp ==="
rg 'extern "C"' crates/mlx-sys/src/mlx_misc_ops.cpp -A 15 | head -100
# Step 7: Check how many functions have proper hardening (null guard + catch(...))
echo ""
echo "=== Checking for null guards in mlx_misc_ops.cpp ==="
grep -n 'if (!' crates/mlx-sys/src/mlx_misc_ops.cpp | head -10Repository: mlx-node/mlx-node
Length of output: 721
🏁 Script executed:
#!/bin/bash
# Step 8: Compare exception handling across files
echo "=== Exception patterns in mlx.cpp (first file, established) ==="
grep -c 'catch (...)' crates/mlx-sys/src/mlx.cpp
grep -c 'catch (const std::exception&' crates/mlx-sys/src/mlx.cpp
grep -c '\[MLX\]' crates/mlx-sys/src/mlx.cpp
echo ""
echo "=== Exception patterns in mlx_misc_ops.cpp (new file) ==="
grep -c 'catch (...)' crates/mlx-sys/src/mlx_misc_ops.cpp
grep -c 'catch (const std::exception&' crates/mlx-sys/src/mlx_misc_ops.cpp
grep -c '\[MLX\]' crates/mlx-sys/src/mlx_misc_ops.cppRepository: mlx-node/mlx-node
Length of output: 386
🏁 Script executed:
#!/bin/bash
# Verify mlx_synchronize and mlx_clear_cache to confirm they have full hardening
echo "=== mlx_synchronize function (for hardening pattern reference) ==="
sed -n '1,30p' crates/mlx-sys/src/mlx_misc_ops.cpp | cat -n
echo ""
echo "=== Check if mlx_stop_gradient has null guard somewhere ==="
sed -n '591,610p' crates/mlx-sys/src/mlx_misc_ops.cpp | cat -nRepository: mlx-node/mlx-node
Length of output: 1868
🏁 Script executed:
#!/bin/bash
# Double-check other functions in mlx_misc_ops.cpp for consistency
echo "=== Sample of functions with proper hardening (grep for [MLX] nearby) ==="
rg '\[MLX\]' crates/mlx-sys/src/mlx_misc_ops.cpp -B 5 -A 2 | head -40Repository: mlx-node/mlx-node
Length of output: 1181
Add null guard, [MLX] prefix, and catch(...) fallback to match hardening standards already applied in this file.
mlx_stop_gradient at lines 591–601 lacks the FFI safety measures applied to other functions in mlx_misc_ops.cpp. It will crash if passed a null handle or if a non-std::exception error occurs. Add the null check, [MLX] logging prefix, and exception fallback to prevent exceptions from crossing the Rust FFI boundary.
🛠️ Suggested fix
mlx_array* mlx_stop_gradient(mlx_array* a) {
- try {
- auto arr = reinterpret_cast<mlx::core::array*>(a);
- auto result = mlx::core::stop_gradient(*arr);
- return reinterpret_cast<mlx_array*>(new mlx::core::array(std::move(result)));
- } catch (const std::exception& e) {
- std::cerr << "mlx_stop_gradient error: " << e.what() << std::endl;
- return nullptr;
- }
+ try {
+ if (!a) {
+ std::cerr << "[MLX] Null handle in mlx_stop_gradient" << std::endl;
+ return nullptr;
+ }
+ auto arr = reinterpret_cast<mlx::core::array*>(a);
+ auto result = mlx::core::stop_gradient(*arr);
+ return reinterpret_cast<mlx_array*>(new mlx::core::array(std::move(result)));
+ } catch (const std::exception& e) {
+ std::cerr << "[MLX] Exception in mlx_stop_gradient: " << e.what() << std::endl;
+ return nullptr;
+ } catch (...) {
+ std::cerr << "[MLX] Unknown exception in mlx_stop_gradient" << std::endl;
+ return nullptr;
+ }
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@crates/mlx-sys/src/mlx_misc_ops.cpp` around lines 591 - 601, Add FFI
hardening to mlx_stop_gradient: first check the incoming mlx_array* a for
nullptr and return nullptr immediately if null; when logging errors use the
"[MLX]" prefix in the std::cerr message; catch both std::exception (logging
e.what() with "[MLX]" prefix) and a catch(...) fallback that logs a generic
"[MLX] unknown error" and returns nullptr; keep existing use of reinterpret_cast
and mlx::core::stop_gradient/result creation but ensure all exceptions are
handled and no exceptions cross the FFI boundary.
| export async function detectModelType(modelPath: string): Promise<string> { | ||
| try { | ||
| const raw = await readFile(join(modelPath, 'config.json'), 'utf-8'); | ||
| const config = JSON.parse(raw); | ||
| return config.model_type ?? 'qwen3'; | ||
| } catch { | ||
| return 'qwen3'; | ||
| throw new Error(`Cannot detect model type: config.json not found in ${modelPath}`); | ||
| } |
There was a problem hiding this comment.
Don’t report every detection failure as “config.json not found”.
The current catch path also masks JSON parse and read-permission errors with an incorrect message, which makes troubleshooting harder.
Proposed fix
export async function detectModelType(modelPath: string): Promise<string> {
+ const configPath = join(modelPath, 'config.json');
+ let raw: string;
try {
- const raw = await readFile(join(modelPath, 'config.json'), 'utf-8');
- const config = JSON.parse(raw);
- return config.model_type ?? 'qwen3';
- } catch {
- throw new Error(`Cannot detect model type: config.json not found in ${modelPath}`);
+ raw = await readFile(configPath, 'utf-8');
+ } catch (error) {
+ const e = error as NodeJS.ErrnoException;
+ if (e?.code === 'ENOENT') {
+ throw new Error(`Cannot detect model type: config.json not found in ${modelPath}`);
+ }
+ const message = error instanceof Error ? error.message : String(error);
+ throw new Error(`Cannot detect model type: failed reading ${configPath}: ${message}`);
}
+
+ try {
+ const config = JSON.parse(raw) as { model_type?: unknown };
+ return typeof config.model_type === 'string' ? config.model_type : 'qwen3';
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ throw new Error(`Cannot detect model type: invalid JSON in ${configPath}: ${message}`);
+ }
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/lm/src/models/model-loader.ts` around lines 77 - 84, The catch block
in detectModelType incorrectly always throws "config.json not found", hiding
JSON parse or permission errors; change it to differentiate ENOENT (file
missing) from other errors by inspecting the caught error (e.g., error.code ===
'ENOENT') and throw a specific "config.json not found in <modelPath>" for that
case, but for other errors include the original error message (or rethrow) so
parse/permission errors are visible; keep the original behavior of reading
join(modelPath, 'config.json') and parsing JSON and returning config.model_type
?? 'qwen3'.
| // Save model weights | ||
| await this.model.saveModel(checkpointPath); |
There was a problem hiding this comment.
Save checkpoints via getModel() to avoid stale Qwen3 weights.
Line 557 saves this.model, but Line 637-639 treats the engine model as authoritative for Qwen3. This can serialize pre-training weights on Qwen3 paths.
💡 Proposed fix
- await this.model.saveModel(checkpointPath);
+ await this.getModel().saveModel(checkpointPath);Also applies to: 636-643
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/trl/src/trainers/sft-trainer.ts` around lines 556 - 557, The
checkpoint save is using this.model which can be stale for Qwen3; change the
save to use the authoritative model returned by getModel() (or engine.getModel()
if that is the canonical accessor) so that saveModel(checkpointPath) is invoked
on getModel() instead of this.model; update any other saves in the same area
(around the block referenced at lines 636-643) to call getModel().saveModel(...)
(or engine.getModel().saveModel(...)) to ensure Qwen3 weights are current.
The training system (GRPO + SFT) was hardcoded to Qwen3Model. This makes all three model families trainable through a unified internal trait. Architecture: - TrainableModel trait + TrainableModelEnum for engine-level polymorphism - ModelType enum for autograd dispatch to correct functional forward pass - Per-model training methods (get_parameters, apply_gradients, generate) - Functional forward passes for Qwen3.5 Dense (GDN + partial-RoPE attention) and MoE (gather_mm-based sparse expert routing) Key changes: - training_model.rs: TrainableModel trait, TrainableModelEnum, ModelType, compute_sgd_updates helper, dispatch macros - training_generate.rs: shared generation loop parameterized by forward closure - functional.rs: Qwen3.5 Dense/MoE functional forwards, gather_mm-based MoE (~16x fewer expert FLOPs vs per-expert loop), unified dispatch - gated_delta.rs: use_kernel flag for ops-based differentiable GDN path - Engine factories: GrpoTrainingEngine.fromQwen35/fromQwen35Moe, SftTrainingEngine.fromQwen35/fromQwen35Moe - TypeScript trainers accept Qwen3 | Qwen35 | Qwen35Moe union type - stop_gradient FFI binding for MoE routing index detachment Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **High Risk** > Touches core training/autograd and adds new unsafe FFI-backed paths (checkpointing, MoE ops) plus optimizer/state serialization; regressions could impact correctness, memory use, or training stability across multiple model families. > > **Overview** > **Model-agnostic training:** Refactors GRPO and SFT engines to train `Qwen3`, `Qwen3.5 Dense`, and `Qwen3.5 MoE` through a new internal `TrainableModel`/`TrainableModelEnum` plus `ModelType` for autograd functional-forward dispatch. > > **Memory + autograd improvements:** Adds MLX gradient checkpointing support via new `checkpoint_apply`/`CheckpointContexts` (with tests), plumbs a `gradient_checkpointing` config flag through GRPO/SFT, and fixes chunked-gradient accumulation to `eval()` after each add to avoid retaining per-chunk graphs. > > **Qwen3.5 training enablement:** Implements parameter extraction/apply-updates and training-generation paths for Qwen3.5 Dense/MoE (including shared generation utilities, kernel-vs-ops differentiable GDN path, and MoE helpers like `gather_mm` and `stop_gradient`), and adds model/optimizer save-load support (SafeTensors) for Qwen3.5 models plus AdamW optimizer state persistence/reset. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 533fd55. 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** * Added gradient checkpointing for memory-efficient training workflows * Extended training support to Qwen 3.5 Dense and Qwen 3.5 MoE models * Introduced model persistence with `saveModel()` functionality * Added optimizer state save/load capabilities * Added AdamW optimizer support for training <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>

The training system (GRPO + SFT) was hardcoded to Qwen3Model. This makes
all three model families trainable through a unified internal trait.
Architecture:
and MoE (gather_mm-based sparse expert routing)
Key changes:
compute_sgd_updates helper, dispatch macros
(~16x fewer expert FLOPs vs per-expert loop), unified dispatch
SftTrainingEngine.fromQwen35/fromQwen35Moe
Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]
Note
High Risk
Touches core training/autograd and adds new unsafe FFI-backed paths (checkpointing, MoE ops) plus optimizer/state serialization; regressions could impact correctness, memory use, or training stability across multiple model families.
Overview
Model-agnostic training: Refactors GRPO and SFT engines to train
Qwen3,Qwen3.5 Dense, andQwen3.5 MoEthrough a new internalTrainableModel/TrainableModelEnumplusModelTypefor autograd functional-forward dispatch.Memory + autograd improvements: Adds MLX gradient checkpointing support via new
checkpoint_apply/CheckpointContexts(with tests), plumbs agradient_checkpointingconfig flag through GRPO/SFT, and fixes chunked-gradient accumulation toeval()after each add to avoid retaining per-chunk graphs.Qwen3.5 training enablement: Implements parameter extraction/apply-updates and training-generation paths for Qwen3.5 Dense/MoE (including shared generation utilities, kernel-vs-ops differentiable GDN path, and MoE helpers like
gather_mmandstop_gradient), and adds model/optimizer save-load support (SafeTensors) for Qwen3.5 models plus AdamW optimizer state persistence/reset.Written by Cursor Bugbot for commit 533fd55. This will update automatically on new commits. Configure here.
Summary by CodeRabbit
saveModel()functionality