Repository navigation
feat: port Qwen3.5 dense + MoE model to Rust/NAPI - #19
Conversation
Implements the full Qwen3.5 hybrid architecture (GatedDeltaNet linear attention + gated full attention) with MoE support, ported from mlx-lm/mlx_lm/models/qwen3_5.py and qwen3_5_moe.py. New components: - FFI: conv1d and gather_mm C++ bridge functions - Conv1d: depthwise convolution wrapper for GatedDeltaNet - GatedDeltaNet: delta rule recurrence with GQA head expansion - Qwen3.5Attention: gated attention with partial RoPE (25%) - SparseMoeBlock: top-k expert routing with SwitchGLU + shared expert - SwitchLinear/SwitchGLU: gather_mm-based expert-indexed layers - RMSNormGated: per-head RMS norm with optional SwiGLU gating - ArraysCache: conv_state + recurrent_state for linear layers - Persistence: multi-shard safetensors with weight sanitization Key correctness fixes vs initial draft: - Delta rule recurrence (kv_mem retrieval + error correction) - Mask restores old state instead of zeroing output - GQA head expansion (Hk=16 → Hv=64) in recurrence - conv_dim = key_dim*2 + value_dim (q+k+v channels) - Per-head q/k RMS normalization with inv_scale^2 and inv_scale - Mask application before conv1d to prevent leakage - Zero-padding for conv_state on first pass - RMSNormGated dim = value_head_dim (128), not value_dim (8192) - Attention q_proj per-head interleaved split (not flat) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…t validation Major fixes across 4 review rounds: - Fix MoE weight-key rewrite producing invalid *.weight.weight keys by stripping trailing .weight before replacement in sanitize_weights - Fix float32 dtype drift in linear attention path — all zeros/ones/scalar calls now propagate input tensor dtype for bf16/f16 correctness - Strengthen checkpoint validation: per-layer completeness checks, require lm_head.weight when tie_word_embeddings=false, warn on missing norms - Fix numerically stable softplus (max(x,0) + log1p(exp(-|x|))) - Fix head_dim div-by-zero, conv1d formula, fa_idx underflow in model - Fix argpartition semantics and add epsilon to MoE weight normalization - Add input validation throughout (config, MoE experts, 3D shape checks) - Refactor decoder_layer is_linear from field to derived method - Rename TS exports: QWEN35_CONFIGS, getQwen35Config, loadQwen35 Co-Authored-By: Claude Opus 4.6 <[email protected]>
📝 WalkthroughWalkthroughAdds a full Qwen-3.5 implementation (dense + MoE) across Rust core, FFI, and JS bindings, plus Conv1d/gather_mm primitives, safetensors persistence, linear/GatedDeltaNet attention, MoE routing, TypeScript surfaces, and new unit tests for config, forward, generation, and MoE behavior. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client
participant Model as Qwen35Model
participant Layer as DecoderLayer
participant Attn as Attention
participant Cache as Cache
participant Sampler as Sampler
Client->>Model: generate(promptTokens, config)
Model->>Model: init_caches()
Model->>Cache: create per-layer caches
loop for each new token
Model->>Model: forward_with_cache(input_ids)
Model->>Layer: forward(x, cache)
Layer->>Attn: forward(x, cache)
alt linear attention
Attn->>Cache: use ArraysCache (gated_delta_update)
else full attention
Attn->>Cache: use KVCache (kv update + SDPA)
end
Attn-->>Layer: attention_output
Layer-->>Model: logits
Model->>Sampler: sample(logits)
Sampler-->>Model: next_token
end
Model-->>Client: GenerationResult(tokens, text, finish_reason)
sequenceDiagram
participant Client as Client
participant Model as Qwen35Model
participant FS as FileSystem
participant ST as SafeTensors
participant Applier as WeightApplier
Client->>Model: load_pretrained(path)
Model->>FS: read config.json
FS-->>Model: config.json
Model->>FS: discover weight files
Model->>ST: load safetensors (single/sharded)
ST-->>Model: raw tensors
Model->>Model: sanitize & stack weights (MoE handling)
Model->>Applier: apply weights to layers/components
Applier-->>Model: model ready
Model-->>Client: loaded model
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes 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)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 10
🧹 Nitpick comments (14)
examples/vlm-inference.ts (1)
36-37: LGTM — formatting-only change.The refactor is purely cosmetic; the conditional logic and default value are identical to before.
One pre-existing nit (not introduced by this PR):
parseFloat(args[thresholdIdx + 1])is evaluated twice — once inside!isNaN(…)and again as the truthy branch value. A local variable would avoid the redundant parse.🔧 Optional cleanup
-const threshold = - thresholdIdx !== -1 && !isNaN(parseFloat(args[thresholdIdx + 1])) ? parseFloat(args[thresholdIdx + 1]) : 0.5; +const _parsedThreshold = thresholdIdx !== -1 ? parseFloat(args[thresholdIdx + 1]) : NaN; +const threshold = !isNaN(_parsedThreshold) ? _parsedThreshold : 0.5;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/vlm-inference.ts` around lines 36 - 37, The threshold assignment redundantly calls parseFloat twice; compute a local variable (e.g., parsedThreshold) from parseFloat(args[thresholdIdx + 1]) once, use !isNaN(parsedThreshold) in the conditional and parsedThreshold as the true branch value for the threshold variable (while keeping the existing default 0.5 and the same thresholdIdx/args checks).__test__/models/qwen3_5-config.test.ts (1)
6-14: HardcodedvocabSizeassertion may be fragile if more configs are added.Line 9 asserts
vocabSize === 151936for every config inQWEN35_CONFIGS. This works today with a single config but could break if future Qwen3.5 variants have different vocabulary sizes. Consider assertingvocabSize > 0here and keeping the exact value check in the named config test below.Suggested change
for (const [_name, config] of Object.entries(QWEN35_CONFIGS)) { - expect(config.vocabSize).toBe(151936); + expect(config.vocabSize).toBeGreaterThan(0); expect(config.fullAttentionInterval).toBeGreaterThan(0);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@__test__/models/qwen3_5-config.test.ts` around lines 6 - 14, The test currently asserts a hardcoded vocabSize for every entry in QWEN35_CONFIGS which is brittle; update the loop in the 'should have valid config presets' test to check that config.vocabSize is a positive integer (e.g., > 0) instead of equal to 151936, while keeping any exact-value assertion for the specific named config test (leave that separate); locate the loop iterating over Object.entries(QWEN35_CONFIGS) and replace the equality check on vocabSize with a positivity check and optionally a Number.isInteger guard.__test__/models/qwen3_5-generation.test.ts (1)
7-21: Generation test uses the full 0.6B config — consider test execution time.Using
getQwen35Config('qwen3.5-0.6b')instantiates a model with 28 layers, hiddenSize=1024, and 151936 vocab. With random (untrained) weights, this may be acceptable for CI, but if test time becomes a concern, a smaller test-only config (like the one inqwen3_5-moe.test.ts) could speed things up significantly.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@__test__/models/qwen3_5-generation.test.ts` around lines 7 - 21, The test instantiates a full-size model via getQwen35Config('qwen3.5-0.6b') which increases CI time; change the test to use a smaller, test-only config (same pattern as qwen3_5-moe.test.ts) by replacing the config construction with a lightweight config generator (or a call to the existing small-test config helper) before creating the Qwen35Model instance in the 'should generate tokens from prompt' test so the prompt generation uses fewer layers/hiddenSize/vocab and runs much faster while preserving the same assertions around model.generate, result.tokens, result.numTokens, and result.finishReason.crates/mlx-core/src/models/qwen3_5/arrays_cache.rs (1)
58-63: ManualCloneimpl can be replaced with#[derive(Clone)].The manual
Cloneimplementation is identical to what#[derive(Clone)]would generate. Consider deriving it instead.♻️ Suggested simplification
+#[derive(Clone)] pub struct ArraysCache { cache: Vec<Option<MxArray>>, } - -impl Clone for ArraysCache { - fn clone(&self) -> Self { - Self { - cache: self.cache.clone(), - } - } -}🤖 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/arrays_cache.rs` around lines 58 - 63, The manual impl Clone for ArraysCache (the impl Clone block implementing fn clone that clones self.cache) is redundant; remove the impl Clone block and add #[derive(Clone)] to the ArraysCache struct declaration so the compiler generates the same clone behavior for the cache field automatically.crates/mlx-core/src/models/qwen3_5/switch_linear.rs (2)
67-73: ManualClonecan be replaced with#[derive(Clone)].Same as
ArraysCache— the manual impl is equivalent to the derived version.🤖 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/switch_linear.rs` around lines 67 - 73, Replace the manual impl Clone for SwitchLinear with a derived implementation: add #[derive(Clone)] to the SwitchLinear struct definition and remove the explicit impl Clone block (the current impl Clone for SwitchLinear and its clone method should be deleted); do the same style as ArraysCache for consistency so the compiler provides the equivalent clone behavior automatically.
14-23: Initialization scale usessqrt(2/fan_in)— verify this matches the intended distribution.The scale factor
(2.0 / input_dims).sqrt()corresponds to a Kaiming/He-style initialization, while many transformer implementations use1/sqrt(fan_in). Since pretrained weights will override this initialization anyway (viaset_weightorfrom_weight), it only matters for testing or fine-tuning from scratch. Worth confirming this matches the Python reference.🤖 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/switch_linear.rs` around lines 14 - 23, The constructor SwitchLinear::new currently computes scale = (2.0 / input_dims as f64).sqrt(), which implements a Kaiming-style initialization; change it to the transformer-style Xavier-ish scale = (1.0 / input_dims as f64).sqrt() (i.e. use 1/sqrt(fan_in)) if that matches the Python reference, and update the bounds passed into MxArray::random_uniform accordingly; locate the logic in the new(input_dims: u32, output_dims: u32, num_experts: u32) -> Result<Self> function and adjust the scale expression and any accompanying comment/tests to reflect the chosen distribution.crates/mlx-core/src/models/qwen3_5/attention.rs (1)
27-29: Minor:scalestored asf32but used asf64.
scaleis stored asf32(line 29) and converted tof64at the SDPA call site (line 163). Sincehead_dimis typically a power of 2, this doesn't cause precision issues in practice, but for consistency with thef64signature ofscaled_dot_product_attention, you could store it asf64directly.🤖 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/attention.rs` around lines 27 - 29, The struct's scale field is declared as f32 but scaled_dot_product_attention expects f64; change the scale field type from f32 to f64 (the field named scale) and update any places that construct or assign to that field (e.g., constructors/new functions or where scale is computed from head_dim) to produce an f64 directly so no cast is needed at the SDPA call site, and ensure any downstream uses that assumed f32 are updated to f64; keep the call site to scaled_dot_product_attention unchanged.crates/mlx-core/src/models/qwen3_5/persistence.rs (2)
656-807: Dual config-parsing paths (serde defaults vsparse_config) create a maintenance burden.
Qwen3_5ConfigderivesDeserializewith serde defaults, butload_pretraineduses the manualparse_configfunction instead. This means there are two parallel sets of defaults and key mappings that must be kept in sync. Currently they match, but future changes to defaults in one path but not the other would cause subtle bugs.Consider either:
- Using
serde_json::from_valuewith#[serde(alias = "...")]for alternative key names, letting serde handle everything.- Documenting that
parse_configis the canonical path and that serde defaults exist only for direct-deserialization consumers.🤖 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 656 - 807, The repository has duplicated config logic: parse_config manually parses JSON while Qwen3_5Config also derives Deserialize with serde defaults, causing maintenance drift; update load_pretrained to use serde_json::from_value to deserialize into Qwen3_5Config (annotate fields in Qwen3_5Config with #[serde(alias = "...")] for alternative keys like "num_attention_heads"/"num_heads" and provide defaults via #[serde(default = "…")] or #[serde(default)] so all defaults live in the struct; then remove or deprecate parse_config (or make it a thin wrapper that calls serde_json::from_value) and ensure places referencing parse_config or load_pretrained use the new serde path to avoid dual parsing logic.
586-654:load_pretrainedcorrectly usesspawn_blockingfor I/O but consider error context on the outer.await.The
spawn_blocking+.awaiton line 652–653 maps the join error but loses the original error's context chain. If the inner closure returnsErr(...), that error is returned directly. However, if the task panics, themap_erron line 653 wraps it in a generic "Failed to load model" message. This is fine for panics but consider whether theJoinErrormessage is sufficiently descriptive on its own.🤖 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 586 - 654, The outer .await on the napi::tokio::task::spawn_blocking in load_pretrained currently maps a JoinError to a generic Error and can lose join panic details; change the map_err on the awaited JoinHandle so it preserves the JoinError information (include the JoinError/message in the Error::from_reason text or chain it) — i.e., update the closure after .await to wrap the join error with a descriptive message like "Failed to load model (join error): {join_error}" so you keep the original join/panic context while still returning an napi::Error from load_pretrained.crates/mlx-core/src/models/qwen3_5/model.rs (2)
149-158:reset_cachesboth resets and drops caches.
reset_cachesiterates each cache callingcache.reset(), then immediately setsself.caches = None. The per-cachereset()calls are redundant since the entire vector is dropped on the next line. This is harmless but slightly misleading — the method name suggests "clear state but keep caches allocated" while it actually deallocates everything.♻️ Simplify to just drop
pub fn reset_caches(&mut self) { - if let Some(ref mut caches) = self.caches { - for cache in caches.iter_mut() { - cache.reset(); - } - } self.caches = None; }🤖 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 149 - 158, The method reset_caches currently calls cache.reset() for each entry and then immediately sets self.caches = None, which makes the per-cache resets redundant; in the reset_caches implementation remove the loop that iterates caches and calling cache.reset() and simply drop the vector by assigning self.caches = None (or, if intent is to keep allocated caches but clear state, replace the drop with caches.clear()); update the reset_caches function accordingly to reflect the chosen behavior.
468-480: All-ones SSM mask allocates a fresh tensor every forward call.
create_ssm_maskcreatesMxArray::ones(...)on each invocation. During generation with N layers × T decode steps, this is called repeatedly. Since the mask shape changes per call (different seq_len), caching requires a shape guard — but for the common decode case (seq_len=1), a cached [B, 1] ones tensor could be reused.🤖 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 468 - 480, create_ssm_mask currently allocates a fresh MxArray::ones([batch, seq_len], dtype) on every call; optimize by caching a reusable [batch, 1] mask for the common decode case (seq_len == 1). Add a field on the model struct (e.g., ssm_mask_single_step: Option<MxArray>) and in create_ssm_mask check seq_len; if seq_len == 1 verify the cached mask exists and matches batch and hidden_states.dtype(), return it (or update it) otherwise create MxArray::ones([batch,1], dtype), store it into ssm_mask_single_step and return Some(cached_mask); for seq_len != 1 keep the existing behaviour of returning a fresh MxArray::ones(...) to avoid wrong shapes. Ensure dtype and batch are validated before reusing the cached mask.crates/mlx-core/src/nn/conv1d.rs (1)
124-135: ManualCloneimpl is identical to derived one.All fields implement
Clone, so#[derive(Clone)]on the struct would be equivalent and less maintenance.♻️ Suggestion
+#[derive(Clone)] pub struct Conv1d { weight: MxArray, bias: Option<MxArray>, stride: i32, padding: i32, dilation: i32, groups: i32, } - -impl Clone for Conv1d { - fn clone(&self) -> Self { - Self { - weight: self.weight.clone(), - bias: self.bias.clone(), - stride: self.stride, - padding: self.padding, - dilation: self.dilation, - groups: self.groups, - } - } -}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/nn/conv1d.rs` around lines 124 - 135, The manual Clone implementation on Conv1d is redundant because all fields (weight, bias, stride, padding, dilation, groups) already implement Clone; remove the impl Clone block and add #[derive(Clone)] to the Conv1d struct definition so the compiler generates identical clone behavior automatically for Conv1d.crates/mlx-core/src/models/qwen3_5/gated_delta_net.rs (1)
309-321:rms_norm_no_weightallocates aonesvector on every call.This helper is invoked twice per forward pass (for q and k normalization). Each call allocates a fresh ones tensor. If this is in a hot path for long sequence generation, consider caching the ones tensor as a field on
GatedDeltaNet, keyed by the last-dim size and dtype.🤖 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/gated_delta_net.rs` around lines 309 - 321, The helper rms_norm_no_weight currently allocates a new ones MxArray on every call; move that allocation into GatedDeltaNet and cache it keyed by (last_dim, dtype) so repeated calls reuse the ones tensor. Add a field to GatedDeltaNet (e.g., ones_cache: HashMap<(usize, DType), MxArray> or ones_cache: HashMap<(usize, i32), MxArray> depending on how dtype is represented), update rms_norm_no_weight to accept &self or make it a GatedDeltaNet method, look up the ones vector by the tuple (last_dim, x.dtype()?) and only create and insert a new MxArray::ones if absent, then pass the cached ones.handle into sys::mlx_fast_rms_norm; ensure the cached MxArray is returned/cloned/borrowed in a way that preserves its handle lifetime when calling MxArray::from_handle.crates/mlx-core/src/models/qwen3_5/sparse_moe.rs (1)
141-169: Inconsistent return types across weight setters create silent error handling gaps.
set_gate_weightandset_shared_expert_*methods returnResult<()>, whileset_switch_mlp_*methods return(). This inconsistency stems from SwitchLinear::set_weight returning()without validation, unlike Linear::set_weight which returnsResult<()>with validation. Callers of theset_switch_mlp_*methods cannot detect or handle errors that might occur in the underlying setters, creating a silent failure mode inconsistent with the rest of the public API.Consider making SwitchLinear::set_weight return
Result<()>with proper validation to match the pattern used in Linear and other weight setters.🤖 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/sparse_moe.rs` around lines 141 - 169, The set_switch_mlp_* methods (set_switch_mlp_gate_proj_weight, set_switch_mlp_up_proj_weight, set_switch_mlp_down_proj_weight) currently return () while other setters like set_gate_weight and set_shared_expert_* return Result<()>, allowing callers to handle validation errors; update SwitchLinear::set_weight to return Result<()> and perform the same validation as Linear::set_weight (check shape/dtype/size and return Err on mismatch), then change the three set_switch_mlp_* methods to return Result<()> and propagate the Result from SwitchLinear::set_weight so failures surface consistently across the API.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@__test__/models/qwen3_5-forward.test.ts`:
- Around line 6-59: Update the tests for Qwen35Model to assert numeric
correctness and add batch/edge cases: for functions forward and forwardWithCache
(and using getQwen35Config, MxArray, model.initCaches, model.resetCaches)
compute reference logits from your trusted reference (PyTorch/MLX‑LM) for the
same inputs and compare model outputs with a small tolerance (e.g., max absolute
or relative difference); add cases with batch>1, very short and longer
sequences, and a partial-decode scenario where you prefill cache, decode a
token, call resetCaches(), then verify subsequent forward/forwardWithCache
outputs match the reference; ensure comparisons check a slice of logits (or
top-k) if full distribution is large and reuse a test helper like
getReferenceLogits to keep tests readable.
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 344-403: The num_parameters() function misses small learnable
params for GatedDeltaNet in the linear-attention branch; inside the for loop
where is_linear is true (in num_parameters), add counts for dt_bias and a_log
using self.config.linear_num_value_heads and for the layer norm weight using
self.config.linear_value_dim (or the appropriate linear value head dim) so the
linear branch increments total by + self.config.linear_num_value_heads as i64
(dt_bias) + self.config.linear_num_value_heads as i64 (a_log) +
self.config.linear_value_dim as i64 (norm.weight) alongside the existing
attention terms.
- Around line 197-290: The generate method is synchronous and will block the
Node.js main thread because it's exposed via #[napi]; convert it into an
asynchronous N-API task (implement napi::Task or napi::AsyncTask similar to the
Qwen3 implementation) so generation runs off the main thread. Specifically, move
the body of Qwen3_5::generate into a new struct implementing napi::Task (or
AsyncTask) that holds &mut self (or a clonable/owned engine handle),
prompt_tokens, and Qwen3_5GenerationConfig, implement compute to perform
reset_caches/init_caches, forward_with_cache loop, sampling and decoding, and
implement resolve to return Qwen3_5GenerationResult; then change the #[napi]
exported generate to spawn and return that Task to JS. Ensure lifetime/ownership
of model state (caches, tokenizer) is safely transferred or synchronized when
creating the task.
In `@crates/mlx-core/src/models/qwen3_5/persistence.rs`:
- Around line 455-556: Move the mandatory-weight validation to run before
apply_weights is invoked so we fail fast and avoid constructing/partially
populating the model when required keys are missing: validate the same sanitized
key set that apply_weights uses (check params for "embedding.weight",
"final_norm.weight", "lm_head.weight" per config.tie_word_embeddings, and
per-layer presence of attention/mlp keys using the same prefixes like
"layers.{i}.self_attn.q_proj.weight" /
"layers.{i}.linear_attn.in_proj_qkvz.weight" / "layers.{i}.mlp.gate_proj.weight"
etc.), and return the Error if missing; also stop relying solely on if let
Some(w) = params.get(...) silently skipping absent weights—either make
apply_weights return a Result and surface missing mandatory keys or have it
assert required keys were present after lookup so the earlier validation and
apply_weights use identical key logic and sanitization.
In `@crates/mlx-core/src/models/qwen3_5/rms_norm_gated.rs`:
- Around line 6-41: Add a manual backward for the RMSNormGated composite layer
in the gradients module: implement a function (e.g., rms_norm_gated_backward)
that takes upstream gradient d_out, inputs x and optional gate, plus the stored
weight/eps, calls the swiglu backward when gate is Some (using existing swiglu
backward to get gradients w.r.t. gate and the normalized output), then calls the
rms_norm backward (or the existing rms_norm gradient helper) on the
normalized-output gradient to produce gradients w.r.t. x and weight; ensure you
accumulate gradients correctly into grad_x, grad_gate (when present), and
grad_weight, mirror the forward signature used in RMSNormGated::forward, and
wire this new backward into the gradients dispatch so the autograd will call
rms_norm_gated_backward for the RMSNormGated layer.
In `@crates/mlx-core/src/nn/conv1d.rs`:
- Around line 22-64: The Conv1d::new constructor can panic on divide-by-zero
when groups is Some(0); validate the groups parameter early (e.g., after let
groups = groups.unwrap_or(1) as i32) and return a Result::Err if groups <= 0 (or
convert to a usize and ensure >0) so the subsequent computation of
weight_shape[(in_channels as i64) / (groups as i64)] is safe; update any error
message to mention invalid groups and ensure callers get a descriptive error
instead of a panic.
In `@crates/mlx-sys/src/mlx.cpp`:
- Around line 5028-5072: Wrap the bodies of the extern "C" entry points (e.g.,
mlx_conv1d and mlx_gather_mm) in a try/catch block so C++ exceptions do not
cross the FFI boundary: catch std::exception and log to stderr with an "[MLX]"
prefix and e.what(), catch(...) and log a generic "[MLX] unknown error", then
return nullptr on failure (these functions return mlx_array*). Ensure the
original logic remains inside the try and only allocate/return the new
mlx::core::array on success.
In `@packages/core/index.d.cts`:
- Around line 623-662: The declarations for Qwen35Model.generate and
Qwen35Model.chat are synchronous and will block the event loop for long runs;
update their signatures and implementation to be asynchronous like
Qwen3Model.generate (i.e., return Promise<Qwen35GenerationResult> and
Promise<Qwen35ChatResult> respectively) or wrap the existing synchronous logic
in the same async/task wrapper used by Qwen3Model so heavy generation runs
execute off the event loop; modify the class declaration (methods generate and
chat) and any callers to await the returned Promises and mirror the Qwen3Model
task-handling pattern to avoid blocking.
- Around line 2524-2532: The Qwen35ChatConfig interface currently types tools as
object[] which discards compile-time checks; update the tools property to use
Array<ToolDefinition> | undefined (matching the existing Qwen3 ChatConfig) and
adjust the Rust N-API annotation that generates the TS type (the #[napi(ts_type
= "...")] on model.rs for the Qwen35 config) to emit "Array<ToolDefinition> |
undefined" so the generated index.d.cts declares tools as Array<ToolDefinition>
and restores proper type safety.
---
Nitpick comments:
In `@__test__/models/qwen3_5-config.test.ts`:
- Around line 6-14: The test currently asserts a hardcoded vocabSize for every
entry in QWEN35_CONFIGS which is brittle; update the loop in the 'should have
valid config presets' test to check that config.vocabSize is a positive integer
(e.g., > 0) instead of equal to 151936, while keeping any exact-value assertion
for the specific named config test (leave that separate); locate the loop
iterating over Object.entries(QWEN35_CONFIGS) and replace the equality check on
vocabSize with a positivity check and optionally a Number.isInteger guard.
In `@__test__/models/qwen3_5-generation.test.ts`:
- Around line 7-21: The test instantiates a full-size model via
getQwen35Config('qwen3.5-0.6b') which increases CI time; change the test to use
a smaller, test-only config (same pattern as qwen3_5-moe.test.ts) by replacing
the config construction with a lightweight config generator (or a call to the
existing small-test config helper) before creating the Qwen35Model instance in
the 'should generate tokens from prompt' test so the prompt generation uses
fewer layers/hiddenSize/vocab and runs much faster while preserving the same
assertions around model.generate, result.tokens, result.numTokens, and
result.finishReason.
In `@crates/mlx-core/src/models/qwen3_5/arrays_cache.rs`:
- Around line 58-63: The manual impl Clone for ArraysCache (the impl Clone block
implementing fn clone that clones self.cache) is redundant; remove the impl
Clone block and add #[derive(Clone)] to the ArraysCache struct declaration so
the compiler generates the same clone behavior for the cache field
automatically.
In `@crates/mlx-core/src/models/qwen3_5/attention.rs`:
- Around line 27-29: The struct's scale field is declared as f32 but
scaled_dot_product_attention expects f64; change the scale field type from f32
to f64 (the field named scale) and update any places that construct or assign to
that field (e.g., constructors/new functions or where scale is computed from
head_dim) to produce an f64 directly so no cast is needed at the SDPA call site,
and ensure any downstream uses that assumed f32 are updated to f64; keep the
call site to scaled_dot_product_attention unchanged.
In `@crates/mlx-core/src/models/qwen3_5/gated_delta_net.rs`:
- Around line 309-321: The helper rms_norm_no_weight currently allocates a new
ones MxArray on every call; move that allocation into GatedDeltaNet and cache it
keyed by (last_dim, dtype) so repeated calls reuse the ones tensor. Add a field
to GatedDeltaNet (e.g., ones_cache: HashMap<(usize, DType), MxArray> or
ones_cache: HashMap<(usize, i32), MxArray> depending on how dtype is
represented), update rms_norm_no_weight to accept &self or make it a
GatedDeltaNet method, look up the ones vector by the tuple (last_dim,
x.dtype()?) and only create and insert a new MxArray::ones if absent, then pass
the cached ones.handle into sys::mlx_fast_rms_norm; ensure the cached MxArray is
returned/cloned/borrowed in a way that preserves its handle lifetime when
calling MxArray::from_handle.
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 149-158: The method reset_caches currently calls cache.reset() for
each entry and then immediately sets self.caches = None, which makes the
per-cache resets redundant; in the reset_caches implementation remove the loop
that iterates caches and calling cache.reset() and simply drop the vector by
assigning self.caches = None (or, if intent is to keep allocated caches but
clear state, replace the drop with caches.clear()); update the reset_caches
function accordingly to reflect the chosen behavior.
- Around line 468-480: create_ssm_mask currently allocates a fresh
MxArray::ones([batch, seq_len], dtype) on every call; optimize by caching a
reusable [batch, 1] mask for the common decode case (seq_len == 1). Add a field
on the model struct (e.g., ssm_mask_single_step: Option<MxArray>) and in
create_ssm_mask check seq_len; if seq_len == 1 verify the cached mask exists and
matches batch and hidden_states.dtype(), return it (or update it) otherwise
create MxArray::ones([batch,1], dtype), store it into ssm_mask_single_step and
return Some(cached_mask); for seq_len != 1 keep the existing behaviour of
returning a fresh MxArray::ones(...) to avoid wrong shapes. Ensure dtype and
batch are validated before reusing the cached mask.
In `@crates/mlx-core/src/models/qwen3_5/persistence.rs`:
- Around line 656-807: The repository has duplicated config logic: parse_config
manually parses JSON while Qwen3_5Config also derives Deserialize with serde
defaults, causing maintenance drift; update load_pretrained to use
serde_json::from_value to deserialize into Qwen3_5Config (annotate fields in
Qwen3_5Config with #[serde(alias = "...")] for alternative keys like
"num_attention_heads"/"num_heads" and provide defaults via #[serde(default =
"…")] or #[serde(default)] so all defaults live in the struct; then remove or
deprecate parse_config (or make it a thin wrapper that calls
serde_json::from_value) and ensure places referencing parse_config or
load_pretrained use the new serde path to avoid dual parsing logic.
- Around line 586-654: The outer .await on the napi::tokio::task::spawn_blocking
in load_pretrained currently maps a JoinError to a generic Error and can lose
join panic details; change the map_err on the awaited JoinHandle so it preserves
the JoinError information (include the JoinError/message in the
Error::from_reason text or chain it) — i.e., update the closure after .await to
wrap the join error with a descriptive message like "Failed to load model (join
error): {join_error}" so you keep the original join/panic context while still
returning an napi::Error from load_pretrained.
In `@crates/mlx-core/src/models/qwen3_5/sparse_moe.rs`:
- Around line 141-169: The set_switch_mlp_* methods
(set_switch_mlp_gate_proj_weight, set_switch_mlp_up_proj_weight,
set_switch_mlp_down_proj_weight) currently return () while other setters like
set_gate_weight and set_shared_expert_* return Result<()>, allowing callers to
handle validation errors; update SwitchLinear::set_weight to return Result<()>
and perform the same validation as Linear::set_weight (check shape/dtype/size
and return Err on mismatch), then change the three set_switch_mlp_* methods to
return Result<()> and propagate the Result from SwitchLinear::set_weight so
failures surface consistently across the API.
In `@crates/mlx-core/src/models/qwen3_5/switch_linear.rs`:
- Around line 67-73: Replace the manual impl Clone for SwitchLinear with a
derived implementation: add #[derive(Clone)] to the SwitchLinear struct
definition and remove the explicit impl Clone block (the current impl Clone for
SwitchLinear and its clone method should be deleted); do the same style as
ArraysCache for consistency so the compiler provides the equivalent clone
behavior automatically.
- Around line 14-23: The constructor SwitchLinear::new currently computes scale
= (2.0 / input_dims as f64).sqrt(), which implements a Kaiming-style
initialization; change it to the transformer-style Xavier-ish scale = (1.0 /
input_dims as f64).sqrt() (i.e. use 1/sqrt(fan_in)) if that matches the Python
reference, and update the bounds passed into MxArray::random_uniform
accordingly; locate the logic in the new(input_dims: u32, output_dims: u32,
num_experts: u32) -> Result<Self> function and adjust the scale expression and
any accompanying comment/tests to reflect the chosen distribution.
In `@crates/mlx-core/src/nn/conv1d.rs`:
- Around line 124-135: The manual Clone implementation on Conv1d is redundant
because all fields (weight, bias, stride, padding, dilation, groups) already
implement Clone; remove the impl Clone block and add #[derive(Clone)] to the
Conv1d struct definition so the compiler generates identical clone behavior
automatically for Conv1d.
In `@examples/vlm-inference.ts`:
- Around line 36-37: The threshold assignment redundantly calls parseFloat
twice; compute a local variable (e.g., parsedThreshold) from
parseFloat(args[thresholdIdx + 1]) once, use !isNaN(parsedThreshold) in the
conditional and parsedThreshold as the true branch value for the threshold
variable (while keeping the existing default 0.5 and the same thresholdIdx/args
checks).
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@__test__/trainers/grpo-integration.test.ts`:
- Around line 570-572: The stdReward assertion is flaky for the same reason as
meanReward: degenerate-completion filtering can leave ≤1 survivors so stdReward
may be 0; update the test that asserts on metrics.stdReward to handle that
nondeterminism the same way you handled metrics.meanReward — either assert
expect(metrics.stdReward).toBeGreaterThanOrEqual(0) or conditionally assert >0
only when the survivor count (derived from groupSize / the degenerate-completion
filtering logic used in the test) is >1; update the assertion near
metrics.stdReward to use the chosen approach and reference the same
survivor-count logic used for meanReward.
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (6)
packages/core/index.d.cts (1)
2551-2551:finishReasontyped asstringinstead of a string-literal union.
Qwen35ChatResult.finishReasonandQwen35GenerationResult.finishReasonare both typed as plainstring, preventing exhaustive switch/if-else narrowing at call sites. The equivalent fields onChatResultandGenerationResultuse literal unions ('stop' | 'length' | 'tool_calls' | 'repetition'and'eos' | 'length' | 'repetition'respectively).Fix requires adding
#[napi(ts_type = "'stop' | 'length' | 'tool_calls' | 'repetition'")](or similar) to the corresponding Rust field so the auto-generated types inherit the narrower type.Also applies to: 2606-2606
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/index.d.cts` at line 2551, Qwen35ChatResult.finishReason and Qwen35GenerationResult.finishReason are currently generated as plain string; update the originating Rust struct fields to add napi ts_type annotations so the generated types use literal unions: add #[napi(ts_type = "'stop' | 'length' | 'tool_calls' | 'repetition'")] on the finishReason field for Qwen35ChatResult and #[napi(ts_type = "'eos' | 'length' | 'repetition'")] on the finishReason field for Qwen35GenerationResult (the annotation must be applied to the Rust field that maps to finishReason so the auto-generated index.d.ts reflects the narrower unions).__test__/models/qwen3_5-generation.test.ts (1)
35-61: Consider adding an error-path test formaxNewTokens <= 0.The Rust
generate()method validatesmax_new_tokens > 0and returns an error. A test exercising this guard would improve coverage of the NAPI error boundary.🧪 Suggested test
it('should reject maxNewTokens <= 0', async () => { const model = new Qwen35Model(TINY_GEN_CONFIG); const prompt = MxArray.fromInt32(new Int32Array([1, 2, 3]), shape(1, 3)); await expect(model.generate(prompt, { maxNewTokens: 0 })).rejects.toThrow(/max_new_tokens must be > 0/); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@__test__/models/qwen3_5-generation.test.ts` around lines 35 - 61, Add a new Jest test in the same suite that calls Qwen35Model.generate with maxNewTokens set to 0 and asserts the promise rejects with the Rust/NAPI validation error; specifically instantiate Qwen35Model (using TINY_GEN_CONFIG), create a prompt MxArray like in the other tests, call model.generate(prompt, { maxNewTokens: 0 }), and use await expect(...).rejects.toThrow(...) to check the error message mentions "max_new_tokens must be > 0" (or a suitable substring) so the NAPI error boundary is covered.crates/mlx-core/src/models/qwen3_5/model.rs (3)
530-594: Parameter count is computed analytically — consider adding a sanity check.The
num_parameters()computes the count from config dimensions rather than summing actual tensor sizes. While this is efficient, it's fragile: any architectural change (e.g., adding biases, changing projection sizes) requires a corresponding manual update here. Consider adding a debug assertion or test that compares this analytical count against the sum of actual loaded tensor sizes afterapply_weights.🤖 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 530 - 594, The analytical parameter counter in num_parameters() can drift from actual weights; add a runtime/debug sanity check after apply_weights that sums the actual tensor sizes and compares to num_parameters(): implement a helper that iterates model tensors (the same storage used in apply_weights) to compute the total parameter count, then assert (or log a warning in non-test builds) that the summed count equals num_parameters(); place this check in/after apply_weights (or expose a public verify_parameter_count() called by tests) so future architecture changes will fail loudly if the analytical formula in num_parameters() becomes out of sync.
243-364: Significant code duplication betweengenerate()andchat().The cache reset/init block, prefill pass, decode loop, and token sampling logic are nearly identical between
generate()(lines 243–364) andchat()(lines 402–526). Extracting a shareddecode_loophelper that accepts the prompt tensor, sampling config, max tokens, and EOS id would reduce ~120 lines of duplication and ensure future fixes apply consistently to both paths.Also applies to: 402-526
🤖 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 243 - 364, The generate()/chat() duplication: extract a shared helper (e.g., decode_loop or run_generation) that encapsulates the cache reset/init (the block manipulating caches_arc and creating Qwen3_5LayerCache entries), the prefill forward pass and last-token extraction using forward_with_locks, and the autoregressive decode loop that calls sample and builds generated_tokens, taking parameters: prompt tensor (prompt_tokens/input), SamplingConfig, max_new_tokens, eos_id, plus references to embedding_weight, layers_arc, final_norm_arc, lm_head_arc, caches_arc, fa_idx and optional tokenizer; have generate() and chat() call this helper and return Qwen3_5GenerationResult, leaving forward_with_locks, sample, and tokenizer usage unchanged so both paths share the same logic.
601-684: Avoid recreating and cloningEmbeddingon every forward pass.Line 611 constructs a new
Embedding::from_weight(embedding_weight)on each call, which clones the weight array. In the decoding loop where this runs per token, this overhead is unnecessary. TheEmbeddingstruct is immutable and only used once. Consider caching theEmbeddingat the model level or extracting just the weight reference to avoid the repeated allocation and cloning.🤖 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 601 - 684, The forward_with_locks function recreates Embedding via Embedding::from_weight(embedding_weight) on every call causing an unnecessary clone; instead create the Embedding once at model init and pass a reference into forward_with_locks (or change the signature to accept &Embedding or &Arc<Embedding>) so forward_with_locks uses the existing immutable Embedding instance and avoids cloning embedding_weight; update all call sites to provide the prebuilt Embedding and remove the local Embedding::from_weight call, ensuring you still use embedding.forward(&input_ids) and access the original embedding_weight only when needed (e.g., for tie_word_embeddings) without cloning.crates/mlx-core/src/models/qwen3_5/persistence.rs (1)
64-70: Duplicate keys across shards are silently overwritten.
HashMap::extendoverwrites existing entries. If two shards contain the same tensor key (e.g., due to a corrupted or incorrectly split checkpoint), the later shard's tensor wins silently. Consider logging a warning when a key collision occurs.🔧 Suggested change
for shard_path in &shard_files { info!(" Loading shard: {}", shard_path.display()); let st_file = SafeTensorsFile::load(shard_path)?; let shard_params = st_file.load_tensors(shard_path)?; - all_params.extend(shard_params); + for (key, value) in shard_params { + if all_params.contains_key(&key) { + warn!("Duplicate tensor key '{}' found in shard {} — overwriting", key, shard_path.display()); + } + all_params.insert(key, value); + } }🤖 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 64 - 70, The code currently extends all_params with shard_params which silently overwrites duplicate tensor keys; update the shard loop (the shard_files loop around SafeTensorsFile::load and load_tensors) to detect collisions before inserting each (key, value) from shard_params into all_params: use the HashMap entry API or check contains_key for each tensor key and if a key already exists, emit a warning log (include the tensor key and shard_path) and skip inserting (so the first-seen shard wins) or explicitly decide to replace if desired; implement the collision check where all_params.extend(shard_params) is now called (replace the extend with per-key insertion and logging).
🤖 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/models/qwen3_5/persistence.rs`:
- Around line 92-106: The current heuristic sets needs_norm_fix from
has_mtp_weights or has_unsanitized_conv1d which can double-apply the +1.0
adjustment; instead, inspect the actual normalization parameter tensors in
params (e.g., keys that look like layer norm / norm weight names) and compute a
simple statistic (mean or median) of their values to decide if they are centered
near 0 (meaning they are raw learned_param and need +1.0) vs centered near 1
(already adjusted); replace the boolean logic that sets needs_norm_fix
(currently based on has_mtp_weights and has_unsanitized_conv1d) with this
distribution check, keep the conv1d weight detection as a fallback but only
apply the +1.0 fix when the norm-tensor statistic indicates raw params.
In `@crates/mlx-core/src/nn/conv1d.rs`:
- Around line 73-89: The from_weights constructor currently accepts groups:
Some(0) and stores groups=0, which defers failure to forward(); add the same
early validation as in new(): check groups.unwrap_or(1) (or the provided groups
value) is > 0 and return an Err (propagating the same error type used by new())
when groups == 0 before constructing Self, so from_weights rejects zero groups
immediately (referencing the from_weights, new, and forward functions to mirror
the validation behavior).
In `@packages/core/index.d.cts`:
- Around line 2546-2552: Qwen35ChatResult currently lacks a toolCalls field so
structured tool invocations from Qwen35ChatConfig.tools are dropped; update the
Rust Qwen35ChatResult struct and its #[napi] export to include toolCalls:
Vec<ToolCallResult> (or the appropriate array type), mirror the shape used by
Qwen3Model's ChatResult.toolCalls, and ensure the JS/CTS generation picks up the
new field so callers receive parsed tool call results alongside text, thinking,
numTokens, and finishReason.
- Around line 2601-2607: The Qwen35GenerationResult interface lacks a logprobs
field required for training; add a property named logprobs: MxArray (matching
the analogous GenerationResult) to Qwen35GenerationResult so callers of
generate() can access per-token log-probabilities; update the
Qwen35GenerationResult declaration to include logprobs: MxArray and ensure any
serialization/usage sites that construct Qwen35GenerationResult (e.g., code
paths that return token arrays/text/numTokens/finishReason) also populate the
new logprobs field consistently.
---
Duplicate comments:
In `@crates/mlx-sys/src/mlx.cpp`:
- Around line 5036-5046: The FFI entry points mlx_conv1d (and similarly
mlx_gather_mm) currently only catch std::exception and log with "mlx_" prefix;
update both to follow the file-wide FFI pattern: add a catch(...) block after
the existing catch(const std::exception& e) that logs the error to std::cerr
using the exact prefix "[MLX]" (e.g. std::cerr << "[MLX] mlx_conv1d error:
..."), and ensure the catch(...) returns nullptr for these pointer-returning
functions; apply the same changes to the other occurrence (around lines for
mlx_gather_mm) so no exception can cross the Rust FFI boundary and logging is
consistent.
---
Nitpick comments:
In `@__test__/models/qwen3_5-generation.test.ts`:
- Around line 35-61: Add a new Jest test in the same suite that calls
Qwen35Model.generate with maxNewTokens set to 0 and asserts the promise rejects
with the Rust/NAPI validation error; specifically instantiate Qwen35Model (using
TINY_GEN_CONFIG), create a prompt MxArray like in the other tests, call
model.generate(prompt, { maxNewTokens: 0 }), and use await
expect(...).rejects.toThrow(...) to check the error message mentions
"max_new_tokens must be > 0" (or a suitable substring) so the NAPI error
boundary is covered.
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 530-594: The analytical parameter counter in num_parameters() can
drift from actual weights; add a runtime/debug sanity check after apply_weights
that sums the actual tensor sizes and compares to num_parameters(): implement a
helper that iterates model tensors (the same storage used in apply_weights) to
compute the total parameter count, then assert (or log a warning in non-test
builds) that the summed count equals num_parameters(); place this check in/after
apply_weights (or expose a public verify_parameter_count() called by tests) so
future architecture changes will fail loudly if the analytical formula in
num_parameters() becomes out of sync.
- Around line 243-364: The generate()/chat() duplication: extract a shared
helper (e.g., decode_loop or run_generation) that encapsulates the cache
reset/init (the block manipulating caches_arc and creating Qwen3_5LayerCache
entries), the prefill forward pass and last-token extraction using
forward_with_locks, and the autoregressive decode loop that calls sample and
builds generated_tokens, taking parameters: prompt tensor (prompt_tokens/input),
SamplingConfig, max_new_tokens, eos_id, plus references to embedding_weight,
layers_arc, final_norm_arc, lm_head_arc, caches_arc, fa_idx and optional
tokenizer; have generate() and chat() call this helper and return
Qwen3_5GenerationResult, leaving forward_with_locks, sample, and tokenizer usage
unchanged so both paths share the same logic.
- Around line 601-684: The forward_with_locks function recreates Embedding via
Embedding::from_weight(embedding_weight) on every call causing an unnecessary
clone; instead create the Embedding once at model init and pass a reference into
forward_with_locks (or change the signature to accept &Embedding or
&Arc<Embedding>) so forward_with_locks uses the existing immutable Embedding
instance and avoids cloning embedding_weight; update all call sites to provide
the prebuilt Embedding and remove the local Embedding::from_weight call,
ensuring you still use embedding.forward(&input_ids) and access the original
embedding_weight only when needed (e.g., for tie_word_embeddings) without
cloning.
In `@crates/mlx-core/src/models/qwen3_5/persistence.rs`:
- Around line 64-70: The code currently extends all_params with shard_params
which silently overwrites duplicate tensor keys; update the shard loop (the
shard_files loop around SafeTensorsFile::load and load_tensors) to detect
collisions before inserting each (key, value) from shard_params into all_params:
use the HashMap entry API or check contains_key for each tensor key and if a key
already exists, emit a warning log (include the tensor key and shard_path) and
skip inserting (so the first-seen shard wins) or explicitly decide to replace if
desired; implement the collision check where all_params.extend(shard_params) is
now called (replace the extend with per-key insertion and logging).
In `@packages/core/index.d.cts`:
- Line 2551: Qwen35ChatResult.finishReason and
Qwen35GenerationResult.finishReason are currently generated as plain string;
update the originating Rust struct fields to add napi ts_type annotations so the
generated types use literal unions: add #[napi(ts_type = "'stop' | 'length' |
'tool_calls' | 'repetition'")] on the finishReason field for Qwen35ChatResult
and #[napi(ts_type = "'eos' | 'length' | 'repetition'")] on the finishReason
field for Qwen35GenerationResult (the annotation must be applied to the Rust
field that maps to finishReason so the auto-generated index.d.ts reflects the
narrower unions).
All 5 autograd integration tests were using the full 0.6B Qwen3 config (28 layers, 896 hidden), causing 2-3 minute timeouts on CI. Switched to a tiny config (2 layers, 64 hidden) that completes in milliseconds. Also includes: async generate/chat for Qwen3.5, FFI try/catch guards, conv1d groups validation, and PR review comment fixes. Co-Authored-By: Claude Opus 4.6 <[email protected]>
375a36a to
e1b81d1
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (8)
crates/mlx-core/src/nn/conv1d.rs (1)
130-141: ManualCloneimpl can be replaced with#[derive(Clone)].All fields (
MxArray,Option<MxArray>,i32) already implementClone, so the manual implementation is identical to what the derive macro would generate and adds unnecessary boilerplate.♻️ Proposed simplification
+#[derive(Clone)] pub struct Conv1d { weight: MxArray, bias: Option<MxArray>, stride: i32, padding: i32, dilation: i32, groups: i32, }Then remove the manual
impl Clone for Conv1dblock entirely (lines 130–141).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/nn/conv1d.rs` around lines 130 - 141, The manual impl Clone for Conv1d duplicates what the compiler derive would produce; remove the entire impl Clone for Conv1d block and add #[derive(Clone)] to the Conv1d struct definition so that weight, bias, stride, padding, dilation and groups are cloned via the derived implementation instead of the manual impl.packages/core/index.d.cts (3)
2592-2599:maxNewTokensis required and the config is missing stop/repetition controls.Two concerns:
maxNewTokens: number(no?) makes everygenerate()call mandatory-config.GenerationConfig.maxNewTokensis optional with a default. Dropping the requirement is more ergonomic and consistent.repetitionPenalty,maxConsecutiveTokens,eosTokenId, andreturnLogprobsare absent, leaving callers unable to control repetition or access logprobs.♻️ Proposed fix
export interface Qwen35GenerationConfig { - maxNewTokens: number; + maxNewTokens?: number | undefined; temperature?: number | undefined; topK?: number | undefined; topP?: number | undefined; minP?: number | undefined; + repetitionPenalty?: number | undefined; + eosTokenId?: number | undefined; + returnLogprobs?: boolean | undefined; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/index.d.cts` around lines 2592 - 2599, The Qwen35GenerationConfig interface currently forces callers to provide maxNewTokens and omits repetition/logprob controls; change the interface Qwen35GenerationConfig to make maxNewTokens optional (maxNewTokens?: number) to match GenerationConfig defaults, and add optional properties repetitionPenalty?: number, maxConsecutiveTokens?: number, eosTokenId?: number, and returnLogprobs?: boolean so callers can control repetition behavior and request log-probabilities when using the Qwen35GenerationConfig in generate().
2589-2589:mlpOnlyLayers?: number[]— useArray<number>for consistency.Every other array field in this file uses
Array<T>notation (e.g.,mropeSection: Array<number>at line 2916). This should match.♻️ Proposed fix
- mlpOnlyLayers?: number[] | undefined; + mlpOnlyLayers?: Array<number> | undefined;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/index.d.cts` at line 2589, Update the type annotation for the mlpOnlyLayers field to use Array<number> instead of number[] to match the project's array style; locate the declaration "mlpOnlyLayers?: number[] | undefined;" in the type definitions and change it to "mlpOnlyLayers?: Array<number> | undefined" so it is consistent with other fields like mropeSection.
2536-2544:Qwen35ChatConfigis missing generation-control fields present inChatConfig.
repetitionPenalty,repetitionContextSize,maxConsecutiveTokens,maxNgramRepeats,ngramSize,eosTokenId, andreturnLogprobsare all absent. These correspond toChatConfigfields (lines 1866–1879) and affect output quality / stop-condition behaviour. The missing fields need to be added to the RustQwen35ChatConfigstruct with matching#[napi]annotations.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/index.d.cts` around lines 2536 - 2544, The Qwen35ChatConfig Rust struct is missing the generation-control fields present on ChatConfig; update the Rust struct that maps to the TypeScript Qwen35ChatConfig (the one annotated with #[napi]) to add the following fields with matching #[napi] annotations and appropriate Option<> types: repetition_penalty (repetitionPenalty), repetition_context_size (repetitionContextSize), max_consecutive_tokens (maxConsecutiveTokens), max_ngram_repeats (maxNgramRepeats), ngram_size (ngramSize), eos_token_id (eosTokenId) and return_logprobs (returnLogprobs); ensure the field names and types correspond to the existing ChatConfig definitions and that serde/napi naming matches the TypeScript property names so the JS-visible Qwen35ChatConfig includes all these controls.__test__/trainers/grpo-autograd-integration.test.ts (1)
23-24:bosTokenIdandpadTokenIdare both0— consider differentiating.Having them equal is fine for autograd correctness tests (gradients don't depend on token identity), but if this config is ever reused for generation tests, BOS=PAD can produce incorrect attention masking. A distinct value like
bosTokenId: 2avoids the potential confusion at zero cost.♻️ Proposed nit
padTokenId: 0, eosTokenId: 1, - bosTokenId: 0, + bosTokenId: 2,🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@__test__/trainers/grpo-autograd-integration.test.ts` around lines 23 - 24, The bosTokenId is currently identical to padTokenId (both 0) which can break attention/masking in future generation tests; update the test config where eosTokenId, bosTokenId, padTokenId are set (look for bosTokenId in this test) to use a distinct bosTokenId (e.g., bosTokenId: 2) while leaving padTokenId: 0 and eosTokenId: 1 so the tokens are uniquely identified.crates/mlx-core/src/models/qwen3_5/persistence.rs (2)
574-597: Logging:total_weightsequalsparams.len()— "total in checkpoint" is slightly misleading.
total_weights(line 575) andparams.len()(line 595) reference the same sanitized map, so they're always equal. The message says "total in checkpoint" but these are post-sanitization counts (MTP stripped, experts stacked, etc.). Consider"total sanitized"for clarity, since the raw checkpoint count is already logged separately inload_pretrained.🤖 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 574 - 597, The log prints total_weights and params.len() which are identical because params is the sanitized map; change the wording (or variable name) to reflect that these are post-sanitization counts: e.g., rename total_weights to total_sanitized (or just keep total_weights) and update the info! call to say "total sanitized in checkpoint" (or "total sanitized") instead of "total in checkpoint"; adjust the message that references recognized, params.len(), and total_weights (symbols: total_weights, params, recognized) so it is clear these counts are sanitized (the raw checkpoint count is already logged in load_pretrained).
187-220:gate_up_projsplit assumes even dimension — no guard against odd shapes.Line 193 divides by 2 with integer truncation. If a malformed checkpoint has an odd dimension at
split_axis, the gate and up tensors will have mismatched shapes, producing a confusing downstream error rather than a clear diagnostic.Proposed defensive check
let split_axis = shape.len() - 2; let mid = shape[split_axis] / 2; + if shape[split_axis] % 2 != 0 { + return Err(Error::from_reason(format!( + "gate_up_proj weight '{}' has odd dim {} at axis {} — cannot split evenly", + name, shape[split_axis], split_axis + ))); + } let gate = array.slice_axis(split_axis, 0, mid)?;🤖 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 187 - 220, The split logic for gate_up_proj in the block that computes split_axis and mid must guard against odd-sized dimensions: check that shape[split_axis] is even before using mid = shape[split_axis] / 2; if it is odd, log a clear warning (including name and the offending dimension) and skip the split (fall through to insert the weight as-is) or return an error; update the branch around variables split_axis, mid, gate, up and the subsequent result.insert(base, gate) / result.insert(up_name, up) so they only run when the dimension is even, and ensure name_stripped/base/up_name remain unchanged when skipping.crates/mlx-core/src/models/qwen3_5/model.rs (1)
246-367: Consider extracting the shared decode loop into a helper function.The prefill → sample first token → decode loop → text decode logic in
generate()(lines 282–355) andchat()(lines 448–513) is nearly identical (~70 duplicated lines). Differences are limited to input preparation and post-processing (thinking extraction). A shared internal function likedecode_loop(prompt: &MxArray, max_tokens: i32, sampling_config: ..., ...) -> Result<(Vec<u32>, String)>would reduce the maintenance surface and prevent the two paths from diverging.Also applies to: 405-528
🤖 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 246 - 367, The generate() and chat() functions duplicate the prefill → first-sample → decode loop and text-decoding logic; extract that shared behavior into a helper (e.g., fn decode_loop(input: &MxArray, embedding_weight: &..., layers_arc: &..., final_norm_arc: &..., lm_head_arc: &..., caches_arc: &..., fa_idx: usize, max_tokens: usize, sampling_config: Option<SamplingConfig>, tokenizer: Option<&TokenizerType>) -> Result<Qwen3_5GenerationResult>) that encapsulates calling forward_with_locks for prefill and single-token steps, invoking sample(), collecting generated_tokens, checking eos_id, and doing tokenizer.decode_sync (or returning tokens when tokenizer is None); then replace the duplicated blocks in generate() and chat() with calls to this helper, passing differing inputs/preprocessing and handling any slight post-processing externally if needed (e.g., finish_reason or num_tokens). Ensure helper returns same Qwen3_5GenerationResult shape so both generate() and chat() can use it directly.
🤖 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/models/qwen3_5/model.rs`:
- Around line 574-594: The full-attention branch in num_parameters omits the
per-head normalization weights q_norm.weight and k_norm.weight that
apply_weights in persistence.rs loads; fix by adding 2 * head_dim into the
full-attention param sum (e.g. introduce let hd = self.config.head_dim as i64
and in the else branch where q_proj/k/v/o are counted add total += 2 * hd) so
the model parameter count includes both q_norm and k_norm per layer.
In `@crates/mlx-core/src/nn/conv1d.rs`:
- Around line 34-52: Add an explicit divisibility check before computing
weight_shape: verify (in_channels % groups) == 0 (using the original integer
types) and return an Err with a clear message if not; update the code around the
variables groups and weight_shape in conv1d.rs (where groups is computed and
weight_shape is built) so you do the check after groups is validated but before
calculating (in_channels as i64) / (groups as i64), preventing silent truncation
and producing a helpful error when in_channels is not divisible by groups.
---
Duplicate comments:
In `@crates/mlx-core/src/nn/conv1d.rs`:
- Around line 80-89: from_weights currently accepts groups: Option<i64> and
stores groups.unwrap_or(1) as i32 without validating it, allowing callers to
pass Some(0) and deferring a poor FFI error into forward(); modify from_weights
to validate the groups value (compute let g = groups.unwrap_or(1); if g <= 0 {
return Err(...) }) and return a descriptive Err from from_weights when g <= 0,
otherwise store g as i32 in the struct (update the assignment that currently
uses groups.unwrap_or(1) as i32); reference the from_weights constructor and the
stored field weight/bias/stride/padding/dilation/groups to locate where to add
this check.
In `@packages/core/index.d.cts`:
- Around line 2601-2607: The Qwen35GenerationResult type is missing per-token
log-probabilities and uses a too-general finishReason: update the
Qwen35GenerationResult interface to include logprobs: MxArray (matching
GenerationResult.logprobs) so generate() callers can access per-token
probabilities, and tighten finishReason from string to the union 'eos' |
'length' | 'repetition' to match GenerationResult.finishReason; locate and
modify the Qwen35GenerationResult definition to add the logprobs field and
change finishReason's type accordingly.
- Around line 2546-2552: Qwen35ChatResult is missing a tool_calls field and uses
a too-broad finishReason type; update the Rust Qwen35ChatResult struct to add
tool_calls: Vec<ToolCallResult> (matching ChatResult.toolCalls /
Qwen35ChatConfig.tools) so parsed tool invocations are surfaced, and constrain
the finish reason by annotating the corresponding field with #[napi(ts_type =
"'stop' | 'length' | 'tool_calls' | 'repetition'")] so the generated TypeScript
type matches ChatResult.finishReason; ensure the field names/map to the existing
TypeScript export names (tool_calls / finish_reason or finishReason as used in
your bindings) to keep parity with ChatResult.
---
Nitpick comments:
In `@__test__/trainers/grpo-autograd-integration.test.ts`:
- Around line 23-24: The bosTokenId is currently identical to padTokenId (both
0) which can break attention/masking in future generation tests; update the test
config where eosTokenId, bosTokenId, padTokenId are set (look for bosTokenId in
this test) to use a distinct bosTokenId (e.g., bosTokenId: 2) while leaving
padTokenId: 0 and eosTokenId: 1 so the tokens are uniquely identified.
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 246-367: The generate() and chat() functions duplicate the prefill
→ first-sample → decode loop and text-decoding logic; extract that shared
behavior into a helper (e.g., fn decode_loop(input: &MxArray, embedding_weight:
&..., layers_arc: &..., final_norm_arc: &..., lm_head_arc: &..., caches_arc:
&..., fa_idx: usize, max_tokens: usize, sampling_config: Option<SamplingConfig>,
tokenizer: Option<&TokenizerType>) -> Result<Qwen3_5GenerationResult>) that
encapsulates calling forward_with_locks for prefill and single-token steps,
invoking sample(), collecting generated_tokens, checking eos_id, and doing
tokenizer.decode_sync (or returning tokens when tokenizer is None); then replace
the duplicated blocks in generate() and chat() with calls to this helper,
passing differing inputs/preprocessing and handling any slight post-processing
externally if needed (e.g., finish_reason or num_tokens). Ensure helper returns
same Qwen3_5GenerationResult shape so both generate() and chat() can use it
directly.
In `@crates/mlx-core/src/models/qwen3_5/persistence.rs`:
- Around line 574-597: The log prints total_weights and params.len() which are
identical because params is the sanitized map; change the wording (or variable
name) to reflect that these are post-sanitization counts: e.g., rename
total_weights to total_sanitized (or just keep total_weights) and update the
info! call to say "total sanitized in checkpoint" (or "total sanitized") instead
of "total in checkpoint"; adjust the message that references recognized,
params.len(), and total_weights (symbols: total_weights, params, recognized) so
it is clear these counts are sanitized (the raw checkpoint count is already
logged in load_pretrained).
- Around line 187-220: The split logic for gate_up_proj in the block that
computes split_axis and mid must guard against odd-sized dimensions: check that
shape[split_axis] is even before using mid = shape[split_axis] / 2; if it is
odd, log a clear warning (including name and the offending dimension) and skip
the split (fall through to insert the weight as-is) or return an error; update
the branch around variables split_axis, mid, gate, up and the subsequent
result.insert(base, gate) / result.insert(up_name, up) so they only run when the
dimension is even, and ensure name_stripped/base/up_name remain unchanged when
skipping.
In `@crates/mlx-core/src/nn/conv1d.rs`:
- Around line 130-141: The manual impl Clone for Conv1d duplicates what the
compiler derive would produce; remove the entire impl Clone for Conv1d block and
add #[derive(Clone)] to the Conv1d struct definition so that weight, bias,
stride, padding, dilation and groups are cloned via the derived implementation
instead of the manual impl.
In `@packages/core/index.d.cts`:
- Around line 2592-2599: The Qwen35GenerationConfig interface currently forces
callers to provide maxNewTokens and omits repetition/logprob controls; change
the interface Qwen35GenerationConfig to make maxNewTokens optional
(maxNewTokens?: number) to match GenerationConfig defaults, and add optional
properties repetitionPenalty?: number, maxConsecutiveTokens?: number,
eosTokenId?: number, and returnLogprobs?: boolean so callers can control
repetition behavior and request log-probabilities when using the
Qwen35GenerationConfig in generate().
- Line 2589: Update the type annotation for the mlpOnlyLayers field to use
Array<number> instead of number[] to match the project's array style; locate the
declaration "mlpOnlyLayers?: number[] | undefined;" in the type definitions and
change it to "mlpOnlyLayers?: Array<number> | undefined" so it is consistent
with other fields like mropeSection.
- Around line 2536-2544: The Qwen35ChatConfig Rust struct is missing the
generation-control fields present on ChatConfig; update the Rust struct that
maps to the TypeScript Qwen35ChatConfig (the one annotated with #[napi]) to add
the following fields with matching #[napi] annotations and appropriate Option<>
types: repetition_penalty (repetitionPenalty), repetition_context_size
(repetitionContextSize), max_consecutive_tokens (maxConsecutiveTokens),
max_ngram_repeats (maxNgramRepeats), ngram_size (ngramSize), eos_token_id
(eosTokenId) and return_logprobs (returnLogprobs); ensure the field names and
types correspond to the existing ChatConfig definitions and that serde/napi
naming matches the TypeScript property names so the JS-visible Qwen35ChatConfig
includes all these controls.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 3 potential issues.
Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.
| topP?: number | undefined | ||
| minP?: number | undefined | ||
| tools?: object[] | undefined | ||
| } |
There was a problem hiding this comment.
Qwen35ChatConfig tools typed as object[] not ToolDefinition[]
Low Severity
The Qwen35ChatConfig.tools field is typed as object[] in the auto-generated index.d.cts, but the Rust source has #[napi(ts_type = "Array<ToolDefinition>")]. This is inconsistent with ChatConfig.tools (used by Qwen3Model) which is correctly typed as Array<ToolDefinition>. The stale type definition loses type safety for tool definitions passed to Qwen35Model.chat().
| } | ||
|
|
||
| total | ||
| } |
There was a problem hiding this comment.
num_parameters omits final_norm and attention norm weights
Low Severity
num_parameters() does not count final_norm.weight (hidden_size params) nor the q_norm and k_norm weights (head_dim each) in full attention layers. The per-layer loop only counts h * 2 for the two layer norms but omits the attention-internal norms. The final_norm is entirely outside the loop and never counted. This undercounts by hidden_size + 2 * head_dim * num_full_attention_layers.
<!-- CURSOR_SUMMARY --> > [!NOTE] > **Medium Risk** > Large addition of new model/runtime code paths (generation, caching, weight loading/sanitization) that could impact correctness and performance; changes are mostly additive but touch core inference APIs and native bindings. > > **Overview** > Adds a new Rust-backed `Qwen3_5Model` (exported to JS as `Qwen35Model`) implementing Qwen3.5’s hybrid linear/full-attention decoder with optional MoE, including cache init/reset, incremental `forwardWithCache`, and async `generate`/`chat` APIs. > > Introduces full pretrained loading for Qwen3.5 from HF-style safetensors (single or sharded) with weight sanitization (key renames, conv1d transpose, RMSNorm fixups, MoE expert stacking/splitting) and mandatory-weight validation to prevent partially-random models. > > Expands the test suite with new Qwen3.5 config/forward/cache/generation/MoE coverage, and updates GRPO integration tests to use tiny configs and relax deterministic reward assertions to avoid CI timeouts and flakiness. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit e1b81d1. 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 Qwen3.5 model (dense + MoE) with generation and chat APIs, pretrained model loading, cache init/reset, and incremental (cached) inference; JS/Node exports and config helpers included. * **Tests** * New test suites covering Qwen3.5 configs, forward/incremental/cached inference, generation limits/finish reasons, MoE vs dense comparisons, and parameter/loading validations. * **NN / Runtime** * Added new convolution and activation ops to support advanced model layers. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>


Note
Medium Risk
Large addition of new model/runtime code paths (generation, caching, weight loading/sanitization) that could impact correctness and performance; changes are mostly additive but touch core inference APIs and native bindings.
Overview
Adds a new Rust-backed
Qwen3_5Model(exported to JS asQwen35Model) implementing Qwen3.5’s hybrid linear/full-attention decoder with optional MoE, including cache init/reset, incrementalforwardWithCache, and asyncgenerate/chatAPIs.Introduces full pretrained loading for Qwen3.5 from HF-style safetensors (single or sharded) with weight sanitization (key renames, conv1d transpose, RMSNorm fixups, MoE expert stacking/splitting) and mandatory-weight validation to prevent partially-random models.
Expands the test suite with new Qwen3.5 config/forward/cache/generation/MoE coverage, and updates GRPO integration tests to use tiny configs and relax deterministic reward assertions to avoid CI timeouts and flakiness.
Written by Cursor Bugbot for commit e1b81d1. This will update automatically on new commits. Configure here.
Summary by CodeRabbit
New Features
Tests
NN / Runtime