Skip to content

feat: add decode profiler, GGUF conversion, Qwen3.5 VLM, and SIMD chunked GDN kernel - #29

Merged
Brooooooklyn merged 1 commit into
mainfrom
feat/perf-profiler-convert-fixes
Mar 16, 2026
Merged

Brooooooklyn merged 1 commit into
mainfrom
feat/perf-profiler-convert-fixes

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Decode profiler: new DecodeProfiler with per-phase wall-clock timing (forward, sample, eval, extract), activated via MLX_PROFILE_DECODE=1 env var. Instrumented in MoE generate/chat loops. Also switches MoE Rust fallback to token-only async eval (matching mlx-lm pattern).

GGUF conversion: full GGUF v3 parser supporting BF16/F16/F32 and Q4_0/Q4_1/Q8_0 quantized tensors with HF name remapping. Adds imatrix parser for Unsloth importance scores, AWQ-style weight pre-scaling, and mixed-bit quantization recipes (mixed_2_6, mixed_3_4, mixed_3_6, mixed_4_6, qwen3_5, unsloth). CLI gains --q-recipe, --imatrix-path, --mmproj, and --glob flags for GGUF-aware model download and conversion workflows.

Qwen3.5 VLM: vision encoder (27-layer ViT with 2D RoPE and spatial merger), image processor (smart resize/normalize/patch extraction), and VLModel with chat() accepting images. Adds M-RoPE (multimodal rotary position embeddings) to full attention layers, C++ VLM prefill pass, and model loader auto-detection of VLM models via vision.safetensors.

SIMD chunked GDN prefill kernel: rewrites chunked kernel from (BV=64, 1, 1) serial threadgroups to (32, DV_PER_TG, 1) SIMD threadgroups. 32 threads form a SIMD group splitting Dk=128 into n_per_t=4 each, all dot products use simd_sum (4 FMAs + reduction vs 128 serial FMAs). State registers reduced 32x (128 → 4 per thread). Gated on M5+ (gpu gen >= 17) via runtime GPU architecture detection — on M1–M4, the per-step kernel remains faster because Apple GPUs lack tensor cores to accelerate the O(BT²) matmuls. Adds mlx_gpu_architecture_gen() FFI using MLX device_info() architecture string parsing.

Supporting: chatStream() streaming API for Qwen3.5 dense and MoE models, fused GDN gating Metal kernel, tokenizer ChatMessage images field, Jinja2 split() maxsplit fix and raise_exception function, per-layer quant overrides in MoE persistence, dependency updates.


Note

High Risk
High risk because it modifies core model conversion/quantization paths and generation hot loops, and introduces new GPU-kernel dispatch logic (fused gating + conditional chunked recurrence) that can impact correctness and performance across devices.

Overview
Adds a decode profiling system: a new DecodeProfiler plus a global NAPI-accessible profiling store (setProfilingEnabled, getProfilingData, resetProfilingData) with tests, and instruments Qwen3 generation/chat to record phase timings, TTFT, and memory snapshots.

Expands the model conversion pipeline to use lazy SafeTensors loading, adds AWQ-style pre-scaling via --imatrix-path, and introduces mixed-bit/per-layer quantization via --q-recipe with config metadata overrides; it also avoids quantizing vision weights, can dequantize pre-quantized vision tensors, and skips redundant sanitization when weights already appear MLX-formatted.

Updates Qwen3/Qwen3.5 model code for new performance reporting (report_performance/PerformanceMetrics), routes Qwen3 chat types to the Qwen3.5 definitions, adds optional M-RoPE support in Qwen3.5 full attention layers, and upgrades gated-delta prefill with a fused gating kernel plus an M5+-gated chunked recurrence path. Minor test/config formatting changes included.

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

Summary by CodeRabbit

  • New Features

    • Vision‑language support: image preprocessing, vision encoder, image-aware chat/streaming, multimodal RoPE and vision caching
    • GGUF → SafeTensors conversion with optional per-layer recipes and imatrix pre-scaling
    • Runtime decode profiler with enable/disable APIs and exportable profiling reports
    • Lazy SafeTensors loading to reduce memory use
  • Improvements

    • Per‑layer mixed‑bit quantization and AWQ pre‑scaling
    • Faster prefill/sequence paths (chunked/fused kernels)
    • CLI: glob filtering and richer conversion feedback
  • Breaking Changes

    • Unified chat API/types (ChatConfig/ChatResult/PerformanceMetrics); prior per-model chat exports removed/renamed

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Mar 16, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Adds VLM (Qwen3.5) vision encoder and preprocessing, M‑RoPE multimodal RoPE, GGUF parsing and GGUF→SafeTensors conversion with per‑layer quantization and imatrix AWQ pre‑scaling, chunked/fused gated‑delta GPU kernels and FFI, lazy SafeTensors loading, a global decode profiler + JS/TS profiling APIs, and CLI/TS binding updates.

Changes

Cohort / File(s) Summary
Configuration & Packaging
\.yarnrc.yml, package.json, packages/core/package.json, vite.config.ts
Small config edits: YAML quoting, dependency bumps, lint script change, and vite config block reorder.
Tests
__test__/models/qwen35-stream.test.ts, __test__/core/profiling.test.ts, __test__/models/qwen3-chat.test.ts
Minor test tweaks and new profiling tests covering enable/disable, summaries, serialization, and tolerant expectations.
Conversion & Quantization CLI
crates/mlx-core/src/convert.rs, packages/cli/src/commands/convert.ts, examples/test-converted-model.ts
GGUF→SafeTensors conversion, per‑layer quant recipes, imatrix AWQ pre‑scaling; CLI options for .gguf, q‑recipe, imatrix, mmproj; example updated for optional image VLM tests.
GGUF / Imatrix / SafeTensors utils
crates/mlx-core/src/utils/gguf.rs, crates/mlx-core/src/utils/imatrix.rs, crates/mlx-core/src/utils/safetensors.rs, crates/mlx-core/src/utils/mod.rs
New GGUF parser/remapper/conversion API, imatrix parser producing per‑weight importance, lazy safetensors loader, exports and key‑normalization helper.
Profiling subsystem & decode profiler
crates/mlx-core/src/profiling.rs, crates/mlx-core/src/decode_profiler.rs, packages/lm/src/profiling.ts, packages/core/index.cjs, packages/core/index.d.cts, packages/lm/src/index.ts, packages/lm/src/stream.ts
Global profiling store and NAPI/TS bindings (enable/disable, get/reset, report); DecodeProfiler for phase/TFT timing; TS types and streaming chunks carry optional performance metrics.
Qwen3 / Qwen3.5 core & API changes
crates/mlx-core/src/models/qwen3/*, crates/mlx-core/src/models/qwen3_5/*, crates/mlx-core/src/models/qwen3_5_moe/*, crates/mlx-core/src/models/qwen3/generation.rs
Extensive VLM/M‑RoPE integration, performance instrumentation (report_performance/PerformanceMetrics), new public model hooks (init_caches, forward_from_embeddings, init_mrope_layers, vision fields), and signature updates for performance/image flows.
Vision processing & encoder
crates/mlx-core/src/models/qwen3_5/processing.rs, crates/mlx-core/src/models/qwen3_5/vision.rs, crates/mlx-core/src/models/paddleocr_vl/processing.rs
New Qwen3.5‑VL image processor, VisionEncoder implementation, pos‑embed interpolation, spatial merger, and public APIs to set weights and run forward.
Attention / Decoder / Gated‑Delta
crates/mlx-core/src/models/qwen3_5/attention.rs, crates/mlx-core/src/models/qwen3_5/decoder_layer.rs, crates/mlx-core/src/models/qwen3_5/gated_delta.rs, *_moe/*
M‑RoPE integration, position_ids plumbing through forwards, init_mrope API, fused gating and chunked gated‑delta paths with GPU generation gating and fallbacks.
Persistence / Weight loading
crates/mlx-core/src/models/qwen3_5/persistence.rs, crates/mlx-core/src/models/qwen3_5_moe/persistence.rs
Vision weight detection & splitting, vision weight loading, per‑layer quant override parsing/propagation, sanitization refinements, and application of per‑layer quant settings.
FFI / Native kernels & mlx‑sys
crates/mlx-sys/src/lib.rs, crates/mlx-sys/src/mlx_nn_ops.cpp, crates/mlx-sys/src/mlx_gated_delta.cpp, crates/mlx-sys/src/mlx_qwen35.cpp, crates/mlx-sys/src/mlx_qwen35_vlm.cpp, crates/mlx-sys/src/mlx_qwen35_common.h, crates/mlx-sys/src/metal/*, crates/mlx-sys/mlx
New extern C APIs (gated_delta_chunked, fused_gdn_gating, gpu_architecture query, VLM prefill/cache APIs, mlx_load_safetensors), Metal kernels for fused/chunked variants, and submodule update.
CLI download enhancements
packages/cli/src/commands/download-model.ts
Glob-based filtering (-g/--glob), expanded getModelFiles signature and diagnostics, GGUF detection and conversion guidance.
TypeScript/JS bindings & exports
packages/core/index.cjs, packages/core/index.d.cts, packages/lm/src/*, packages/core/package.json, packages/lm/src/models/model-loader.ts, packages/lm/src/stream.ts, packages/lm/src/index.ts
Unified ChatConfig/ChatResult types, profiling API exports, GGUF conversion export, ChatMessage images field, stream types updated to include performance, and minor package deps bump.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ImgProc as Image Processor
    participant VisionEnc as Vision Encoder
    participant Model as Qwen3.5 Model
    participant Kernel as Native Kernel

    Client->>ImgProc: process_bytes(image)
    ImgProc-->>Client: ProcessedImage (pixel_values, grid_thw)
    Client->>VisionEnc: set_patch_embed / set_pos_embed / add_layer
    Client->>VisionEnc: forward(pixel_values, grid_thw)
    VisionEnc->>VisionEnc: patch_embed + pos_embed interp
    loop per transformer layer
        VisionEnc->>Model: attention forward (position_ids)
        Model->>Kernel: apply_mrope? / gated_delta ops
        Kernel-->>Model: layer outputs
    end
    VisionEnc-->>Client: image_features
    Client->>Model: merge image_features into token flow (vlm_prefill)
Loading
sequenceDiagram
    participant CLI
    participant GGUF as GGUF Parser
    participant Imatrix as Imatrix Parser
    participant Quant as Quantizer
    participant Writer as SafeTensors Writer

    CLI->>GGUF: parse_gguf(path)
    GGUF-->>CLI: GgufFile + tensors metadata
    alt imatrix provided
        CLI->>Imatrix: parse_imatrix(path)
        Imatrix-->>CLI: per‑weight importance maps
        CLI->>Quant: apply AWQ pre-scaling (imatrix)
    end
    alt quant recipe provided
        CLI->>Quant: build per‑layer recipe predicates
    end
    CLI->>Quant: quantize_weights_with_recipe
    Quant-->>Writer: quantized tensors + config.json (per-layer overrides)
    Writer-->>CLI: output.safetensors (+config/tokenizer)
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

🐰 I nibble bytes and patch the frame,

RoPE and kernels learn my name.
GGUF folds, the profiler sings,
Converters hum and vision brings.
— Tiny rabbit: "Ship the build, delight the thing!"

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the four main features introduced: decode profiler, GGUF conversion, Qwen3.5 VLM support, and SIMD chunked GDN kernel.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/perf-profiler-convert-fixes
📝 Coding Plan
  • Generate coding plan for human review comments

Comment thread crates/mlx-core/src/convert.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

🟠 Major comments (24)
examples/test-converted-model.ts-9-27 (1)

9-27: ⚠️ Potential issue | 🟠 Major

CLI flag contract mismatch (--image documented, --ocr parsed).

Line 9 documents --image, but Lines 21 and 27 only read ocr. Users following usage text won’t hit the image path.

Suggested fix
 const { values, positionals } = parseArgs({
   args: process.argv.slice(2),
   options: {
-    ocr: { type: 'string' },
+    image: { type: 'string' },
+    ocr: { type: 'string' }, // optional backward compatibility
   },
   allowPositionals: true,
 });

 const modelName = positionals[0] || 'qwen3.5-9b-mlx';
-const imagePath = values.ocr;
+const imagePath = values.image ?? values.ocr;
🤖 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 9 - 27, The CLI documentation
and the parseArgs usage are mismatched: the header and help reference a --image
flag but parseArgs defines and reads --ocr (values.ocr) and sets imagePath =
values.ocr; update parseArgs options to use image instead of ocr (or rename
variables to ocr everywhere) so the flag and variable names align—specifically
change the options key in parseArgs and references to values.ocr/imagePath (or
rename imagePath to ocrPath) so the documented --image flag actually populates
the imagePath used by the script.
packages/cli/src/commands/download-model.ts-241-272 (1)

241-272: ⚠️ Potential issue | 🟠 Major

The new glob fast-path reports partial downloads as complete.

matchedExisting.length > 1 only proves that some requested files exist. After an interrupted run, config.json plus one GGUF is enough to trigger this early return even when other requested variants are still missing, and the GGUF branch later skips verifyDownload() entirely.

💡 Keep the heuristic lightweight
-    // For glob downloads, check if all glob-matched files are present
-    if (hasGguf && globPatterns?.length) {
-      const globs = globPatterns.map(globToRegex);
-      const matchedExisting = files.filter((f) => matchesAnyGlob(f, globs) || CORE_FILES.includes(f));
-      if (matchedExisting.length > 1) {
-        console.log('Matched files already downloaded!\n');
-        console.log('To re-download, delete the output directory first:');
-        console.log(`   rm -rf ${outputDir}\n`);
-        return;
-      }
-    }
+    // Let the normal globbed GGUF path run. The top-level directory contents
+    // are not enough to prove that every requested match is present.

Based on learnings, the existing "already downloaded" quick heuristic in this file is intentional and not a full integrity check, so I’d keep the fix narrow to this new glob path instead of expanding it into shard-by-shard verification.

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

In `@packages/cli/src/commands/download-model.ts` around lines 241 - 272, The glob
fast-path is incorrectly satisfied when only some requested files exist; change
the check to ensure every glob pattern has at least one matching file present
before early-returning. In the block using globPatterns, build globs =
globPatterns.map(globToRegex) and then verify with something like
globPatterns.every((_, i) => files.some(f => matchesAnyGlob(f, [globs[i]]) ||
CORE_FILES.includes(f))). Only if that per-pattern check passes should you log
"Matched files already downloaded" and return; leave verifyDownload() and other
logic unchanged.
packages/cli/src/commands/download-model.ts-102-142 (1)

102-142: ⚠️ Potential issue | 🟠 Major

Differentiate real glob hits from auto-included metadata files.

With --glob, CORE_FILES keep filesToDownload non-empty even when none of the user patterns matched. A typoed pattern on repos that expose config.json or tokenizer files will download metadata only, skip the helpful mismatch diagnostics here, and fail later with No weight files found.

💡 Narrow fix
 async function getModelFiles(modelName: string, accessToken?: string, globPatterns?: string[]) {
   let totalSize = 0;
   const filesToDownload: ListFileEntry[] = [];
   const allFiles: ListFileEntry[] = [];
+  let globMatchCount = 0;

   // Compile glob patterns if provided
   const globs = globPatterns?.map(globToRegex);

   for await (const file of listFiles({ repo: { type: 'model', name: modelName }, accessToken })) {
     allFiles.push(file);

     if (globs) {
       const basename = file.path.split('/').pop() || file.path;
       if (matchesAnyGlob(basename, globs) || matchesAnyGlob(file.path, globs)) {
         filesToDownload.push(file);
+        globMatchCount += 1;
         if (file.size) totalSize += file.size;
       } else if (CORE_FILES.includes(basename)) {
         filesToDownload.push(file);
         if (file.size) totalSize += file.size;
       }
     } else {
       // ...
     }
   }

-  return { totalSize, filesToDownload, allFiles };
+  return { totalSize, filesToDownload, allFiles, globMatchCount };
 }
-  const { totalSize, filesToDownload, allFiles } = await getModelFiles(modelName, HUGGINGFACE_TOKEN, globPatterns);
+  const { totalSize, filesToDownload, allFiles, globMatchCount } =
+    await getModelFiles(modelName, HUGGINGFACE_TOKEN, globPatterns);

-  if (filesToDownload.length === 0) {
+  if (globPatterns?.length ? globMatchCount === 0 : filesToDownload.length === 0) {
     console.error('No files matched the given criteria.\n');
     // ...
   }

Also applies to: 278-293

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

In `@packages/cli/src/commands/download-model.ts` around lines 102 - 142, When
globPatterns are provided, CORE_FILES are currently auto-included which can mask
the case where none of the user globs actually matched; add a boolean (e.g.,
userGlobMatched) in getModelFiles to set true only when matchesAnyGlob(basename,
globs) || matchesAnyGlob(file.path, globs) is true, still push CORE_FILES into
filesToDownload for completeness but keep the user match state separate, and at
the end of getModelFiles when globPatterns were given, return or surface a clear
indicator/error when userGlobMatched is false (so the caller can show a “no
patterns matched” diagnostic instead of silently proceeding with only metadata
files); reference getModelFiles, CORE_FILES, matchesAnyGlob, globToRegex and
listFiles to locate and implement this change.
packages/cli/src/commands/download-model.ts-322-336 (1)

322-336: ⚠️ Potential issue | 🟠 Major

Avoid printing overwrite-prone GGUF convert commands.

Once any .gguf is present, this branch prints one mlx convert command per weightFiles entry but always targets ${outputDir}-mlx. Downloads with multiple quantizations or a separate projector GGUF will either overwrite the previous conversion or suggest converting a non-standalone mmproj file by itself.

💡 Generate commands from GGUFs only, with unique outputs
-  const hasGgufFiles = weightFiles.some((f) => f.endsWith('.gguf'));
+  const ggufFiles = weightFiles.filter((f) => f.endsWith('.gguf'));
+  const hasGgufFiles = ggufFiles.length > 0;
   if (hasGgufFiles) {
-    console.log(`\nDownload complete! ${weightFiles.length} file(s) saved to ${outputDir}\n`);
+    console.log(`\nDownload complete! ${ggufFiles.length} GGUF file(s) saved to ${outputDir}\n`);
     console.log('To convert GGUF to MLX SafeTensors format:');
-    for (const wf of weightFiles) {
-      const ggufPath = join(outputDir, wf);
-      console.log(`  mlx convert -i ${ggufPath} -o ${outputDir}-mlx`);
+    const mmproj = ggufFiles.find((f) => /mmproj/i.test(f));
+    for (const wf of ggufFiles.filter((f) => f !== mmproj)) {
+      const stem = wf.split('/').pop()!.replace(/\.gguf$/i, '');
+      const extra = mmproj ? ` --mmproj ${join(outputDir, mmproj)}` : '';
+      console.log(`  mlx convert -i ${join(outputDir, wf)}${extra} -o ${outputDir}-${stem}-mlx`);
     }
     console.log('');
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/commands/download-model.ts` around lines 322 - 336, The
current GGUF branch iterates weightFiles and prints identical conversion
commands that overwrite each other; update the loop so it filters weightFiles to
only GGUF entries (use hasGgufFiles and weightFiles.filter(f =>
f.endsWith('.gguf'))) and generate unique output targets per file (e.g., derive
a basename from wf without extension or append an index) when building ggufPath
and the output argument instead of always using `${outputDir}-mlx`, ensuring
each `mlx convert -i <ggufPath> -o <uniqueOutput>` is unique.
crates/mlx-core/src/utils/safetensors.rs-503-543 (1)

503-543: ⚠️ Potential issue | 🟠 Major

Don't return a partial tensor map on callback failures.

If MxArray::from_handle() fails here, the callback just drops that tensor and load_safetensors_lazy() still returns Ok(ctx.tensors) as long as mlx_load_safetensors() itself didn't fail. That turns one bad handle into a silently incomplete model load. Capture the first callback error in LoadCtx and fail the whole call before returning.

💡 Proposed fix
     struct LoadCtx {
         tensors: HashMap<String, crate::array::MxArray>,
+        error: Option<Error>,
     }
@@
-            if let Ok(arr) = crate::array::MxArray::from_handle(handle, "lazy_load") {
-                ctx.tensors.insert(name, arr);
-            }
+            match crate::array::MxArray::from_handle(handle, "lazy_load") {
+                Ok(arr) => {
+                    ctx.tensors.insert(name, arr);
+                }
+                Err(err) => {
+                    if ctx.error.is_none() {
+                        ctx.error = Some(err);
+                    }
+                }
+            }
         }
     }
 
     let mut ctx = LoadCtx {
         tensors: HashMap::new(),
+        error: None,
     };
@@
     if count < 0 {
         return Err(Error::from_reason(format!(
             "Failed to load safetensors: {}",
             path_str
         )));
     }
 
+    if let Some(err) = ctx.error {
+        return Err(err);
+    }
+    if count as usize != ctx.tensors.len() {
+        return Err(Error::from_reason(format!(
+            "Loaded {} tensors, expected {}",
+            ctx.tensors.len(),
+            count
+        )));
+    }
+
     Ok(ctx.tensors)
 }
🤖 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 503 - 543, The
callback currently drops tensors when MxArray::from_handle() fails, allowing
load_safetensors_lazy() to return Ok with a silently incomplete tensor map;
modify LoadCtx (used by on_tensor) to store the first encountered error (e.g.,
an Option<Error> or Option<String>), update on_tensor to set that error instead
of silently ignoring failures from crate::array::MxArray::from_handle, and after
calling sys::mlx_load_safetensors check ctx for any stored callback error and
return Err if present (rather than returning Ok(ctx.tensors)); reference
LoadCtx, on_tensor, and the surrounding load_safetensors_lazy call to locate
where to add the error field, set it inside on_tensor, and validate it before
returning.
crates/mlx-core/src/utils/mod.rs-25-31 (1)

25-31: ⚠️ Potential issue | 🟠 Major

Don't treat every language_model.* key as already normalized.

language_model.layers... currently comes out unchanged even though the helper promises language_model.model.*. Those overrides will miss the external class predicate and silently not apply. Only bypass rewriting when the key already has the full language_model.model. prefix.

💡 Proposed fix
 pub(crate) fn normalize_override_key(path: &str) -> String {
-    if path.starts_with("language_model.") {
+    if path.starts_with("language_model.model.") {
         path.to_string()
+    } else if let Some(rest) = path.strip_prefix("language_model.") {
+        format!("language_model.model.{rest}")
     } else if let Some(rest) = path.strip_prefix("model.") {
         format!("language_model.model.{rest}")
     } else {
         format!("language_model.model.{path}")
     }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/mod.rs` around lines 25 - 31, The function
normalize_override_key incorrectly treats any key starting with
"language_model." as already normalized; update normalize_override_key so it
only bypasses rewriting when the key starts with the full prefix
"language_model.model." and not just "language_model."; keep the existing branch
that rewrites keys with "model." into "language_model.model.{rest}" and the
fallback that prepends "language_model.model." for all other keys so keys like
"language_model.layers..." are rewritten to
"language_model.model.language_model.layers..." (or more correctly, only leave
keys starting with "language_model.model." unchanged).
crates/mlx-core/src/models/qwen3_5/gated_delta.rs-48-79 (1)

48-79: ⚠️ Potential issue | 🟠 Major

Please verify the new fused/chunked fast paths still participate in autograd.

gated_delta_update() now routes the hot path through mlx_fused_gdn_gating() and, on long M5+ prefills, mlx_gated_delta_chunked(). If either custom op lacks gradient registration, fine-tuning will silently stop propagating gradients through the gated-delta parameters whenever that branch is taken. Based on learnings, "For files under crates/mlx-core/src/**/*.rs, do not require manual backward passes for layers composed of MLX primitive operations (e.g., rms_norm, mul, silu) when using MLX's built-in value_and_grad automatic differentiation. MLX automatically handles gradient flow through such composite layers (e.g., RMSNormGated) by tracing the forward computation graph of primitive ops (see autograd.rs). If a custom op or layer breaks autograd, flag it and document how gradients are managed."

