Repository navigation
feat: qwen 3.5 dense and moe optimization - #24
Conversation
… (1.2→6.4 tok/s) Root cause: scalar ops (mul_scalar, add_scalar, etc.) in C++ created f32 scalars that promoted bf16 inputs to f32, causing 5x GPU slowdown. Fixed by casting scalars to input dtype. Also added mlx::core::compile()-based decode path that caches the 64-layer computation graph, and split monolithic mlx.cpp into 10 logical files. Cleaned up dead code (forward_fused, unused methods) and fixed missing compiled_reset in chat() method. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…bf16 type promotion Split the unified Qwen3.5 model into two distinct modules following the mlx-lm convention of separate model modules per variant: - `qwen3_5/` — Dense-only (compiled C++ forward path, no MoE code) - `qwen3_5_moe/` — MoE variant (SparseMoeBlock, SwitchGLU, expert routing) MoE shares attention/GatedDeltaNet/cache types from dense via re-exports. Fix bf16→f32 type promotion in MoE model (0.6 → 9.8+ tok/s): - A_log stored as f32 in HF checkpoints, cast to bf16 in set_a_log() - norm.weight stored as f32 in HF checkpoints, cast to bf16 in set_norm_weight() - Loading order: dt_bias (bf16) loaded first as dtype reference Also fix eval_key() removal from MLX submodule by replacing with next() + eval() to break lazy RNG split chains after model init. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…Qwen3.5 dense/MoE split Move gated delta recurrence Metal shader source from inline C++ raw strings into dedicated .metal.inc files under crates/mlx-sys/src/metal/. Four variant files (non-vectorized/vectorized x non-masked/masked) replace the runtime string builder, giving proper editor support and cleaner separation of concerns. Also includes Qwen3.5 dense/MoE architecture cleanup: shared code deduplication, quantized linear layer support, and bf16 type promotion fixes. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…FFI safety fixes Add offline model conversion that dequantizes FP8 HuggingFace checkpoints to bf16 and re-quantizes to MXFP8 or 4-bit affine format. This avoids the ~70GB runtime memory of keeping bf16 weights, producing ~34GB MXFP8 or ~18GB 4-bit models that load directly into QuantizedLinear/QuantizedSwitchLinear layers. Key changes: - Add quantize_weights() with should_quantize/is_router_gate predicates - Add sanitize_qwen35_moe: FP8 dequant, expert stacking, projection merging - Add config-driven quantized loading (config.json "quantization" metadata) - Add U32/Uint8 SafeTensors save/load, from_fp8/to_uint8 on MxArray - Add CLI flags: --quantize, --q-bits, --q-group-size, --q-mode - Fix FFI safety: null checks + try-catch on mlx_from_fp8, mlx_array_from_uint8 - Add validation: quant_mode, NaN CLI args, warn on silent config defaults - Fix comment accuracy: dequant_fp8 doc, sanitize doc, module doc Tested: 49 tok/s MXFP8 inference, 34.8GB RSS, 747 Rust tests pass. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds Qwen3.5 Mixture‑of‑Experts (MoE) support, FP8 dequantization and affine quantization flows, quantized linear primitives and MoE-specific Rust modules, large C++/Metal fused kernels and FFI APIs, SafeTensors streaming I/O, loader/CLI updates for multi-model detection, and related tests/examples adjustments. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Client as Client
participant Loader as Loader
participant Persistence as Persistence
participant MLX as MLX (C++/Metal)
participant Model as Model (Rust)
participant Cache as Cache
Client->>Loader: loadPretrained(path)
Loader->>Persistence: parse config & detect model_type
alt qwen3_5_moe
Persistence->>MLX: load safetensors, dequantize FP8, build quantized layers
Persistence->>Model: apply weights, register compiled weights (optional)
Model->>Cache: init_caches()
Loader->>Client: return Qwen3_5MoeModel
else qwen3_5 / qwen3
Persistence->>MLX: load weights, sanitize, maybe quantize
Loader->>Client: return Model
end
Client->>Model: generate(prompt, config)
Model->>Cache: reset/init per-request caches
loop per token
Model->>MLX: forward (compiled C++ path or Rust path)
MLX->>Cache: update caches
Model->>MLX: sampling (compiled helpers)
MLX->>Model: next_token
end
Model->>Client: return generation result
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
|
This was a HuggingFace Transformers API compatibility shim (device_map="auto" for multi-GPU weight distribution) that has no equivalent in MLX's unified memory architecture. Also fix type errors in tool-use-example.ts by narrowing model type to Qwen3Model. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 16
Note
Due to the large number of review comments, Critical severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
crates/mlx-core/src/convert.rs (1)
252-277:⚠️ Potential issue | 🟠 MajorNon-FP8 Qwen3.5 sanitizer path skips requested dtype conversion.
Lines 252-277 bypass generic conversion for
qwen3_5*, but insidesanitize_qwen35_moedtype conversion currently happens only in thehas_fp8branch. For non-FP8 checkpoints, tensors keep original dtype instead oftarget_dtype.Suggested fix
- if has_fp8 { + if has_fp8 { let scale_keys: Vec<String> = new_weights .keys() .filter(|k| k.contains("weight_scale_inv")) .cloned() .collect(); @@ info!(" After FP8 dequantization: {} tensors", new_weights.len()); + } else { + // Non-FP8 checkpoints still need dtype conversion. + let keys: Vec<String> = new_weights.keys().cloned().collect(); + for k in keys { + let v = new_weights.get(&k).unwrap(); + let current_dtype = v.dtype()?; + if current_dtype != target_dtype { + let converted = v.astype(target_dtype)?; + new_weights.insert(k, converted); + } + } + info!(" After dtype conversion: {} tensors", new_weights.len()); }Also applies to: 760-798
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/convert.rs` around lines 252 - 277, The qwen3_5 sanitizer bypass (has_custom_sanitizer) causes tensors to skip conversion to target_dtype because sanitize_qwen35_moe only performs dtype conversion inside the has_fp8 branch; update sanitize_qwen35_moe (and the other qwen3_5 sanitizer path referenced by has_custom_sanitizer) to always convert tensors to target_dtype when has_fp8 is false as well (i.e., perform the same dtype conversion logic for non-FP8 checkpoints), or move the dtype conversion out of the has_fp8-only branch so that target_dtype is applied for both FP8 and non-FP8 flows; ensure conversions update converted_tensors and respect tie_word_embeddings and verbose behavior.crates/mlx-core/src/models/qwen3_5/sparse_moe.rs (1)
73-94:⚠️ Potential issue | 🟡 MinorMissing validation in
new_quantizedconstructor (same as MoE variant).Similar to the MoE module's
sparse_moe.rs, thenew_quantized()constructor here skips the validation present innew()fornum_expertsandnum_experts_per_tok.🛡️ Proposed fix to add validation
pub fn new_quantized( config: &Qwen3_5Config, gate: QuantizedLinear, switch_mlp: SwitchGLU, shared_expert: MLPVariant, shared_expert_gate: QuantizedLinear, ) -> Result<Self> { let num_experts = config.num_experts.unwrap_or(0); let num_experts_per_tok = config.num_experts_per_tok.unwrap_or(1); let norm_topk_prob = config.norm_topk_prob.unwrap_or(true); + if num_experts <= 0 { + return Err(Error::from_reason(format!( + "SparseMoeBlock requires num_experts > 0, got {}", + num_experts + ))); + } + if num_experts_per_tok <= 0 || num_experts_per_tok > num_experts { + return Err(Error::from_reason(format!( + "SparseMoeBlock requires 0 < num_experts_per_tok <= num_experts, got {} (num_experts={})", + num_experts_per_tok, num_experts + ))); + } + Ok(Self {🤖 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 73 - 94, The new_quantized constructor copies config defaults but lacks the same validations as new(): validate num_experts and num_experts_per_tok from Qwen3_5Config (the local variables num_experts and num_experts_per_tok) exactly like the MoE variant's new() — ensure num_experts > 0, num_experts_per_tok > 0 and num_experts_per_tok <= num_experts (return Err if not) and preserve norm_topk_prob handling; update the new_quantized function to perform these checks before constructing Self so the returned Result mirrors new()’s validation behavior.
🟠 Major comments (19)
crates/mlx-core/src/models/qwen3_5/persistence.rs-679-685 (1)
679-685:⚠️ Potential issue | 🟠 MajorValidate quantization config values before use.
bitsandgroup_sizeare accepted directly from config. Invalid values (e.g.,<= 0) can propagate into quantized layer construction and kernel invocation paths.🤖 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 679 - 685, Validate parsed quantization values after reading quant_cfg: ensure quant_bits and quant_group_size are positive and within expected ranges before they are used to construct quantized layers. In persistence.rs, after computing quant_bits and quant_group_size from quant_cfg (and before the block guarded by quant_cfg.is_some()), check that quant_bits > 0 and quant_group_size > 0 (and optionally clamp to sensible maxima or replace with DEFAULT_QUANT_BITS / DEFAULT_QUANT_GROUP_SIZE) and return an Err or fall back to defaults if invalid; reference the variables quant_bits, quant_group_size, quant_cfg, DEFAULT_QUANT_BITS and DEFAULT_QUANT_GROUP_SIZE to locate the logic to change. Ensure downstream code that constructs quantized layers/kernel calls receives only validated values.crates/mlx-core/src/models/qwen3_5/persistence.rs-746-783 (1)
746-783:⚠️ Potential issue | 🟠 MajorSplit-weight fusion logic is nondeterministic due
HashMapiteration order.If
.in_proj_z.weight/.in_proj_a.weightis visited before its pair, it can be stored standalone first, then fused key gets stored later. Registration output becomes order-dependent and inconsistent across runs.🤖 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 746 - 783, The fusion is nondeterministic because you iterate the HashMap `params` directly; fix by iterating deterministic, e.g., collect `params.keys()` into a Vec, sort it, and then loop over the sorted keys (use those to index `params`) so handling of pairs like `.in_proj_qkv.weight`/`.in_proj_z.weight` and `.in_proj_b.weight`/`.in_proj_a.weight` is stable; keep existing logic that uses `handled_splits`, `store`, and `MxArray::concatenate` but replace the `for (name, array) in params` iteration with a sorted-key iteration to ensure consistent fusion ordering.crates/mlx-core/src/models/qwen3_5/layer_cache.rs-121-145 (1)
121-145:⚠️ Potential issue | 🟠 MajorClear cache slots on null/failed imports to avoid stale state.
At Line 122 / Line 127 / Line 134 / Line 139, null or failed handle imports are skipped, so previous cache tensors remain. That conflicts with your own contract at Line 66 (“null pointers if slot is empty”) and can leak stale KV/linear state into later decode steps.
[suggested fix] reset or explicitly clear affected slots before import, and propagate import failures instead of silently ignoring them (
Result<()>is safer here).🤖 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/layer_cache.rs` around lines 121 - 145, The Linear and FullAttention branches currently skip null or failed MxArray imports, leaving previous cache tensors in place; update the handlers for Self::Linear and Self::FullAttention to explicitly clear/reset the corresponding slots before attempting import (e.g., call c.set(0, None)/clear for fused_conv_state and c.set(1, None)/clear for fused_recurrent_state in the Linear branch, and clear keys/values via c.set_keys(None)/c.set_values(None) in the FullAttention branch) and on import failure propagate an error instead of silently ignoring it (replace silent ignores of MxArray::from_handle(p0, ...) / from_handle(p1, ...) with logic that clears the slot then returns Err) while still setting c.set_offset(new_offset) only after successful handling of imports or after clearing when appropriate.crates/mlx-sys/src/mlx_autograd.cpp-103-106 (1)
103-106:⚠️ Potential issue | 🟠 MajorAdd null validation for each input handle before dereferencing.
Both functions validate the
input_handlespointer itself (line 91 and 161) but fail to check individual array elements before dereferencing them. A null element atinput_handles[i]will cause a crash at the pointer dereference.Add a null check inside the loop:
for (size_t i = 0; i < input_count; i++) { if (!input_handles[i]) { return 0; // or handle error appropriately } auto arr = reinterpret_cast<array*>(input_handles[i]); inputs.emplace_back(*arr); }Also applies to lines 174-177 in
mlx_value_and_gradients.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_autograd.cpp` around lines 103 - 106, The loop that builds inputs from input_handles must validate each handle before dereferencing: inside the for loop that iterates over input_count and uses reinterpret_cast<array*>(input_handles[i]) (the block that does auto arr = reinterpret_cast<array*>(input_handles[i]); inputs.emplace_back(*arr);), add a null check for input_handles[i] and return an error (e.g., return 0) or propagate an appropriate error if any element is null. Apply the same null-checking fix to the analogous loop in mlx_value_and_gradients (the loop around lines 174-177) so neither function dereferences a null element.crates/mlx-sys/src/mlx_common.h-200-220 (1)
200-220:⚠️ Potential issue | 🟠 MajorGuard
outbeforestd::copyin all buffer-copy helpers to prevent null pointer dereference across FFI boundaries.All five overloads—
copy_to_buffer(float, int32_t, uint32_t) andcopy_to_buffer_noeval(float, int32_t)—dereferenceoutwithstd::copywithout validating it is non-null. Whenlen > 0andoutis null, this causes undefined behavior and potential crashes. Add a null check before eachstd::copycall (lines 218, 240, 262, 281, 298).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_common.h` around lines 200 - 220, Guard the output pointer before performing the std::copy in all buffer-copy helpers: in copy_to_buffer (float, int32_t, uint32_t) and copy_to_buffer_noeval (float, int32_t) check that out is non-null when len > 0 and return false (or handle error) if it is null; locate the std::copy calls in the functions named copy_to_buffer and copy_to_buffer_noeval and add a simple if (len > 0 && out == nullptr) return false; immediately before each std::copy to avoid null pointer dereference across FFI boundaries.crates/mlx-sys/src/mlx_stream.cpp-182-185 (1)
182-185:⚠️ Potential issue | 🟠 Major
mlx_array_nbytesneeds null-handle guarding.At line 183, null
handleis immediately dereferenced without validation. Add a null-check that returns0(safe sentinel forsize_t) when handle is null or invalid, consistent with FFI safety requirements for this entry point.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_stream.cpp` around lines 182 - 185, The function mlx_array_nbytes currently dereferences the incoming mlx_array* handle without validation; add a null-check at the start of mlx_array_nbytes to return 0 when handle is nullptr (or otherwise invalid) before casting, then proceed to reinterpret_cast<array*>(handle) and call arr->nbytes(); reference the mlx_array_nbytes function, the mlx_array* parameter, and the array::nbytes() call when locating where to insert the guard.crates/mlx-core/src/models/qwen3_5/persistence.rs-737-739 (1)
737-739:⚠️ Potential issue | 🟠 MajorSkip invalid weight names gracefully in registration path.
At line 738,
CString::new(name).expect(...)panics if weight names from checkpoint files contain embedded null bytes. This crashes model loading. Other CString operations in the codebase properly handle errors; use the same pattern here.Proposed fix
- let c_name = CString::new(name).expect("Weight name contains null byte"); + let c_name = match CString::new(name) { + Ok(v) => v, + Err(_) => { + warn!("Skipping invalid weight name with embedded NUL: {}", name); + return; + } + };🤖 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 737 - 739, The closure store currently calls CString::new(name).expect(...) which panics on names with embedded nulls; change store (in persistence.rs) to attempt CString::new(name) and handle the Err by logging or quietly returning early so the registration path skips invalid weight names instead of crashing (i.e., detect the CString::new error inside the store closure and bail out of that invocation rather than panicking).crates/mlx-sys/src/mlx_autograd.cpp-209-215 (1)
209-215:⚠️ Potential issue | 🟠 MajorDefer
loss_handleassignment until after gradients size validation.At line 210,
*loss_handleis allocated before validatinggradients.size()at line 213. If validation fails and the function returns 0, the caller (which checksgrad_count == 0 || loss_handle.is_null()) will have a non-null loss_handle but an error return code, creating ambiguous ownership and a memory leak. Note thatgrad_handlesare correctly assigned only after the validation succeeds (lines 216–218); apply the same pattern toloss_handle.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_autograd.cpp` around lines 209 - 215, The code currently constructs and assigns *loss_handle (via reinterpret_cast<mlx_array*>(new array(std::move(value)))) before validating gradients.size() against input_count, which can leak memory if validation fails; move the allocation/assignment of loss_handle to occur only after verifying gradients.size() == input_count (the same point where grad_handles are populated), i.e., remove the early assignment near loss_handle and perform the new array(...) and *loss_handle = ... only after the gradients size check succeeds so ownership is unambiguous and consistent with how grad_handles are set.crates/mlx-sys/src/mlx_stream.cpp-83-116 (1)
83-116:⚠️ Potential issue | 🟠 Major
mlx_metal_device_info()has a data race on shared static JSON buffer.
static std::string info_jsonis mutated without synchronization across multiple code paths (lines 87, 110, 113), and the function returns a pointer to this buffer. Concurrent calls can race and corrupt data, or callers may use the pointer after it's been overwritten by another invocation.crates/mlx-core/src/models/qwen3_5/quantized_linear.rs-99-104 (1)
99-104:⚠️ Potential issue | 🟠 MajorAdd dtype validation to
try_build_mxfp8_quantized_linearto ensure per-layer MXFP8 applicability.
try_build_mxfp8_quantized_linearcurrently builds MXFP8 whenever the weight and scales keys exist, without verifying that scales is actuallyUint8. In mixed checkpoints with heterogeneous quantization, this misclassifies layers and runs them with incorrect quantization mode.Proposed fix
pub fn try_build_mxfp8_quantized_linear( params: &HashMap<String, MxArray>, key_prefix: &str, ) -> Option<QuantizedLinear> { let weight = params.get(&format!("{}.weight", key_prefix))?; let scales = params.get(&format!("{}.scales", key_prefix))?; + if !matches!(scales.dtype(), Ok(crate::array::DType::Uint8)) { + return None; + } Some(QuantizedLinear::new( weight.clone(), scales.clone(), None, None, MXFP8_GROUP_SIZE, MXFP8_BITS, MXFP8_MODE.to_string(), )) }🤖 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/quantized_linear.rs` around lines 99 - 104, The builder try_build_mxfp8_quantized_linear currently assumes MXFP8 if weight and scales keys exist; update it to validate that the per-layer scales MxArray has dtype Uint8 before constructing MXFP8 Linear so heterogeneous checkpoints aren't misclassified; locate the weight/scales key lookup in try_build_mxfp8_quantized_linear, check the scales value via v.dtype() == Ok(crate::array::DType::Uint8) (or call the helper is_mxfp8_checkpoint behavior per-key), and only proceed to build the MXFP8 quantized linear when that dtype check passes, otherwise fall back to the non-MXFP8 path.crates/mlx-sys/src/mlx_qwen35.cpp-621-629 (1)
621-629:⚠️ Potential issue | 🟠 MajorGuard out-parameters before dereferencing.
Line 628 and Line 675 assign through
*output_logitswithout first checkingoutput_logits != nullptr, which can segfault on malformed callers.🛡️ Suggested guard
void mlx_qwen35_forward_compiled(..., mlx_array** output_logits, ...) { + if (!output_logits) return; + *output_logits = nullptr; if (!g_compile_inited) { - *output_logits = nullptr; return; }Also applies to: 672-680
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_qwen35.cpp` around lines 621 - 629, In mlx_qwen35_forward_compiled, guard the out-parameters before any dereference: check if output_logits and cache_offset_out are non-null before assigning through *output_logits or *cache_offset_out, and if the pointers are null still return early (or skip assignments) to avoid segfaults; locate assignments to *output_logits and *cache_offset_out in mlx_qwen35_forward_compiled and add null checks so you only write to them when the corresponding pointer is valid, and still set local defaults or return gracefully when they are null.crates/mlx-sys/src/mlx_array_ops.cpp-131-136 (1)
131-136:⚠️ Potential issue | 🟠 MajorGuard
value_handleinmlx_array_full.Line 131 dereferences
value_handleunconditionally; null input will crash.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_array_ops.cpp` around lines 131 - 136, The function that builds a full array dereferences value_handle unconditionally (see value_handle, mlx_array_full, array, make_shape, full); add a null check at the start of mlx_array_full to guard value_handle, return nullptr (or an appropriate error sentinel) immediately if value_handle is null, and avoid dereferencing it when constructing result; ensure subsequent code still uses the checked value_handle (e.g., cast to array* only after the null check) so no null deref occurs.crates/mlx-sys/src/mlx_advanced_ops.cpp-1201-1203 (1)
1201-1203:⚠️ Potential issue | 🟠 MajorValidate
num_layers > 0before readingcache_indices[0].Line 1202/1333/1625/1728 assumes at least one layer. If
num_layers == 0, this is out-of-bounds and undefined behavior.Also applies to: 1332-1334, 1625-1626, 1728-1729
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_advanced_ops.cpp` around lines 1201 - 1203, Before dereferencing cache_indices[0], validate that num_layers > 0 and handle the empty case: add a guard (e.g., if (num_layers == 0) { /* handle */ }) that either returns an error status or assigns a safe value to *out_cache_idx and exits the function; update the same pattern at the other occurrences mentioned. Locate the code that writes *out_cache_idx using cache_indices[0] (uses symbols cache_indices, out_cache_idx, num_layers) and implement the early check+graceful handling there.crates/mlx-sys/src/mlx_nn_ops.cpp-31-39 (1)
31-39:⚠️ Potential issue | 🟠 MajorGuard
handlesbefore indexing inmlx_async_eval.Line 36 reads
handles[i]without checkinghandles != nullptr. If caller passes null withcount > 0, this segfaults.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_nn_ops.cpp` around lines 31 - 39, In mlx_async_eval, guard the handles pointer before indexing: check if handles is nullptr at the start of the function (and handle the case when count > 0) and early-return or propagate an error instead of dereferencing; update the code around the loop that reads handles[i] to only iterate when handles != nullptr (or throw/log when handles==nullptr && count>0) so the code that constructs the std::vector<array> from handles is safe.crates/mlx-sys/src/mlx_advanced_ops.cpp-1864-1870 (1)
1864-1870:⚠️ Potential issue | 🟠 MajorFix inconsistent optional parameter handling in quantized operations.
mlx_quantized_matmulandmlx_gather_qmmpassgroup_sizeandbitsdirectly intostd::optionalwithout validating for non-positive values, unlikemlx_quantizeandmlx_dequantizewhich convert non-positive values tostd::nullopt. This inconsistency can cause unexpected behavior.Apply the same validation pattern used in
mlx_quantize/mlx_dequantize:Suggested fix for mlx_quantized_matmul (lines 1864-1870)
+ std::optional<int> gs = group_size > 0 ? std::optional<int>(group_size) : std::nullopt; + std::optional<int> b = bits > 0 ? std::optional<int>(bits) : std::nullopt; mlx::core::array result = mlx::core::quantized_matmul( *x_arr, *w_arr, *scales_arr, biases_opt, transpose, - std::optional<int>(group_size), - std::optional<int>(bits), + gs, + b, mode_str );Also applies to
mlx_gather_qmm(lines 1919-1923).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_advanced_ops.cpp` around lines 1864 - 1870, The call into mlx::core::quantized_matmul is creating std::optional<int> from group_size and bits directly; mirror the pattern from mlx_quantize/mlx_dequantize by converting non-positive values to std::nullopt: compute std::optional<int> opt_group = (group_size > 0 ? std::optional<int>(group_size) : std::nullopt) and similarly for opt_bits, then pass opt_group and opt_bits into quantized_matmul (and apply the same change in mlx_gather_qmm where group_size/bits are wrapped). Ensure you reference the existing local names group_size and bits and replace the direct std::optional<int>(...) usages with these validated optionals.packages/lm/src/models/model-loader.ts-31-41 (1)
31-41:⚠️ Potential issue | 🟠 MajorDo not silently coerce unknown/invalid
model_typeto Qwen3.
Line 83returns arbitraryconfig.model_type, andLines 33-41default everything unrecognized toQwen3Model. That can load the wrong architecture and fail later with hard-to-debug runtime errors.💡 Proposed fix
+type SupportedModelType = 'qwen3' | 'qwen3_5' | 'qwen3_5_moe'; + static async loadPretrained( modelPath: string, _deviceMap: string = 'auto', ): Promise<Qwen3Model | Qwen3_5Model | Qwen3_5MoeModel> { const modelType = await detectModelType(modelPath); if (modelType === 'qwen3_5_moe') { return await Qwen35MoeModel.loadPretrained(modelPath); } if (modelType === 'qwen3_5') { return await Qwen35Model.loadPretrained(modelPath); } + if (modelType !== 'qwen3') { + throw new Error(`Unsupported model_type: ${modelType}`); + } return await Qwen3Model.loadPretrained(modelPath); } -async function detectModelType(modelPath: string): Promise<string> { +async function detectModelType(modelPath: string): Promise<SupportedModelType> { try { const raw = await readFile(join(modelPath, 'config.json'), 'utf-8'); - const config = JSON.parse(raw); - return config.model_type ?? 'qwen3'; - } catch { - return 'qwen3'; + const config = JSON.parse(raw) as { model_type?: string }; + const mt = config.model_type ?? 'qwen3'; + if (mt === 'qwen3' || mt === 'qwen3_5' || mt === 'qwen3_5_moe') return mt; + throw new Error(`Unsupported model_type in config.json: ${mt}`); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'qwen3'; + throw error; } }As per coding guidelines: "Model loaders must handle SafeTensors weight files and return fully initialized model instances with inference capability".
Also applies to: 79-86
🤖 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 31 - 41, The loader currently coerces any unknown config.model_type into Qwen3 by calling Qwen3Model.loadPretrained, which can load the wrong architecture; update detectModelType/model loading logic (the code around detectModelType, and the branches that call Qwen35MoeModel.loadPretrained, Qwen35Model.loadPretrained, Qwen3Model.loadPretrained) to explicitly handle only known types and throw a descriptive error for unrecognized model types (include the raw config.model_type value in the error message) instead of defaulting to Qwen3; ensure the thrown error prevents further loading so callers know the model_type is invalid.crates/mlx-core/src/models/qwen3_5/switch_glu.rs-55-57 (1)
55-57:⚠️ Potential issue | 🟠 MajorGuard against panics and zero-divide in shape/index handling.
Line 76(unwrap) andLines 152-153(direct indexing) can panic on malformed input. AlsoLine 83can divide by zero when the lastindicesdim is0.💡 Proposed fix
fn 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"))?; + if m <= 0 { + return Err(Error::from_reason("indices last dimension must be > 0")); + } @@ let x_shape = x.shape()?; - let d = *x_shape.last().unwrap(); + let d = *x_shape + .last() + .ok_or_else(|| Error::from_reason("x must have at least 1 dimension"))?; @@ pub fn forward(&self, x: &MxArray, indices: &MxArray) -> Result<MxArray> { let x_shape = x.shape()?; + if x_shape.len() < 2 { + return Err(Error::from_reason("x must be rank-2 [B*T, D]")); + } let ne = x_shape[0]; let d = x_shape[1];Also applies to: 76-83, 150-154
🤖 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_glu.rs` around lines 55 - 57, The gather_sort function must defensively handle empty/malformed shapes and zero-length dimensions: replace all direct unwraps and direct indexing on idx_shape/indices with checked operations (use idx_shape.last().ok_or_else(...) already started—ensure every call that used unwrap uses ok_or or match), return an Err if idx_shape is empty or if m (the last dimension size) is zero to avoid division-by-zero, and replace direct indexing into x/indices (the spots referenced around lines 150–154) with bounds-checked access (e.g., get or match on Option) and return a clear Error::from_reason on out-of-bounds; ensure all calculations that divide by m first check m != 0. Apply these changes to the gather_sort function and any helper code it calls so no unwraps or unchecked indexing remain.crates/mlx-core/src/models/qwen3_5_moe/persistence.rs-809-827 (1)
809-827:⚠️ Potential issue | 🟠 MajorTighten mandatory-weight validation to prevent partial model loads.
has_attn/has_mlpcurrently pass when only one key exists. That can report success while required projections are still missing for a layer.🔧 Suggested direction (strict per-layer checks)
- for i in 0..num_layers { + for (i, layer) in layers.iter().enumerate() { let prefix = format!("layers.{}", i); - let has_attn = params.contains_key(&format!("{}.self_attn.q_proj.weight", prefix)) - || params.contains_key(&format!("{}.self_attn.q_proj.scales", prefix)) - || params.contains_key(&format!("{}.linear_attn.in_proj_qkvz.weight", prefix)) - || params.contains_key(&format!("{}.linear_attn.in_proj_qkvz.scales", prefix)) - || params.contains_key(&format!("{}.linear_attn.in_proj_qkv.weight", prefix)) - || params.contains_key(&format!("{}.linear_attn.in_proj_qkv.scales", prefix)); + let has_attn = match (&layer.attn, is_quantized) { + (AttentionType::Full(_), true) => { + ["q_proj","k_proj","v_proj","o_proj"].iter().all(|p| + params.contains_key(&format!("{}.self_attn.{}.scales", prefix, p)) || + params.contains_key(&format!("{}.self_attn.{}.weight", prefix, p)) + ) + } + (AttentionType::Full(_), false) => { + ["q_proj","k_proj","v_proj","o_proj"].iter().all(|p| + params.contains_key(&format!("{}.self_attn.{}.weight", prefix, p)) + ) + } + (AttentionType::Linear(_), _) => { + // require in_proj_qkvz + in_proj_ba + out_proj (+conv/dt_bias/etc. if mandatory) + ... + } + };Based on learnings: Model loaders must handle SafeTensors weight files and return fully initialized model instances with inference capability.
Also applies to: 855-860
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/models/qwen3_5_moe/persistence.rs` around lines 809 - 827, The current per-layer checks (has_attn / has_mlp) treat a layer as having attention/MLP if any one of several keys exists, allowing partial/invalid loads; change the logic in the loop that iterates 0..num_layers to require all mandatory keys for each subsystem to be present: for attention ensure the full set of required keys (e.g., "{prefix}.self_attn.q_proj.weight", "{prefix}.self_attn.q_proj.scales", "{prefix}.linear_attn.in_proj_qkvz.weight", "{prefix}.linear_attn.in_proj_qkvz.scales", "{prefix}.linear_attn.in_proj_qkv.weight", "{prefix}.linear_attn.in_proj_qkv.scales") are present in params before considering has_attn true, and similarly require the complete set of MLP keys (e.g., "{prefix}.mlp.gate_proj.weight", "{prefix}.mlp.gate.weight", "{prefix}.mlp.gate.scales", "{prefix}.mlp.switch_mlp.gate_proj.weight", "{prefix}.mlp.switch_mlp.gate_proj.scales") for has_mlp; if any required key is missing, push the layer index into layers_missing_attn or layers_missing_mlp respectively so partial layers fail validation (apply the same stricter check to the analogous checks around the other occurrence you noted).crates/mlx-core/src/models/qwen3_5_moe/persistence.rs-999-1060 (1)
999-1060:⚠️ Potential issue | 🟠 MajorValidate core head/routing fields before constructing config.
parse_configcurrently allows invalid values (e.g.,num_heads <= 0,num_kv_heads <= 0,num_experts_per_tok <= 0or> num_experts) to pass through.🔧 Suggested validation additions
if hidden_size <= 0 { return Err(Error::from_reason(format!( "Invalid config: hidden_size must be > 0, got {}", hidden_size ))); } + if num_heads <= 0 { + return Err(Error::from_reason(format!( + "Invalid config: num_attention_heads must be > 0, got {}", + num_heads + ))); + } + if num_kv_heads <= 0 { + return Err(Error::from_reason(format!( + "Invalid config: num_key_value_heads must be > 0, got {}", + num_kv_heads + ))); + } + if head_dim <= 0 { + return Err(Error::from_reason(format!( + "Invalid config: head_dim must be > 0, got {}", + head_dim + ))); + } @@ if num_experts <= 0 { return Err(Error::from_reason(format!( "MoE config requires num_experts > 0, got {}", num_experts ))); } + if num_experts_per_tok <= 0 || num_experts_per_tok > num_experts { + return Err(Error::from_reason(format!( + "Invalid config: num_experts_per_tok must be in [1, num_experts], got {} with num_experts={}", + num_experts_per_tok, num_experts + ))); + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/models/qwen3_5_moe/persistence.rs` around lines 999 - 1060, parse_config reads num_heads, num_kv_heads, num_experts, num_experts_per_tok and computes head_dim but never validates core routing/head fields; add checks right after those values are read (before using head_dim or returning the config) to ensure num_heads > 0, num_kv_heads > 0, num_experts > 0 (already checked) and num_experts_per_tok > 0 and <= num_experts, and also validate computed head_dim > 0; return an Error::from_reason with a clear message when any check fails. Reference the variables/functions in the diff: num_heads, num_kv_heads, num_experts, num_experts_per_tok, head_dim and the parse_config code path that constructs the config.
🟡 Minor comments (3)
examples/test-converted-model.ts-71-73 (1)
71-73:⚠️ Potential issue | 🟡 MinorHandle 0ms elapsed time in throughput calculation.
Line 72 can emit
Infinitytokens/s whenduration === 0.Suggested fix
- const duration = Date.now() - startTime; - const tokensPerSecond = (numTokens / duration) * 1000; + const duration = Date.now() - startTime; + const elapsedMs = Math.max(duration, 1); + const tokensPerSecond = (numTokens / elapsedMs) * 1000;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/test-converted-model.ts` around lines 71 - 73, The throughput calc can produce Infinity when duration === 0; change the computation around variables duration, startTime, numTokens and tokensPerSecond to guard against zero elapsed time by checking if duration === 0 and using a safe fallback (for example, extrapolate tokens/sec as numTokens * 1000 or set to 0) instead of performing (numTokens / duration) * 1000; update the assignment to tokensPerSecond to use that conditional expression so the value is finite.crates/mlx-core/src/models/qwen3_5_moe/decoder_layer.rs-114-125 (1)
114-125:⚠️ Potential issue | 🟡 MinorProtect MoE layers from accidental overwrite in
set_quantized_dense_mlp.This mutator always replaces
self.mlpwithDense, even if the layer is currentlyMoE. It should fail fast on non-dense layers.🔧 Suggested API hardening
- pub fn set_quantized_dense_mlp( + pub fn set_quantized_dense_mlp( &mut self, gate_proj: QuantizedLinear, up_proj: QuantizedLinear, down_proj: QuantizedLinear, - ) { + ) -> Result<()> { + if !matches!(self.mlp, MLPType::Dense(_)) { + return Err(Error::from_reason("set_quantized_dense_mlp called on MoE layer")); + } self.mlp = MLPType::Dense(MLPVariant::Quantized { gate_proj, up_proj, down_proj, }); + Ok(()) }🤖 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/decoder_layer.rs` around lines 114 - 125, The mutator set_quantized_dense_mlp currently unconditionally replaces self.mlp with MLPType::Dense(MLPVariant::Quantized{...}); change it to first check the current enum variant of self.mlp and fail fast if it's not a Dense variant (e.g., if it's an MoE variant) — either return a Result error or panic with a clear message like "attempt to overwrite MoE layer" — ensuring the guard is performed in set_quantized_dense_mlp before assigning the new MLPVariant::Quantized (referencing set_quantized_dense_mlp, self.mlp, MLPType::Dense, MLPVariant::Quantized and MoE).crates/mlx-core/src/models/qwen3_5_moe/sparse_moe.rs-68-88 (1)
68-88:⚠️ Potential issue | 🟡 MinorMissing validation in
new_quantizedconstructor.The
new()constructor validates thatnum_experts > 0and0 < num_experts_per_tok <= num_experts, butnew_quantized()does not. This could allow invalid configurations when creating quantized blocks directly.🛡️ Proposed fix to add validation
pub fn new_quantized( config: &Qwen3_5MoeConfig, gate: QuantizedLinear, switch_mlp: SwitchGLU, shared_expert: MLPVariant, shared_expert_gate: QuantizedLinear, ) -> Result<Self> { let num_experts = config.num_experts; let num_experts_per_tok = config.num_experts_per_tok; let norm_topk_prob = config.norm_topk_prob; + if num_experts <= 0 { + return Err(Error::from_reason(format!( + "SparseMoeBlock requires num_experts > 0, got {}", + num_experts + ))); + } + if num_experts_per_tok <= 0 || num_experts_per_tok > num_experts { + return Err(Error::from_reason(format!( + "SparseMoeBlock requires 0 < num_experts_per_tok <= num_experts, got {} (num_experts={})", + num_experts_per_tok, num_experts + ))); + } + Ok(Self {🤖 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/sparse_moe.rs` around lines 68 - 88, new_quantized currently omits the input validation performed in new(), so add the same checks at the start of new_quantized: verify config.num_experts > 0 and that 0 < config.num_experts_per_tok && config.num_experts_per_tok <= config.num_experts; if a check fails return an Err with a clear message (matching the crate's Result/Error convention). Implement this in the pub fn new_quantized(...) before constructing Self (referencing new_quantized, config.num_experts, and config.num_experts_per_tok).
🧹 Nitpick comments (11)
crates/mlx-sys/src/mlx_misc_ops.cpp (1)
358-589: Consider extracting shared filter logic to avoid drift.
mlx_sample_and_logprobsandmlx_compiled_sample_and_logprobsduplicate the top_k/top_p/min_p filtering pipeline almost verbatim. A shared helper would reduce maintenance risk and keep behavior aligned.🤖 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 358 - 589, Both mlx_sample_and_logprobs and mlx_compiled_sample_and_logprobs duplicate the top_k/top_p/min_p filtering pipeline; extract that pipeline into a single helper (e.g., a function named apply_sampling_filters or filter_logprobs that takes_array logprobs, int top_k, float top_p, float min_p and returns a filtered array) and call it from both mlx_sample_and_logprobs and mlx_compiled_sample_and_logprobs. Ensure the helper preserves the original_logprobs for return (call it before modifying original_logprobs or return a new filtered array), implements the same operations used now (negation/argpartition/put_along_axis for top_k, argsort/cumsum/where with EPSILON for top_p, and the min_p sorted/keep-first logic), and is used in both code paths (including the compiled_sampler path) so behavior remains identical and maintenance is centralized.scripts/convert-model.ts (1)
75-97: Add strict CLI validation for quantization flag values.
--q-bits,--q-group-size, and--q-modeare only partially validated. Enforcing valid ranges/enums here gives clearer errors before calling native conversion.Suggested fix
case '--q-bits': { - const bits = parseInt(argv[++i], 10); - if (isNaN(bits)) { - console.error('Error: --q-bits requires a numeric value'); + const bits = Number.parseInt(argv[++i] ?? '', 10); + if (!Number.isInteger(bits) || (bits !== 4 && bits !== 8)) { + console.error('Error: --q-bits must be 4 or 8'); process.exit(1); } args.quantBits = bits; break; } case '--q-group-size': { - const gs = parseInt(argv[++i], 10); - if (isNaN(gs)) { - console.error('Error: --q-group-size requires a numeric value'); + const gs = Number.parseInt(argv[++i] ?? '', 10); + if (!Number.isInteger(gs) || gs <= 0) { + console.error('Error: --q-group-size must be a positive integer'); process.exit(1); } args.quantGroupSize = gs; break; } - case '--q-mode': - args.quantMode = argv[++i]; + case '--q-mode': { + const mode = argv[++i]; + if (mode !== 'affine' && mode !== 'mxfp8') { + console.error('Error: --q-mode must be "affine" or "mxfp8"'); + process.exit(1); + } + args.quantMode = mode; break; + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@scripts/convert-model.ts` around lines 75 - 97, Validate and enforce allowed values for the quant flags: after parsing argv for --q-bits set args.quantBits only if the parsed value is one of the supported integers (e.g., 2,3,4,8) otherwise print a clear error and exit; for --q-group-size set args.quantGroupSize only if parsed value is a positive integer (and optionally within a max or power-of-two constraint your converter expects) otherwise print a clear error and exit; for --q-mode validate argv[++i] against the allowed enum of mode strings (e.g., "pertensor", "perchannel", "symmetric", etc.) before assigning to args.quantMode and error/exit on unknown values; update the error messages in these branches to include the invalid value and the allowed set and ensure assignments only happen after validation (referencing args.quantBits, args.quantGroupSize, and args.quantMode).crates/mlx-sys/src/metal/gated_delta_step_vec.metal.inc (1)
2-3: Preconditions ARE enforced upstream in Rust wrapper; adding dispatcher guards would improve robustness.The constraints
Hv % Hk == 0andDk % 32 == 0are already validated in the Rust caller (gated_delta.rslines 319–346): the GQA expansion checksnum_v_heads % num_k_heads != 0, and the kernel selection checksk_dim % 32 == 0. However, the C++ dispatcher itself (mlx_gated_delta.cpplines 71–145) does not validate these preconditions before selecting the vectorized kernel variant. While the current design relies on caller validation and poses no risk with proper usage, adding explicit guards in the dispatcher would improve code robustness and prevent potential issues if the C++ function is called directly or from other paths.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/metal/gated_delta_step_vec.metal.inc` around lines 2 - 3, Add explicit precondition checks in the C++ dispatcher in mlx_gated_delta.cpp before selecting the vectorized kernel: verify that Hv % Hk == 0 (or equivalently num_v_heads % num_k_heads == 0) and that Dk % 32 == 0 (k_dim % 32 == 0); if either check fails, log a clear error including the offending values and return a failure (or fall back to the non-vectorized kernel) instead of unconditionally choosing the vectorized path. Update the dispatcher selection logic that currently picks the vectorized kernel variant to perform these guards using the same symbols (Hv, Hk, Dk / num_v_heads, num_k_heads, k_dim) so callers that bypass the Rust wrapper are protected.crates/mlx-sys/src/metal/gated_delta_step.metal.inc (1)
10-10: Consider removing the redundantif (true)branch.The
if (true)condition on line 10 is a no-op that adds unnecessary branching. While it maintains structural consistency with the masked variant (gated_delta_step_mask.metal.inc), removing it would simplify the code and may provide a minor performance benefit by eliminating dead code evaluation.♻️ Optional: Remove redundant condition
- 0; t < T; ++t) { if (true) { float kv_mem = 0.0f; for (int i = 0; i < n_per_t; ++i) { auto s_idx = n_per_t * dk_idx + + 0; t < T; ++t) { float kv_mem = 0.0f; for (int i = 0; i < n_per_t; ++i) { auto s_idx = n_per_t * dk_idx +Note: This would also require removing the corresponding closing brace.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/metal/gated_delta_step.metal.inc` at line 10, Remove the redundant if (true) branch inside gated_delta_step.metal.inc around the inner loop (the block starting with "if (true) {") by deleting the "if (true) {" token and its matching closing brace so the code directly executes the inner for-loop (the loop over i and use of kv_mem and s_idx) without the no-op conditional; update indentation as needed to keep the surrounding outer loop (the "for (int t = 0; t < T; ++t)") structure intact.crates/mlx-core/src/models/qwen3_5/gated_delta.rs (1)
276-281: Log kernel fallback errors for diagnosability.
Line 278drops the kernel error and silently falls back. Emitting a warn/debug log with the error would make Metal-path regressions much easier to triage.🤖 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.rs` around lines 276 - 281, The fallback swallow in the gated_delta implementation should log the kernel error for diagnosability: in the match over gated_delta_kernel(&q, &k, v, &g, &beta, &initial_state, mask) replace Err(_) with Err(e) and emit a warning/debug log (e.g., via the module logger or tracing::warn! / log::warn!) that includes the error value and context (mentioning gated_delta_kernel and relevant inputs like device/path), then continue with the existing fallback path; ensure the log message is concise but contains the error to aid triage.crates/mlx-core/src/models/qwen3_5/model.rs (1)
245-467: Extract shared decode logic used bygenerateandchat.These blocks now duplicate nearly the entire prefill/compiled-init/decode loop. A shared internal worker would reduce drift and bug-fix duplication.
Also applies to: 505-719
🤖 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 245 - 467, The generate and chat implementations duplicate the entire prefill / compiled-init / decode loop (including forward_with_locks, forward_compiled, eval_token_and_compiled_caches, eval_token_and_caches and the postfill cleanup), so extract that logic into a shared internal worker function (e.g., qwen3_5_shared_decode or decode_worker) that accepts the common inputs (prompt_tokens, embedding_weight, embedding_weight_t, layers_arc, final_norm_arc, lm_head_arc, caches_arc, model_config, config/sampling params, tokenizer, fa_idx, generation_stream/max_tokens) and returns Qwen3_5GenerationResult; then have both generate and chat call this new function, moving prefill, compiled init, decode loop, compiled reset, and decoding-to-text into the shared worker to eliminate duplication and keep helpers like forward_with_locks/forward_compiled/eval_* usage unchanged.crates/mlx-core/src/models/qwen3_5/switch_glu.rs (1)
191-205: Avoid silent no-op behavior inset_*_proj_weightfor quantized variants.These setters currently do nothing when the projection is quantized, which can hide configuration mistakes. Returning
Result<()>with an explicit error for quantized variants would be safer.🤖 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_glu.rs` around lines 191 - 205, The setters set_gate_proj_weight, set_up_proj_weight, and set_down_proj_weight silently no-op when self.gate_proj / up_proj / down_proj is a quantized SwitchProj; change each to return Result<(), E> (e.g., anyhow::Result<()> or the crate's error type), match on SwitchProj and call l.set_weight(w) in the Standard arm returning Ok(()), and return an explicit Err(...) for the quantized variant with a clear message referencing the projection and that quantized weights cannot be set; update all call sites to propagate the Result. Ensure you reference the SwitchProj enum and the three methods when making these changes.crates/mlx-core/src/utils/safetensors.rs (1)
463-468: Expand tests for the newly added dtype branches.
test_dtype_byte_sizesstill covers only legacy variants; the new U8/U32/F8 paths are currently unguarded by unit tests.✅ Suggested test additions
#[test] fn test_dtype_byte_sizes() { assert_eq!(SafeTensorDType::F32.byte_size(), 4); assert_eq!(SafeTensorDType::F16.byte_size(), 2); assert_eq!(SafeTensorDType::BF16.byte_size(), 2); assert_eq!(SafeTensorDType::I32.byte_size(), 4); + assert_eq!(SafeTensorDType::U8.byte_size(), 1); + assert_eq!(SafeTensorDType::U32.byte_size(), 4); + assert_eq!(SafeTensorDType::F8_E4M3.byte_size(), 1); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/utils/safetensors.rs` around lines 463 - 468, The unit test test_dtype_byte_sizes only asserts legacy variants; add assertions for the new SafeTensorDType variants U8, U32, and F8 to ensure their byte_size() returns the correct values (e.g., U8 -> 1, U32 -> 4, F8 -> appropriate size defined by F8.byte_size()). Update the test function test_dtype_byte_sizes to include assert_eq! calls for SafeTensorDType::U8.byte_size(), SafeTensorDType::U32.byte_size(), and SafeTensorDType::F8.byte_size() so all branches are covered by tests.crates/mlx-core/src/models/qwen3_5_moe/switch_glu.rs (2)
37-60: Potential panic on empty shape ingather_sort.At line 49,
x_shape.last().unwrap()could panic ifx_shapeis empty. While this is unlikely given the expected usage, it would be safer to handle this consistently with line 41 which usesok_or_else.🛡️ Proposed defensive fix
let x_shape = x.shape()?; - let d = *x_shape.last().unwrap(); + let d = *x_shape + .last() + .ok_or_else(|| Error::from_reason("empty x shape"))?; let x_flat = x.reshape(&[-1, 1, d])?;🤖 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/switch_glu.rs` around lines 37 - 60, The function gather_sort currently uses x_shape.last().unwrap() which can panic on an empty shape; replace that unwrap with the same defensive pattern used for indices (e.g., let d = *x_shape.last().ok_or_else(|| Error::from_reason("empty x shape"))?;) so the function returns a proper Error instead of panicking, keeping the rest of the logic (MxArray::scalar_int, reshape/take operations, and the GatherSortResult construction) unchanged.
125-139: Weight setters silently no-op for quantized projections.The
set_*_proj_weightmethods silently do nothing when called on quantized projections. This is likely intentional for a unified loading API, but could mask bugs if a caller mistakenly tries to set weights on a quantized model expecting it to work.Consider adding a debug/trace log or returning
Result<()>to make the behavior explicit.🤖 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/switch_glu.rs` around lines 125 - 139, The three setters (set_gate_proj_weight, set_up_proj_weight, set_down_proj_weight) currently silently no-op for non-Standard SwitchProj variants; change them to return a Result<(), YourErrorType> (or Option) and return an Err or None when the projection is not SwitchProj::Standard so callers are explicitly informed, updating all call sites accordingly; alternatively, if you prefer logging, add a debug/trace log inside the non-Standard branch that includes the projection variant and the function name (set_gate_proj_weight/set_up_proj_weight/set_down_proj_weight) so the no-op is observable during testing.crates/mlx-core/src/models/qwen3_5_moe/model.rs (1)
516-571: Parameter counting formula may need verification.The
num_parameters()method provides useful diagnostics. The linear layer parameter formula (lines 546-554) appears complex - consider adding inline comments to clarify each term for maintainability.🤖 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 516 - 571, The num_parameters() implementation has a complex linear-layer parameter expression in the loop (see num_parameters, is_linear_layer, is_moe_layer and config fields like linear_key_dim, linear_value_dim, linear_num_value_heads, linear_value_head_dim, linear_conv_kernel_dim) that needs verification and clarification: rewrite the linear-branch to compute each contribution in clearly named temporaries (e.g., key_proj_params, value_proj_params, value_head_params, conv_params, bias_terms) and add concise inline comments explaining what each term counts (shapes and why multiplied), or extract a small helper function (e.g., count_linear_layer_params(layer_idx) -> i64) to encapsulate the math; ensure the final sum reproduces the existing terms (kd, vd, num_vh, vhd, conv kernel dim, etc.) and run a quick cross-check so totals match expected dimensions after refactor.
ℹ️ Review info
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (59)
__test__/models/qwen3-chat.test.ts__test__/models/qwen3_5-moe.test.tscrates/mlx-core/src/array/creation.rscrates/mlx-core/src/array/data.rscrates/mlx-core/src/array/mod.rscrates/mlx-core/src/convert.rscrates/mlx-core/src/models/mod.rscrates/mlx-core/src/models/qwen3_5/arrays_cache.rscrates/mlx-core/src/models/qwen3_5/attention.rscrates/mlx-core/src/models/qwen3_5/config.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/layer_cache.rscrates/mlx-core/src/models/qwen3_5/mod.rscrates/mlx-core/src/models/qwen3_5/model.rscrates/mlx-core/src/models/qwen3_5/persistence.rscrates/mlx-core/src/models/qwen3_5/quantized_linear.rscrates/mlx-core/src/models/qwen3_5/sparse_moe.rscrates/mlx-core/src/models/qwen3_5/switch_glu.rscrates/mlx-core/src/models/qwen3_5_moe/config.rscrates/mlx-core/src/models/qwen3_5_moe/decoder_layer.rscrates/mlx-core/src/models/qwen3_5_moe/mod.rscrates/mlx-core/src/models/qwen3_5_moe/model.rscrates/mlx-core/src/models/qwen3_5_moe/persistence.rscrates/mlx-core/src/models/qwen3_5_moe/quantized_linear.rscrates/mlx-core/src/models/qwen3_5_moe/sparse_moe.rscrates/mlx-core/src/models/qwen3_5_moe/switch_glu.rscrates/mlx-core/src/models/qwen3_5_moe/switch_linear.rscrates/mlx-core/src/nn/activations.rscrates/mlx-core/src/transformer/kv_cache.rscrates/mlx-core/src/transformer/quantized_kv_cache.rscrates/mlx-core/src/utils/safetensors.rscrates/mlx-sys/build.rscrates/mlx-sys/src/lib.rscrates/mlx-sys/src/metal/gated_delta_step.metal.inccrates/mlx-sys/src/metal/gated_delta_step_mask.metal.inccrates/mlx-sys/src/metal/gated_delta_step_vec.metal.inccrates/mlx-sys/src/metal/gated_delta_step_vec_mask.metal.inccrates/mlx-sys/src/mlx.cppcrates/mlx-sys/src/mlx_advanced_ops.cppcrates/mlx-sys/src/mlx_array_ops.cppcrates/mlx-sys/src/mlx_autograd.cppcrates/mlx-sys/src/mlx_common.hcrates/mlx-sys/src/mlx_fused_ops.cppcrates/mlx-sys/src/mlx_gated_delta.cppcrates/mlx-sys/src/mlx_misc_ops.cppcrates/mlx-sys/src/mlx_nn_ops.cppcrates/mlx-sys/src/mlx_qwen35.cppcrates/mlx-sys/src/mlx_stream.cppexamples/debug_unwarp.tsexamples/test-converted-model.tsexamples/test-mlx-vlm-speed.pyexamples/tool-use-example.tspackages/core/index.cjspackages/core/index.d.ctspackages/lm/src/index.tspackages/lm/src/models/model-loader.tsscripts/convert-model.ts
💤 Files with no reviewable changes (3)
- examples/test-mlx-vlm-speed.py
- examples/debug_unwarp.ts
- crates/mlx-core/src/models/qwen3_5/arrays_cache.rs
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/lm/src/models/model-loader.ts`:
- Around line 19-21: Update the docstring for loadPretrained to mention that it
delegates not only to loadQwen35 for "qwen3_5" models but also to the MoE
variant for "qwen3_5_moe"; specifically, expand the comment block that currently
references loadQwen35 to also call out the qwen3_5_moe case and the function or
code path used to handle MoE models so readers know loadPretrained will forward
both qwen3_5 and qwen3_5_moe to the appropriate loader.
- Around line 77-85: The detectModelType function silently falls back to 'qwen3'
on any error; change it to first determine whether modelPath is a file or
directory (use fs.stat or equivalent) and, if modelPath is a file, look for
config.json in its parent directory; then read and JSON.parse the config and
validate that config.model_type is a string before returning it; only return
'qwen3' when the config file is genuinely missing (ENOENT) or not present, but
rethrow or surface other errors (like JSON parse errors, permission errors) so
malformed/permission issues aren't masked; keep references to detectModelType,
readFile, join and modelPath when making the changes.
…catch guards Fix 4 real issues from CodeRabbit review: 1. convert.rs: validate quant_group_size/quant_bits > 0 to prevent division by zero panic when user passes invalid values via NAPI 2. mlx_common.h: add missing `using mlx::core::add` import (relied on ADL) 3. mlx_gated_delta.cpp: add null checks + try/catch to mlx_fused_compute_g 4. mlx_qwen35.cpp: add try/catch to mlx_qwen35_compiled_init_from_prefill Also restore corrupted .metal.inc files (were minified to 19 lines, should be 69 lines with proper R"( raw string formatting). Co-Authored-By: Claude Opus 4.6 <[email protected]>
PR Review ResponseFixed (4 real issues) — commit facf85e
False Positives (12 dismissed)Items 3, 4, 6, 8, 12, 13, 15 (partial), 16 — "Wrap ALL FFI functions in try/catch" This PR split the monolithic Item 2 — "Thread safety of compiled decode global state" Pre-existing design pattern, not introduced by this PR. Node.js is single-threaded; model generation calls are serialized by the JS event loop. Weight mutation already uses Item 5 — "Validate axis before indexing" Callers always pass validated axis values from Rust model code. MLX's own Item 9 — "Causal masking incorrect for cached multi-token chunks" Dead code — Item 10 — "Guard FFI pointers in mlx_gated_delta_kernel" Already guarded: the function has try/catch (lines 82-142) and checks Item 14 — "Synchronize global weight cache access" Weight mutations ( |
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (4)
crates/mlx-sys/src/mlx_gated_delta.cpp (1)
71-143:⚠️ Potential issue | 🔴 CriticalHarden
mlx_gated_delta_kernelFFI boundary before any dereference.
mlx_gated_delta_kernelstill dereferences raw handles and output pointers before validating them. A null input/output pointer can crash the process, and the catch path currently also dereferencesout_y/out_stateunconditionally.🔧 Suggested hardening
bool mlx_gated_delta_kernel( mlx_array* q_handle, @@ mlx_array** out_y, mlx_array** out_state ) { + if (!q_handle || !k_handle || !v_handle || !g_handle || !beta_handle || !state_handle || + !out_y || !out_state) { + if (out_y) *out_y = nullptr; + if (out_state) *out_state = nullptr; + std::cerr << "[MLX] mlx_gated_delta_kernel: null handle" << std::endl; + return false; + } + try { @@ *out_y = reinterpret_cast<mlx_array*>(new array(std::move(results[0]))); *out_state = reinterpret_cast<mlx_array*>(new array(std::move(results[1]))); return true; } catch (const std::exception& e) { - std::cerr << "mlx_gated_delta_kernel error: " << e.what() << std::endl; - *out_y = nullptr; - *out_state = nullptr; + std::cerr << "[MLX] mlx_gated_delta_kernel: " << e.what() << std::endl; + if (out_y) *out_y = nullptr; + if (out_state) *out_state = nullptr; + return false; + } catch (...) { + std::cerr << "[MLX] mlx_gated_delta_kernel: unknown exception" << std::endl; + if (out_y) *out_y = nullptr; + if (out_state) *out_state = nullptr; return false; } }Based on learnings: In
crates/mlx-sys/src/mlx.cpp, allextern "C"FFI entry points must be wrapped in try/catch, log with an[MLX]prefix, and set safe sentinel outputs on failure.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_gated_delta.cpp` around lines 71 - 143, Validate all incoming raw pointers at the top of mlx_gated_delta_kernel before any dereference: check q_handle, k_handle, v_handle, g_handle, beta_handle, state_handle, and the output pointers out_y/out_state (mask_handle may be nullptr); if any required input is null, log an error with an "[MLX]" prefix (e.g. "[MLX] mlx_gated_delta_kernel error: <reason>") to std::cerr, and if out_y/out_state are non-null set them to safe sentinels (nullptr) and return false. Move all reinterpret_cast and array dereferences (q_arr, k_arr, v_arr, g_arr, beta_arr, state_arr, and mask when present) after the null checks. Also update the existing catch block to use the "[MLX]" prefix and only assign to *out_y/*out_state after verifying those pointers are non-null. Ensure no path writes through a null out pointer.crates/mlx-sys/src/mlx_qwen35.cpp (3)
500-515:⚠️ Potential issue | 🔴 CriticalWrap remaining exported C-ABI functions in
try/catch(Line 500).
mlx_qwen35_store_weight,mlx_qwen35_clear_weights,mlx_qwen35_weight_count, andmlx_qwen35_compiled_resetare still unguarded. Exceptions from STL/container ops can cross the FFI boundary.Proposed fix pattern
void mlx_qwen35_store_weight(const char* name, mlx_array* weight) { - std::lock_guard<std::mutex> lock(g_weights_mutex); - auto& arr = *reinterpret_cast<array*>(weight); - g_weights.insert_or_assign(std::string(name), arr); + try { + std::lock_guard<std::mutex> lock(g_weights_mutex); + auto& arr = *reinterpret_cast<array*>(weight); + g_weights.insert_or_assign(std::string(name), arr); + } catch (const std::exception& e) { + fprintf(stderr, "[MLX] mlx_qwen35_store_weight: %s\n", e.what()); + fflush(stderr); + } catch (...) { + fprintf(stderr, "[MLX] mlx_qwen35_store_weight: unknown exception\n"); + fflush(stderr); + } }Based on learnings: In
crates/mlx-sys/src/mlx.cpp, allextern "C"FFI entry points must be wrapped in try/catch to prevent exceptions from crossing the Rust FFI boundary.Also applies to: 725-730
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_qwen35.cpp` around lines 500 - 515, Wrap each exported C-ABI function (mlx_qwen35_store_weight, mlx_qwen35_clear_weights, mlx_qwen35_weight_count, and mlx_qwen35_compiled_reset) body in a try/catch block so STL exceptions cannot cross the FFI boundary: put the existing implementation inside try { ... } and add catch(const std::exception& e) { /* record e.what() via the project's FFI error-reporting helper (same pattern used in mlx.cpp) and return a safe error/zero value if needed */ } catch(...) { /* record a generic error and return safe value */ }; ensure the catch handlers mirror the pattern used in crates/mlx-sys/src/mlx.cpp for error reporting and return semantics so ABI callers never see C++ exceptions.
27-50:⚠️ Potential issue | 🔴 CriticalFix concurrent map access races in
get_weight*/has_weight(Line 27).
g_weightsandg_weight_transposesare accessed here without locking, while other paths mutate/clear them underg_weights_mutex(e.g., Line 506-510). This is undefined behavior under concurrent forward/reset/clear activity.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_qwen35.cpp` around lines 27 - 50, Accesses to g_weights and g_weight_transposes in get_weight, get_weight_t and has_weight must be synchronized with the existing g_weights_mutex to avoid UB from concurrent mutation; wrap reads and map lookups in a lock (e.g., std::lock_guard/std::scoped_lock on g_weights_mutex) and for get_weight_t use the double-checked pattern: lock and check g_weight_transposes, if missing copy or read the original weight under lock (or grab a reference but better to copy key data), unlock, perform the potentially expensive transpose, then lock again and insert the transposed result only if another thread hasn't already inserted it (use emplace and use the returned iterator), ensuring all direct accesses/insertions to g_weights and g_weight_transposes are done while holding g_weights_mutex.
500-504:⚠️ Potential issue | 🟠 MajorAdd null-pointer guards and try/catch wrapping to all extern "C" FFI functions to prevent crashes across the Rust boundary.
The function
mlx_qwen35_store_weight(line 500) dereferences bothnameandweightpointers without null checks or exception handling. Related functions at lines 526–546, 626–631, and 706–711 similarly lack complete protection: some have try/catch but no input validation; others have neither. Per FFI safety requirements, all extern "C" entry points must validate pointer inputs before dereferencing and wrap logic in try/catch to prevent exceptions crossing to Rust. On failure, return nullptr for pointer-returning functions and set out-parameters to safe sentinel values (e.g., nullptr for array pointers).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_qwen35.cpp` around lines 500 - 504, The function mlx_qwen35_store_weight currently dereferences name and weight without validation and lacks exception wrapping; update this extern "C" entry to first check that name and weight are non-null (validate pointers before reinterpret_cast or dereference) and if invalid, early-return (for void functions) or set out-parameters/sentinels for others; then wrap the body (mutex lock, reinterpret_cast<array*>, and g_weights.insert_or_assign) in a try/catch block that catches std::exception and (...) and prevents exceptions from propagating across the FFI boundary (log or swallow and return safely). Apply the same pattern to the related extern "C" functions referenced (those around lines 526–546, 626–631, 706–711): validate all pointer inputs first, then execute core logic inside try/catch, and on error return nullptr or set safe sentinel out-parameters as appropriate.
🧹 Nitpick comments (2)
crates/mlx-core/src/convert.rs (1)
642-691: Consider de-duplicating FP8 dequant logic into a shared helper.
dequant_fp8here mirrors the implementation incrates/mlx-core/src/models/qwen3_5/persistence.rs(same block-padding/reshape flow). Centralizing this would reduce drift risk.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/convert.rs` around lines 642 - 691, The FP8 dequant logic in dequant_fp8 duplicates the block-pad/reshape/multiply/unpad flow found in crates/mlx-core/src/models/qwen3_5/persistence.rs; refactor by extracting a shared helper (e.g., fn dequant_fp8_blockwise(weight: &MxArray, scale_inv: &MxArray, target_dtype: DType, bs: usize) -> Result<MxArray>) that implements the 1D check, pad computation, reshape to [m_blocks, bs, n_blocks, bs], scale broadcast, reshape back and unpad, and final astype; then replace the current dequant_fp8 and the duplicate code in persistence.rs to call this helper (pass bs=128 or make bs configurable) so both call sites share the same implementation and avoid drift.crates/mlx-sys/src/mlx_common.h (1)
29-32: Consider adding C++static_assertformlx_streamlayout verification (optional enhancement).The Rust struct in
crates/mlx-sys/src/lib.rsalready uses#[repr(C)]with matchingi32field order (index,device_type), so ABI compatibility is secured on the Rust side. For extra compile-time verification, you can addstatic_assertchecks in the C++ header to validate struct size and field offsets, though this is not strictly required given the current matching definitions.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_common.h` around lines 29 - 32, Add C++ compile-time layout checks for struct mlx_stream: use static_assert to verify sizeof(mlx_stream) == 8 and offsetof(mlx_stream, index) == 0 and offsetof(mlx_stream, device_type) == 4 (or equivalent depending on target) so the C/C++ definition matches the Rust #[repr(C)] i32 fields; include the appropriate header for offsetof (cstddef or stddef.h) and place these assertions near the struct definition referencing struct mlx_stream and its fields index and device_type.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@crates/mlx-core/src/convert.rs`:
- Around line 773-811: The dtype conversion loop for converting tensors to
target_dtype is currently guarded by the if has_fp8 block, so non-FP8
checkpoints (e.g., Qwen3.5 sanitizer path) never get their dtypes converted;
move or duplicate the conversion logic so that after handling FP8 dequantization
(the dequant_fp8 calls that update new_weights and the subsequent info log), you
always run the dtype-normalization pass over new_weights (using the same keys
iteration, v.dtype()? and v.astype(target_dtype)? logic) even when has_fp8 is
false — update references to new_weights, has_fp8, dequant_fp8, and target_dtype
accordingly to ensure all tensors end up in target_dtype.
- Around line 860-873: The code eagerly removes pairs (qkv_key/z_key and
b_key/a_key) from new_weights so if one is missing the other is discarded;
change the logic in the blocks handling qkv_key/z_key and b_key/a_key to first
check for presence (e.g., peek with get or remove one and reinsert on failure)
and only remove both permanently when both exist, otherwise reinsert the
surviving tensor back into new_weights; update the branches around
MxArray::concatenate that create "{}.in_proj_qkvz.weight" and
"{}.in_proj_ba.weight" accordingly so no tensor is lost when its partner is
absent.
In `@crates/mlx-sys/src/metal/gated_delta_step.metal.inc`:
- Around line 7-8: Add explicit pre-dispatch validation for the head/dimension
invariants required by the Metal kernel: before calling
gated_delta_kernel_call() (in the dispatch function in mlx_qwen35.cpp) and
before the kernel launch in mlx_gated_delta.cpp, check and fail fast if Dk % 32
!= 0, if Hk > Hv, or if Hv % Hk != 0; return an error or assert with a clear
message rather than letting the kernel run. Annotate the
gated_delta_kernel_call() declaration and the top of mlx_gated_delta.cpp with
comments documenting the requirements (Hk <= Hv, Hv % Hk == 0, Dk % 32 == 0) so
callers must validate these invariants prior to dispatch.
In `@crates/mlx-sys/src/mlx_qwen35.cpp`:
- Around line 198-203: Add a dedicated mutex (e.g., std::mutex g_compile_mutex)
and use RAII locks (std::lock_guard or std::scoped_lock) around every access and
mutation of the shared globals g_compiled_caches, g_offset_int,
g_compile_inited, g_compiled_offset, and g_compile_config; specifically wrap the
body of mlx_qwen35_compiled_init_from_prefill(), mlx_qwen35_forward_compiled(),
mlx_qwen35_eval_token_and_compiled_caches(), and mlx_qwen35_compiled_reset()
with the lock so reads and writes are atomic and vector modifications are
protected, and include <mutex> if not already present.
- Around line 415-416: Validate the full_attention_interval parameter at the
start of mlx_qwen35_compiled_init_from_prefill to ensure 1 <=
full_attention_interval <= num_layers; if the check fails, log an error and
return/fail early. Specifically, before computing first_fa or indexing inputs,
verify full_attention_interval is > 0 and <= num_layers (where num_layers is the
model layer count used elsewhere), then proceed to compute first_fa =
full_attention_interval - 1 and use inputs[2 + first_fa * 2]; this prevents
divide-by-zero in expressions like (i + 1) % full_attention_interval and
out-of-bounds access when full_attention_interval > num_layers. Ensure any error
path uses existing logging/error-return conventions in
mlx_qwen35_compiled_init_from_prefill.
---
Duplicate comments:
In `@crates/mlx-sys/src/mlx_gated_delta.cpp`:
- Around line 71-143: Validate all incoming raw pointers at the top of
mlx_gated_delta_kernel before any dereference: check q_handle, k_handle,
v_handle, g_handle, beta_handle, state_handle, and the output pointers
out_y/out_state (mask_handle may be nullptr); if any required input is null, log
an error with an "[MLX]" prefix (e.g. "[MLX] mlx_gated_delta_kernel error:
<reason>") to std::cerr, and if out_y/out_state are non-null set them to safe
sentinels (nullptr) and return false. Move all reinterpret_cast and array
dereferences (q_arr, k_arr, v_arr, g_arr, beta_arr, state_arr, and mask when
present) after the null checks. Also update the existing catch block to use the
"[MLX]" prefix and only assign to *out_y/*out_state after verifying those
pointers are non-null. Ensure no path writes through a null out pointer.
In `@crates/mlx-sys/src/mlx_qwen35.cpp`:
- Around line 500-515: Wrap each exported C-ABI function
(mlx_qwen35_store_weight, mlx_qwen35_clear_weights, mlx_qwen35_weight_count, and
mlx_qwen35_compiled_reset) body in a try/catch block so STL exceptions cannot
cross the FFI boundary: put the existing implementation inside try { ... } and
add catch(const std::exception& e) { /* record e.what() via the project's FFI
error-reporting helper (same pattern used in mlx.cpp) and return a safe
error/zero value if needed */ } catch(...) { /* record a generic error and
return safe value */ }; ensure the catch handlers mirror the pattern used in
crates/mlx-sys/src/mlx.cpp for error reporting and return semantics so ABI
callers never see C++ exceptions.
- Around line 27-50: Accesses to g_weights and g_weight_transposes in
get_weight, get_weight_t and has_weight must be synchronized with the existing
g_weights_mutex to avoid UB from concurrent mutation; wrap reads and map lookups
in a lock (e.g., std::lock_guard/std::scoped_lock on g_weights_mutex) and for
get_weight_t use the double-checked pattern: lock and check g_weight_transposes,
if missing copy or read the original weight under lock (or grab a reference but
better to copy key data), unlock, perform the potentially expensive transpose,
then lock again and insert the transposed result only if another thread hasn't
already inserted it (use emplace and use the returned iterator), ensuring all
direct accesses/insertions to g_weights and g_weight_transposes are done while
holding g_weights_mutex.
- Around line 500-504: The function mlx_qwen35_store_weight currently
dereferences name and weight without validation and lacks exception wrapping;
update this extern "C" entry to first check that name and weight are non-null
(validate pointers before reinterpret_cast or dereference) and if invalid,
early-return (for void functions) or set out-parameters/sentinels for others;
then wrap the body (mutex lock, reinterpret_cast<array*>, and
g_weights.insert_or_assign) in a try/catch block that catches std::exception and
(...) and prevents exceptions from propagating across the FFI boundary (log or
swallow and return safely). Apply the same pattern to the related extern "C"
functions referenced (those around lines 526–546, 626–631, 706–711): validate
all pointer inputs first, then execute core logic inside try/catch, and on error
return nullptr or set safe sentinel out-parameters as appropriate.
---
Nitpick comments:
In `@crates/mlx-core/src/convert.rs`:
- Around line 642-691: The FP8 dequant logic in dequant_fp8 duplicates the
block-pad/reshape/multiply/unpad flow found in
crates/mlx-core/src/models/qwen3_5/persistence.rs; refactor by extracting a
shared helper (e.g., fn dequant_fp8_blockwise(weight: &MxArray, scale_inv:
&MxArray, target_dtype: DType, bs: usize) -> Result<MxArray>) that implements
the 1D check, pad computation, reshape to [m_blocks, bs, n_blocks, bs], scale
broadcast, reshape back and unpad, and final astype; then replace the current
dequant_fp8 and the duplicate code in persistence.rs to call this helper (pass
bs=128 or make bs configurable) so both call sites share the same implementation
and avoid drift.
In `@crates/mlx-sys/src/mlx_common.h`:
- Around line 29-32: Add C++ compile-time layout checks for struct mlx_stream:
use static_assert to verify sizeof(mlx_stream) == 8 and offsetof(mlx_stream,
index) == 0 and offsetof(mlx_stream, device_type) == 4 (or equivalent depending
on target) so the C/C++ definition matches the Rust #[repr(C)] i32 fields;
include the appropriate header for offsetof (cstddef or stddef.h) and place
these assertions near the struct definition referencing struct mlx_stream and
its fields index and device_type.
ℹ️ Review info
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
crates/mlx-core/src/convert.rscrates/mlx-sys/src/metal/gated_delta_step.metal.inccrates/mlx-sys/src/metal/gated_delta_step_mask.metal.inccrates/mlx-sys/src/metal/gated_delta_step_vec.metal.inccrates/mlx-sys/src/metal/gated_delta_step_vec_mask.metal.inccrates/mlx-sys/src/mlx_common.hcrates/mlx-sys/src/mlx_gated_delta.cppcrates/mlx-sys/src/mlx_qwen35.cpp
🚧 Files skipped from review as they are similar to previous changes (3)
- crates/mlx-sys/src/metal/gated_delta_step_vec.metal.inc
- crates/mlx-sys/src/metal/gated_delta_step_vec_mask.metal.inc
- crates/mlx-sys/src/metal/gated_delta_step_mask.metal.inc
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
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.
Actionable comments posted: 15
♻️ Duplicate comments (5)
crates/mlx-sys/src/mlx_gated_delta.cpp (2)
71-88:⚠️ Potential issue | 🔴 CriticalAdd null guards before raw-handle dereference and null-safe output writes.
mlx_gated_delta_kerneldereferences inputs at Line 83-Line 88 and writes*out_y/*out_stateat Line 134-Line 140 without validating pointers first. A null caller argument can segfault before yourcatchexecutes.Based on learnings: In `crates/mlx-sys/src/mlx.cpp`, all extern "C" FFI entry points should prevent exceptions crossing the Rust FFI boundary and return safe sentinel outputs on failure.Proposed hardening
bool mlx_gated_delta_kernel( @@ ) { + if (!q_handle || !k_handle || !v_handle || !g_handle || !beta_handle || !state_handle || + !out_y || !out_state) { + if (out_y) *out_y = nullptr; + if (out_state) *out_state = nullptr; + return false; + } try { @@ - } catch (const std::exception& e) { - std::cerr << "mlx_gated_delta_kernel error: " << e.what() << std::endl; + } catch (const std::exception& e) { + std::cerr << "[MLX] mlx_gated_delta_kernel: " << e.what() << std::endl; *out_y = nullptr; *out_state = nullptr; return false; + } catch (...) { + std::cerr << "[MLX] mlx_gated_delta_kernel: unknown exception" << std::endl; + *out_y = nullptr; + *out_state = nullptr; + return false; } }Also applies to: 134-141
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_gated_delta.cpp` around lines 71 - 88, Add null checks at the start of mlx_gated_delta_kernel: validate that out_y and out_state pointers are non-null and set *out_y = nullptr and *out_state = nullptr immediately (so callers get safe sentinels), then validate required input handles (q_handle, k_handle, v_handle, g_handle, beta_handle, state_handle) are non-null before any reinterpret_cast/dereference; treat mask_handle as optional (allow nullptr). If any required pointer is null, return false early. Keep the existing try/catch but ensure the catch also sets *out_y and *out_state to nullptr before returning false so no raw pointers are written on failure.
93-98:⚠️ Potential issue | 🟠 MajorValidate kernel shape invariants before dispatch.
The Metal kernels assume
Hk <= Hv,Hv % Hk == 0, andDk % 32 == 0. Without checks before Line 120 dispatch, invalid shapes can produce incorrect mapping or dropped channels.Suggested pre-dispatch guard
int Hk = q_arr.shape(2); int Dk = q_arr.shape(3); int Hv = v_arr.shape(2); int Dv = v_arr.shape(3); + if (Hk <= 0 || Hv <= 0 || Hk > Hv || (Hv % Hk) != 0 || (Dk % 32) != 0) { + std::cerr << "[MLX] mlx_gated_delta_kernel: invalid dims " + << "(Hk=" << Hk << ", Hv=" << Hv << ", Dk=" << Dk << ")\n"; + *out_y = nullptr; + *out_state = nullptr; + return false; + }Also applies to: 120-132
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_gated_delta.cpp` around lines 93 - 98, Add explicit pre-dispatch validation for the kernel shape invariants: check variables Hk, Hv, and Dk (from q_arr.shape and v_arr.shape) to assert Hk <= Hv, Hv % Hk == 0, and Dk % 32 == 0 before launching the Metal kernels (before the dispatch/launch code that uses these shapes). Use the project's standard error handling (e.g., TORCH_CHECK or returning a clear error) so invalid shapes fail fast with a descriptive message indicating which invariant failed and the offending values (reference Hk, Hv, Dk, B, T to include context).crates/mlx-sys/src/mlx_qwen35.cpp (1)
114-129:⚠️ Potential issue | 🔴 CriticalAdd exception boundaries to remaining exported C-ABI entry points.
mlx_qwen35_store_weight,mlx_qwen35_clear_weights,mlx_qwen35_weight_count, andmlx_qwen35_compiled_resetcurrently have no try/catch guard. Any thrown C++ exception crossingextern "C"is undefined behavior.Based on learnings: In
crates/mlx-sys/src/mlx.cpp, extern "C" FFI entry points should be wrapped in try/catch and return safe sentinel outputs on failure.Also applies to: 268-273
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_qwen35.cpp` around lines 114 - 129, Wrap the bodies of the exported C-ABI functions mlx_qwen35_store_weight, mlx_qwen35_clear_weights, mlx_qwen35_weight_count (and similarly mlx_qwen35_compiled_reset) in a try/catch boundary so no C++ exception can escape extern "C": move the existing logic (locking g_weights_mutex(), accessing g_weights(), g_weight_transposes(), and reinterpret_cast of mlx_array) into a try block, catch std::exception to log the error and for mlx_qwen35_weight_count return a safe sentinel (0), and catch (...) to log an unknown error and return the same sentinel for non-void functions; for void functions just swallow after logging so the FFI surface never propagates an exception.packages/lm/src/models/model-loader.ts (2)
75-83:⚠️ Potential issue | 🟠 MajorDon’t silently downgrade all detection errors to
qwen3.Line 80 masks JSON parse/permission/path errors and can route checkpoints to the wrong loader. Also, Line 77 assumes
modelPathis always a directory while Line 23 documents directory or file.Based on learnings: Model loaders must handle SafeTensors weight files and return fully initialized model instances with inference capability.🔧 Suggested hardening
-import { readFile } from 'node:fs/promises'; -import { join } from 'node:path'; +import { readFile, stat } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; @@ -async function detectModelType(modelPath: string): Promise<string> { +type SupportedModelType = 'qwen3' | 'qwen3_5' | 'qwen3_5_moe'; + +async function detectModelType(modelPath: string): Promise<SupportedModelType> { try { - const raw = await readFile(join(modelPath, 'config.json'), 'utf-8'); + const modelDir = (await stat(modelPath)).isDirectory() ? modelPath : dirname(modelPath); + const configPath = join(modelDir, 'config.json'); + const raw = await readFile(configPath, 'utf-8'); const config = JSON.parse(raw); - return config.model_type ?? 'qwen3'; - } catch { - return 'qwen3'; + if ( + config.model_type === 'qwen3' || + config.model_type === 'qwen3_5' || + config.model_type === 'qwen3_5_moe' + ) { + return config.model_type; + } + if (config.model_type == null) return 'qwen3'; + throw new Error(`Unsupported model_type "${String(config.model_type)}" in ${configPath}`); + } catch (error: unknown) { + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + (error as { code?: string }).code === 'ENOENT' + ) { + return 'qwen3'; + } + throw error; } }🤖 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 75 - 83, detectModelType currently swallows all errors and always returns 'qwen3'; update it to (1) check whether modelPath is a file or directory and handle both cases (referencing modelPath), (2) verify existence of join(modelPath, 'config.json') before trying to read it, (3) catch and surface JSON parse or fs permission/path errors instead of silently downgrading—only return the default 'qwen3' when config.json is missing/unreadable for an expected benign reason, otherwise rethrow or return a propagated error so callers know detection failed; ensure you reference detectModelType, readFile and the config.json lookup in the change.
19-21:⚠️ Potential issue | 🟡 MinorUpdate the
loadPretraineddoc comment to include MoE delegation.Line 19-Line 21 mentions only
qwen3_5delegation, but Line 29-Line 31 also delegatesqwen3_5_moe.✏️ Suggested doc update
- * For Qwen3.5 models, use {`@link` loadQwen35} instead. - * If the config.json indicates a qwen3_5 model, this method will - * automatically delegate to loadQwen35. + * For Qwen3.5 models, use {`@link` loadQwen35} / {`@link` loadQwen35Moe} instead. + * If config.json indicates `qwen3_5` or `qwen3_5_moe`, this method + * automatically delegates to the corresponding loader.🤖 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 19 - 21, The doc comment for loadPretrained currently mentions delegation to loadQwen35 for qwen3_5 models but omits qwen3_5_moe; update the comment to state that if config.json indicates either qwen3_5 or qwen3_5_moe the method will automatically delegate to the appropriate loader (loadQwen35 and the MoE loader, e.g., loadQwen35Moe), and mention both identifiers (qwen3_5 and qwen3_5_moe) explicitly so readers know both paths are handled.
🧹 Nitpick comments (5)
examples/tool-use-example.ts (1)
103-107: Consider making generation params configurable in this example.Hard-coding
maxNewTokens: 32768plus fixed temperatures can make the script unexpectedly slow/costly. Exposing these via env/args keeps the example safer and easier to tune.Suggested patch
const MODEL_PATH = process.argv[2] || process.env.MODEL_PATH || DEFAULT_MODEL_PATH; +const MAX_NEW_TOKENS = Number(process.env.MAX_NEW_TOKENS || 4096); +const INITIAL_TEMPERATURE = Number(process.env.INITIAL_TEMPERATURE || 0.7); +const FINAL_TEMPERATURE = Number(process.env.FINAL_TEMPERATURE || 0.9); @@ const result = await model.chat(messages, { tools, - maxNewTokens: 32768, - temperature: 0.7, + maxNewTokens: MAX_NEW_TOKENS, + temperature: INITIAL_TEMPERATURE, }); @@ const finalResult = await model.chat(messages, { tools, maxNewTokens: 2048, - temperature: 0.9, + temperature: FINAL_TEMPERATURE, });Also applies to: 140-144
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/tool-use-example.ts` around lines 103 - 107, Replace hard-coded generation params in the model.chat call by reading configurable values (e.g., from environment variables or CLI args) and passing them as variables to model.chat; specifically, make maxNewTokens and temperature (and any other generation settings used in the file) configurable with sensible defaults and validation, then use those variables in the model.chat invocation(s) that reference messages/tools, and apply the same change to the other identical call later in the file so both places use the shared configurable parameters instead of literal values.crates/mlx-core/src/sampling.rs (1)
570-593: Short-circuit n-gram scanning when cutoff is unattainable.The n-gram loop still runs even when
lenis too short to ever hitmax_ngram_repeats. Add a feasibility guard to skip extra comparisons in the decode hot path.⚡ Suggested optimization
if check_ngram { let ngram_size = ngram_size as usize; let max_ngram_repeats = max_ngram_repeats as usize; - if len >= ngram_size * 2 { + if len >= ngram_size * 2 + && len >= ngram_size.saturating_mul(max_ngram_repeats.max(2)) + { let ngram = &tokens[len - ngram_size..]; let mut repeats = 1usize; let mut pos = len - ngram_size * 2;As per coding guidelines, "Sampling strategies must support temperature, top-k, top-p, min-p, and repetition penalty with efficient implementation."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/sampling.rs` around lines 570 - 593, The n-gram repeat scan in check_ngram can waste cycles when the sequence is too short to ever reach max_ngram_repeats; add a feasibility guard before entering the repeat loop (use the existing symbols tokens, len, ngram_size, max_ngram_repeats, and the loop block) that skips the entire scan when len < ngram_size * max_ngram_repeats because it’s impossible to reach the required number of consecutive n-gram repeats, leaving the rest of the logic unchanged.crates/mlx-core/src/models/qwen3_5/sparse_moe.rs (1)
73-94: Mirrornew()invariant checks innew_quantized().
new()enforcesnum_experts > 0and0 < num_experts_per_tok <= num_experts, butnew_quantized()currently skips those checks. Keeping both constructors aligned avoids mode-specific behavior differences.🤖 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 73 - 94, The new_quantized() constructor currently omits the validation present in new(): replicate the same invariants by validating config.num_experts and config.num_experts_per_tok (ensure num_experts > 0 and 0 < num_experts_per_tok <= num_experts) before constructing the SparseMoeBlock; if validation fails, return an Err(Result) with an appropriate error (matching the error variant/format used by new()), and only build the struct (setting gate: LinearProj::Quantized, shared_expert_gate: LinearProj::Quantized, etc.) after the checks pass.crates/mlx-core/src/models/qwen3_5_moe/sparse_moe.rs (1)
68-88: Keep constructor invariants consistent between standard and quantized paths.
new_quantized()should enforce the same expert-count checks used innew()to prevent invalid configs from only failing later in forward.🤖 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/sparse_moe.rs` around lines 68 - 88, new_quantized() currently constructs the struct without validating expert-related invariants; mirror the same checks performed in new() (e.g., verify num_experts and num_experts_per_tok are positive, num_experts_per_tok <= num_experts, and that num_experts is divisible by num_experts_per_tok or whatever divisibility/assertion new() enforces) before returning Ok(Self). Locate the validation logic in new() and copy the same guard conditions and early Err(...) returns into new_quantized(), referencing symbols gate, shared_expert_gate, num_experts, and num_experts_per_tok to ensure both constructors enforce identical expert-count invariants.packages/core/index.d.cts (1)
2004-2009: Tighten quantization option types for safer API calls.Using literal unions here prevents invalid values from reaching runtime conversion paths.
💡 Proposed type refinement
- /** Quantization bits: 4 (default) or 8 */ - quantBits?: number; + /** Quantization bits: 4 (default) or 8 */ + quantBits?: 4 | 8; /** Quantization group size (default: 64 for affine, 32 for mxfp8) */ quantGroupSize?: number; /** Quantization mode: "affine" (default) or "mxfp8" */ - quantMode?: string; + quantMode?: 'affine' | 'mxfp8';🤖 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 2004 - 2009, Update the quantization option types to literal unions to prevent invalid values at compile time: change quantBits?: number to quantBits?: 4 | 8, change quantGroupSize?: number to quantGroupSize?: 32 | 64 (reflecting the two supported group sizes), and change quantMode?: string to quantMode?: "affine" | "mxfp8" in the declarations that define these options (the properties named quantBits, quantGroupSize and quantMode).
🤖 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_moe/model.rs`:
- Around line 312-313: The check using global mlx_qwen35_weight_count() to set
use_cpp is unreliable because weight_count is shared across registrations;
update the logic in the model initialization (where use_cpp is set) to rely on a
model-local readiness flag instead: introduce a cpp_moe_ready boolean on the
model struct and set it to true only after successful C++ MoE registration
inside load_pretrained (or the registration function), then replace uses of
mlx_qwen35_weight_count() > 0 with reading this model-local cpp_moe_ready (e.g.,
in the place where use_cpp is computed and at the other site around lines
643-644) so the C++ MoE path is only taken when this specific model registered
successfully.
- Around line 215-225: The decode logic in generate() assumes batch size 1 (uses
reshape(&[1, 1]) and item_at_int32(0)), so add an upfront guard in
Qwen3_5Moe::generate that inspects the prompt_tokens shape/dimensions (e.g.,
check prompt_tokens.ndim()/shape()[0] or equivalent MxArray API) and returns
Err(Error::from_reason(...)) if the batch dimension is not 1, with a clear
message like "generate() only supports batch size 1; got batch_size = X"; place
this check near the start of generate() (before decoding and after validating
max_new_tokens) to prevent silent misuse.
- Around line 314-437: The C++ MoE runtime is initialized via
mlx_qwen35_moe_init_from_prefill but mlx_qwen35_moe_reset() is only called on
the normal exit path, leaving global state set if any `?` returns occur (e.g.,
in forward_moe_cpp, sample, eval_token_and_moe_caches or
y.reshape/item_at_int32). Fix by introducing an RAII guard (e.g., a small struct
MoERuntimeGuard with Drop calling mlx_qwen35_moe_reset) immediately after
successful mlx_qwen35_moe_init_from_prefill and store it in the C++ branch so
that the Drop runs on all exits; ensure the guard is created before any fallible
calls (forward_moe_cpp, sample, eval_token_and_moe_caches, y.reshape,
y.item_at_int32) and dropped only after the existing cleanup (or let it drop
automatically at end of scope).
In `@crates/mlx-core/src/models/qwen3_5_moe/persistence.rs`:
- Around line 246-262: The destination key for stacking per-expert tensors is
hardcoded to use the suffix ".weight" in the expert_weights map, causing
suffixes like ".scales" or ".biases" to be merged incorrectly. To fix this in
the code that constructs the key in the block checking has_individual_experts
and name.contains(".mlp.experts."), modify the key creation to preserve the
original suffix from the tensor name instead of hardcoding ".weight". This
ensures that the correct tensor types remain separate during stacking.
In `@crates/mlx-core/src/models/qwen3_5/persistence.rs`:
- Around line 780-786: When skipping register_weights_with_cpp (inside the
is_quantized_checkpoint/is_mxfp8_checkpoint branch), explicitly clear any stale
C++ weight state so mlx_qwen35_weight_count() cannot remain non‑zero and
accidentally enable the compiled decode path; add a call in that else-branch to
the FFI/cleanup routine (e.g., an unregister or reset function such as
unregister_weights_with_cpp() or mlx_qwen35_clear_weights()) that ensures the
C++ weight count is reset to zero, and update the info log to note that C++
weights were cleared for quantized models.
In `@crates/mlx-sys/src/mlx_advanced_ops.cpp`:
- Around line 1005-1013: The repetition-penalty application may divide by
non-positive values (causing inf/NaN); update the guard around the block that
uses repetition_penalty (the if around repetition_penalty != 1.0f) to ensure
repetition_penalty is strictly positive (e.g., repetition_penalty > 0.0f &&
repetition_penalty != 1.0f) or clamp/replace non-positive values with a safe
epsilon before using it; adjust the check used with
recent_tokens/repetition_context_size and leave the inner logic using slice,
where, scatter, array, squeeze, and logits unchanged so division never occurs
when repetition_penalty <= 0.0f.
In `@crates/mlx-sys/src/mlx_array_ops.cpp`:
- Around line 375-381: Replace the silent fallback to 1.0 for near-zero step in
mlx_array_arange: validate that fabs(step) >= 1e-12 and if not, log an error
message and return nullptr instead of constructing an array; do not call arange
or allocate a new array when the step is invalid, and keep the rest of the
function (use arange(start, stop, step, to_mlx_dtype(dtype)) and return
reinterpret_cast<mlx_array*>(new array(...))) unchanged when the step passes
validation to avoid memory leaks.
In `@crates/mlx-sys/src/mlx_gated_delta.cpp`:
- Around line 161-164: The softplus computation for sp (currently computed as
log(exp(x) + array(1.0f, a.dtype()))) can overflow for large x; replace it with
the numerically stable softplus identity sp = max(x, 0) + log1p(exp(-abs(x))) to
avoid bf16/f32 overflow. Modify the block where A, x, and sp are computed
(variables A, x, sp in mlx_gated_delta.cpp) to compute sp using elementwise
maximum, absolute value, and log1p (ensuring you create constants with
array(0.0f, a.dtype())/array(1.0f, a.dtype()) as needed) and then return
exp(negative(A * sp)) as before. Ensure you use the library’s elementwise ops
for max, abs/fabs, exp, and log1p so types and shapes remain correct.
In `@crates/mlx-sys/src/mlx_nn_ops.cpp`:
- Around line 533-545: The function mlx_array_split_multi currently writes into
out_handles without checking for nullptr, which can crash; update
mlx_array_split_multi to compute splits and count as before but guard the write
loop with a null check (e.g., if (out_handles != nullptr && max_outputs > 0) {
for (...) { out_handles[i] = reinterpret_cast<uint64_t>(new
array(std::move(splits[i]))); } }), and return count even when out_handles is
null (or return 0 early if max_outputs == 0) so no dereference occurs; reference
symbols: mlx_array_split_multi, out_handles, max_outputs, splits.
- Around line 124-138: The read_scalar switch in function read_scalar is missing
a branch for mlx::core::int64, so scalars from arrays created by
mlx_array_from_int64 are falling through to default and returning Out{}; add a
case for mlx::core::int64 that returns
static_cast<Out>(arr.data<int64_t>()[index]) (analogous to the other integer
cases) to correctly read int64 values.
In `@crates/mlx-sys/src/mlx_qwen35_common.h`:
- Around line 76-81: The linear_proj helper is hard-coding quantization
parameters (group_size=32, bits=8, mode="mxfp8" and group_size=64, bits=4,
mode="affine") when calling mlx::core::quantized_matmul; instead, thread the
actual quantization settings through or decode them from the checkpoint
metadata/scales and pass those values into quantized_matmul (e.g., obtain
group_size, bits, mode from the quantization metadata associated with scales or
add parameters to linear_proj and its callers) rather than using the fixed
constants so quantized_matmul receives the correct group_size, bits, and mode
for each checkpoint.
In `@crates/mlx-sys/src/mlx_qwen35_moe.cpp`:
- Around line 608-620: The detect_quant lambda currently hardcodes affine
quantization parameters group_size=64 and bits=4, which can cause mismatch with
checkpoints using different settings. Modify detect_quant to load affine
quantization parameters dynamically from the checkpoint configuration or
metadata rather than using fixed values. This may involve fetching these
parameters similarly to how you check for biases or scales, allowing
detect_quant to adapt to non-default quantization settings.
In `@crates/mlx-sys/src/mlx_qwen35.cpp`:
- Around line 29-33: The decode call is bypassing the compiled wrapper and still
reads the offset from global g_offset_int; update qwen35_decode_fn usage so it
consumes the offset from inputs[1] instead of the global and ensure the compiled
wrapper compiled_qwen35_decode(...) is invoked: change qwen35_decode_fn to read
int offset = inputs[1] (or accept an explicit offset parameter from inputs) and
replace the direct call sites (the place that currently calls qwen35_decode_fn
directly) with a call to compiled_qwen35_decode(...) passing that offset so the
compiled path is used and globals
g_offset_int/g_compiled_offset/g_compiled_caches are no longer relied upon.
- Around line 207-247: Validate pointers at the start of
mlx_qwen35_forward_compiled: check output_logits, input_ids_ptr, and
embedding_weight_ptr for nullptr and if any are null, optionally log an error,
set *output_logits = nullptr only if output_logits is non-null (or avoid
dereference if null) and return early; also add null checks immediately before
any other writes through *output_logits and before dereferencing
input_ids_ptr/embedding_weight_ptr (used when creating input_ids and
embedding_weight arrays) following the same pattern used for cache_offset_out to
avoid unconditional dereferences.
In `@examples/tool-use-example.ts`:
- Around line 29-30: Update the usage/header text to reflect the new default
model name used by DEFAULT_MODEL_PATH (now 'qwen3.5-4B-mlx-bf16'); locate the
human-readable usage/description near the top of the file that still mentions
'qwen3-0.6b-mlx-bf16' and change it to match DEFAULT_MODEL_PATH (and, if
present, any example shown for MODEL_PATH or environment variable guidance) so
documentation and runtime default remain consistent.
---
Duplicate comments:
In `@crates/mlx-sys/src/mlx_gated_delta.cpp`:
- Around line 71-88: Add null checks at the start of mlx_gated_delta_kernel:
validate that out_y and out_state pointers are non-null and set *out_y = nullptr
and *out_state = nullptr immediately (so callers get safe sentinels), then
validate required input handles (q_handle, k_handle, v_handle, g_handle,
beta_handle, state_handle) are non-null before any reinterpret_cast/dereference;
treat mask_handle as optional (allow nullptr). If any required pointer is null,
return false early. Keep the existing try/catch but ensure the catch also sets
*out_y and *out_state to nullptr before returning false so no raw pointers are
written on failure.
- Around line 93-98: Add explicit pre-dispatch validation for the kernel shape
invariants: check variables Hk, Hv, and Dk (from q_arr.shape and v_arr.shape) to
assert Hk <= Hv, Hv % Hk == 0, and Dk % 32 == 0 before launching the Metal
kernels (before the dispatch/launch code that uses these shapes). Use the
project's standard error handling (e.g., TORCH_CHECK or returning a clear error)
so invalid shapes fail fast with a descriptive message indicating which
invariant failed and the offending values (reference Hk, Hv, Dk, B, T to include
context).
In `@crates/mlx-sys/src/mlx_qwen35.cpp`:
- Around line 114-129: Wrap the bodies of the exported C-ABI functions
mlx_qwen35_store_weight, mlx_qwen35_clear_weights, mlx_qwen35_weight_count (and
similarly mlx_qwen35_compiled_reset) in a try/catch boundary so no C++ exception
can escape extern "C": move the existing logic (locking g_weights_mutex(),
accessing g_weights(), g_weight_transposes(), and reinterpret_cast of mlx_array)
into a try block, catch std::exception to log the error and for
mlx_qwen35_weight_count return a safe sentinel (0), and catch (...) to log an
unknown error and return the same sentinel for non-void functions; for void
functions just swallow after logging so the FFI surface never propagates an
exception.
In `@packages/lm/src/models/model-loader.ts`:
- Around line 75-83: detectModelType currently swallows all errors and always
returns 'qwen3'; update it to (1) check whether modelPath is a file or directory
and handle both cases (referencing modelPath), (2) verify existence of
join(modelPath, 'config.json') before trying to read it, (3) catch and surface
JSON parse or fs permission/path errors instead of silently downgrading—only
return the default 'qwen3' when config.json is missing/unreadable for an
expected benign reason, otherwise rethrow or return a propagated error so
callers know detection failed; ensure you reference detectModelType, readFile
and the config.json lookup in the change.
- Around line 19-21: The doc comment for loadPretrained currently mentions
delegation to loadQwen35 for qwen3_5 models but omits qwen3_5_moe; update the
comment to state that if config.json indicates either qwen3_5 or qwen3_5_moe the
method will automatically delegate to the appropriate loader (loadQwen35 and the
MoE loader, e.g., loadQwen35Moe), and mention both identifiers (qwen3_5 and
qwen3_5_moe) explicitly so readers know both paths are handled.
---
Nitpick comments:
In `@crates/mlx-core/src/models/qwen3_5_moe/sparse_moe.rs`:
- Around line 68-88: new_quantized() currently constructs the struct without
validating expert-related invariants; mirror the same checks performed in new()
(e.g., verify num_experts and num_experts_per_tok are positive,
num_experts_per_tok <= num_experts, and that num_experts is divisible by
num_experts_per_tok or whatever divisibility/assertion new() enforces) before
returning Ok(Self). Locate the validation logic in new() and copy the same guard
conditions and early Err(...) returns into new_quantized(), referencing symbols
gate, shared_expert_gate, num_experts, and num_experts_per_tok to ensure both
constructors enforce identical expert-count invariants.
In `@crates/mlx-core/src/models/qwen3_5/sparse_moe.rs`:
- Around line 73-94: The new_quantized() constructor currently omits the
validation present in new(): replicate the same invariants by validating
config.num_experts and config.num_experts_per_tok (ensure num_experts > 0 and 0
< num_experts_per_tok <= num_experts) before constructing the SparseMoeBlock; if
validation fails, return an Err(Result) with an appropriate error (matching the
error variant/format used by new()), and only build the struct (setting gate:
LinearProj::Quantized, shared_expert_gate: LinearProj::Quantized, etc.) after
the checks pass.
In `@crates/mlx-core/src/sampling.rs`:
- Around line 570-593: The n-gram repeat scan in check_ngram can waste cycles
when the sequence is too short to ever reach max_ngram_repeats; add a
feasibility guard before entering the repeat loop (use the existing symbols
tokens, len, ngram_size, max_ngram_repeats, and the loop block) that skips the
entire scan when len < ngram_size * max_ngram_repeats because it’s impossible to
reach the required number of consecutive n-gram repeats, leaving the rest of the
logic unchanged.
In `@examples/tool-use-example.ts`:
- Around line 103-107: Replace hard-coded generation params in the model.chat
call by reading configurable values (e.g., from environment variables or CLI
args) and passing them as variables to model.chat; specifically, make
maxNewTokens and temperature (and any other generation settings used in the
file) configurable with sensible defaults and validation, then use those
variables in the model.chat invocation(s) that reference messages/tools, and
apply the same change to the other identical call later in the file so both
places use the shared configurable parameters instead of literal values.
In `@packages/core/index.d.cts`:
- Around line 2004-2009: Update the quantization option types to literal unions
to prevent invalid values at compile time: change quantBits?: number to
quantBits?: 4 | 8, change quantGroupSize?: number to quantGroupSize?: 32 | 64
(reflecting the two supported group sizes), and change quantMode?: string to
quantMode?: "affine" | "mxfp8" in the declarations that define these options
(the properties named quantBits, quantGroupSize and quantMode).
ℹ️ Review info
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (33)
crates/mlx-core/Cargo.tomlcrates/mlx-core/src/array/memory.rscrates/mlx-core/src/array/mod.rscrates/mlx-core/src/convert.rscrates/mlx-core/src/models/qwen3/model.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/persistence.rscrates/mlx-core/src/models/qwen3_5/sparse_moe.rscrates/mlx-core/src/models/qwen3_5_moe/model.rscrates/mlx-core/src/models/qwen3_5_moe/persistence.rscrates/mlx-core/src/models/qwen3_5_moe/sparse_moe.rscrates/mlx-core/src/nn/activations.rscrates/mlx-core/src/sampling.rscrates/mlx-core/src/tools/mod.rscrates/mlx-sys/mlxcrates/mlx-sys/src/lib.rscrates/mlx-sys/src/metal/gated_delta_step.metal.inccrates/mlx-sys/src/metal/gated_delta_step_mask.metal.inccrates/mlx-sys/src/metal/gated_delta_step_vec.metal.inccrates/mlx-sys/src/metal/gated_delta_step_vec_mask.metal.inccrates/mlx-sys/src/mlx_advanced_ops.cppcrates/mlx-sys/src/mlx_array_ops.cppcrates/mlx-sys/src/mlx_gated_delta.cppcrates/mlx-sys/src/mlx_nn_ops.cppcrates/mlx-sys/src/mlx_qwen35.cppcrates/mlx-sys/src/mlx_qwen35_common.hcrates/mlx-sys/src/mlx_qwen35_moe.cppexamples/test-converted-model.tsexamples/tool-use-example.tspackages/core/index.d.ctspackages/lm/src/models/model-loader.ts
💤 Files with no reviewable changes (1)
- crates/mlx-core/Cargo.toml
✅ Files skipped from review due to trivial changes (1)
- crates/mlx-sys/mlx
🚧 Files skipped from review as they are similar to previous changes (3)
- examples/test-converted-model.ts
- crates/mlx-sys/src/metal/gated_delta_step_mask.metal.inc
- crates/mlx-sys/src/metal/gated_delta_step_vec_mask.metal.inc
…afety - Add RAII drop guards (MoeResetGuard, CompiledResetGuard) so C++ state is always reset even on error unwind in generate()/chat() - Add batch_size=1 validation in generate() for both dense and MoE models - Use numerically stable softplus: where(x > 20, x, log1p(exp(x))) instead of log(exp(x) + 1) which overflows in bf16 - Add int64/uint64 cases to read_scalar<Out> template - Add null guard in mlx_array_split_multi - Add null pointer checks in mlx_qwen35_forward_compiled - Remove dead compiled_qwen35_decode() (compile() wrapper never called) - Document quantization heuristic in linear_proj() - Fix .metal.inc raw string literals: move R"( to own line, remove XML corruption from Read/Write round-trip - Fix tool-use-example.ts default model name in docstring Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
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.
Actionable comments posted: 10
♻️ Duplicate comments (1)
crates/mlx-sys/src/mlx_qwen35_common.h (1)
84-89:⚠️ Potential issue | 🟠 MajorDo not hard-code
quantized_matmulquantization params.Line 86 and Line 88 force fixed
(group_size, bits, mode)tuples. This can decode weights incorrectly when checkpoint quant metadata differs from those constants.#!/bin/bash # Verify whether quantization metadata can vary and whether linear_proj can consume it. # Expected: if multiple group_size/bits/mode values exist in conversion/runtime config # but linear_proj only uses fixed constants, this confirms the mismatch risk. rg -n "quant_group_size|group_size|quant_bits|bits|quant_mode|mxfp8|affine" crates/mlx-core crates/mlx-sys -g '!**/target/**' echo "---- linear_proj call/definition sites ----" rg -n "linear_proj\\(" crates/mlx-sys/src/mlx_qwen35_common.h crates/mlx-sys/src/mlx_qwen35.cpp crates/mlx-sys/src/mlx_qwen35_moe.cpp🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-sys/src/mlx_qwen35_common.h` around lines 84 - 89, The current code in mlx_qwen35_common.h hard-codes quantization params when calling mlx::core::quantized_matmul (using fixed (32,8,"mxfp8") or (64,4,"affine")), which can mismatch checkpoint quant metadata; update the call in the branch that returns mlx::core::quantized_matmul to derive group_size, bits and mode from the quant metadata associated with the weights or the provided scales (or expose/propagate those params from linear_proj's caller) and pass those dynamic values instead of literals, preserving the existing boolean for biases detection and signature of mlx::core::quantized_matmul.
🧹 Nitpick comments (2)
examples/tool-use-example.ts (1)
105-105: Make the initial token budget configurable for safer local runs.
32768is valid, but it can make this example unexpectedly slow/memory-heavy on smaller machines. Consider an env-configured value with a moderate default.Suggested patch
const DEFAULT_MODEL_PATH = resolve(process.cwd(), '.cache', 'models', 'qwen3.5-4B-mlx-bf16'); const MODEL_PATH = process.argv[2] || process.env.MODEL_PATH || DEFAULT_MODEL_PATH; +const DEFAULT_MAX_NEW_TOKENS = 4096; +const maxNewTokens = Number(process.env.MAX_NEW_TOKENS ?? DEFAULT_MAX_NEW_TOKENS); @@ const result = await model.chat(messages, { tools, - maxNewTokens: 32768, + maxNewTokens: Number.isFinite(maxNewTokens) && maxNewTokens > 0 ? maxNewTokens : DEFAULT_MAX_NEW_TOKENS, temperature: 0.7, });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/tool-use-example.ts` at line 105, The hardcoded maxNewTokens: 32768 in examples/tool-use-example.ts should be made configurable via an environment variable with a reasonable default (e.g., 1024 or 2048) to avoid huge memory/CPU usage on small machines; update the configuration that sets maxNewTokens (the object/variable currently containing maxNewTokens) to read process.env.MAX_NEW_TOKENS (or similar) parsed as an integer, fall back to the moderate default when unset or invalid, and validate the value is >0 before using it.crates/mlx-core/src/models/qwen3_5/model.rs (1)
423-487: Consider extracting a shared decode driver forgenerateandchat.The compiled/fallback decode flow is duplicated in both methods. This will be easy to desynchronize on future fixes (cache eval, stream handling, compiled init/reset behavior).
Also applies to: 707-791
🤖 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 423 - 487, Extract the duplicated decode loop into a single shared driver function (e.g., decode_stream_driver) that both generate and chat call; the driver should encapsulate the StreamContext handling (generation_stream), the compiled vs fallback paths (forward_compiled, forward_with_locks), token sampling and cache evaluation calls (eval_token_and_compiled_caches, eval_token_and_caches), yielding/appending token ids to generated_tokens, EOS detection, advancing y, and the periodic cleanup (synchronize_and_clear_cache). Ensure the driver accepts parameters for max_tokens, eos_id, sampling_config, embedding_weight/embedding_weight_t, layers_arc/final_norm_arc/lm_head_arc/caches_arc/fa_idx, and a flag/use of compiled, and returns the final generated_tokens and finish_reason so both generate and chat simply call this driver to avoid code divergence.
🤖 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 267-275: The check in generate() uses prompt_tokens.shape_at(0) to
only validate batch size but misses tensor rank (e.g., a rank-1 tensor [1] would
pass and break the decode path); update generate() to verify prompt_tokens has
at least 2 dimensions (rank >= 2) and that prompt_tokens.shape_at(0) == 1 and
prompt_tokens.shape_at(1) (the sequence length) exists before proceeding. Locate
the prompt_tokens usage and replace the single shape_at(0) gate with a
rank/dimension check (e.g., confirm dims/ndim or shape length) and then assert
shape_at(0) == 1 to enforce the expected [B, T] contract used by reshape and
item_at_int32(0).
- Around line 565-569: The new repetition controls (repetition_penalty,
repetition_context_size, max_consecutive_tokens, max_ngram_repeats, ngram_size)
are consumed directly and need bounds checking; add validation right after
reading the config values (where repetition_penalty =
config.repetition_penalty.unwrap_or(1.0) etc.) to either clamp or reject unsafe
values: ensure repetition_penalty > 0 (e.g., clamp to a minimum like 0.01 or
return an Err), repetition_context_size >= 1 (and cap to a sensible upper
bound), max_consecutive_tokens >= 1, max_ngram_repeats >= 0, and ngram_size >= 1
(and cap ngram_size to match internal n-gram tracking limits); update the code
that constructs/uses these variables so invalid inputs are handled
deterministically (clamp or error) and include the variable names above to
locate the checks.
In `@crates/mlx-sys/src/metal/gated_delta_step_mask.metal.inc`:
- Around line 10-15: The loop currently only writes y[dv_idx] when mask[b_idx *
T + t] is true, leaving outputs uninitialized for masked timesteps; update the
code around the mask branch (referencing mask, y, dv_idx, and
thread_index_in_simdgroup) to ensure a deterministic write when mask is false —
e.g., add an else path that, under the same thread_index_in_simdgroup == 0
condition, sets y[dv_idx] = static_cast<InT>(0) (or another defined fill value),
while preserving the existing pointer increments (q_, k_, v_, y) after the
conditional so pointer progression remains identical.
In `@crates/mlx-sys/src/mlx_gated_delta.cpp`:
- Around line 93-132: Before calling get_or_create_kernel and launching
kernel(...), validate the shape invariants: ensure Dk is divisible by 32 (lane
pack requirement) and Hv is divisible by Hk (GQA head mapping integral). If
either check fails, throw or return a clear error (e.g., runtime_error) with a
message referencing Dk and Hv/Hk so the failure is fast and descriptive. Add
these checks right before building template_args/launch so callers cannot reach
the kernel invocation with unsupported shapes.
In `@crates/mlx-sys/src/mlx_nn_ops.cpp`:
- Around line 704-715: The functions mlx_array_floor_divide and
mlx_array_remainder currently reinterpret_cast lhs/rhs to array* and immediately
dereference them (variables a and b) which will crash on null FFI handles;
update both functions to check if lhs or rhs is null after the reinterpret_cast
(or check the incoming mlx_array* before casting), and return nullptr (or an
appropriate error sentinel consistent with the module) if either is null instead
of dereferencing; then only call floor_divide(*a, *b) / remainder(*a, *b) and
allocate the result when both pointers are valid.
- Around line 31-37: The function mlx_async_eval must guard the incoming pointer
before indexing: check that handles is not null when count > 0 and return (or
throw an appropriate exception) if it is; update mlx_async_eval to early-return
when count == 0 or when handles == nullptr to avoid dereferencing a null
pointer, and keep the rest of the logic that iterates over handles and pushes
into arrays unchanged (referencing the handles and count parameters and the
arrays vector in your fix).
- Around line 123-152: read_scalar currently returns a default-constructed Out
on unsupported dtypes which makes callers like mlx_array_item_at_float32 report
success while returning bogus zeros; change read_scalar to signal failure (e.g.,
return std::optional<Out> or a pair<bool,Out>) instead of silently returning
Out{}, and update callers (mlx_array_item_at_float32 and the other
mlx_array_item_at_* functions) to check the optional/flag and return false when
the dtype is unsupported; ensure the read_scalar implementation returns
std::nullopt or false for the default branch and all callers propagate that
failure rather than unconditionally writing a value and returning true.
In `@crates/mlx-sys/src/mlx_qwen35.cpp`:
- Around line 255-260: In mlx_qwen35_eval_token_and_compiled_caches, add a
null-check for the FFI parameter next_token_ptr before dereferencing it: if
next_token_ptr is nullptr, handle it immediately (e.g., return early or signal
an error) to avoid crashes on invalid input; locate the dereference of
next_token_ptr in the vector push (the reinterpret_cast<array*>(next_token_ptr)
usage) and guard that code path so the function never dereferences a null
pointer.
- Around line 166-175: The code currently dereferences cache_arrays entries
inside the loop (used to construct g_compiled_caches and to bind kk/kv) without
validating pointers; update the loop in the function that iterates num_layers so
you first check that cache_arrays is non-null and that cache_arrays[i * 2] and
cache_arrays[i * 2 + 1] are non-null before any reinterpret_cast or dereference
(for both the is_linear branch that pushes into g_compiled_caches and the else
branch that binds kk/kv and reads kk.shape(2)); if a pointer is null, handle it
explicitly (return/throw an error or log and skip) so you avoid segfaults and
ensure any error path occurs before using array objects.
- Around line 115-119: In mlx_qwen35_store_weight, guard the FFI pointers before
dereferencing: check that both name and weight are non-null (and optionally that
name is not empty) and return early (or log and return) if invalid; only after
validating do the reinterpret_cast to array and use g_weights().insert_or_assign
while holding g_weights_mutex(). This prevents crashes at the FFI boundary when
callers pass null mlx_array* or const char*.
---
Duplicate comments:
In `@crates/mlx-sys/src/mlx_qwen35_common.h`:
- Around line 84-89: The current code in mlx_qwen35_common.h hard-codes
quantization params when calling mlx::core::quantized_matmul (using fixed
(32,8,"mxfp8") or (64,4,"affine")), which can mismatch checkpoint quant
metadata; update the call in the branch that returns mlx::core::quantized_matmul
to derive group_size, bits and mode from the quant metadata associated with the
weights or the provided scales (or expose/propagate those params from
linear_proj's caller) and pass those dynamic values instead of literals,
preserving the existing boolean for biases detection and signature of
mlx::core::quantized_matmul.
---
Nitpick comments:
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 423-487: Extract the duplicated decode loop into a single shared
driver function (e.g., decode_stream_driver) that both generate and chat call;
the driver should encapsulate the StreamContext handling (generation_stream),
the compiled vs fallback paths (forward_compiled, forward_with_locks), token
sampling and cache evaluation calls (eval_token_and_compiled_caches,
eval_token_and_caches), yielding/appending token ids to generated_tokens, EOS
detection, advancing y, and the periodic cleanup (synchronize_and_clear_cache).
Ensure the driver accepts parameters for max_tokens, eos_id, sampling_config,
embedding_weight/embedding_weight_t,
layers_arc/final_norm_arc/lm_head_arc/caches_arc/fa_idx, and a flag/use of
compiled, and returns the final generated_tokens and finish_reason so both
generate and chat simply call this driver to avoid code divergence.
In `@examples/tool-use-example.ts`:
- Line 105: The hardcoded maxNewTokens: 32768 in examples/tool-use-example.ts
should be made configurable via an environment variable with a reasonable
default (e.g., 1024 or 2048) to avoid huge memory/CPU usage on small machines;
update the configuration that sets maxNewTokens (the object/variable currently
containing maxNewTokens) to read process.env.MAX_NEW_TOKENS (or similar) parsed
as an integer, fall back to the moderate default when unset or invalid, and
validate the value is >0 before using it.
ℹ️ Review info
Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 7748c1fe-40eb-4c5b-bf44-f7aac70460bb
📒 Files selected for processing (11)
crates/mlx-core/src/models/qwen3_5/model.rscrates/mlx-core/src/models/qwen3_5_moe/model.rscrates/mlx-sys/src/metal/gated_delta_step.metal.inccrates/mlx-sys/src/metal/gated_delta_step_mask.metal.inccrates/mlx-sys/src/metal/gated_delta_step_vec.metal.inccrates/mlx-sys/src/metal/gated_delta_step_vec_mask.metal.inccrates/mlx-sys/src/mlx_gated_delta.cppcrates/mlx-sys/src/mlx_nn_ops.cppcrates/mlx-sys/src/mlx_qwen35.cppcrates/mlx-sys/src/mlx_qwen35_common.hexamples/tool-use-example.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- crates/mlx-sys/src/metal/gated_delta_step.metal.inc
- crates/mlx-sys/src/metal/gated_delta_step_vec_mask.metal.inc
…ection Two fixes: 1. Add explicit eval() before all item_at_int32/item_at_float32 calls. The new read_scalar<> template requires arrays to be pre-evaluated (no implicit eval like the old astype path). Fixes CI test failures in qwen3-chat, qwen3-generate-batch, qwen3-chunked-prefill tests. 2. Rewrite check_repetition_cutoff with vLLM-style range-based pattern detection. Instead of checking only one fixed ngram_size (was 3), now checks ALL pattern sizes from 2 up to max_pattern_size (now 64). Defaults changed: ngram_size 3→64, max_ngram_repeats 8→3. Fixes infinite loop in small models like Qwen3.5-2B where the model repeats 50-100 token phrases that the old 3-gram check couldn't detect. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
The vite fmt (prettier) was treating .metal.inc files as HTML due to angle brackets in Metal shader code (static_cast<float>, etc.), collapsing them to broken single-line format. Added *.metal.inc to ignorePatterns in vite.config.ts to prevent this. Co-Authored-By: Claude Opus 4.6 <[email protected]>
With the new range-based repetition detection (ngram_size=64, min_count=3), random-weight models can trigger repetition detection before the 5-token length limit. Disable ngram detection in this specific test with ngramSize: 0. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
…bug code data<T>() does not block on async_eval completion, so y.eval() must be called every step before item_at_int32(), not just step 0. Also removes all timing instrumentation (Instant::now, t_forward_us, eprintln TIMING) from the MoE model. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Extract current token and push to token_history BEFORE computing next token's logits with apply_repetition_penalty. Previously the penalty was computed against token_history that was missing the most recently generated token, allowing immediate repetition. Same fix that Qwen3 model already had (the "CRITICAL FIX" comment). Affects: Qwen3.5 dense chat loop, Qwen3.5 MoE chat loop (both C++ and Rust fallback paths). Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
<!-- CURSOR_SUMMARY --> > [!NOTE] > **High Risk** > High risk because it changes core Qwen3.5 weight loading, dtype/quantization handling, and the token-by-token generation loop while adding new FFI-backed kernels/compiled forward paths that can affect correctness and memory behavior. > > **Overview** > Adds first-class **Qwen3.5 MoE** support alongside the dense model by splitting configs/types (new `Qwen3_5MoeConfig`/`Qwen3_5MoeModel`) and updating tests to construct the correct dense vs MoE classes. > > Expands model conversion to support **FP8 dequantization**, model-specific sanitization for `qwen3_5(_moe)`, and optional offline **quantization** (`affine`/`mxfp8`) with injected quantization metadata in `config.json`. > > Introduces runtime support and performance work for Qwen3.5 inference: quantized linear projections (`quantized_matmul`), cache-aware async evaluation to prevent lazy-graph growth, optional C++ **compiled single-token decode** for dense non-quantized checkpoints, and a fused/Metal-accelerated gated-delta recurrence plus cache pointer import/export for the compiled path. > > Extends core array/dtype plumbing with `Uint8`/FP8 helpers (`from_uint8`, `from_fp8`, raw uint8/uint16 extraction, `DType::byte_size`) to support the new safetensors/quantization flows. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit facf85e. 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** * Qwen3.5 MoE model variant added with load/generate/chat support, automatic model-type detection, and expanded repetition/tool-call controls. * Quantization workflows: 4-bit, MXFP8 and affine quant; FP8 dequant and quant-aware loading/conversion; CLI conversion options. * Faster fused/compiled GPU-backed generation & sampling paths and broader SafeTensors support (Uint8/Uint32/FP8). * **Tests** * Expanded test coverage for Qwen3, Qwen3.5, and Qwen3.5 MoE variants. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
Merge-forward of mirror/upstream (237ab8a, tag v0.0.10). 10 upstream commits: mlx-node#108/mlx-node#109 template-authoritative chat + continuation cache reuse, mlx-node#110 desktop control panel, mlx-node#111 gemma4 long-context decode, mlx-node#113 quantized inference fast paths. NOT a low-risk bump. crates/mlx-sys/src/lib.rs (+93), mlx_na_int8.cpp (+162), mlx_paged_*.cpp/.h (~550), and mlx_paged_stubs_linux.cpp (+24, our platform) all move; build.mjs rebuilds mlx-sys as a cargo dependency, so this reaches the binary GenMLX loads. 7 conflicts, then 38 rustc errors from API ripples that auto-merged cleanly into regions our fork also touches. Three ripple classes: mlx-node#113 Embedding refactor — project_logits_from_hidden and the forward/prefill family now take `embedding: &Embedding` instead of a raw weight + optional transposed twin. Adopted wholesale. inject_image_placeholders — now returns Result<Vec<u32>>; fork VLM call sites needed `?` (16 of the 38 errors, and NO resolver reported this class). ChatStreamChunk — gained three required fields; fork-added literals filled by mirroring the dense sibling's own values rather than blind-defaulting. THE TRANSPOSED EMBEDDING WEIGHT WAS NEVER OURS. It was flagged mid-merge as a lost fork perf patch; provenance says otherwise. The merge base already carried it (69 dense / 42 MoE occurrences), traced to upstream's own mlx-node#24, and upstream removed it in mlx-node#113. Our fork merely FOLLOWED that convention at call sites we added. Preserving it would have been a regression, not a rescue: Embedding documents `get_weight()` as a tripwire — "production inference must never call get_weight() on a packed embedding because that constructs a full [vocab, hidden] dequantization graph" — and mlx-node#113's `as_linear` routes packed checkpoints through mlx_quantized_matmul(transpose=true) so the dense table is never materialized. FORK PATCHES VERIFIED INTACT: genmlx-d3yn (one generation stream per model) — byte-exact. Stream::new sites 4/4 dense and 2/2 MoE vs HEAD; generation_stream refs 90/90 and 80/80. This is the patch most at risk of silent loss, and note it CANNOT be validated here: the leak is Metal-only (Stream::new collapses to the default stream without Metal), which is why it never reproduced on Thor. A green battery on a CUDA box proves nothing about it. mlx-cft4 (merged_qkvz in MoE weight loading) — was HALF-LOST and is restored. Upstream demoted apply_weights_moe_inner to a #[cfg(test)] wrapper and moved production loading into apply_weights_moe_inner_with_residency, which had no merged_qkvz param; our parameter survived only on the test-only wrapper while its consuming logic rode into the production body. Re-plumbed (:522, consumed :765). Left unfixed this would have silently corrupted MoE expert weight loading — no test would have caught it. genmlx-uhtp (mlx_report_error on paged-attn catch sites) — intact, rebased onto upstream's renamed context label. mlx gitlink UNCHANGED (fef8890f both sides — no nax replay needed). Superset invariant re-verified on freshly fetched refs after finding the first check ran against a stale up/main: `git cherry -v origin/main fef8890f up/main` -> 0 '+'. cargo check -p mlx-core --release: 0 errors. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Note
High Risk
High risk because it changes core Qwen3.5 weight loading, dtype/quantization handling, and the token-by-token generation loop while adding new FFI-backed kernels/compiled forward paths that can affect correctness and memory behavior.
Overview
Adds first-class Qwen3.5 MoE support alongside the dense model by splitting configs/types (new
Qwen3_5MoeConfig/Qwen3_5MoeModel) and updating tests to construct the correct dense vs MoE classes.Expands model conversion to support FP8 dequantization, model-specific sanitization for
qwen3_5(_moe), and optional offline quantization (affine/mxfp8) with injected quantization metadata inconfig.json.Introduces runtime support and performance work for Qwen3.5 inference: quantized linear projections (
quantized_matmul), cache-aware async evaluation to prevent lazy-graph growth, optional C++ compiled single-token decode for dense non-quantized checkpoints, and a fused/Metal-accelerated gated-delta recurrence plus cache pointer import/export for the compiled path.Extends core array/dtype plumbing with
Uint8/FP8 helpers (from_uint8,from_fp8, raw uint8/uint16 extraction,DType::byte_size) to support the new safetensors/quantization flows.Written by Cursor Bugbot for commit facf85e. This will update automatically on new commits. Configure here.
Summary by CodeRabbit
New Features
Tests