Expected result: either explicit backward/VJP registration for the new ops, or a clear wrapper showing they are built from gradient-aware MLX primitives. If the search only finds forward declarations/implementations, the accelerated paths still need documented gradient handling.

#!/bin/bash
set -euo pipefail

for f in crates/mlx-sys/src/lib.rs crates/mlx-sys/src/mlx_gated_delta.cpp; do
  echo "=== $f ==="
  if [ -f "$f" ]; then
    sed -n '/mlx_fused_gdn_gating/,+40p' "$f"
    sed -n '/mlx_gated_delta_chunked/,+40p' "$f"
    sed -n '/mlx_fused_compute_g/,+40p' "$f"
  else
    echo "Missing $f"
  fi
done

echo "=== Autograd/backward references ==="
rg -n -C3 'fused_gdn_gating|gated_delta_chunked|fused_compute_g|backward|vjp|jvp|grad' \
  crates/mlx-sys/src/lib.rs \
  crates/mlx-sys/src/mlx_gated_delta.cpp \
  crates/mlx-core/src/models/qwen3_5/gated_delta.rs \
  crates/mlx-core/src/autograd.rs \
  crates/mlx-core/src/gradients || true

Also applies to: 83-116, 347-414

🤖 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 48 - 79, The
new fused/chunked fast paths (mlx_fused_gdn_gating, mlx_gated_delta_chunked,
fused_compute_g) may bypass MLX autograd; inspect the C++ declarations in
crates/mlx-sys (mlx_fused_gdn_gating, mlx_gated_delta_chunked) and the Rust
wrapper fused_gdn_gating in gated_delta.rs and either (A) register explicit
backward/VJP implementations for these custom ops in the MLX autograd registry
(add VJP/backward hooks where the native ops are defined), or (B) re-expose the
fast path as a composition of existing gradient-aware MLX primitives (RMSNorm,
mul, silu, etc.) so autograd can trace them automatically and document this in
comments; ensure the chosen approach is reflected where gated_delta_update
routes to mlx_fused_gdn_gating/mlx_gated_delta_chunked and add tests or a small
runtime check to assert gradients flow through these paths.
crates/mlx-sys/src/mlx_qwen35_vlm.cpp-50-50 (1)

50-50: ⚠️ Potential issue | 🟠 Major

Use rope_deltas when publishing the decode offset.

The prefill API accepts rope_deltas, but g_vlm_offset is set to raw T. That makes the first decode step start from the token count instead of the multimodal RoPE position that was actually used during prefill.

Also applies to: 145-147

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

In `@crates/mlx-sys/src/mlx_qwen35_vlm.cpp` at line 50, The code currently sets
the global decode offset g_vlm_offset to the raw token count T, causing the
first decode step to start from token count instead of the RoPE-adjusted
position used during prefill; update the logic where g_vlm_offset is published
(and the related spots around the prefill handling at the places noted, e.g.,
the parameter int rope_deltas and the publish/assignment near lines ~145-147) to
use the provided rope_deltas value (or T + rope_deltas if the offset should be
cumulative) instead of T alone so the decode offset reflects the multimodal RoPE
position used by the prefill API.
crates/mlx-core/src/convert.rs-1655-1658 (1)

1655-1658: ⚠️ Potential issue | 🟠 Major

Don’t materialize the entire model after touching a few AWQ tensors.

Evaluating every entry defeats the lazy SafeTensors path you just added and can spike memory on large models. Only the tensors you actually modified need to be forced.

🤖 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 1655 - 1658, The loop that calls
w.eval() for every entry in weights forces materialization of the whole model;
instead track which tensors were actually modified and only eval those: add a
mutable collection (e.g., modified_weights: HashSet<Key> or Vec<Key>) where you
push the tensor key whenever you modify an AWQ tensor in the code paths that
touch tensors, then replace the for w in weights.values() { w.eval(); } with a
loop that looks up each key from modified_weights and calls eval() only on those
Weight instances (weights.get(&key).unwrap().eval()), or use a predicate like
weight.is_lazy() if available to avoid forcing already-materialized tensors.
Ensure the modification sites reference the same unique identifiers (weights and
w.eval()) so only touched tensors are forced.
crates/mlx-core/src/convert.rs-1594-1638 (1)

1594-1638: ⚠️ Potential issue | 🟠 Major

AWQ lookups miss every sanitized Qwen3.5 key.

parse_imatrix() produces HF names like model.layers.*, but this function switches to language_model.model.layers.* when the weights are sanitized. Those prefixed keys never exist in imatrix.importance, so prescaling silently becomes a no-op for the Qwen3.5/VLM path.

🤖 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 1594 - 1638, The code chooses
layer_prefix by inspecting weights.keys() only, but imatrix.importance uses
HF-style keys so lookups like compute_group_a_scales/imatrix access fail for
sanitized Qwen3.5 keys; change the prefix detection to consider both maps
(weights and imatrix.importance) or normalize keys before lookup. Concretely,
update the logic that sets layer_prefix (the block using weights.keys().any(...)
and the variable layer_prefix) to check for the presence of keys starting with
"language_model.model.layers." OR "model.layers." in imatrix.importance as well
(or strip a leading "language_model." when querying imatrix inside
compute_group_a_scales/compute_scales_for_key) so the same prefix is used for
both weights and imatrix lookups (references: parse_imatrix, layer_prefix,
compute_group_a_scales, compute_scales_for_key, imatrix.importance).
crates/mlx-sys/src/mlx_qwen35_vlm.cpp-138-141 (1)

138-141: ⚠️ Potential issue | 🟠 Major

This only returns logits for the last item in the batch.

After flattening to [B*T, vocab], slicing (B*T)-1 drops every other batch member. If this path is invoked with B > 1, decode starts from logits for only the final sample.

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

In `@crates/mlx-sys/src/mlx_qwen35_vlm.cpp` around lines 138 - 141, The current
code slices h_flat with index (B*T)-1 which returns only the very last row
across all batches; instead reshape h_flat back to {B, T, vocab} and then select
the final timestep for every batch to produce logits of shape {B, vocab}.
Concretely, replace the single-row slice of h_flat with a reshape(h_flat, {B, T,
vocab}) followed by slicing at timestep T-1 (or an axis-select on axis 1) to
yield logits = reshape(slice(reshaped_h_flat, {0, T-1, 0}, {B, T, vocab}?), {B,
vocab}) — i.e., use h_flat, B, T, vocab, reshape and slice so you return
per-batch last-token logits instead of only the last batch item.
crates/mlx-core/src/convert.rs-687-709 (1)

687-709: ⚠️ Potential issue | 🟠 Major

The mixed-bit recipe never reaches its lm_head branch.

This closure calls should_quantize() first, and that helper returns false for lm_head. Untied models therefore skip lm_head entirely instead of giving it the documented high-bit setting.

Suggested fix
     Ok(Box::new(move |key: &str| -> QuantDecision {
+        // lm_head always gets high bits
+        if key.contains("lm_head") {
+            return QuantDecision::Custom {
+                bits: high_bits,
+                group_size: gs,
+                mode: "affine".to_string(),
+            };
+        }
+
         // Non-quantizable weights are skipped
         if !should_quantize(key) {
             return QuantDecision::Skip;
         }
 
         // Router gates → 8-bit affine (same as existing behavior)
         if is_router_gate(key) {
             return QuantDecision::Custom {
                 bits: 8,
                 group_size: 64,
                 mode: "affine".to_string(),
             };
         }
-
-        // lm_head always gets high bits
-        if key.contains("lm_head") {
-            return QuantDecision::Custom {
-                bits: high_bits,
-                group_size: gs,
-                mode: "affine".to_string(),
-            };
-        }
🤖 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 687 - 709, The closure returned
in convert.rs checks should_quantize(key) before special-casing lm_head, but
should_quantize returns false for lm_head so the lm_head branch is never
reached; fix by checking for lm_head prior to calling should_quantize (or modify
should_quantize to allow lm_head) so that keys containing "lm_head" return the
intended QuantDecision::Custom with bits = high_bits, group_size = gs, mode =
"affine". Ensure the lm_head check appears before the early-return skip and keep
the existing is_router_gate handling intact.
crates/mlx-sys/src/mlx_qwen35.cpp-273-275 (1)

273-275: ⚠️ Potential issue | 🟠 Major

Clamp the adjusted offset to [0, max_kv_len).

g_offset_int += delta can move the next write position negative or past the KV cache, and the following decode step will fail when it writes with that invalid offset.

Suggested fix
 void mlx_qwen35_compiled_adjust_offset(int delta) {
-  g_offset_int += delta;
-  g_compiled_offset = array(g_offset_int, mlx::core::int32);
+  if (!g_compile_inited) return;
+  int next = g_offset_int + delta;
+  if (next < 0 || next >= g_compile_config.max_kv_len) return;
+  g_offset_int = next;
+  g_compiled_offset = array(g_offset_int, mlx::core::int32);
 }
🤖 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 273 - 275, The function
mlx_qwen35_compiled_adjust_offset should clamp g_offset_int into the valid range
before rebuilding g_compiled_offset: after computing g_offset_int += delta,
clamp it to be between 0 and max_kv_len-1 (i.e., [0, max_kv_len)), then set
g_compiled_offset = array(g_offset_int, mlx::core::int32). Update
mlx_qwen35_compiled_adjust_offset to perform this clamp (using std::min/std::max
or std::clamp) so writes never use a negative or out-of-bounds offset.
crates/mlx-core/src/convert.rs-1331-1355 (1)

1331-1355: ⚠️ Potential issue | 🟠 Major

Restore the removed biases on dequantize failure.

This branch removes {base}.biases up front, but on a null handle it only puts the weight and scales back. One failed vision dequantization leaves that tensor group half-missing.

Suggested fix
                     if handle.is_null() {
                         warn!("  Failed to dequantize vision weight: {}", weight_key);
                         // Put originals back
                         new_weights.insert(weight_key, w);
                         new_weights.insert(scale_key.clone(), s);
+                        if let Some(b) = biases {
+                            new_weights.insert(biases_key, b);
+                        }
                     } else {
🤖 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 1331 - 1355, The null-handle
branch after calling mlx_sys::mlx_dequantize removes biases but only reinserts
weight and scales; ensure biases are restored too: when handle.is_null() in the
dequantize block that uses new_weights, weight_key, scale_key, biases_key and
variables w, s, biases, also reinsert the original biases (if any) back into
new_weights (similar to how w and s are reinserted) so the tensor group is not
left half-missing on failure.
crates/mlx-core/src/tokenizer.rs-126-129 (1)

126-129: ⚠️ Potential issue | 🟠 Major

Plumb images into the template context too.

Adding the field here is only half of the VLM path: render_chat_template_jinja2() still serializes only text/tool fields, so message.images never exists inside the official VLM template and image prompts fall back to text-only rendering.

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

In `@crates/mlx-core/src/tokenizer.rs` around lines 126 - 129,
render_chat_template_jinja2 currently only serializes text/tool fields so
message.images never reaches the Jinja2 template; update
render_chat_template_jinja2 to plumb the new images field into the template
context by serializing message.images (the Option<Vec<Uint8Array>> declared on
the message type) into a template-friendly form (e.g., array of byte buffers or
data-URLs) and include it alongside existing text/tool properties in the
per-message context object; ensure the template key name matches how templates
reference it (message.images) and add/adjust tests to cover VLM image prompts.
crates/mlx-core/src/models/qwen3_5/processing.rs-129-170 (1)

129-170: ⚠️ Potential issue | 🟠 Major

temporal_patch_size=2 is documented but never applied.

This still returns single-frame [num_patches, 3, patch_h, patch_w] patches. Nothing here duplicates the image or packs a temporal depth of 2, so the output no longer lines up with the new 3D patch-embed path unless that duplication happens somewhere else later.

🤖 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/processing.rs` around lines 129 - 170, The
code never uses self.config.temporal_patch_size (the documented
temporal_patch_size=2), so grid_t is hardcoded to 1 and patches are
single-frame; fix by reading temporal_patch_size into grid_t (let grid_t =
self.config.temporal_patch_size as usize) and when grid_t > 1 duplicate the
per-patch pixel content across the temporal dimension: expand num_patches =
grid_t * grid_h * grid_w and, inside the nested loops that build patch_data (the
loop over ph, pw, c, py, px), add an outer loop over t in 0..grid_t that repeats
pushing the same patch pixels for each temporal slice; ensure
MxArray::from_float32 and ProcessedImage::new still receive the updated
num_patches and vec![grid_t as i32, grid_h as i32, grid_w as i32] respectively
so downstream 3D patch-embed code receives temporal depth.
crates/mlx-core/src/tokenizer.rs-752-767 (1)

752-767: ⚠️ Potential issue | 🟠 Major

Fix split(None, maxsplit) to match Python's behavior.

The splitn(..., char::is_whitespace) branch at line 764 does not match Python's str.split(None, maxsplit). Python strips leading/trailing whitespace and collapses consecutive whitespace runs, but the Rust implementation splits at the first whitespace character only. This produces mismatched results: 'hello world'.split(None, 1) yields ['hello', 'world'] in Python but ['hello', ' world'] with the current code. Templates using content.split(None, maxsplit) will parse different tokens than the upstream Python template expects.

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

In `@crates/mlx-core/src/tokenizer.rs` around lines 752 - 767, The (None, Some(n))
branch currently uses s.splitn(..., char::is_whitespace) which splits at single
whitespace characters and doesn't collapse runs like Python's str.split(None,
maxsplit); change that branch to use s.split_whitespace().take(n as usize +
1).collect() so it strips/collapses whitespace and limits results correctly.
Update the match arm that builds parts (referencing s, delim, maxsplit, splitn,
split_whitespace) to use split_whitespace().take(...) for the None + Some(n)
case.
crates/mlx-core/src/utils/gguf.rs-150-167 (1)

150-167: ⚠️ Potential issue | 🟠 Major

Add validation for metadata alignment values to reject zero and negative inputs.

The as_u32() and as_u64() methods cast signed integers with as, so negative metadata values get reinterpreted as huge unsigned numbers (e.g., -1 becomes u64::MAX). When general.alignment is read via as_u64() at line 425, negative values leak through as enormous values, and a zero alignment value reaches align_offset() at line 470 where it will panic on modulo (line 483). Add validation to ensure alignment is a positive, reasonable value before use.

Also applies to: 423-489

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

In `@crates/mlx-core/src/utils/gguf.rs` around lines 150 - 167, The as_u32 and
as_u64 helpers currently cast signed negatives into huge unsigned values; update
them to validate and reject zero/negative values instead of silently casting:
for Int32/Int64 return None if *v <= 0, and for Uint32/Uint64 return None if *v
== 0; preserve existing Some(...) for positive unsigned values. This ensures
callers like the general.alignment consumer (which calls as_u64() before
align_offset()) will not receive 0 or wrapped negative alignments that would
cause modulo/overflow panics.
crates/mlx-core/src/utils/imatrix.rs-240-249 (1)

240-249: ⚠️ Potential issue | 🟠 Major

Reject GGUF tensor type 6 instead of accepting it as F32.

Type 6 is GGML_TYPE_Q5_0 (5-bit quantized), not F32. The code reads all tensor payloads as raw f32 values (line 279–283), which is only correct for type 0. Accepting type 6 will silently interpret quantized block data (packed bits, scales) as floats, producing garbage importance scores instead of failing fast.

Suggested fix
-        if type_u32 != 6 {
-            // F32 = 0 in GGUF types, but imatrix stores raw F32 data as type 6?
-            // Actually GGUF tensor type F32 = 0. Let's accept both.
-            if type_u32 != 0 {
-                return Err(Error::from_reason(format!(
-                    "imatrix tensor '{name}' has unexpected type {type_u32} (expected F32=0)"
-                )));
-            }
-        }
+        if type_u32 != 0 {
+            return Err(Error::from_reason(format!(
+                "imatrix tensor '{name}' has unexpected type {type_u32} (expected F32=0)"
+            )));
+        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/imatrix.rs` around lines 240 - 249, The code
currently treats GGUF tensor type 6 as F32; update the type check in the block
that calls read_u32_le and validates type_u32 so it only accepts 0 (F32) and
rejects 6 (GGML_TYPE_Q5_0) by returning an Error::from_reason when type_u32 !=
0; locate the check around the variable type_u32 and the error that references
imatrix tensor '{name}' and ensure the error message clearly reports the actual
type and that F32=0 is expected, so quantized types (e.g., 6) fail fast instead
of being interpreted as raw f32 payloads.
crates/mlx-sys/src/mlx_gated_delta.cpp-174-189 (1)

174-189: ⚠️ Potential issue | 🟠 Major

Validate chunked-kernel tensor layouts before dispatch.

This path derives every q/k/g/state stride from Hv, Dv, and Dk, but it never checks that the handles actually satisfy [B, S, Hv, Dk], [B, S, Hv], and [B, Hv, Dv, Dk]. Passing an unexpanded GQA tensor or mismatched state shape will make the Metal kernel index the wrong memory instead of failing fast.

🤖 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 174 - 189, The code
currently derives B,S,Hv,Dk,Dv from q_arr/v_arr but does not validate that the
provided tensors actually have the expected chunked-kernel layouts; add explicit
runtime checks before building inputs to verify q_arr.shape == [B,S,Hv,Dk],
k_arr.shape == [B,S,Hv,Dk], v_arr.shape == [B,S,Hv,Dv], g_arr.shape == [B,S,Hv],
beta_arr.shape == [B,S,Hv], and state_arr.shape == [B,Hv,Dv,Dk] (and optionally
validate contiguous/expected strides for the Hv/Dk/Dv dimensions) and throw or
return a clear error if any mismatch is found so the Metal kernel is not
dispatched with incorrect memory layout.
crates/mlx-core/src/models/qwen3_5/persistence.rs-41-53 (1)

41-53: ⚠️ Potential issue | 🟠 Major

Also merge vision.safetensors on the sharded path.

This sidecar load only runs in the single-file branch. The sharded branch below still returns text weights only, so large VL checkpoints with model-00001-of-N.safetensors plus vision.safetensors will silently load as text-only.

🤖 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 41 - 53, The
sharded-loading branch currently only returns text weights and misses merging
vision.safetensors; update the sharded path to mirror the single-file branch by
checking dir.join("vision.safetensors") when handling the shard files, loading
it with SafeTensorsFile::load and calling load_tensors to obtain vision_params,
then extend the existing params vector with vision_params before returning;
reference the params variable, SafeTensorsFile::load, load_tensors calls, and
the vision_path logic when making the change.
crates/mlx-core/src/models/qwen3_5_moe/persistence.rs-919-951 (1)

919-951: ⚠️ Potential issue | 🟠 Major

The new MoE-VL split never sees vision.safetensors sidecars.

raw_params here only contains whatever load_all_safetensors() returned, and this file still doesn't load the separate vision.safetensors emitted by the GGUF --mmproj flow. That leaves has_vision false for converted MoE-VL checkpoints, so the new vision encoder initialization is skipped entirely.

🤖 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 919 -
951, The split logic is never triggered because raw_params doesn't include the
separate vision.safetensors sidecar from the GGUF --mmproj flow; modify the code
that prepares raw_params (before the has_vision check in persistence.rs) to
attempt loading a sidecar named like "<base>.vision.safetensors" (or
"vision.safetensors") using the same loader used by load_all_safetensors(),
merge its entries into raw_params (or into a new map that is then merged) so
keys with "vision_tower." or "visual." are present, and only then compute
has_vision and perform the existing split into text_params and vision_params
(symbols to locate: raw_params, has_vision, vision_params, text_params, and the
loader function load_all_safetensors or equivalent).
packages/cli/src/commands/convert.ts-136-146 (1)

136-146: ⚠️ Potential issue | 🟠 Major

Reject --mmproj on non-GGUF inputs.

Outside the .gguf branch this flag is never consumed, so the command can succeed while silently skipping the vision encoder conversion and produce an incomplete VL checkpoint.

Proposed guard
   const mmprojPath = args.mmproj ? resolve(args.mmproj) : undefined;
   if (mmprojPath !== undefined) {
+    if (!inputPath.endsWith('.gguf')) {
+      console.error('Error: --mmproj can only be used when --input points to a .gguf file');
+      process.exit(1);
+    }
     if (!existsSync(mmprojPath)) {
       console.error(`Error: mmproj file not found: ${mmprojPath}`);
       process.exit(1);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/commands/convert.ts` around lines 136 - 146, Reject the
--mmproj flag when the conversion input/output is not a GGUF so the vision
encoder conversion isn't silently skipped: after computing mmprojPath
(args.mmproj -> mmprojPath) add a guard that validates the current conversion
path/format (the same condition used to enter the .gguf-specific branch) and if
mmprojPath is provided but the conversion is not targeting a .gguf checkpoint,
print an error like "Error: --mmproj is only valid for .gguf inputs" and
process.exit(1). Ensure you keep the existing file-existence and .gguf suffix
checks (mmprojPath and mmprojPath.endsWith('.gguf')) and place the new guard
before any non-GGUF code paths so the flag cannot be ignored.
crates/mlx-sys/src/metal/gated_delta_chunked.metal.inc-145-148 (1)

145-148: ⚠️ Potential issue | 🟠 Major

Load q_buf with a strided cooperative loop.

This only copies one q element per thread, so the shared buffer is fully initialized only when BK <= 32 * DV_PER_TG. With the current dispatch, Dv = 1..3 already leaves part of q_buf stale, and any larger BK would do the same before the q@state / q@k reductions run.

Proposed fix
-            if (linear_tid < BK) {
-                q_buf[linear_tid] = static_cast<float>(q_t[linear_tid]);
-            }
+            for (int d = linear_tid; d < BK; d += num_threads) {
+                q_buf[d] = static_cast<float>(q_t[d]);
+            }
🤖 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_chunked.metal.inc` around lines 145 -
148, The current per-thread load into q_buf only writes one element
(q_buf[linear_tid]) which leaves q_buf partially uninitialized when BK > number
of threads; change the copy to a strided cooperative loop so each thread
iterates with stride = blockDim.x (or the kernel's thread-group size) and writes
q_buf[idx] = float(q_t[idx]) for idx starting at linear_tid and stepping by
stride while staying < BK. Update the load site that references q_t, q_buf,
linear_tid, BK, and qk_time_stride (inside the loop using chunk_start + i) to
use this strided pattern so the shared q_buf is fully initialized before the
q@state/q@k reductions run.
🟡 Minor comments (6)
examples/test-converted-model.ts-66-66 (1)

66-66: ⚠️ Potential issue | 🟡 Minor

Guard tokens/sec computation against zero-duration runs.

If duration is 0ms, the current formula returns Infinity/NaN, which makes perf logs unreliable.

Suggested fix
-  const tokensPerSecond = (result.numTokens / duration) * 1000;
+  const tokensPerSecond = duration > 0 ? (result.numTokens / duration) * 1000 : 0;

Also applies to: 95-95

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

In `@examples/test-converted-model.ts` at line 66, Guard the tokens/sec
calculation against zero or near-zero durations by checking duration before
dividing: when computing tokensPerSecond from result.numTokens and duration (the
expression tokensPerSecond = (result.numTokens / duration) * 1000), if duration
is 0 (or <= 0) set tokensPerSecond to a safe fallback (e.g., 0) instead of
performing the division; update both occurrences that use tokensPerSecond (the
computation at tokensPerSecond = (result.numTokens / duration) * 1000 and the
similar one reported at the second occurrence) to perform this check and compute
the fallback.
crates/mlx-core/src/decode_profiler.rs-45-48 (1)

45-48: ⚠️ Potential issue | 🟡 Minor

Honor the documented MLX_PROFILE_DECODE=1 contract.

This enables profiling for any present value, so MLX_PROFILE_DECODE=0 still turns it on. Compare the value explicitly so operators can disable the profiler without unsetting the variable.

💡 Proposed fix
-    *ENABLED.get_or_init(|| std::env::var("MLX_PROFILE_DECODE").is_ok())
+    *ENABLED.get_or_init(|| matches!(std::env::var("MLX_PROFILE_DECODE").as_deref(), Ok("1")))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/decode_profiler.rs` around lines 45 - 48, The
is_enabled() routine currently treats any presence of MLX_PROFILE_DECODE as
enabled; change the closure passed to ENABLED.get_or_init so it explicitly
checks that the environment variable's value equals "1" (e.g., compare the
result of std::env::var("MLX_PROFILE_DECODE") to the string "1") instead of
using is_ok(), leaving the static ENABLED and function is_enabled unchanged.
crates/mlx-core/src/decode_profiler.rs-138-169 (1)

138-169: ⚠️ Potential issue | 🟡 Minor

Guard the throughput math against sub-ms runs.

as_millis() truncates short runs to 0, and cpu_total_us can also be 0 when no phases were ended, so the report can print inf/NaN tok/s. Using floating-point seconds with zero guards keeps the summary stable.

💡 Proposed fix
-        let wall_ms = self.loop_start.elapsed().as_millis() as f64;
-        let wall_tok_s = n / (wall_ms / 1000.0);
+        let wall_s = self.loop_start.elapsed().as_secs_f64();
+        let wall_ms = wall_s * 1000.0;
+        let wall_tok_s = if wall_s > 0.0 { n / wall_s } else { 0.0 };
@@
-        let cpu_ms = cpu_total_us as f64 / 1000.0;
-        let cpu_tok_s = n / (cpu_total_us as f64 / 1_000_000.0);
+        let cpu_ms = cpu_total_us as f64 / 1000.0;
+        let cpu_s = cpu_total_us as f64 / 1_000_000.0;
+        let cpu_tok_s = if cpu_s > 0.0 { n / cpu_s } else { 0.0 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/decode_profiler.rs` around lines 138 - 169, The
throughput math in decode_profiler.rs can divide by zero because as_millis() and
cpu_total_us may be zero; update the calculations in the report to use
floating-second durations (e.g., loop_start.elapsed().as_secs_f64()) and guard
divides by zero: compute wall_s and cpu_s as floats, compute wall_tok_s = if
wall_s > 0.0 && self.num_tokens>0 { (self.num_tokens as f64) / wall_s } else {
0.0 }, and similarly compute cpu_tok_s using cpu_s or set to 0.0 when
cpu_total_us==0 or num_tokens==0, and replace usages of wall_ms and
cpu_total_us-divisions with these guarded values so the summary never prints
inf/NaN (refer to symbols loop_start, num_tokens, wall_ms/wall_tok_s,
cpu_total_us, cpu_tok_s, and TOTAL (measured)).
crates/mlx-core/src/models/qwen3_5/vision.rs-173-190 (1)

173-190: ⚠️ Potential issue | 🟡 Minor

forward() currently hard-requires batch == 1.

The unconditional squeeze(Some(&[0])) will fail for any real batched input even though the API/docs expose a batch dimension. Either preserve the batch axis throughout this path or reject batch != 1 explicitly so callers get a clear error.

Possible guard
         let shape = hidden_states.shape()?;
         let batch = shape[0];
+        if batch != 1 {
+            return Err(Error::from_reason(format!(
+                "Qwen3_5VisionEncoder::forward currently expects batch=1, got {}",
+                batch
+            )));
+        }
         let seq_len = shape[1];
🤖 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/vision.rs` around lines 173 - 190, The
forward() implementation unconditionally calls embeddings.squeeze(Some(&[0]))
which assumes batch == 1 and will break for real batched inputs; either preserve
the batch axis through the patch embedding path or add an explicit check that
returns an error for batch != 1. Locate the forward() method (symbols:
hidden_states.shape(), reshape(), transpose(), self.patch_embed.forward(),
embeddings.squeeze()) and replace the unconditional squeeze by (a) keeping
embeddings as shape [batch, seq_len, embed_dim] and adjust downstream consumers
to accept the batch dimension, or (b) add a guard after computing batch (if
batch != 1 { return Err(...) }) that returns a clear error explaining only
batch==1 is supported. Ensure the error uses the same Result/MxArray error
patterns used in this file.
crates/mlx-core/src/models/qwen3_5/model.rs-1345-1347 (1)

1345-1347: ⚠️ Potential issue | 🟡 Minor

Same token_history issue in chat_stream VLM path.

Same issue as chat() — in VLM mode, token_history should be initialized from final_tokens (with image placeholders) rather than tokens.

🤖 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 1345 - 1347, In the
chat_stream VLM path the token history is incorrectly initialized from tokens
instead of from final_tokens (which includes image placeholders); update the
code that creates token_history (the let mut token_history: Vec<u32> declaration
in the chat_stream VLM branch) to clone from final_tokens so repetition
penalties and history include the image placeholders rather than using tokens.
crates/mlx-core/src/models/qwen3_5/model.rs-849-851 (1)

849-851: ⚠️ Potential issue | 🟡 Minor

Token history not updated with image placeholders in VLM mode.

In the VLM branch, final_tokens includes injected image placeholders, but token_history is initialized from the original tokens after the branching. This differs from the MoE model which updates token_history = final_tokens.clone() in the VLM path (see qwen3_5_moe/model.rs lines 738-739).

This could cause repetition penalty to behave incorrectly for VLM requests since the penalty would be computed against tokens the model didn't actually see.

🔧 Suggested fix: Move token_history initialization inside branches
             let (mut last_logits, seq_len, vlm_compiled_init_done) =
                 if let (true, Some(vision_enc), Some(img_proc)) = (
                     has_images,
                     vision_encoder_arc.as_ref(),
                     image_processor_arc.as_ref(),
                 ) {
                     // --- VLM path: process images and run VLM prefill ---
                     let sms = spatial_merge_size.unwrap_or(2);
                     let all_images = extract_images_from_messages(&messages);
 
                     // Process images and inject placeholders
                     let image_refs: Vec<&[u8]> = all_images.iter().map(|v| v.as_slice()).collect();
                     let processed = img_proc.process_many(&image_refs)?;
                     let num_image_tokens = compute_num_image_tokens(&processed.grid_thw(), sms)?;
                     let final_tokens = inject_image_placeholders(&tokens, num_image_tokens);
+                    
+                    // Update token_history to include image placeholders
+                    token_history = final_tokens.clone();
 
                     let input_ids =
                         MxArray::from_uint32(&final_tokens, &[1, final_tokens.len() as i64])?;

Note: You'll need to move let mut token_history: Vec<u32> = tokens.clone(); before the branching block for this to work.

🤖 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 849 - 851, The
token_history is not updated to include injected image placeholders in the VLM
branch, causing repetition penalty to be computed against the original tokens;
update token_history to reflect final_tokens in the VLM path (e.g., set
token_history = final_tokens.clone() or move let mut token_history: Vec<u32> =
tokens.clone() so it's initialized per-branch) so that token_history matches the
actual sequence used for scoring (mirror the qwen3_5_moe/model.rs approach for
the VLM branch involving final_tokens).
🧹 Nitpick comments (4)
crates/mlx-core/src/models/paddleocr_vl/processing.rs (1)

141-147: Consider validating image_grid_thw length for consistency.

The doc comment on line 137 specifies that image_grid_thw should have dimensions [t, h, w] (3 elements). The constructor accepts any Vec<i32> without validation. While this is an internal API, callers could inadvertently pass vectors of incorrect length.

Since the existing internal construction at line 349 always produces a 3-element vector, and image_grid_thw() returns a clone without checking, this is a minor robustness concern.

Optional: Add a debug assertion for the expected length
     pub fn new(pixel_values: MxArray, image_grid_thw: Vec<i32>) -> Self {
+        debug_assert_eq!(image_grid_thw.len(), 3, "image_grid_thw must have exactly 3 elements [t, h, w]");
         Self {
             pixel_values,
             image_grid_thw,
         }
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/paddleocr_vl/processing.rs` around lines 141 -
147, The constructor ProcessedImage::new currently accepts any Vec<i32> for
image_grid_thw even though it must represent [t,h,w]; add a validation (e.g.,
debug_assert_eq!(image_grid_thw.len(), 3) or an explicit check that panics with
a clear message) at the start of ProcessedImage::new to ensure
image_grid_thw.len() == 3, and keep image_grid_thw() behavior unchanged; this
enforces the expected 3-element shape while remaining lightweight for internal
usage.
packages/lm/src/stream.ts (1)

29-32: Use UPPER_SNAKE_CASE for these cached native method constants.

_nativeDenseChatStream and _nativeMoeChatStream are module-level constants. Renaming them to NATIVE_DENSE_CHAT_STREAM / NATIVE_MOE_CHAT_STREAM would match the repo convention and make them easier to distinguish from instance methods. Based on learnings, "In TypeScript files across mlx-node/mlx-node, adopt camelCase for variables, functions, and methods, while using UPPER_SNAKE_CASE for module-level constants (for example: const TEXT_LABELS = ...; const DEFAULT_BASE_PATH = ...)."

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

In `@packages/lm/src/stream.ts` around lines 29 - 32, The module-level cached
method constants _nativeDenseChatStream and _nativeMoeChatStream should be
renamed to UPPER_SNAKE_CASE to follow project convention; update their
identifiers to NATIVE_DENSE_CHAT_STREAM and NATIVE_MOE_CHAT_STREAM and replace
all uses accordingly (they are assigned from
Qwen35ModelNative.prototype.chatStream and
Qwen35MoeModelNative.prototype.chatStream) so references and any lint-disable
comments remain valid and no instance method names are changed.
crates/mlx-sys/src/mlx_nn_ops.cpp (1)

850-873: Error message prefix should use "[MLX]" for consistency.

The error log at line 870 uses "mlx_load_safetensors error:" but other FFI functions in this file use the "[MLX]" prefix (e.g., line 269: "[MLX] copy_to_buffer(uint16):"). This inconsistency can make log aggregation and filtering more difficult.

🔧 Proposed fix for consistent error prefix
     } catch (const std::exception& e) {
-        std::cerr << "mlx_load_safetensors error: " << e.what() << std::endl;
+        std::cerr << "[MLX] mlx_load_safetensors: " << e.what() << std::endl;
         return -1;
     }
🤖 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 850 - 873, The error message
in mlx_load_safetensors should use the standardized "[MLX]" prefix; locate the
catch block inside the mlx_load_safetensors function and replace the current
std::cerr output ("mlx_load_safetensors error: " << e.what()) with a message
that begins with "[MLX]" (e.g., "[MLX] mlx_load_safetensors: " followed by
e.what()) so logs are consistent with other FFI functions like copy_to_buffer.
packages/cli/src/commands/convert.ts (1)

4-4: Import conversion helpers via a package entry point.

Please re-export these APIs from a supported package entry point instead of importing @mlx-node/core into the CLI directly.

As per coding guidelines, "Import from package entry points only: use '@mlx-node/lm' for inference utilities and '@mlx-node/trl' for training utilities, never import directly from '@mlx-node/core'."

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

In `@packages/cli/src/commands/convert.ts` at line 4, The CLI currently imports
conversion helpers directly from `@mlx-node/core`; change the import to use the
public package entry point that re-exports these helpers (e.g., import
convertModel, convertForeignWeights, convertGgufToSafetensors from
'@mlx-node/lm' instead of '@mlx-node/core') and if those symbols are not yet
re-exported from the entry point update the library's entry exports to re-export
the original core implementations so the CLI only imports from the public entry
point; ensure you update the import statements that reference convertModel,
convertForeignWeights, and convertGgufToSafetensors to use the entry-point
package.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6fd4faec-404d-4e95-b67b-1721bcceed8c

📥 Commits

Reviewing files that changed from the base of the PR and between c81a084 and beae500.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (42)
  • .yarnrc.yml
  • __test__/models/qwen35-stream.test.ts
  • crates/mlx-core/src/convert.rs
  • crates/mlx-core/src/decode_profiler.rs
  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/models/paddleocr_vl/processing.rs
  • crates/mlx-core/src/models/qwen3/model.rs
  • crates/mlx-core/src/models/qwen3_5/attention.rs
  • crates/mlx-core/src/models/qwen3_5/decoder_layer.rs
  • crates/mlx-core/src/models/qwen3_5/gated_delta.rs
  • crates/mlx-core/src/models/qwen3_5/mod.rs
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/mlx-core/src/models/qwen3_5/persistence.rs
  • crates/mlx-core/src/models/qwen3_5/processing.rs
  • crates/mlx-core/src/models/qwen3_5/vision.rs
  • crates/mlx-core/src/models/qwen3_5_moe/decoder_layer.rs
  • crates/mlx-core/src/models/qwen3_5_moe/model.rs
  • crates/mlx-core/src/models/qwen3_5_moe/persistence.rs
  • crates/mlx-core/src/tokenizer.rs
  • crates/mlx-core/src/utils/gguf.rs
  • crates/mlx-core/src/utils/imatrix.rs
  • crates/mlx-core/src/utils/mod.rs
  • crates/mlx-core/src/utils/safetensors.rs
  • crates/mlx-sys/mlx
  • crates/mlx-sys/src/lib.rs
  • crates/mlx-sys/src/metal/gated_delta_chunked.metal.inc
  • crates/mlx-sys/src/metal/gated_delta_fused_gating.metal.inc
  • crates/mlx-sys/src/mlx_gated_delta.cpp
  • crates/mlx-sys/src/mlx_nn_ops.cpp
  • crates/mlx-sys/src/mlx_qwen35.cpp
  • crates/mlx-sys/src/mlx_qwen35_common.h
  • crates/mlx-sys/src/mlx_qwen35_vlm.cpp
  • examples/test-converted-model.ts
  • package.json
  • packages/cli/src/commands/convert.ts
  • packages/cli/src/commands/download-model.ts
  • packages/core/index.cjs
  • packages/core/index.d.cts
  • packages/core/package.json
  • packages/lm/src/models/model-loader.ts
  • packages/lm/src/stream.ts
  • vite.config.ts

@Brooooooklyn
Brooooooklyn force-pushed the feat/perf-profiler-convert-fixes branch from beae500 to 7f138dc Compare March 16, 2026 07:05

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

🟠 Major comments (20)
examples/test-converted-model.ts-8-9 (1)

8-9: ⚠️ Potential issue | 🟠 Major

--image is documented but not actually parsed.

Line 9 documents --image, but Lines 18-23/27 only parse ocr. This makes the documented command fail for users.

Suggested fix
- *   oxnode examples/test-converted-model.ts <model-name> [--image <path>]
+ *   oxnode examples/test-converted-model.ts <model-name> [--image <path>]
...
 const { values, positionals } = parseArgs({
   args: process.argv.slice(2),
   options: {
-    ocr: { type: 'string' },
+    image: { type: 'string' },
+    ocr: { type: 'string' }, // optional backward-compat alias
   },
   allowPositionals: true,
 });
 
 const modelName = positionals[0] || 'qwen3.5-9b-mlx';
-const imagePath = values.ocr;
+const imagePath = values.image ?? values.ocr;

Also applies to: 18-23, 27-27

🤖 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 8 - 9, The usage documents a
--image flag but the script only parses the ocr argument; update the argument
parsing in the top-level script (where argv/args are processed around the ocr
parsing) to also recognize and extract --image (e.g., imagePath or imageArg) and
wire that variable into the downstream logic that currently uses only the ocr
value (same scope/functions where ocr is referenced); ensure the usage string
and any help output remain consistent with the new --image variable name so
running "oxnode examples/test-converted-model.ts <model-name> --image <path>"
actually supplies the image path to the code.
crates/mlx-core/src/decode_profiler.rs-344-349 (1)

344-349: ⚠️ Potential issue | 🟠 Major

Serialize test access to global profiling state

with_profiling mutates PROFILING_ENABLED and PROFILING_STORE globals. In parallel test execution this can race with other tests and cause flakes.

Suggested fix
 fn with_profiling<F: FnOnce()>(f: F) {
+    static TEST_PROFILING_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
+    let _guard = TEST_PROFILING_GUARD.lock().unwrap();
     profiling::PROFILING_ENABLED.store(true, Ordering::Relaxed);
     profiling::PROFILING_STORE.lock().unwrap().clear();
     f();
     profiling::PROFILING_ENABLED.store(false, Ordering::Relaxed);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/decode_profiler.rs` around lines 344 - 349,
with_profiling mutates the global PROFILING_ENABLED and PROFILING_STORE and can
race in parallel tests; serialize access by acquiring a dedicated global mutex
for test profiling before changing the globals and holding it for the duration
of f() so no other test can mutate/read them concurrently. Add a static
TEST_PROFILING_MUTEX (or use an existing crate mutex) and lock it at the start
of with_profiling, then perform PROFILING_ENABLED.store(...), clear
PROFILING_STORE, call f(), and finally restore PROFILING_ENABLED while the lock
is held so the entire sequence is atomic relative to other tests that also use
with_profiling.
crates/mlx-sys/src/mlx_qwen35.cpp-273-276 (1)

273-276: ⚠️ Potential issue | 🟠 Major

Wrap the new extern entrypoint in try/catch

mlx_qwen35_compiled_adjust_offset is a new FFI boundary function that currently lacks exception handling. The array() constructor and global state mutations can throw C++ exceptions, which would cross into Rust and cause undefined behavior. Follow the established pattern used by other FFI functions in this file.

Suggested fix
 void mlx_qwen35_compiled_adjust_offset(int delta) {
-  g_offset_int += delta;
-  g_compiled_offset = array(g_offset_int, mlx::core::int32);
+  try {
+    g_offset_int += delta;
+    g_compiled_offset = array(g_offset_int, mlx::core::int32);
+  } catch (const std::exception& e) {
+    fprintf(stderr, "[MLX] Exception in mlx_qwen35_compiled_adjust_offset: %s\n", e.what());
+    fflush(stderr);
+  } catch (...) {
+    fprintf(stderr, "[MLX] Unknown exception in mlx_qwen35_compiled_adjust_offset\n");
+    fflush(stderr);
+  }
 }
🤖 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 273 - 276,
mlx_qwen35_compiled_adjust_offset currently performs g_offset_int mutation and
constructs array(...) without exception handling; wrap the function body in the
same try/catch pattern used by other FFI entrypoints in this file so C++
exceptions do not cross into Rust: enclose the existing statements (g_offset_int
+= delta; g_compiled_offset = array(g_offset_int, mlx::core::int32);) in a try
block and in the catch blocks call the module's FFI error handler (e.g., the
existing mlx::ffi error-reporting helper such as set_last_error / equivalent
used elsewhere) for std::exception and a catch(...) to report unknown errors,
ensuring no exceptions escape the function.
crates/mlx-sys/src/mlx_nn_ops.cpp-855-873 (1)

855-873: ⚠️ Potential issue | 🟠 Major

Fix error logging prefix and add catch for unknown exceptions in mlx_load_safetensors

Line 870 is missing the [MLX] prefix used throughout the file's error messages. Additionally, the function should catch unknown exceptions (catch (...)) to prevent unhandled exceptions from crossing the FFI boundary, consistent with other FFI entry points like array_eval and async_eval in this file.

Suggested fix
     } catch (const std::exception& e) {
-        std::cerr << "mlx_load_safetensors error: " << e.what() << std::endl;
+        std::cerr << "[MLX] mlx_load_safetensors error: " << e.what() << std::endl;
+        return -1;
+    } catch (...) {
+        std::cerr << "[MLX] Unknown exception in mlx_load_safetensors" << std::endl;
         return -1;
     }
🤖 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 855 - 873, The error handling
in mlx_load_safetensors is missing the standard "[MLX]" log prefix and lacks a
catch-all to prevent exceptions crossing the FFI boundary; update the existing
catch(const std::exception& e) to log with "[MLX] mlx_load_safetensors error: "
+ e.what(), and add a catch(...) after it that logs "[MLX] mlx_load_safetensors
unknown error" (to stderr) and returns -1, leaving the tensor loop and callback
(name.c_str(), name.size(), handle, ctx) logic unchanged; use the function
symbol mlx_load_safetensors to locate the code and ensure new handlers return
the same -1 error sentinel as other FFI entry points.
crates/mlx-core/src/models/qwen3_5_moe/persistence.rs-916-951 (1)

916-951: ⚠️ Potential issue | 🟠 Major

This VL path still misses common vision-weight layouts.

load_all_safetensors() only brings in weights.safetensors, model.safetensors, or model-*-of-* shards, so a standalone vision.safetensors never reaches this split. On top of that, the new prefix check only recognizes vision_tower. / visual., while sanitize_weights() still drops model.visual* and visual_encoder*. Those checkpoints will silently load as text-only.

🩹 Suggested fix
-        let raw_params = load_all_safetensors(path)?;
+        let mut raw_params = load_all_safetensors(path)?;
+        let vision_path = path.join("vision.safetensors");
+        if vision_path.exists() {
+            let st_file = SafeTensorsFile::load(&vision_path)?;
+            raw_params.extend(st_file.load_tensors(&vision_path)?);
+        }
         info!("Loaded {} raw tensors", raw_params.len());

-        let has_vision = raw_params
-            .keys()
-            .any(|k| k.starts_with("vision_tower.") || k.starts_with("visual."));
+        let is_vision_key = |name: &str| {
+            name.starts_with("vision_tower.")
+                || name.starts_with("visual.")
+                || name.starts_with("model.visual.")
+                || name.starts_with("visual_encoder.")
+        };
+        let has_vision = raw_params.keys().any(|k| is_vision_key(k));
@@
-                if name.starts_with("vision_tower.") || name.starts_with("visual.") {
+                if is_vision_key(&name) {
                     let vkey = name
                         .strip_prefix("vision_tower.")
                         .or_else(|| name.strip_prefix("visual."))
+                        .or_else(|| name.strip_prefix("model.visual."))
+                        .or_else(|| name.strip_prefix("visual_encoder."))
                         .unwrap_or(&name)
                         .to_string();
                     vision_params.insert(vkey, array);
🤖 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 916 -
951, The split logic currently misses standalone vision shards and additional
vision key prefixes; update the loader/split to include files like
"vision.safetensors" and any "model.visual*" or "visual_encoder*" shards
returned by load_all_safetensors, and expand the prefix checks used when
partitioning raw_params to also detect keys starting with "model.visual",
"visual_encoder", and any other vision-related prefixes produced by
sanitize_weights(); specifically modify the code paths around
load_all_safetensors and the has_vision/name.starts_with checks in the block
that builds vision_params/text_params (and ensure sanitize_weights and the
loader produce consistent key prefixes) so vision tensors are recognized and
moved into vision_params instead of silently remaining as text tensors.
crates/mlx-core/src/utils/safetensors.rs-508-543 (1)

508-543: ⚠️ Potential issue | 🟠 Major

Don't return success after a failed lazy tensor callback.

on_tensor() ignores MxArray::from_handle() failures, and the outer function only checks count < 0. If one callback fails, this still returns Ok(...) with a partial tensor map, so the real error is deferred into much harder-to-diagnose missing-weight failures later.

🩹 Suggested fix
     struct LoadCtx {
         tensors: HashMap<String, crate::array::MxArray>,
+        error: Option<Error>,
     }

     unsafe extern "C" fn on_tensor(
         name: *const std::os::raw::c_char,
         name_len: usize,
@@
         unsafe {
             let ctx = &mut *(ctx as *mut LoadCtx);
             let name_bytes = std::slice::from_raw_parts(name as *const u8, name_len);
             let name = String::from_utf8_lossy(name_bytes).to_string();
-            if let Ok(arr) = crate::array::MxArray::from_handle(handle, "lazy_load") {
-                ctx.tensors.insert(name, arr);
+            match crate::array::MxArray::from_handle(handle, "lazy_load") {
+                Ok(arr) => {
+                    ctx.tensors.insert(name, arr);
+                }
+                Err(err) => {
+                    if ctx.error.is_none() {
+                        ctx.error = Some(err);
+                    }
+                }
             }
         }
     }

     let mut ctx = LoadCtx {
         tensors: HashMap::new(),
+        error: None,
     };
@@
     if count < 0 {
         return Err(Error::from_reason(format!(
             "Failed to load safetensors: {}",
             path_str
         )));
     }
+
+    if let Some(err) = ctx.error {
+        return Err(err);
+    }
+
+    if ctx.tensors.len() != count as usize {
+        return Err(Error::from_reason(format!(
+            "Expected {} tensors from lazy loader, collected {}",
+            count,
+            ctx.tensors.len()
+        )));
+    }

     Ok(ctx.tensors)
 }
🤖 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 508 - 543, The
on_tensor callback currently ignores failures from MxArray::from_handle and the
outer code only checks sys::mlx_load_safetensors' return value, so a single
callback error yields an Ok with partial ctx.tensors; fix by adding an error
field to LoadCtx (e.g., Option<anyhow::Error> or Option<Error>), set that field
when MxArray::from_handle(...) returns Err inside on_tensor (do not insert into
ctx.tensors), and after sys::mlx_load_safetensors completes check ctx.error and
return Err(ctx.error.unwrap()) if present (in addition to the existing count < 0
check); reference on_tensor, LoadCtx, MxArray::from_handle,
sys::mlx_load_safetensors, and ctx.tensors when making the change.
packages/lm/src/profiling.ts-59-67 (1)

59-67: ⚠️ Potential issue | 🟠 Major

The shutdown write path is fragile with beforeExit + async.

Node.js does not await promises returned by EventEmitter listeners—they are ignored/discarded. Additionally, beforeExit is not emitted after process.exit() or uncaught exceptions, meaning the profiling report write can be lost entirely on explicit termination. The current handler silently discards the promise from writeProfilingReport() without capturing write failures.

🩹 Suggested fix
 function registerExitHandler(): void {
   if (exitHandlerRegistered) return;
   exitHandlerRegistered = true;
-  process.on('beforeExit', async () => {
+  process.on('beforeExit', () => {
     if (isProfilingEnabled()) {
       setProfilingEnabled(false);
-      await writeProfilingReport();
+      void writeProfilingReport().catch((error) => {
+        console.warn(`Failed to write profiling report: ${String(error)}`);
+      });
     }
   });
 }

If the env-var flow needs to survive process.exit() or signal termination, add a synchronous fallback on exit/SIGINT/SIGTERM.

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

In `@packages/lm/src/profiling.ts` around lines 59 - 67, The current
registerExitHandler installs an async 'beforeExit' listener which discards the
promise and misses process.exit()/uncaught exceptions; update
registerExitHandler to also register synchronous handlers for 'exit' and
termination signals (SIGINT, SIGTERM) and ensure a sync fallback path that calls
a synchronous writer or flush (create or use a blocking variant of
writeProfilingReport, e.g., writeProfilingReportSync) so the profiling data is
persisted on hard exits; keep the existing beforeExit async logic for graceful
shutdowns but guard with exitHandlerRegistered/isProfilingEnabled and ensure
errors from both async and sync paths are caught/logged via processLogger or
similar.
crates/mlx-core/src/convert.rs-1326-1355 (1)

1326-1355: ⚠️ Potential issue | 🟠 Major

Restore *.biases on every vision-dequant fallback path.

This block removes weight, scales, and biases, but if dequantization cannot proceed you only put back the weight and scales. For affine-quantized vision tensors that leaves the checkpoint incomplete.

🤖 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 1326 - 1355, The code removes
weight, scales and biases (via new_weights.remove for weight_key, scale_key and
biases_key) but on dequantization failure you only reinsert weight and scales,
leaving biases missing; update the failure/fallback paths around the
mlx_sys::mlx_dequantize call (the block where handle.is_null() is checked and
any other early-return/failure branches handling dequantization of
vision_scale_keys) to also reinsert the original biases (use the biases variable
tied to biases_key) into new_weights; ensure you reference biases_key and biases
when restoring so affine-quantized vision tensors are fully restored.
crates/mlx-core/src/convert.rs-1655-1658 (1)

1655-1658: ⚠️ Potential issue | 🟠 Major

Only materialize the tensors AWQ actually changed.

The comment says “modified weights”, but this loop calls eval() on every tensor in weights. With load_safetensors_lazy() that defeats the lazy-loading memory win and can reintroduce OOMs on large checkpoints.

🤖 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 1655 - 1658, The current loop
calls w.eval() on every tensor in the weights map, defeating lazy loading;
change it to only eval() tensors actually modified by AWQ by tracking which
entries were changed during conversion and iterating over that set instead of
weights.values(). Locate the conversion logic that mutates tensors (e.g.,
functions that perform AWQ transformations) and add/maintain a modified_weights
collection (or mark a flag on entries) and replace the for w in weights.values()
{ w.eval(); } loop with iteration over modified_weights calling eval() only for
those tensors that were altered; ensure this interacts correctly with
load_safetensors_lazy() so untouched tensors remain lazy.
crates/mlx-core/src/models/qwen3/model.rs-5181-5187 (1)

5181-5187: ⚠️ Potential issue | 🟠 Major

Don’t return synthetic phase metrics as PerformanceMetrics.

ttft_ms is derived from total_ms / gen_toks, while total_ms also includes templating and tokenization. That makes ttft_ms, prefill_tokens_per_second, and decode_tokens_per_second guesses rather than actual model timings, which is misleading for callers consuming this API. Please plumb the decode-profiler data out of generation or leave performance unset on this path.

Also applies to: 5212-5279

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

In `@crates/mlx-core/src/models/qwen3/model.rs` around lines 5181 - 5187, The code
currently constructs synthetic phase metrics (ttft_ms,
prefill_tokens_per_second, decode_tokens_per_second) in PerformanceMetrics using
gen_start and total_ms which include templating/tokenization, producing
misleading timings; instead either propagate the actual decode-profiler results
from the generation path into the PerformanceMetrics or omit/leave the
performance field None when real decode timings aren’t available. Update the
generation code paths around gen_start/PerformanceMetrics creation (including
the related blocks at the 5212-5279 region) to: (1) accept and use the real
decode-profiler output from the decoder/generation routine when present to
populate ttft_ms and token/s throughput, or (2) if decode-profiler data is not
available, do not fabricate
ttft_ms/prefill_tokens_per_second/decode_tokens_per_second and set performance
to None. Ensure the unique symbols PerformanceMetrics, ttft_ms,
prefill_tokens_per_second, decode_tokens_per_second, gen_start, and the
decode-profiler/generation return value are used to locate and fix the code.
crates/mlx-core/src/convert.rs-687-709 (1)

687-709: ⚠️ Potential issue | 🟠 Major

lm_head never reaches the mixed-bit override here.

The closure returns Skip on !should_quantize(key) before the lm_head branch runs, and should_quantize() already excludes lm_head. The mixed recipes therefore silently omit one of the tensors the comment says should get high_bits.

🤖 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 687 - 709, The lm_head branch
never executes because the closure returns early on !should_quantize(key) and
should_quantize already excludes lm_head; move the lm_head check ahead of the
should_quantize guard (i.e., check if key.contains("lm_head") before calling
should_quantize) so lm_head tensors always return QuantDecision::Custom with
bits = high_bits, group_size = gs, mode = "affine"; ensure this change keeps the
existing is_router_gate handling and other branches intact.
crates/mlx-core/src/models/qwen3/model.rs-1352-1373 (1)

1352-1373: ⚠️ Potential issue | 🟠 Major

Keep the async path on the tokenizer’s chat-template implementation.

This now diverges from apply_chat_template_sync() and hardcodes plain ChatML, so any tokenizer-defined Jinja template, tool rendering, or future ChatMessage fields handled by the tokenizer will be ignored in async/training flows.

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

In `@crates/mlx-core/src/models/qwen3/model.rs` around lines 1352 - 1373, The
async path currently hardcodes ChatML and calls tokenizer.encode_sync, which
bypasses the tokenizer's chat-template logic (used by
apply_chat_template_sync()); change the async flow to use the tokenizer's
template APIs instead of manual formatting: call the tokenizer's async template
method (e.g., apply_chat_template_async or an equivalent async helper) with the
original messages and add_prompt to produce the formatted text, then pass that
output into the tokenizer's async encode method (e.g., encode_async) rather than
using spawn_blocking + encode_sync; preserve any existing flags (like the
Some(false)) when calling the async encoder so the async/training flows honor
tokenizer-defined Jinja templates, tool rendering, and extra ChatMessage fields.
crates/mlx-core/src/utils/gguf.rs-211-216 (1)

211-216: ⚠️ Potential issue | 🟠 Major

Reject non-block-aligned quantized tensors instead of truncating.

Both data_size() and loader logic derive block counts via floor division. If element count is not block-aligned, remainder gets silently dropped, causing corrupted loads.

Suggested fix
 let num_elements = tensor.num_elements() as usize;
 let block_size: usize = 32;
+if num_elements % block_size != 0 {
+    return Err(Error::from_reason(format!(
+        "Quantized tensor '{}' has {} elements, not divisible by block size {}",
+        tensor.name, num_elements, block_size
+    )));
+}
 let n_blocks = num_elements / block_size;

Also applies to: 559-562

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

In `@crates/mlx-core/src/utils/gguf.rs` around lines 211 - 216, The data_size()
computation currently truncates quantized tensors by using floor division on n /
block_size; instead, detect non-block-aligned input and fail fast: in
data_size() (referencing methods num_elements(), tensor_type.is_quantized(),
tensor_type.block_size(), tensor_type.type_size()) check if self.num_elements()
% block_size != 0 and return an explicit error (or Result::Err) indicating
"tensor not block-aligned" rather than silently computing a smaller size; make
the equivalent check in the loader path that derives block counts (the same
logic around n / block_size) so loading rejects non-aligned tensors instead of
dropping the remainder.
crates/mlx-core/src/models/qwen3_5/model.rs-824-828 (1)

824-828: ⚠️ Potential issue | 🟠 Major

Use placeholder-injected tokens as repetition history in VLM mode.

In VLM branches, prefill runs on final_tokens, but Line 888 / Line 1441 initialize token_history from original tokens. Repetition penalty then uses a different context than the actual prefill input.

Suggested fix
 // VLM branch
 let final_tokens = inject_image_placeholders(&tokens, num_image_tokens);
+let mut token_history: Vec<u32> = final_tokens.clone();

 // text branch
-let mut token_history: Vec<u32> = tokens.clone();
+let mut token_history: Vec<u32> = tokens.clone();

Also applies to: 887-889, 1375-1380, 1440-1441

🤖 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 824 - 828, The
repetition-penalty history is being initialized from the original tokens instead
of the placeholder-injected sequence used for prefill; update all VLM branches
to build token_history from final_tokens (the result of
inject_image_placeholders) rather than tokens so the repetition penalty uses the
same context as the prefill input—locate uses of token_history initialization
near where final_tokens is created and replace the source to final_tokens for
the VLM code paths in the functions/blocks referencing
inject_image_placeholders, final_tokens, tokens, and token_history (also fix the
other occurrences noted around the repeated regions).
crates/mlx-core/src/models/qwen3_5/model.rs-2451-2454 (1)

2451-2454: ⚠️ Potential issue | 🟠 Major

The cache “LRU” counter does not advance after warm-up.

Using cache.len() as u64 for Line 2451/2486 means the generation value stabilizes at capacity, so eviction is no longer true LRU.

Suggested fix
+use std::sync::atomic::{AtomicU64, Ordering};
+static VISION_CACHE_TICK: AtomicU64 = AtomicU64::new(1);

 // on hit / insert
-let next_lru = cache.len() as u64;
+let next_lru = VISION_CACHE_TICK.fetch_add(1, Ordering::Relaxed);

Also applies to: 2486-2488

🤖 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 2451 - 2454, The
LRU timestamp should be a monotonically-increasing counter, not cache.len(), so
replace the local next_lru = cache.len() as u64 usage with an incrementing field
on the model (e.g., self.next_lru or lru_counter) and use that value when
bumping *lru; update both places where next_lru is computed (the
cache.get_mut(&combined_hash) block and the other occurrence around lines
2486-2488) to increment the counter (wrapping_add(1) or similar) and assign the
incremented value to *lru so eviction reflects true recency rather than
capacity.
crates/mlx-core/src/models/qwen3_5_moe/model.rs-755-759 (1)

755-759: ⚠️ Potential issue | 🟠 Major

Do not silently drop images when VLM components are missing.

When has_images is true but either vision_encoder or image_processor is None, the code silently falls back to text-only prefill. That hides a configuration error and produces incorrect multimodal behavior.

Suggested fix
+if has_images && (vision_encoder_arc.is_none() || image_processor_arc.is_none()) {
+    return Err(Error::from_reason(
+        "Images were provided, but VLM components are not initialized (vision_encoder/image_processor)",
+    ));
+}

Also applies to: 1302-1306

🤖 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 755 - 759, The
code currently treats has_images == true with missing VLM pieces
(vision_encoder_arc or image_processor_arc == None) as a text-only prefill,
silently dropping images; update the logic in the block using has_images,
vision_encoder_arc, and image_processor_arc (the branch producing last_logits
and seq_len) to explicitly error out or return a Result::Err (or propagate a
clear panic/log and error) when has_images is true but either vision_encoder_arc
or image_processor_arc is None, instead of falling back to text-only; apply the
same change to the analogous branch around the code at lines ~1302-1306 so that
missing VLM components produce an explicit failure with a clear message naming
vision_encoder_arc/image_processor_arc.
crates/mlx-core/src/models/qwen3_5/model.rs-811-815 (1)

811-815: ⚠️ Potential issue | 🟠 Major

Fail fast when images are provided but VLM is not initialized.

Current branching quietly takes the text-only path if image messages exist but vision_encoder/image_processor is missing. This should be an explicit error.

Suggested fix
+if has_images && (vision_encoder_arc.is_none() || image_processor_arc.is_none()) {
+    return Err(Error::from_reason(
+        "Images were provided, but VLM components are not initialized (vision_encoder/image_processor)",
+    ));
+}

Also applies to: 1360-1364

🤖 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 811 - 815, The code
silently falls back to the text-only branch when has_images is true but
vision_encoder_arc or image_processor_arc is None; change this to fail fast by
checking if has_images && (vision_encoder_arc.is_none() ||
image_processor_arc.is_none()) and returning an explicit error (e.g.,
Err(anyhow!("Images provided but VLM (vision_encoder/image_processor) is not
initialized"))) instead of continuing; apply the same check and error path at
both locations where the tuple match currently occurs (the block that uses
has_images, vision_encoder_arc, image_processor_arc around the current if-let
and the similar block at lines ~1360-1364), and use the local symbols
vision_enc/img_proc only after confirming they are Some.
crates/mlx-core/src/utils/gguf.rs-296-299 (1)

296-299: ⚠️ Potential issue | 🟠 Major

Bound GGUF string lengths before allocation.

Line 297 allocates Vec directly from file-provided length. A malformed GGUF can force huge allocations and OOM.

Suggested fix
 fn read_string(r: &mut impl Read) -> std::io::Result<String> {
     let len = read_u64(r)? as usize;
+    const MAX_GGUF_STRING_LEN: usize = 16 * 1024 * 1024; // 16 MiB safety cap
+    if len > MAX_GGUF_STRING_LEN {
+        return Err(std::io::Error::new(
+            std::io::ErrorKind::InvalidData,
+            format!("GGUF string too large: {len} bytes"),
+        ));
+    }
     let mut buf = vec![0u8; len];
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/gguf.rs` around lines 296 - 299, The code reads a
length with read_u64 then allocates a Vec of that size (lines using read_u64,
r.read_exact, and String::from_utf8) allowing an attacker-supplied huge length
to OOM; fix by validating/bounding the length before allocation (e.g., define a
sensible MAX_GGUF_STRING_LEN constant) and return an error if len is greater
than the bound or otherwise invalid, only then allocate the Vec and read_exact,
preserving the existing String::from_utf8 error mapping.
crates/mlx-core/src/models/qwen3_5/vision.rs-112-123 (1)

112-123: ⚠️ Potential issue | 🟠 Major

Add explicit grid_thw shape validation before flat indexing.

Line 120/121/122 assumes a [num_images, 3] layout but the code never verifies it. Malformed input can trigger out-of-bounds indexing/panic.

Suggested fix
 fn compute_rot_pos_emb(&self, grid_thw: &MxArray) -> Result<MxArray> {
+    let grid_shape = grid_thw.shape()?;
+    if grid_shape.len() != 2 || grid_shape[1] != 3 {
+        return Err(Error::from_reason(format!(
+            "grid_thw must have shape [num_images, 3], got {:?}",
+            grid_shape
+        )));
+    }
     let grid_data = grid_thw.to_int32()?;
-    let num_images = grid_thw.shape()?[0] as usize;
+    let num_images = grid_shape[0] as usize;

Also applies to: 192-194

🤖 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/vision.rs` around lines 112 - 123, The
code in compute_rot_pos_emb uses flat indexing into grid_thw assuming a
[num_images, 3] shape but never validates it; add explicit validation before
indexing: call grid_thw.shape()? and verify it has exactly 2 dimensions and
shape()[1] == 3 and that grid_data.len() >= num_images * 3, returning an Err
with a clear message if the checks fail; apply the same validation pattern to
the other location in this file where grid_thw is flat-indexed (the occurrences
around lines 192-194) so all uses enforce the [N,3] layout before accessing
grid_data by img_idx*3 offsets.
crates/mlx-core/src/models/qwen3_5/vision.rs-63-66 (1)

63-66: ⚠️ Potential issue | 🟠 Major

Validate vision head geometry before RoPE setup.

Line 64 divides by num_heads with no guard, and Line 65 assumes an even head dimension. Invalid configs can panic or produce invalid rotary dims.

Suggested fix
 pub fn new(config: Qwen3_5VisionConfig) -> Result<Self> {
+    if config.num_heads <= 0 || config.hidden_size % config.num_heads != 0 {
+        return Err(Error::from_reason(format!(
+            "Invalid vision config: hidden_size={} must be divisible by num_heads={}",
+            config.hidden_size, config.num_heads
+        )));
+    }
     let head_dim = config.hidden_size / config.num_heads;
+    if head_dim % 2 != 0 {
+        return Err(Error::from_reason(format!(
+            "Invalid vision config: head_dim={} must be even for 2D RoPE",
+            head_dim
+        )));
+    }
     let rotary_pos_emb = VisionRotaryEmbedding::new((head_dim / 2) as u32, None);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5/vision.rs` around lines 63 - 66, The
constructor Qwen3_5Vision::new currently divides config.hidden_size by
config.num_heads and assumes head_dim is even before constructing
VisionRotaryEmbedding; add validation at the start of Qwen3_5Vision::new to
ensure config.num_heads > 0, config.hidden_size % config.num_heads == 0, and
(config.hidden_size / config.num_heads) % 2 == 0 (so head_dim is even and
head_dim/2 is an integer > 0); if any check fails return an Err with a clear
message referencing the failing condition so callers know the bad config instead
of panicking when creating VisionRotaryEmbedding.
🟡 Minor comments (5)
examples/test-converted-model.ts-65-67 (1)

65-67: ⚠️ Potential issue | 🟡 Minor

Guard tokens/sec against zero-duration runs.

If duration is 0, Lines 66/95 produce Infinity/NaN. Clamp denominator to at least 1ms.

Suggested fix
-  const duration = Date.now() - startTime;
-  const tokensPerSecond = (result.numTokens / duration) * 1000;
+  const duration = Date.now() - startTime;
+  const safeDurationMs = Math.max(duration, 1);
+  const tokensPerSecond = (result.numTokens / safeDurationMs) * 1000;
...
-    const duration = Date.now() - startTime;
-    const tokensPerSecond = (result.numTokens / duration) * 1000;
+    const duration = Date.now() - startTime;
+    const safeDurationMs = Math.max(duration, 1);
+    const tokensPerSecond = (result.numTokens / safeDurationMs) * 1000;

Also applies to: 94-97

🤖 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 65 - 67, Guard the tokens/sec
computation against a zero-duration by clamping the measured duration to at
least 1ms before dividing; replace the raw duration calculation (where startTime
is used to compute duration and tokensPerSecond is computed from
result.numTokens) with a clamped value (e.g., use Math.max(1, Date.now() -
startTime)) and use that clamped duration for both the first tokensPerSecond
calculation and the later one around lines 94-97 so you never divide by 0.
crates/mlx-core/src/decode_profiler.rs-220-224 (1)

220-224: ⚠️ Potential issue | 🟡 Minor

Make step() a true no-op when disabled

Line 223 increments num_tokens even when profiling is disabled. That conflicts with the “all methods are no-ops when disabled” contract in this file.

Suggested fix
 pub fn step(&mut self) {
+    if !self.enabled {
+        return;
+    }
     self.num_tokens += 1;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/decode_profiler.rs` around lines 220 - 224, The step()
method currently increments num_tokens unconditionally; change it to only
increment when profiling is enabled so it becomes a true no-op when disabled —
i.e., inside pub fn step(&mut self) check the profiler-enabled flag (e.g.,
self.enabled or the struct's enable/is_enabled field/method used elsewhere in
this file) and only do self.num_tokens += 1 when that flag is true, leaving the
method as an immediate return when disabled; keep the #[inline] attribute and
method signature intact to preserve performance hints.
crates/mlx-core/src/decode_profiler.rs-57-61 (1)

57-61: ⚠️ Potential issue | 🟡 Minor

Honor MLX_PROFILE_DECODE value semantics (=1)

Line 60 currently enables profiling if the env var merely exists, so MLX_PROFILE_DECODE=0 still turns profiling on. That contradicts the documented =1 behavior.

Suggested fix
 fn is_env_enabled() -> bool {
     use std::sync::OnceLock;
     static ENABLED: OnceLock<bool> = OnceLock::new();
-    *ENABLED.get_or_init(|| std::env::var("MLX_PROFILE_DECODE").is_ok())
+    *ENABLED.get_or_init(|| {
+        matches!(
+            std::env::var("MLX_PROFILE_DECODE").ok().as_deref(),
+            Some("1") | Some("true") | Some("TRUE")
+        )
+    })
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/decode_profiler.rs` around lines 57 - 61, The
is_env_enabled function currently treats any presence of MLX_PROFILE_DECODE as
enabled; change it to read the env var value and only return true when it equals
"1" (i.e., std::env::var("MLX_PROFILE_DECODE").map(|v| v ==
"1").unwrap_or(false)). Update the static OnceLock<bool> initialization in
is_env_enabled so ENABLED.get_or_init uses that value check (refer to function
is_env_enabled and the MLX_PROFILE_DECODE env var) to match the documented "=1"
semantics.
crates/mlx-sys/src/mlx_qwen35_vlm.cpp-184-186 (1)

184-186: ⚠️ Potential issue | 🟡 Minor

mlx_qwen35_vlm_get_cache returns pointer to internal array - caller must not delete.

The function returns a pointer to an element in g_vlm_caches vector. If the caller incorrectly deletes this pointer or if the vector is modified (e.g., via reset), this could cause use-after-free. Consider documenting this contract or returning a copy.

📝 Document the ownership contract

Add a comment above the function:

// Returns a borrowed pointer to an internal cache array.
// Caller must NOT delete the returned pointer.
// Pointer is invalidated by mlx_qwen35_vlm_reset().
mlx_array* mlx_qwen35_vlm_get_cache(int index) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-sys/src/mlx_qwen35_vlm.cpp` around lines 184 - 186, The function
mlx_qwen35_vlm_get_cache returns a borrowed pointer into the internal vector
g_vlm_caches, so add a brief ownership comment above mlx_qwen35_vlm_get_cache
stating that the returned mlx_array* is borrowed (caller must NOT delete it) and
that the pointer is invalidated by any modification/resizing of g_vlm_caches or
by calling mlx_qwen35_vlm_reset(); alternatively consider changing the API to
return a copy/owned object if callers need independent lifetime.
crates/mlx-core/src/models/qwen3_5/processing.rs-131-136 (1)

131-136: ⚠️ Potential issue | 🟡 Minor

Remove or correct the misleading comment about frame duplication.

The comment at line 131 claims "temporal_patch_size=2 means we duplicate the frame," but the implementation sets grid_t = 1 with no duplication logic, and temporal_patch_size is never referenced in the processing code. Either update the comment to accurately reflect that grid_t=1 for images (no temporal dimension), or implement the frame duplication using the configured temporal_patch_size value.

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

In `@crates/mlx-core/src/models/qwen3_5/processing.rs` around lines 131 - 136, The
comment claiming "temporal_patch_size=2 means we duplicate the frame" is
misleading because grid_t is set to 1 and temporal_patch_size is not used;
update the comment above the patch calculation (referencing patch_size, grid_h,
grid_w, grid_t, and num_patches) to state that for images the temporal dimension
is 1 (no temporal duplication) and that temporal_patch_size is not applied in
this code path, or alternatively implement duplication by using
self.config.temporal_patch_size to set grid_t and replicate frames
accordingly—choose one approach and make the code and comment consistent.
🧹 Nitpick comments (12)
crates/mlx-core/src/utils/imatrix.rs (1)

176-186: Silent error handling may mask file corruption.

Using unwrap_or(0) for metadata reads (e.g., read_u32_le(&mut reader).unwrap_or(0)) silently substitutes zero on I/O errors instead of propagating them. This could mask truncated or corrupted files.

Consider propagating errors with ? and handling missing optional metadata separately:

♻️ Example for chunk_count parsing
             "imatrix.chunk_count" => {
                 chunk_count = match vtype {
-                    GGUF_TYPE_UINT32 => read_u32_le(&mut reader).unwrap_or(0),
-                    GGUF_TYPE_INT32 => read_u32_le(&mut reader).unwrap_or(0),
+                    GGUF_TYPE_UINT32 => read_u32_le(&mut reader)
+                        .map_err(|e| Error::from_reason(format!("Failed to read chunk_count: {e}")))?,
+                    GGUF_TYPE_INT32 => read_u32_le(&mut reader)
+                        .map_err(|e| Error::from_reason(format!("Failed to read chunk_count: {e}")))? as u32,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/imatrix.rs` around lines 176 - 186, The match arm
setting chunk_count currently swallows I/O errors by using unwrap_or(0); instead
propagate read errors instead of defaulting to zero: replace uses of
read_u32_le(&mut reader).unwrap_or(0) and read_u64_le(&mut reader).unwrap_or(0)
as u32 with the fallible reads using the ? operator (or map_err to convert to
Error) so read failures bubble up from the chunk_count assignment in the match
on vtype; keep the skip_meta_value branch and its Error::from_reason handling
unchanged (refer to chunk_count, vtype, read_u32_le, read_u64_le, and
skip_meta_value to locate the code).
crates/mlx-core/src/models/qwen3_5/gated_delta.rs (2)

410-419: Minor: redundant exp() in double-fallback path.

If the per-step kernel at line 412 fails, g_log.exp() is computed again at line 418. Since this is already the fallback-of-fallback scenario (both chunked and per-step Metal kernels failed), the overhead is negligible.

♻️ Optional fix to avoid redundant exp()
     // Per-step kernel needs exponentiated decay factor
     let g = g_log.exp()?;
     if let Ok(result) = gated_delta_kernel(&q, &k, v, &g, &beta, &initial_state, mask) {
         return Ok(result);
     }
+
+    // Ops-based sequential loop fallback (reuse already-exponentiated g)
+    gated_delta_ops(&q, &k, v, &g, &beta, &initial_state, mask)
-
-    // Ops-based sequential loop fallback (also needs exp(g_log))
-    let g = g_log.exp()?;
-    gated_delta_ops(&q, &k, v, &g, &beta, &initial_state, mask)
🤖 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 410 - 419,
Compute g once and reuse it instead of calling g_log.exp() twice: evaluate let g
= g_log.exp()? before attempting the chunked/per-step kernels and then pass that
same g into gated_delta_kernel and gated_delta_ops; update the code paths around
gated_delta_kernel and gated_delta_ops so they both use the precomputed g
(remove the second g_log.exp() call) to avoid the redundant exponentiation.

354-361: Consider avoiding the exp/log roundtrip in the fallback path.

When fused_gdn_gating fails, the fallback computes g = compute_g(...) which returns exp(g_log), then immediately calls g.log() to recover g_log. This exp→log roundtrip introduces unnecessary computation and potential precision loss.

If compute_g could optionally return the log-space value directly, or if a separate compute_g_log variant existed, this path would be more efficient. However, since this is the fallback path (only triggered when the fused kernel fails), the impact is likely minimal.

🤖 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 354 - 361,
The fallback path in the fused_gdn_gating failure branch currently calls
compute_g(a_log, a, dt_bias) which returns exp(g_log) and then immediately calls
.log() causing an unnecessary exp→log roundtrip; change the implementation so
the fallback uses a log-returning variant (e.g., add compute_g_log or add a
boolean flag to compute_g to return g_log directly) and replace the call in the
Err(_) branch to obtain g_log without exponentiating, keeping the existing
Activations::sigmoid(a)? assignment for beta and returning (beta, g_log) from
that branch.
packages/cli/src/commands/download-model.ts (1)

262-271: Clarify the > 1 threshold for already-downloaded check.

The condition matchedExisting.length > 1 seems to allow re-download if only 1 file matches. Was this intended to account for the case where only config.json is present (a CORE_FILE)? If so, the logic is correct but could benefit from a comment explaining the rationale.

📝 Optional: add clarifying comment
     if (hasGguf && globPatterns?.length) {
       const globs = globPatterns.map(globToRegex);
       const matchedExisting = files.filter((f) => matchesAnyGlob(f, globs) || CORE_FILES.includes(f));
+      // > 1 because a single match could be just config.json (core file), not the actual GGUF
       if (matchedExisting.length > 1) {
         console.log('Matched files already downloaded!\n');
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/commands/download-model.ts` around lines 262 - 271, The
check using matchedExisting.length > 1 is non-obvious: clarify via a short
comment above the block that we only treat the set as "already downloaded" when
more than one file matches because CORE_FILES (e.g., config.json) may exist
alone and should not block re-download; refer to globPatterns, globToRegex,
matchesAnyGlob, CORE_FILES, matchedExisting and outputDir so reviewers can find
the logic to update the comment. Ensure the comment explains the special-case
(single CORE_FILE allowed) and that the early return prevents re-download only
when multiple matching files are present.
crates/mlx-sys/src/mlx_gated_delta.cpp (1)

364-386: Architecture string parsing may fail silently on unexpected formats.

The parsing assumes architecture strings follow the pattern applegpu_g<gen><size> (e.g., applegpu_g15s). If the format changes or includes unexpected characters, the function returns 0, which disables chunked kernels. This is a safe fallback, but consider logging a warning when parsing fails to aid debugging:

🔧 Optional: add debug logging for parse failures
 int32_t mlx_gpu_architecture_gen() {
     try {
         auto& info = mlx::core::gpu::device_info(0);
         auto it = info.find("architecture");
-        if (it == info.end()) return 0;
+        if (it == info.end()) {
+            // Architecture info not available; chunked kernel disabled
+            return 0;
+        }
         auto& arch = std::get<std::string>(it->second);
         // ...parsing...
-        return gen;
+        if (gen == 0) {
+            std::cerr << "[MLX] Could not parse GPU gen from: " << arch << std::endl;
+        }
+        return gen;
     } catch (...) {
         return 0;
     }
 }
🤖 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 364 - 386, The
architecture parsing in mlx_gpu_architecture_gen silently returns 0 on
unexpected formats; update mlx_gpu_architecture_gen to emit a warning when
parsing fails or the format is unexpected (e.g., missing "architecture" key,
arch.size() < 3, no digits found before the final size letter, or any
exception). Use the project’s existing logging facility (the same logging used
elsewhere in mlx::core) to log a concise warning containing the raw arch string
and the failure reason before returning 0 so debugging malformed strings (from
device_info(0)) is easier.
crates/mlx-core/src/profiling.rs (1)

302-316: Test state isolation could affect parallel test runs.

The test modifies global state (PROFILING_ENABLED) and attempts to restore it. In parallel test execution, this could cause flaky behavior. Consider using a test-specific isolation mechanism or ensuring tests run sequentially.

🧪 Consider using serial test execution for global state tests

Add a comment or use a crate like serial_test if parallel test flakiness is observed:

// These tests modify global state and should not run in parallel
// with other tests that access PROFILING_ENABLED or PROFILING_STORE.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/profiling.rs` around lines 302 - 316, The test
test_is_active_reflects_atomic mutates global PROFILING_ENABLED and can race
with other tests; make it isolated by marking it to run serially (e.g., add a
comment and apply a serialization mechanism such as the serial_test crate’s
#[serial] attribute) or otherwise ensure it runs non-parallel, and keep the
save/restore of PROFILING_ENABLED around the is_active checks to preserve state;
update the test function definition (test_is_active_reflects_atomic) and add a
note that it touches PROFILING_ENABLED/PROFILING_STORE so future contributors
know it must not run in parallel.
crates/mlx-core/src/models/qwen3_5/persistence.rs (2)

1228-1229: LayerNorm epsilon is hardcoded to 1e-6.

The epsilon value for vision encoder LayerNorm layers is hardcoded. Consider using a config value or verifying this matches the expected model configuration.

♻️ Consider making epsilon configurable
+        let layer_norm_eps = 1e-6; // Could be added to Qwen3_5VisionConfig
+
-        let ln1 = LayerNorm::from_weights(norm1_w, norm1_b, Some(1e-6))?;
-        let ln2 = LayerNorm::from_weights(norm2_w, norm2_b, Some(1e-6))?;
+        let ln1 = LayerNorm::from_weights(norm1_w, norm1_b, Some(layer_norm_eps))?;
+        let ln2 = LayerNorm::from_weights(norm2_w, norm2_b, Some(layer_norm_eps))?;
🤖 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 1228 - 1229,
LayerNorm epsilon is hardcoded to 1e-6 in the vision encoder loading; replace
the magic literal by reading an epsilon from the model config and passing it
into LayerNorm::from_weights (instead of Some(1e-6)). Add a field (e.g.,
layer_norm_epsilon) to the model/config struct or loader args, load/parse it
where weights like norm1_w/norm1_b and norm2_w/norm2_b are read, and use that
value for both LayerNorm::from_weights calls (ln1 and ln2). Provide a sensible
default fallback (matching the original 1e-6 if the config is absent) and
validate the value before use.

900-906: Consider reading M-RoPE section from configuration instead of hardcoding.

The M-RoPE section [11, 11, 10] is hardcoded for all Qwen3.5-VL loads. If future model variants use different section values or if the configuration format evolves to include this parameter, the hardcoded value will cause incorrect 3D positional encoding. Following the pattern established in PaddleOCR-VL, extract mrope_section from the configuration file and validate it matches the rope dimensions (sum(mrope_section) * 2 should equal rope_dims), similar to the validation in crates/mlx-core/src/models/paddleocr_vl/language.rs.

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

In `@crates/mlx-core/src/models/qwen3_5/persistence.rs` around lines 900 - 906,
Replace the hardcoded M-RoPE section with a value read from the model config:
add reading of a mrope_section field (e.g., Vec<usize>) from the same config
used by this loader and pass it into model.init_mrope_layers instead of
vec![11,11,10]; validate that the provided mrope_section is non-empty and that
sum(mrope_section) * 2 == rope_dims (or the existing rope dimension value)
before calling model.init_mrope_layers, returning an error if validation fails;
keep using config.rope_theta and config.max_position_embeddings when invoking
model.init_mrope_layers.
crates/mlx-sys/src/mlx_qwen35_vlm.cpp (1)

180-197: Cache accessor functions lack exception handling.

While mlx_qwen35_vlm_prefill has proper try/catch, the accessor functions (mlx_qwen35_vlm_cache_count, mlx_qwen35_vlm_get_cache, mlx_qwen35_vlm_get_offset, mlx_qwen35_vlm_reset) do not. Per project learnings, all extern "C" FFI entry points should be wrapped in try/catch. However, these are simple accessors with minimal failure risk.

Based on learnings: "After the mlx-sys file split (9f60db7), the FFI surface expanded... Try-catch requirements should be applied incrementally to new functions or as part of dedicated FFI hardening work." Consider adding try/catch for completeness in a future hardening pass.

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

In `@crates/mlx-sys/src/mlx_qwen35_vlm.cpp` around lines 180 - 197, Wrap each
extern "C" accessor (mlx_qwen35_vlm_cache_count, mlx_qwen35_vlm_get_cache,
mlx_qwen35_vlm_get_offset, mlx_qwen35_vlm_reset) in a try/catch that catches
std::exception and (...) to prevent exceptions crossing the FFI boundary; on
exception, return safe defaults (e.g., cache_count -> 0, get_cache -> nullptr,
get_offset -> 0) and for reset ensure any partial state is left consistent, and
optionally log the error via the existing logging facility or a fallback;
implement this consistently across the four functions so they never throw out of
the FFI layer.
crates/mlx-core/src/models/qwen3_5/processing.rs (1)

142-155: Nested loop for patch extraction could be optimized.

The 5-level nested loop for reordering pixels into patches works but may have cache-unfriendly access patterns. For large images, this could be a performance bottleneck. Consider using a more cache-efficient approach or vectorized operations.

♻️ Consider iterator-based approach for better optimization

The current implementation is correct and clear. If profiling shows this as a bottleneck, consider:

  1. Pre-computing row strides
  2. Using chunks/iterators with known sizes
  3. Leveraging SIMD through std::simd when stable
🤖 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/processing.rs` around lines 142 - 155, The
nested 5-loop that fills patch_data from pixel_data (iterating ph, pw, c, py,
px) is cache-unfriendly; refactor in the function that builds patches to iterate
memory-contiguously by precomputing row_stride = width * channels and then loop
y over image rows and x over patch columns so you walk pixel_data in linear
order, using slices and extend_from_slice or copy_from_slice for contiguous
channel blocks (referencing patch_data, pixel_data, grid_h, grid_w, patch_size,
channels, width) to reduce random access and enable further vectorization/SIMD
optimizations.
packages/core/index.d.cts (2)

2058-2068: Documented recipe options differ from GgufConversionOptions.

ConversionOptions.quantRecipe lists: mixed_2_6, mixed_3_4, mixed_3_6, mixed_4_6, qwen3_5

GgufConversionOptions.quantRecipe (line 2406) lists: mixed_2_6, mixed_3_4, mixed_3_6, mixed_4_6, qwen3_5, unsloth

Consider aligning the documented options if both interfaces support the same recipes, or clarifying in documentation which recipes are specific to GGUF conversion.

🤖 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 2058 - 2068, The documented
quantRecipe options in ConversionOptions.quantRecipe do not match
GgufConversionOptions.quantRecipe (GgufConversionOptions includes "unsloth");
update the documentation to align both or clarify differences: inspect the
types/interfaces ConversionOptions and GgufConversionOptions and either add
"unsloth" to the documented list under ConversionOptions.quantRecipe if
supported, or add a clarifying note stating that "unsloth" is specific to
GgufConversionOptions.quantRecipe; ensure the comment strings for quantRecipe in
both interfaces consistently reflect the supported recipes.

1969-1971: Type inconsistency with other VLM image fields.

ChatMessage.images uses Array<Uint8Array> while VlmChatConfig.images (line 2442) and VlmBatchItem.images (line 3436) use Array<Buffer>. While Buffer extends Uint8Array in Node.js, the inconsistency may confuse API consumers.

Consider aligning to one type. Since this is auto-generated from Rust via NAPI-RS, verify the Rust-side types match the intended behavior.

🤖 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 1969 - 1971, ChatMessage.images is
typed as Array<Uint8Array> while VlmChatConfig.images and VlmBatchItem.images
use Array<Buffer>, causing an inconsistent public API; pick one consistent type
(prefer Array<Buffer> if Node Buffer semantics are intended, or
Array<Uint8Array> for broader JS/wasm compatibility), update the
ChatMessage.images type to match the chosen variant (or change the other two to
Uint8Array) across the generated defs, and then verify and adjust the Rust
NAPI-RS source types so regeneration produces the aligned type for ChatMessage,
VlmChatConfig, and VlmBatchItem.

Comment thread crates/mlx-core/src/utils/gguf.rs Resolved
Comment thread crates/mlx-core/src/utils/imatrix.rs Resolved
@Brooooooklyn
Brooooooklyn force-pushed the feat/perf-profiler-convert-fixes branch from 7f138dc to 9b095e3 Compare March 16, 2026 07:33
Comment thread crates/mlx-core/src/decode_profiler.rs Resolved
…nked GDN kernel

Decode profiler: new DecodeProfiler with per-phase wall-clock timing (forward, sample,
eval, extract), activated via MLX_PROFILE_DECODE=1 env var. Instrumented in MoE generate/chat
loops. Also switches MoE Rust fallback to token-only async eval (matching mlx-lm pattern).

GGUF conversion: full GGUF v3 parser supporting BF16/F16/F32 and Q4_0/Q4_1/Q8_0 quantized
tensors with HF name remapping. Adds imatrix parser for Unsloth importance scores, AWQ-style
weight pre-scaling, and mixed-bit quantization recipes (mixed_2_6, mixed_3_4, mixed_3_6,
mixed_4_6, qwen3_5, unsloth). CLI gains --q-recipe, --imatrix-path, --mmproj, and --glob
flags for GGUF-aware model download and conversion workflows.

Qwen3.5 VLM: vision encoder (27-layer ViT with 2D RoPE and spatial merger), image processor
(smart resize/normalize/patch extraction), and VLModel with chat() accepting images. Adds
M-RoPE (multimodal rotary position embeddings) to full attention layers, C++ VLM prefill
pass, and model loader auto-detection of VLM models via vision.safetensors.

SIMD chunked GDN prefill kernel: rewrites chunked kernel from (BV=64, 1, 1) serial
threadgroups to (32, DV_PER_TG, 1) SIMD threadgroups. 32 threads form a SIMD group
splitting Dk=128 into n_per_t=4 each, all dot products use simd_sum (4 FMAs + reduction
vs 128 serial FMAs). State registers reduced 32x (128 → 4 per thread). Gated on M5+
(gpu gen >= 17) via runtime GPU architecture detection — on M1–M4, the per-step kernel
remains faster because Apple GPUs lack tensor cores to accelerate the O(BT²) matmuls.
Adds mlx_gpu_architecture_gen() FFI using MLX device_info() architecture string parsing.

Supporting: chatStream() streaming API for Qwen3.5 dense and MoE models, fused GDN gating
Metal kernel, tokenizer ChatMessage images field, Jinja2 split() maxsplit fix and
raise_exception function, per-layer quant overrides in MoE persistence, dependency updates.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/perf-profiler-convert-fixes branch from 9b095e3 to a4c5b37 Compare March 16, 2026 07:49

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

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 (1)
crates/mlx-core/src/models/qwen3/model.rs (1)

4983-4990: ⚠️ Potential issue | 🟠 Major

Populate first_token_elapsed_ms in generate_for_training()

first_token_elapsed_ms is always None here, so chat() cannot produce performance even when report_performance=true (downstream at Lines 5261-5284).

💡 Suggested fix
@@
-        let prefill_step_size = config.prefill_step_size.unwrap_or(2048) as usize;
+        let prefill_step_size = config.prefill_step_size.unwrap_or(2048) as usize;
+        let report_performance = config.report_performance.unwrap_or(false);
@@
-            // ⚡ PREFILL: Process prompt (chunked for long sequences)
+            let perf_start = if report_performance {
+                Some(std::time::Instant::now())
+            } else {
+                None
+            };
+            let mut first_token_elapsed_ms: Option<f64> = None;
+
+            // ⚡ PREFILL: Process prompt (chunked for long sequences)
@@
-                let token_value = token.item_at_int32(0)? as u32;
+                let token_value = token.item_at_int32(0)? as u32;
+                if let Some(start) = perf_start && first_token_elapsed_ms.is_none() {
+                    first_token_elapsed_ms = Some(start.elapsed().as_secs_f64() * 1000.0);
+                }
@@
             Ok(GenerationResult {
@@
-                first_token_elapsed_ms: None,
+                first_token_elapsed_ms,
             })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3/model.rs` around lines 4983 - 4990, In
generate_for_training() the GenerationResult.first_token_elapsed_ms is left as
None so downstream chat() cannot report performance; start a high-resolution
timer (e.g., Instant::now()) just before the token-generation/sampling loop in
generate_for_training(), capture the elapsed time when the first token is
produced (on the first push into generated_tokens or the first time a token is
emitted), convert to milliseconds and set
GenerationResult.first_token_elapsed_ms = Some(elapsed_ms as u64) (matching the
Option type used), and return that populated field so chat() can compute
performance when report_performance=true.
♻️ Duplicate comments (4)
crates/mlx-sys/src/metal/gated_delta_chunked.metal.inc (1)

25-29: ⚠️ Potential issue | 🔴 Critical

The tail-thread early return still breaks barrier participation.

When Dv % DV_PER_TG != 0, the last tile has inactive lanes. Returning those lanes at Line 29 means the remaining lanes still hit threadgroup_barrier later in the kernel, which is undefined in Metal and can deadlock the threadgroup. Keep every lane alive through the barriers and guard only the invalid loads/stores with an active_v mask.

In Metal Shading Language, is it valid for some threads in a threadgroup to return before later `threadgroup_barrier` calls while other threads continue?
🤖 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_chunked.metal.inc` around lines 25 - 29,
The early return based on v_idx (if (v_idx >= Dv) return;) causes some lanes to
skip later threadgroup_barrier calls and may deadlock when Dv % DV_PER_TG != 0;
instead remove the return and compute an active_v boolean mask (e.g., bool
active_v = v_idx < Dv) then keep all threads alive through every
threadgroup_barrier and wrap only invalid memory accesses and work
(loads/stores, writes) with checks against active_v; ensure any usages of v_idx,
v_col_in_tg, or simd_lane that assume validity are guarded by active_v so
inactive lanes do nothing but still participate in barriers.
crates/mlx-core/src/utils/imatrix.rs (1)

240-250: ⚠️ Potential issue | 🔴 Critical

Reject GGUF tensor type 6 here.

6 is GGML_TYPE_Q5_0, not raw F32. Accepting it on the raw-float path will silently corrupt the parsed importance values unless you add a real Q5_0 dequantization path.

Suggested fix
-        if type_u32 != 6 {
-            // F32 = 0 in GGUF types, but imatrix stores raw F32 data as type 6?
-            // Actually GGUF tensor type F32 = 0. Let's accept both.
-            if type_u32 != 0 {
-                return Err(Error::from_reason(format!(
-                    "imatrix tensor '{name}' has unexpected type {type_u32} (expected F32=0)"
-                )));
-            }
-        }
+        if type_u32 != 0 {
+            return Err(Error::from_reason(format!(
+                "imatrix tensor '{name}' has unexpected type {type_u32} (expected F32=0)"
+            )));
+        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/imatrix.rs` around lines 240 - 250, The code
currently treats GGUF tensor type 6 as F32 which can corrupt parsed importance
values; change the check around type_u32 (the value returned by read_u32_le) to
only accept F32 (0) and reject 6 (GGML_TYPE_Q5_0) instead; update the error path
that returns Error::from_reason for imatrix tensor '{name}' to report the
unexpected type_u32 value (and keep guidance that proper handling of 6 would
require a Q5_0 dequantization path) so the parser fails fast instead of silently
accepting type 6.
crates/mlx-core/src/utils/gguf.rs (1)

423-427: ⚠️ Potential issue | 🔴 Critical

Guard general.alignment against zero before modulo.

Line 483 can panic on offset % alignment if metadata sets alignment to 0.

Proposed fix
 let alignment = metadata
     .get("general.alignment")
     .and_then(|v| v.as_u64())
-    .unwrap_or(GGUF_DEFAULT_ALIGNMENT);
+    .filter(|&a| a != 0)
+    .unwrap_or(GGUF_DEFAULT_ALIGNMENT);

Also applies to: 482-484

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

In `@crates/mlx-core/src/utils/gguf.rs` around lines 423 - 427, The code reads
alignment from metadata into the variable alignment and later does offset %
alignment which will panic if alignment == 0; modify the retrieval of
"general.alignment" (the alignment variable) to guard against zero by treating
zero as invalid and falling back to GGUF_DEFAULT_ALIGNMENT (or using
alignment.max(1)), e.g. check the as_u64 value != 0 before unwrap_or and ensure
the final alignment used in offset % alignment is nonzero (and correctly typed)
so the modulo cannot panic.
crates/mlx-core/src/models/qwen3_5/model.rs (1)

2651-2653: ⚠️ Potential issue | 🔴 Critical

Do not swallow causal-mask construction failures in VLM Rust prefill.

Line 2652 converts mask creation failures to None via .ok(), which can silently disable causal masking.

Proposed fix
-            let fa_mask = if seq_len > 1 {
-                crate::array::mask::create_causal_mask(seq_len as i32, None, None).ok()
-            } else {
-                None
-            };
+            let fa_mask = if seq_len > 1 {
+                Some(crate::array::mask::create_causal_mask(seq_len as i32, None, None)?)
+            } else {
+                None
+            };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/qwen3_5/model.rs` around lines 2651 - 2653, The
code currently silences failures by calling .ok() on
crate::array::mask::create_causal_mask when building fa_mask, which can silently
disable causal masking; change this to propagate or handle the Result instead of
converting to None—e.g., replace the .ok() usage on the create_causal_mask call
used to set fa_mask so errors bubble up (use the ? operator to return the error
from the enclosing function) or explicitly map the Err to a returned error with
context; ensure the change targets the fa_mask assignment that calls
crate::array::mask::create_causal_mask within the VLM prefill logic so failures
are not swallowed.
🟠 Major comments (21)
packages/cli/src/commands/download-model.ts-328-336 (1)

328-336: ⚠️ Potential issue | 🟠 Major

Only take the GGUF fast path when every downloaded weight is GGUF.

This branch currently triggers on some('.gguf'), so a mixed selection skips verifyDownload() and the loop emits mlx convert -i ... commands for non-GGUF weights. It also reuses the same ${outputDir}-mlx target for every GGUF, which makes the multi-variant flow clobber itself.

Suggested fix
-  const hasGgufFiles = weightFiles.some((f) => f.endsWith('.gguf'));
-  if (hasGgufFiles) {
+  const ggufWeightFiles = weightFiles.filter((f) => f.endsWith('.gguf'));
+  const hasOnlyGgufFiles = ggufWeightFiles.length > 0 && ggufWeightFiles.length === weightFiles.length;
+  if (hasOnlyGgufFiles) {
     console.log(`\nDownload complete! ${weightFiles.length} file(s) saved to ${outputDir}\n`);
     console.log('To convert GGUF to MLX SafeTensors format:');
-    for (const wf of weightFiles) {
+    for (const wf of ggufWeightFiles) {
       const ggufPath = join(outputDir, wf);
-      console.log(`  mlx convert -i ${ggufPath} -o ${outputDir}-mlx`);
+      const variantName = wf.split('/').pop()!.replace(/\.gguf$/i, '');
+      console.log(`  mlx convert -i ${ggufPath} -o ${outputDir}-${variantName}-mlx`);
     }
     console.log('');
   } else {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/commands/download-model.ts` around lines 328 - 336, The GGUF
fast path currently triggers when any file endsWith('.gguf') which incorrectly
skips verifyDownload() for mixed downloads and reuses the same
`${outputDir}-mlx` target for every file; change the predicate to require every
weightFile to endWith('.gguf') (e.g., use all/.every on weightFiles), only skip
verifyDownload() when that is true, and in the loop emit a unique output path
per GGUF (derive a per-file target from the weight filename such as including
the basename or variant in the `${outputDir}`-based mlx output) so conversions
do not clobber one another; update uses of hasGgufFiles, the verifyDownload()
decision, and the mlx convert output construction accordingly.
packages/cli/src/commands/download-model.ts-102-142 (1)

102-142: ⚠️ Potential issue | 🟠 Major

Separate actual glob matches from always-included metadata.

A glob miss still returns CORE_FILES from this function, so the caller never sees a true “no matches” case. With something like -g "*Q8*" against a repo that only has Q4_*, the command downloads config/tokenizer files and then fails later instead of showing the GGUF diagnostics.

Suggested fix
 async function getModelFiles(modelName: string, accessToken?: string, globPatterns?: string[]) {
   let totalSize = 0;
   const filesToDownload: ListFileEntry[] = [];
   const allFiles: ListFileEntry[] = [];
+  let globMatchCount = 0;

   // Compile glob patterns if provided
   const globs = globPatterns?.map(globToRegex);

   for await (const file of listFiles({ repo: { type: 'model', name: modelName }, accessToken })) {
     allFiles.push(file);

     if (globs) {
       // When glob patterns are active, include files that match the pattern
       // OR are essential metadata files (config, tokenizer)
       const basename = file.path.split('/').pop() || file.path;
       if (matchesAnyGlob(basename, globs) || matchesAnyGlob(file.path, globs)) {
         filesToDownload.push(file);
+        globMatchCount++;
         if (file.size) totalSize += file.size;
       } else if (CORE_FILES.includes(basename)) {
         // Always include core config/tokenizer files
         filesToDownload.push(file);
         if (file.size) totalSize += file.size;
       }
     } else {
       // Default behavior: download model files
       if (
         CORE_FILES.includes(file.path) ||
         file.path.endsWith('.safetensors') ||
         file.path.endsWith('.json') ||
         file.path.endsWith('.pdiparams') ||
         file.path.endsWith('.yml')
       ) {
         filesToDownload.push(file);
         if (file.size) {
           totalSize += file.size;
         }
       }
     }
   }

-  return { totalSize, filesToDownload, allFiles };
+  return { totalSize, filesToDownload, allFiles, globMatchCount };
 }

Then gate the caller’s “no files matched” branch on globMatchCount === 0, not filesToDownload.length === 0.

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

In `@packages/cli/src/commands/download-model.ts` around lines 102 - 142, In
getModelFiles, separate “real” glob matches from always-included metadata by
tracking a globMatchCount when globPatterns are provided: increment
globMatchCount only when matchesAnyGlob(basename, globs) or
matchesAnyGlob(file.path, globs) is true, but still push CORE_FILES into
filesToDownload without incrementing the globMatchCount; return globMatchCount
along with totalSize, filesToDownload, and allFiles; then update the caller that
currently gates the “no files matched” branch to check globMatchCount === 0
instead of filesToDownload.length === 0 so metadata files don’t mask a true
zero-match case.
packages/cli/src/commands/download-model.ts-261-269 (1)

261-269: ⚠️ Potential issue | 🟠 Major

Don't let matchedExisting.length > 1 short-circuit globbed GGUF downloads.

config.json plus one GGUF is enough to hit this branch, even if the repo has more files that match the requested glob(s). That makes a partial folder look complete and blocks the remaining downloads.

Suggested fix
-    // For glob downloads, check if all glob-matched files are present
-    if (hasGguf && globPatterns?.length) {
-      const globs = globPatterns.map(globToRegex);
-      const matchedExisting = files.filter((f) => matchesAnyGlob(f, globs) || CORE_FILES.includes(f));
-      if (matchedExisting.length > 1) {
-        console.log('Matched files already downloaded!\n');
-        console.log('To re-download, delete the output directory first:');
-        console.log(`   rm -rf ${outputDir}\n`);
-        return;
-      }
-    }
+    // Keep globbed GGUF downloads on the normal path. A local directory
+    // listing here cannot prove the full remote glob selection is present.
Based on learnings, the local “already downloaded” check in this file is intentionally only a quick heuristic, and authoritative verification happens after the download completes.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/commands/download-model.ts` around lines 261 - 269, The
short-circuit treats any folder with more than one matching file (e.g.,
config.json + one GGUF) as "already downloaded"; change the check so we only
skip when the set of matched existing files truly covers all files we would
download instead of using matchedExisting.length > 1. In the block that uses
hasGguf, globPatterns, globToRegex, matchesAnyGlob, CORE_FILES and
matchedExisting, replace the loose condition with a precise containment check
(e.g., ensure matchedExisting includes every expected download target or equals
the list of repo files-to-download) before logging and returning, so partial
folders won’t block remaining globbed GGUF downloads.
crates/mlx-sys/src/mlx_qwen35.cpp-273-276 (1)

273-276: ⚠️ Potential issue | 🟠 Major

g_compiled_offset diverges from the real decode position after one forward step.

This helper updates both g_offset_int and g_compiled_offset, but mlx_qwen35_forward_compiled() still only increments g_offset_int. After the first decode call the array mirror is stale, so anything using g_compiled_offset for rope/position handling will read the wrong offset. Update it in the main decode path too, or remove the duplicate state.

Possible fix
     *output_logits = reinterpret_cast<mlx_array*>(new array(outputs[0]));
     g_offset_int++;
+    g_compiled_offset = array(g_offset_int, mlx::core::int32);
     for (int i = 0; i < cfg.num_layers * 2; i++) {
       g_compiled_caches[i] = outputs[2 + i];
     }
🤖 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 273 - 276, The code keeps two
sources of position state (g_offset_int and g_compiled_offset) but only
mlx_qwen35_compiled_adjust_offset updates both; mlx_qwen35_forward_compiled
increments g_offset_int leaving g_compiled_offset stale. Fix by making the
forward path update the mirror too (after mlx_qwen35_forward_compiled increments
g_offset_int set g_compiled_offset = array(g_offset_int, mlx::core::int32)), or
remove the duplicate state entirely and replace uses of g_compiled_offset with a
single computed array(g_offset_int, mlx::core::int32) to ensure a single
authoritative offset; update references in mlx_qwen35_forward_compiled and any
callers that rely on g_compiled_offset accordingly.
crates/mlx-core/src/models/qwen3_5/attention.rs-152-170 (1)

152-170: ⚠️ Potential issue | 🟠 Major

Don't silently ignore multimodal positions when M-RoPE is uninitialized.

If position_ids is Some but self.mrope is still None, this falls back to scalar text RoPE and produces incorrect positions instead of failing fast. That makes loader/init bugs look like model-quality regressions. Please make (Some(_), None) an error and reserve the text fallback for None position IDs.

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

In `@crates/mlx-core/src/models/qwen3_5/attention.rs` around lines 152 - 170, The
code currently falls back to scalar RoPE when position_ids is Some but
self.mrope is None; change the branching in the attention RoPE application so
that (Some(_), None) returns an error instead of using the text-only fallback.
Concretely, in the block that computes (queries, keys) (the if let currently
matching (Some(pos_ids), Some(mrope)) and the else fallback), handle the three
cases explicitly: (Some(pos_ids), Some(mrope)) -> keep current M-RoPE path
(mrope.forward, apply_multimodal_rotary_pos_emb, transposes), (Some(_), None) ->
return Err with a clear message like "multimodal position IDs provided but
M-RoPE (self.mrope) is None", and (None, _) -> keep the existing scalar
rope.path using self.rope.forward with offset; reference position_ids,
self.mrope, mrope.forward, apply_multimodal_rotary_pos_emb, and
self.rope.forward to locate the code to modify.
crates/mlx-core/src/utils/safetensors.rs-479-514 (1)

479-514: ⚠️ Potential issue | 🟠 Major

Propagate callback conversion failures instead of returning a partial lazy load.

If MxArray::from_handle() fails for any tensor, the callback just skips that entry and load_safetensors_lazy() still returns Ok(ctx.tensors). That turns an FFI/ownership failure into a partial weight map and leaks the rejected raw handle.

Suggested fix
     struct LoadCtx {
         tensors: HashMap<String, crate::array::MxArray>,
+        first_error: Option<String>,
     }
@@
-            if let Ok(arr) = crate::array::MxArray::from_handle(handle, "lazy_load") {
-                ctx.tensors.insert(name, arr);
-            }
+            match crate::array::MxArray::from_handle(handle, "lazy_load") {
+                Ok(arr) => {
+                    ctx.tensors.insert(name, arr);
+                }
+                Err(err) => {
+                    unsafe { mlx_sys::mlx_array_delete(handle) };
+                    ctx.first_error = Some(format!("failed to wrap tensor `{name}`: {err}"));
+                }
+            }
         }
     }
 
     let mut ctx = LoadCtx {
         tensors: HashMap::new(),
+        first_error: None,
     };
@@
     if count < 0 {
         return Err(Error::from_reason(format!(
             "Failed to load safetensors: {}",
             path_str
         )));
     }
+    if let Some(err) = ctx.first_error {
+        return Err(Error::from_reason(err));
+    }
+    if count as usize != ctx.tensors.len() {
+        return Err(Error::from_reason(format!(
+            "Expected {} tensors from lazy loader, wrapped {}",
+            count,
+            ctx.tensors.len()
+        )));
+    }
 
     Ok(ctx.tensors)
 }
crates/mlx-sys/src/mlx_nn_ops.cpp-855-873 (1)

855-873: ⚠️ Potential issue | 🟠 Major

Add null-argument guards, catch-all handler, and [MLX] prefix to this new FFI entry point.

The function lacks null checks on path and callback parameters, and only catches std::exception, allowing non-standard exceptions to cross the Rust FFI boundary. Error logging is also missing the [MLX] prefix used throughout the codebase. Other functions in this file (e.g., mlx_array_eval) follow a hardened pattern with parameter validation, catch-all handlers, and prefixed logging.

Suggested hardening
 int32_t mlx_load_safetensors(
     const char* path,
     void (*callback)(const char* name, size_t name_len, mlx_array* handle, void* ctx),
     void* ctx
 ) {
     try {
+        if (!path || !callback) {
+            std::cerr << "[MLX] mlx_load_safetensors: null path or callback" << std::endl;
+            return -1;
+        }
         auto [tensors, metadata] = mlx::core::load_safetensors(std::string(path));
         int32_t count = 0;
         for (auto& [name, arr] : tensors) {
             auto* handle = reinterpret_cast<mlx_array*>(new array(std::move(arr)));
             callback(name.c_str(), name.size(), handle, ctx);
             count++;
         }
         return count;
     } catch (const std::exception& e) {
-        std::cerr << "mlx_load_safetensors error: " << e.what() << std::endl;
+        std::cerr << "[MLX] mlx_load_safetensors error: " << e.what() << std::endl;
+        return -1;
+    } catch (...) {
+        std::cerr << "[MLX] Unknown exception in mlx_load_safetensors" << std::endl;
         return -1;
     }
 }
🤖 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 855 - 873, The
mlx_load_safetensors FFI entry lacks null-argument guards, a catch-all exception
handler, and the standard "[MLX]" log prefix; update mlx_load_safetensors to
validate that path and callback are non-null (return -1 and log with std::cerr
prefixed by "[MLX]") before doing work, keep existing try/catch for
std::exception but add a final catch(...) block that logs "[MLX]
mlx_load_safetensors unknown error" and returns -1, and ensure any error logging
uses the "[MLX]" prefix and consistent messages referencing the function name
and reason.
packages/cli/src/commands/convert.ts-136-146 (1)

136-146: ⚠️ Potential issue | 🟠 Major

Reject --mmproj when the primary input is not GGUF.

Outside the .gguf branch, mmprojPath is never consumed. mlx convert -i ./hf-model --mmproj vision.gguf ... currently succeeds but silently drops the vision encoder.

Suggested fix
   const mmprojPath = args.mmproj ? resolve(args.mmproj) : undefined;
   if (mmprojPath !== undefined) {
+    if (!inputPath.endsWith('.gguf')) {
+      console.error('Error: --mmproj is only supported when --input points to a .gguf file');
+      process.exit(1);
+    }
     if (!existsSync(mmprojPath)) {

Also applies to: 218-230

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

In `@packages/cli/src/commands/convert.ts` around lines 136 - 146, The code
accepts --mmproj even when the primary input isn't a GGUF, causing the mmproj to
be ignored; update the convert command handler to validate that when args.mmproj
is provided (const mmprojPath = args.mmproj ? resolve(args.mmproj) : undefined)
the primary input (e.g., args.input / inputPath or the variable used to
represent the source model) is a .gguf and otherwise print an error and exit;
add the same validation where mmprojPath is handled later (the other block
referenced by the reviewer) so --mmproj is rejected unless the primary input is
GGUF and the mmproj will be consumed.
crates/mlx-sys/src/mlx_qwen35_common.h-215-221 (1)

215-221: ⚠️ Potential issue | 🟠 Major

Validate the M-RoPE config before indexing into it.

apply_mrope() assumes exactly 3 sections, an even rope_dims, and sum(mrope_section) == rope_dims / 2. A bad model config currently turns into mrope_section[s] UB or out-of-range head-dim slices.

Suggested fix
 inline std::pair<array, array> apply_mrope(
     const array& queries,      // [B, T, H, D]
     const array& keys,         // [B, T, Hkv, D]
     const array& position_ids, // [3, B, T]
     int rope_dims,             // total rotary dims (e.g. 64)
     float rope_theta,
     const std::vector<int>& mrope_section) {  // e.g. [11, 11, 10], sum=32 half-dims
+  if (mrope_section.size() != 3) {
+    throw std::invalid_argument("mrope_section must contain exactly 3 entries");
+  }
+  if (rope_dims % 2 != 0) {
+    throw std::invalid_argument("rope_dims must be even");
+  }
+  int half_rotary = rope_dims / 2;
+  if (mrope_section[0] + mrope_section[1] + mrope_section[2] != half_rotary) {
+    throw std::invalid_argument("mrope_section must sum to rope_dims / 2");
+  }
+  if (rope_dims > queries.shape(3) || rope_dims > keys.shape(3)) {
+    throw std::invalid_argument("rope_dims exceeds head_dim");
+  }
 
   auto dt = queries.dtype();
   int B = queries.shape(0);
   int T = queries.shape(1);
-  int half_rotary = rope_dims / 2;  // = sum of mrope_section

Also applies to: 223-285

🤖 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 215 - 221, apply_mrope
currently assumes mrope_section has exactly 3 entries and that rope_dims is even
with sum(mrope_section) == rope_dims/2, which can cause OOB/UB when indexing;
before doing any slicing/indexing in apply_mrope (and the logic covering lines
~223-285) validate that mrope_section.size() == 3, rope_dims % 2 == 0, each
mrope_section[i] > 0, and std::accumulate(mrope_section.begin(),
mrope_section.end(), 0) == rope_dims / 2, and if any check fails return an
error/throw or gracefully handle the invalid config (e.g. throw
std::invalid_argument or log and return identity pair) so subsequent uses of
mrope_section[s] and head-dim slices are safe.
crates/mlx-core/src/utils/imatrix.rs-286-291 (1)

286-291: ⚠️ Potential issue | 🟠 Major

Validate .counts tensors before indexing.

data[0] panics on a malformed zero-length tensor and silently accepts larger tensors by ignoring extra values. Return an error unless the tensor shape is exactly [1].

Suggested fix
         } else if ti.name.ends_with(".counts") {
             let base = ti.name.strip_suffix(".counts").unwrap().to_string();
-            counts_map.insert(base, data[0]);
+            if data.len() != 1 {
+                return Err(Error::from_reason(format!(
+                    "imatrix tensor '{}' must have shape [1]",
+                    ti.name
+                )));
+            }
+            counts_map.insert(base, data[0]);
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/imatrix.rs` around lines 286 - 291, The counts
branch currently does counts_map.insert(base, data[0]) and can panic or silently
accept wrong shapes; update the branch handling ti.name.ends_with(".counts")
(the block that computes base and inserts into counts_map) to validate the
tensor shape/length before indexing: require that the tensor has exactly one
element (shape == [1] or data.len() == 1) and return an Err with a descriptive
message if not, rather than indexing data[0]; only insert data[0] into
counts_map after this validation.
packages/lm/src/profiling.ts-59-67 (1)

59-67: ⚠️ Potential issue | 🟠 Major

beforeExit is not a reliable flush hook for this use case.

The event is not emitted when the process terminates via process.exit(), receives SIGINT/SIGTERM signals (without custom handlers), or encounters uncaught exceptions. This means profiling data can be lost on abrupt termination. Additionally, the async callback lacks error handling—if writeProfilingReport() rejects, the error is unhandled and the report may not be written.

Consider using process.on('exit') (synchronous only) or installing signal handlers for SIGINT/SIGTERM to ensure profiling data is flushed. Wrap writeProfilingReport() in a try-catch block to prevent unhandled rejections.

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

In `@packages/lm/src/profiling.ts` around lines 59 - 67, The current
registerExitHandler uses process.on('beforeExit') which won't run on
process.exit/SIGINT/SIGTERM/uncaught exceptions and calls async
writeProfilingReport() without error handling; update registerExitHandler to:
install handlers for 'exit' (use a synchronous flush or a sync fallback), and
also add signal handlers for 'SIGINT' and 'SIGTERM' (and optionally an
uncaughtException handler) that call a safe flush path; wrap calls to
writeProfilingReport() in try/catch and provide a synchronous fallback (or a
dedicated writeProfilingReportSync) so that setProfilingEnabled,
isProfilingEnabled and writeProfilingReport are invoked safely and errors are
caught/logged to avoid unhandled rejections and lost profiling data.
crates/mlx-core/src/convert.rs-1656-1659 (1)

1656-1659: ⚠️ Potential issue | 🟠 Major

Only eval the tensors AWQ actually modified.

This loop materializes every weight in the checkpoint, not just the tensors touched above. That defeats the lazy-loading path and can spike memory hard enough to OOM large conversions before quantization begins.

🤖 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 1656 - 1659, The current loop
calls w.eval() for every entry in weights, materializing all tensors; instead
only materialize the tensors that were actually modified by the AWQ pass. Update
the code around convert.rs so that when you modify a weight you record its key
(e.g., push into a modified_weights HashSet or Vec), and replace the global for
w in weights.values() { w.eval(); } with iterating only over those recorded keys
(lookup weights.get(key).unwrap().eval()). Use the existing weights map and the
same key names used where modifications occur so only touched tensors are
eagerly evaluated.
crates/mlx-core/src/models/qwen3_5/persistence.rs-1174-1187 (1)

1174-1187: ⚠️ Potential issue | 🟠 Major

Don't collapse Conv3d patch weights by taking only slice 0.

A temporal-size-2 patch embed still uses both depth slices for image mode, so reducing the kernel to [:, 0, ...] drops half of the learned projection. If this path is meant to emulate the image case with a 2D patch embed, the temporal slices need to be combined, not truncated.

🤖 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 1174 - 1187,
The current Conv3d handling wrongly drops temporal slices by taking only slice
0; instead, when pe_weight.ndim() == 5 use the full temporal dimension (kD =
pe_weight.shape_at(1)?), slice out [:, 0..kD, :, :, :] (i.e. &[out_c, kD, kh,
kw, in_c]), then reduce/merge the temporal axis (dimension 1) into the 2D
kernel—e.g. compute an average or sum across that axis—to produce a [out, kh,
kw, in] tensor and pass that result to encoder.set_patch_embed(&conv2d_weight)?;
update the code around get_opt("patch_embed.proj.weight"), pe_weight, slice,
squeeze and encoder.set_patch_embed to implement this temporal combination
instead of taking only slice 0.
crates/mlx-sys/src/mlx_qwen35_vlm.cpp-143-176 (1)

143-176: ⚠️ Potential issue | 🟠 Major

Fully unwind partial state when prefill throws.

If an exception is raised after *output_logits = new array(logits), the catch blocks leak that allocation and leave g_vlm_caches / g_vlm_offset partially updated. The next decode can then observe stale cache state even though prefill failed.

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

In `@crates/mlx-sys/src/mlx_qwen35_vlm.cpp` around lines 143 - 176, When
mlx_qwen35_vlm_prefill allocates and assigns *output_logits = new array(logits)
then later throws, the allocation and global state can leak/partially persist;
update the catch blocks to delete/free that allocation (or convert the local
allocation to a smart pointer before assigning to *output_logits) and always
reset globals to a clean state: set *output_logits = nullptr (after freeing),
reset g_vlm_offset to its prefill sentinel, clear or reset g_vlm_caches, and set
g_vlm_inited = false so no stale cache/offset remains after an exception.
crates/mlx-core/src/models/qwen3_5/persistence.rs-43-53 (1)

43-53: ⚠️ Potential issue | 🟠 Major

Sharded VL checkpoints still skip the separate vision weights.

This merge only happens in the single-file branch. When the text weights are sharded, vision.safetensors is never added to raw_params, so the later vision split silently falls back to a text-only model.

🤖 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 43 - 53,
Sharded checkpoints never merge vision.safetensors into the raw parameter list,
so when text weights are sharded the separate vision weights are skipped; after
the sharded-text loading logic (the branch that populates raw_params from
multiple shard files), detect and load vision.safetensors (using
SafeTensorsFile::load and .load_tensors on vision_path) and extend raw_params
(or the same params vector used later) with those vision tensors—mirroring the
single-file branch's vision loading (vision_path, vision_st, vision_params,
params.extend(vision_params)) so the subsequent vision/text split sees the
vision tensors.
crates/mlx-core/src/models/qwen3_5_moe/persistence.rs-919-951 (1)

919-951: ⚠️ Potential issue | 🟠 Major

MoE-VL detection can't see split-file checkpoints.

has_vision only inspects raw_params, but load_all_safetensors() still populates that map from the text checkpoint files only. A model that keeps its vision encoder in vision.safetensors will therefore fall through this branch and load as plain MoE.

🤖 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 919 -
951, The detection for vision tensors only checks keys in raw_params
(has_vision) but load_all_safetensors can produce separate maps/files so
vision-only checkpoints (e.g., vision.safetensors) are missed; update the
detection to consider all loaded safetensor sources: change the has_vision check
to inspect both raw_params and any other safetensor map or filenames returned by
load_all_safetensors (or the collection of input safetensor file names) for
prefixes "vision_tower." or "visual.", and when splitting into
text_params/vision_params use the union of those sources so vision tensors in a
separate file are correctly placed into vision_params (refer to has_vision,
raw_params, vision_params, text_raw_params, and the load_all_safetensors call to
locate where to add this cross-map inspection).
crates/mlx-core/src/convert.rs-687-696 (1)

687-696: ⚠️ Potential issue | 🟠 Major

Don't quantize lm_head until the dense loader supports it.

The mixed recipes now force lm_head.weight through quantization, but crates/mlx-core/src/models/qwen3_5/persistence.rs still loads the dense LM head with set_weight() and never reconstructs a quantized projection. Non-tied dense checkpoints converted with mixed_* will therefore load packed weights as if they were dense.

🤖 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 687 - 696, The code currently
forces lm_head.weight through quantization by returning QuantDecision::Custom
for keys matching "lm_head" (the closure that returns QuantDecision::Custom with
bits=high_bits, group_size=gs, mode="affine"), but the Qwen3.5 dense loader
(crates/mlx-core/src/models/qwen3_5/persistence.rs) still uses set_weight() and
cannot reconstruct a quantized lm_head; remove or gate this special-case so
lm_head.weight is NOT forced into quantization until the dense loader supports
quantized projections — either delete the if block that matches
key.contains("lm_head") && key.ends_with(".weight") or wrap it behind a
feature/flag (e.g., support_quantized_lm_head) and check that flag before
returning QuantDecision::Custom (leave other keys to the existing
should_quantize logic).
crates/mlx-core/src/models/qwen3/model.rs-1673-1683 (1)

1673-1683: ⚠️ Potential issue | 🟠 Major

TTFT timing starts too late in sync generation path

decode_start is initialized after prefill and first-token sampling setup, so the reported TTFT excludes major latency and is systematically under-reported.

💡 Suggested fix
@@
-        // Profiler for generate decode loop
+        // Profiler for generate decode loop
         let mut profiler = crate::decode_profiler::DecodeProfiler::new("generate", "qwen3");
         profiler.set_prompt_tokens(current_ids.shape_at(1).unwrap_or(0) as u32);
         profiler.snapshot_memory_before();
+        let report_performance = config.report_performance.unwrap_or(false);
+        let ttft_start = if report_performance {
+            Some(std::time::Instant::now())
+        } else {
+            None
+        };
@@
-        let report_performance = config.report_performance.unwrap_or(false);
-        let decode_start = if report_performance {
-            Some(std::time::Instant::now())
-        } else {
-            None
-        };
         let mut first_token_elapsed_ms: Option<f64> = None;
@@
-            if let Some(ds) = decode_start
+            if let Some(ds) = ttft_start
                 && first_token_elapsed_ms.is_none()
             {
                 first_token_elapsed_ms = Some(ds.elapsed().as_secs_f64() * 1000.0);
             }

Also applies to: 1702-1706

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

In `@crates/mlx-core/src/models/qwen3/model.rs` around lines 1673 - 1683, The TTFT
timer is being started too late — move the report_performance check and the
decode_start Instant initialization earlier in the sync generation path so it is
created before prefill and first-token sampling logic (so decode_start, created
when report_performance.unwrap_or(false) is true, wraps the entire generation
latency); ensure first_token_elapsed_ms remains Option<f64> and is set from
decode_start.elapsed() when the first token is produced; apply the same change
to the other identical block that initializes
decode_start/first_token_elapsed_ms later in the file.
crates/mlx-core/src/utils/gguf.rs-210-216 (1)

210-216: ⚠️ Potential issue | 🟠 Major

Validate quantized tensor element count is block-aligned.

For quantized tensors, floor division (n / 32) can silently truncate malformed tensors instead of erroring.

Proposed fix
 fn load_quantized_tensor(
@@
 ) -> Result<Vec<(String, MxArray)>> {
@@
     let num_elements = tensor.num_elements() as usize;
     let block_size: usize = 32;
+    if num_elements % block_size != 0 {
+        return Err(Error::from_reason(format!(
+            "Quantized tensor '{}' has {} elements, not divisible by block size {}",
+            tensor.name, num_elements, block_size
+        )));
+    }
     let n_blocks = num_elements / block_size;

Also applies to: 559-562

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

In `@crates/mlx-core/src/utils/gguf.rs` around lines 210 - 216, The data_size()
implementation for quantized tensors currently uses floor division which
silently truncates malformed tensors; update data_size() to validate that
num_elements() is block-aligned by computing let block_size =
self.tensor_type.block_size() as u64; let n = self.num_elements(); if n %
block_size != 0 { panic!("quantized tensor element count {} is not a multiple of
block_size {}", n, block_size); } and then compute n_blocks = n / block_size and
return n_blocks * self.tensor_type.type_size() as u64; apply the same alignment
check and error behavior to the other quantized-size calculation at the
referenced location (the second occurrence around lines 559-562) so both places
fail loudly on malformed tensors.
crates/mlx-core/src/utils/gguf.rs-395-399 (1)

395-399: ⚠️ Potential issue | 🟠 Major

Reject unsupported future GGUF versions explicitly.

This parser is implemented for GGUF v3 semantics, but current logic accepts any version >= 3, which can silently misparse future format revisions.

Proposed fix
-    if version < GGUF_VERSION_3 {
+    if version != GGUF_VERSION_3 {
         return Err(Error::from_reason(format!(
-            "Unsupported GGUF version {version} (only v3+ supported)"
+            "Unsupported GGUF version {version} (only v3 supported)"
         )));
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/gguf.rs` around lines 395 - 399, The current
version check allows any version >= GGUF_VERSION_3; change it to explicitly
accept only GGUF v3 by replacing the condition using the version variable and
GGUF_VERSION_3 so that if version != GGUF_VERSION_3 it returns an error (using
Error::from_reason) that clearly states only v3 is supported and rejects future
versions rather than silently accepting them. Ensure the error message includes
the actual version found and references GGUF_VERSION_3 for clarity.
crates/mlx-core/src/models/qwen3_5/model.rs-733-744 (1)

733-744: ⚠️ Potential issue | 🟠 Major

Fail fast when images are provided but vision components are unavailable.

Current branching silently falls back to text prefill if has_images == true but encoder/processor is None. That drops image conditioning without an explicit error.

Proposed fix (apply in both chat and chat_stream)
 let vision_encoder_arc = if has_images {
     self.vision_encoder.clone()
 } else {
     None
 };
 let image_processor_arc = if has_images {
     self.image_processor.clone()
 } else {
     None
 };
+if has_images && (vision_encoder_arc.is_none() || image_processor_arc.is_none()) {
+    return Err(Error::from_reason(
+        "Images were provided, but this model was loaded without vision components",
+    ));
+}

Also applies to: 819-823, 1264-1276, 1368-1372

🤖 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 733 - 744, If
has_images is true but the model's vision components are missing, fail fast
instead of silently dropping image conditioning: in the chat and chat_stream
functions, replace the current conditional clones for vision_encoder_arc and
image_processor_arc with an explicit check (use has_images &&
(self.vision_encoder.is_none() || self.image_processor.is_none())) and return an
error (or propagate/raise an appropriate error value) when that condition is
true; otherwise proceed to clone self.vision_encoder and self.image_processor
into vision_encoder_arc and image_processor_arc as before. Apply the same
explicit-check-and-error logic to the other similar blocks (the ranges
referenced around 819–823, 1264–1276, 1368–1372) so any call with
has_images=true and missing vision_encoder/image_processor fails immediately.
🟡 Minor comments (6)
package.json-30-32 (1)

30-32: ⚠️ Potential issue | 🟡 Minor

Add explicit engines.node field or downgrade @types/node to match tested runtime.

README declares Node.js 18+ support, but @types/[email protected] provides types for Node.js 25 APIs—while CI only tests on Node 24. This creates a gap where developers may accidentally use Node 25–exclusive APIs that won't work in tested environments.

Either:

  • Add "engines": { "node": ">=24" } to package.json AND update CI to test on Node 25, or
  • Downgrade @types/node to ^24.x.x to match CI's tested version (Node 24)

The oxc-parser@^0.118.0 compatibility with @oxc-node/*@^0.0.35 is not obviously problematic but could not be definitively verified without access to @oxc-node package metadata.

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

In `@package.json` around lines 30 - 32, The package.json currently depends on
"@types/node": "^25.5.0" which mismatches the CI-tested Node runtime; either add
an "engines": { "node": ">=24" } field to package.json and update the CI matrix
to include Node 25 (so types and runtime align), or downgrade the dependency to
"@types/node": "^24.x.x" to match CI's Node 24 testing; update the package.json
dependency entry accordingly and adjust CI workflow/test matrix, and optionally
note the unresolved compatibility check for "oxc-parser" vs "@oxc-node/*" if you
choose to update Node in CI.
crates/mlx-core/src/models/paddleocr_vl/processing.rs-141-147 (1)

141-147: ⚠️ Potential issue | 🟡 Minor

Preserve the shape invariants when exposing these raw constructors.

ProcessedImage expects exactly [t, h, w], and ProcessedImages expects grid_thw shaped [num_images, 3]. The processor methods enforce that today, but these new public new() paths do not. A malformed instance will look valid until much later in the VLM pipeline. Either validate here and return Result<Self>, or keep the constructors non-public.

Also applies to: 171-177

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

In `@crates/mlx-core/src/models/paddleocr_vl/processing.rs` around lines 141 -
147, The public constructors ProcessedImage::new and ProcessedImages::new are
exposing instances that can violate required shape invariants ([t,h,w] for
ProcessedImage and [num_images,3] for ProcessedImages). Make these constructors
either non-pub or change their signatures to return Result<Self, Error> and
perform runtime validation: for ProcessedImage::new verify pixel_values has
exactly 3 dimensions and image_grid_thw.len() == 3; for ProcessedImages::new
verify grid_thw represents rows of 3 (e.g. grid_thw.len() % 3 == 0 and treat as
num_images x 3) or accept Vec<[i32;3]> and validate accordingly; return an Err
with a clear message on validation failure. Ensure you update callers or keep
constructors private if you choose non-pub.
examples/test-converted-model.ts-8-27 (1)

8-27: ⚠️ Potential issue | 🟡 Minor

Align the documented OCR flag with the parser.

The usage banner advertises --image, but parseArgs() only defines ocr, so copying the documented invocation fails with an unknown option.

🤖 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 8 - 27, The usage banner and
parseArgs options are mismatched: the comment shows `--image` but parseArgs only
defines `ocr` and the code reads values.ocr into imagePath; update them to
match. Either change the top usage string to document `--ocr` (so the comment
and the existing parseArgs/options and imagePath remain correct) or modify
parseArgs to accept an `image` option (and update references from values.ocr to
values.image or imagePath accordingly), ensuring the symbols parseArgs, options,
values.ocr, and imagePath are consistent.
examples/test-converted-model.ts-65-68 (1)

65-68: ⚠️ Potential issue | 🟡 Minor

Guard the tokens/sec calculation against a 0 ms run.

Date.now() is millisecond-resolution, so fast calls can produce duration === 0 and print Infinity tokens/s. Clamp the denominator to at least 1 ms before dividing.

Suggested fix
-  const duration = Date.now() - startTime;
-  const tokensPerSecond = (result.numTokens / duration) * 1000;
+  const durationMs = Math.max(Date.now() - startTime, 1);
+  const tokensPerSecond = (result.numTokens / durationMs) * 1000;
 
-  console.log(`\nGenerated (${result.numTokens} tokens, ${duration}ms, ${tokensPerSecond.toFixed(2)} tokens/s):`);
+  console.log(`\nGenerated (${result.numTokens} tokens, ${durationMs}ms, ${tokensPerSecond.toFixed(2)} tokens/s):`);

Also applies to: 95-97

🤖 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 65 - 68, Guard the tokens/sec
calculation by clamping the measured duration to at least 1ms before dividing:
replace uses of "const duration = Date.now() - startTime;" followed by "const
tokensPerSecond = (result.numTokens / duration) * 1000;" with a clamped-duration
approach (e.g., compute duration then use Math.max(duration, 1) as the divisor)
and apply the same change to the second occurrence that prints tokens/s (the
block using result.numTokens, duration, tokensPerSecond at the later lines).
packages/lm/src/profiling.ts-4-11 (1)

4-11: ⚠️ Potential issue | 🟡 Minor

Parse MLX_PROFILE_DECODE by value, not just presence.

!!process.env[ENV_VAR] makes MLX_PROFILE_DECODE=0/false look enabled, so profiling auto-starts and the explicit API becomes a no-op even when the variable is meant to turn profiling off.

Suggested fix
-const envVarSet = !!process.env[ENV_VAR];
+const envVarSet = (process.env[ENV_VAR] ?? '').trim() === '1';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lm/src/profiling.ts` around lines 4 - 11, ENV_VAR is currently
treated as boolean presence via envVarSet = !!process.env[ENV_VAR], which treats
MLX_PROFILE_DECODE=0/false as enabled; change logic to parse the environment
value explicitly (e.g., normalize to lower-case and check for "1", "true",
"yes") and only call setProfilingEnabled(true) and registerExitHandler() when
the parsed value indicates enabling. Update the envVarSet variable and the
conditional around setProfilingEnabled and registerExitHandler to use this
parsed check so MLX_PROFILE_DECODE=0/false/no will not auto-enable profiling.
crates/mlx-core/src/decode_profiler.rs-55-60 (1)

55-60: ⚠️ Potential issue | 🟡 Minor

Treat MLX_PROFILE_DECODE as an explicit opt-in value.

std::env::var(...).is_ok() enables profiling for MLX_PROFILE_DECODE=0 and even an empty string. That disagrees with the documented MLX_PROFILE_DECODE=1 contract and makes it hard to disable profiling in shared environments.

Suggested fix
-    *ENABLED.get_or_init(|| std::env::var("MLX_PROFILE_DECODE").is_ok())
+    *ENABLED.get_or_init(|| matches!(std::env::var("MLX_PROFILE_DECODE").as_deref(), Ok("1")))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/decode_profiler.rs` around lines 55 - 60, The
is_env_enabled function currently treats any present MLX_PROFILE_DECODE value as
enabled; change it to require an explicit opt-in by checking that the env var
value equals "1" (after retrieving via std::env::var and e.g. comparing to "1"
or trimmed "1") before returning true. Update the closure used by the static
ENABLED in is_env_enabled to parse the environment variable and return true only
when it matches "1" (leave other values, missing var, or empty string as false)
so profiling only activates for MLX_PROFILE_DECODE=1.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 082be739-db12-4ce1-9451-66d923802844

📥 Commits

Reviewing files that changed from the base of the PR and between 7f138dc and 9b095e3.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (50)
  • .yarnrc.yml
  • CLAUDE.md
  • __test__/core/profiling.test.ts
  • __test__/models/qwen35-stream.test.ts
  • crates/mlx-core/src/convert.rs
  • crates/mlx-core/src/decode_profiler.rs
  • crates/mlx-core/src/grpo/engine.rs
  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/models/paddleocr_vl/model.rs
  • crates/mlx-core/src/models/paddleocr_vl/processing.rs
  • crates/mlx-core/src/models/qwen3/generation.rs
  • crates/mlx-core/src/models/qwen3/model.rs
  • crates/mlx-core/src/models/qwen3_5/attention.rs
  • crates/mlx-core/src/models/qwen3_5/decoder_layer.rs
  • crates/mlx-core/src/models/qwen3_5/gated_delta.rs
  • crates/mlx-core/src/models/qwen3_5/mod.rs
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/mlx-core/src/models/qwen3_5/persistence.rs
  • crates/mlx-core/src/models/qwen3_5/processing.rs
  • crates/mlx-core/src/models/qwen3_5/vision.rs
  • crates/mlx-core/src/models/qwen3_5_moe/decoder_layer.rs
  • crates/mlx-core/src/models/qwen3_5_moe/model.rs
  • crates/mlx-core/src/models/qwen3_5_moe/persistence.rs
  • crates/mlx-core/src/profiling.rs
  • crates/mlx-core/src/tokenizer.rs
  • crates/mlx-core/src/utils/gguf.rs
  • crates/mlx-core/src/utils/imatrix.rs
  • crates/mlx-core/src/utils/mod.rs
  • crates/mlx-core/src/utils/safetensors.rs
  • crates/mlx-sys/mlx
  • crates/mlx-sys/src/lib.rs
  • crates/mlx-sys/src/metal/gated_delta_chunked.metal.inc
  • crates/mlx-sys/src/metal/gated_delta_fused_gating.metal.inc
  • crates/mlx-sys/src/mlx_gated_delta.cpp
  • crates/mlx-sys/src/mlx_nn_ops.cpp
  • crates/mlx-sys/src/mlx_qwen35.cpp
  • crates/mlx-sys/src/mlx_qwen35_common.h
  • crates/mlx-sys/src/mlx_qwen35_vlm.cpp
  • examples/test-converted-model.ts
  • package.json
  • packages/cli/src/commands/convert.ts
  • packages/cli/src/commands/download-model.ts
  • packages/core/index.cjs
  • packages/core/index.d.cts
  • packages/core/package.json
  • packages/lm/src/index.ts
  • packages/lm/src/models/model-loader.ts
  • packages/lm/src/profiling.ts
  • packages/lm/src/stream.ts
  • vite.config.ts
✅ Files skipped from review due to trivial changes (1)
  • crates/mlx-sys/mlx
🚧 Files skipped from review as they are similar to previous changes (9)
  • crates/mlx-core/src/utils/mod.rs
  • crates/mlx-core/src/lib.rs
  • test/models/qwen35-stream.test.ts
  • CLAUDE.md
  • packages/lm/src/models/model-loader.ts
  • packages/lm/src/index.ts
  • crates/mlx-core/src/models/qwen3_5/decoder_layer.rs
  • packages/core/package.json
  • crates/mlx-core/src/tokenizer.rs

Comment thread crates/mlx-sys/src/mlx_qwen35_vlm.cpp Resolved
Comment thread crates/mlx-sys/src/mlx_qwen35_vlm.cpp Resolved
@Brooooooklyn
Brooooooklyn merged commit e443a58 into main Mar 16, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/perf-profiler-convert-fixes branch March 16, 2026 08:06
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
…nked GDN kernel (#29)

Decode profiler: new DecodeProfiler with per-phase wall-clock timing
(forward, sample, eval, extract), activated via MLX_PROFILE_DECODE=1 env
var. Instrumented in MoE generate/chat loops. Also switches MoE Rust
fallback to token-only async eval (matching mlx-lm pattern).

GGUF conversion: full GGUF v3 parser supporting BF16/F16/F32 and
Q4_0/Q4_1/Q8_0 quantized tensors with HF name remapping. Adds imatrix
parser for Unsloth importance scores, AWQ-style weight pre-scaling, and
mixed-bit quantization recipes (mixed_2_6, mixed_3_4, mixed_3_6,
mixed_4_6, qwen3_5, unsloth). CLI gains --q-recipe, --imatrix-path,
--mmproj, and --glob flags for GGUF-aware model download and conversion
workflows.

Qwen3.5 VLM: vision encoder (27-layer ViT with 2D RoPE and spatial
merger), image processor (smart resize/normalize/patch extraction), and
VLModel with chat() accepting images. Adds M-RoPE (multimodal rotary
position embeddings) to full attention layers, C++ VLM prefill pass, and
model loader auto-detection of VLM models via vision.safetensors.

SIMD chunked GDN prefill kernel: rewrites chunked kernel from (BV=64, 1,
1) serial threadgroups to (32, DV_PER_TG, 1) SIMD threadgroups. 32
threads form a SIMD group splitting Dk=128 into n_per_t=4 each, all dot
products use simd_sum (4 FMAs + reduction vs 128 serial FMAs). State
registers reduced 32x (128 → 4 per thread). Gated on M5+ (gpu gen >= 17)
via runtime GPU architecture detection — on M1–M4, the per-step kernel
remains faster because Apple GPUs lack tensor cores to accelerate the
O(BT²) matmuls. Adds mlx_gpu_architecture_gen() FFI using MLX
device_info() architecture string parsing.

Supporting: chatStream() streaming API for Qwen3.5 dense and MoE models,
fused GDN gating Metal kernel, tokenizer ChatMessage images field,
Jinja2 split() maxsplit fix and raise_exception function, per-layer
quant overrides in MoE persistence, dependency updates.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> High risk because it modifies core model conversion/quantization paths
and generation hot loops, and introduces new GPU-kernel dispatch logic
(fused gating + conditional chunked recurrence) that can impact
correctness and performance across devices.
> 
> **Overview**
> Adds a **decode profiling system**: a new `DecodeProfiler` plus a
global NAPI-accessible profiling store (`setProfilingEnabled`,
`getProfilingData`, `resetProfilingData`) with tests, and instruments
Qwen3 generation/chat to record phase timings, TTFT, and memory
snapshots.
> 
> Expands the **model conversion pipeline** to use lazy SafeTensors
loading, adds AWQ-style pre-scaling via `--imatrix-path`, and introduces
mixed-bit/per-layer quantization via `--q-recipe` with config metadata
overrides; it also avoids quantizing vision weights, can dequantize
pre-quantized vision tensors, and skips redundant sanitization when
weights already appear MLX-formatted.
> 
> Updates Qwen3/Qwen3.5 model code for new performance reporting
(`report_performance`/`PerformanceMetrics`), routes Qwen3 chat types to
the Qwen3.5 definitions, adds optional M-RoPE support in Qwen3.5 full
attention layers, and upgrades gated-delta prefill with a fused gating
kernel plus an M5+-gated chunked recurrence path. Minor test/config
formatting changes included.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
a4c5b37. 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**
* Vision‑language support: image preprocessing, vision encoder,
image-aware chat/streaming, multimodal RoPE and vision caching
* GGUF → SafeTensors conversion with optional per-layer recipes and
imatrix pre-scaling
* Runtime decode profiler with enable/disable APIs and exportable
profiling reports
  * Lazy SafeTensors loading to reduce memory use

* **Improvements**
  * Per‑layer mixed‑bit quantization and AWQ pre‑scaling
  * Faster prefill/sequence paths (chunked/fused kernels)
  * CLI: glob filtering and richer conversion feedback

* **Breaking Changes**
* Unified chat API/types (ChatConfig/ChatResult/PerformanceMetrics);
prior per-model chat exports removed/renamed
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant