Repository navigation
Fix/package metadata vlm prefill chat template - #31
Conversation
…edup - Add license (MIT), repository, homepage, bugs to all 5 npm packages - Add detailed READMEs for @mlx-node/core, lm, vlm, trl, cli - Eliminate duplicate image processing in VLM prefill (process_many called once instead of twice per chat call) - Fix Jinja2 chat template always bypassed without tools — now used for all chats when template exists in tokenizer_config.json - Consolidate message sanitization into single sanitize_messages() step before template dispatch (prevents injection in all paths) - Extract shared vlm_prepare_vision_features() for vision cache + encoder + embedding merge + M-RoPE (eliminates ~80 lines duplication between dense/MoE) - Extract shared aggregate_processed_images() for process_many aggregation (eliminates duplication between PaddleOCR-VL and Qwen3.5 processors) - Remove unused _model_config parameter from vlm_prefill_moe - Pass image_cache_key (u64) instead of raw bytes into vlm_prefill functions - Clean up stale docs/, update README, LICENSE Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Qwen3 returned "stop" on EOS, Qwen3.5 Dense/MoE returned "eos", and the Qwen3 ts_return_type annotation said 'eos' while the code emitted "stop". Standardize all models to return "stop" (matching OpenAI API convention): - Qwen3: fix ts_return_type from 'eos' to 'stop' (code already correct) - Qwen3.5 Dense: change "eos" → "stop" in all generation paths - Qwen3.5 MoE: change "eos" → "stop" in all generation paths - training_generate: change "eos" → "stop" - Update comments in grpo/engine.rs, qwen3/generation.rs, qwen3/model.rs - Update TS comment in grpo-trainer.ts and fix hardcoded 'eos' literal - Regenerate index.d.cts with corrected type annotations Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
max_ngram_repeats doc said "default: 8" but code uses 3. ngram_size doc said "default: 3" but code uses 64. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1. GRPOLossConfig Default changed from "dapo" to "grpo" — the named type should match its own name. The engine already defaulted to "grpo" via GrpoEngineConfig, but Default::default() on the loss config silently produced DAPO dynamics. 2. SFT engine now exposes getQwen35Model() and getQwen35MoeModel() NAPI methods so the TS layer can retrieve trained Qwen3.5 models for checkpointing instead of falling back to the original pre-training model reference. 3. Remove dead MLXGRPOConfig TOML config system — it was never wired to GRPOTrainer, had stale defaults (Qwen2.5, fields like use_compile that don't exist in the trainer), and confused users with two competing config systems. SFT TOML config (sft-config.ts) is unaffected. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Three conflicting ChatMessage/ChatRole types existed:
- core ChatMessage had role: string (no type safety)
- core ChatRole enum had capitalized values ('User' not 'user')
- lm/trl ChatRole was a lowercase union type ('user' | 'assistant' | ...)
Fixed:
- core ChatMessage.role now typed as 'system'|'user'|'assistant'|'tool'|(string&{})
providing autocomplete while remaining backward-compatible with string
- core ChatRole enum values changed from 'User' to 'user', 'Assistant' to
'assistant', 'System' to 'system' via #[napi(value = "...")] annotations
- Added 'tool' variant to ChatRole enum (was missing)
- trl ChatMessage.role uses same union type as core for compatibility
- lm ChatRole type alias kept as single source of truth for the union
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…-unwind" Issue 18: vlm_get_cache returned a pointer into std::vector (non-heap). If wrapped in MxArray::from_handle, dropping it would call mlx_array_delete on a stack address — UB. Fixed by heap-allocating a copy via `new array(...)`. Added matching mlx_array_delete cleanup in Rust after compiled_init_from_prefill. Issue 19: C++ exceptions across extern "C" are formally UB. On macOS arm64, Rust and C++ share the Itanium ABI unwinding mechanism, so exceptions propagate safely through Rust frames to NAPI-RS catch_unwind boundaries. Changed all FFI declarations from extern "C" to extern "C-unwind" to make this formally correct — extern "C-unwind" explicitly permits unwinding across the language boundary. This applies to: - All 221 FFI function declarations in mlx-sys/src/lib.rs - All Rust callback functions passed to C++ (autograd, gradients, safetensors) No try/catch wrappers needed: the shared macOS ABI + extern "C-unwind" + NAPI-RS catch_unwind provide a complete safety chain from C++ throw to JS Error without any undefined behavior. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…sion 1. GGUF Q4_K/Q5_K/Q6_K conversion now errors instead of silently dropping tensors. Previously, unsupported tensor types were skipped with a warn!() log, producing broken models with missing weights and no user-visible error. Now returns a clear error naming the tensor and unsupported type. 2. Download progress: prints "[1/12] filename (size)..." before each file download so users see progress for multi-GB models. 3. HuggingFace cache moved from process.cwd()/.cache/huggingface to ~/.cache/huggingface (standard location). Added --cache-dir flag to both download-model and download-dataset for custom cache locations. 4. Dataset download de-GSM8K'd: env vars renamed from GSM8K_* to MLX_DATASET/MLX_DATASET_REVISION/MLX_DATASET_OUTPUT. Default output directory now derived from dataset name (data/<dataset-slug>) instead of hardcoded data/gsm8k. 5. Added --version/-v flag to CLI entry point, reading from package.json. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
GGUF read_string() and read_meta_array() now enforce a 256MB allocation limit. Previously, a crafted GGUF with a huge length field (up to 2^64) would attempt unbounded allocation, causing OOM crash. Replaced unwrap() calls in gguf.rs name mapping with if-let patterns, and in pickle.rs with indexed access / if-let. All four were logically unreachable (guarded by prior checks), but explicit handling is clearer for code review on untrusted file parsers. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
27: Replace `export *` from dataset and xml-parser with named exports.
SYSTEM_PROMPT, XML_COT_FORMAT, defaultPromptTemplate no longer leak
as public API from @mlx-node/trl.
28: Clarify _createChatStream export comment (needed by tests, not truly
internal — the underscore prefix already signals non-public).
29: Naming inconsistency (Qwen35Model vs GRPOTrainer) is intentional:
NAPI exports use Rust conventions, TS wrappers use TS conventions.
Not changed (would be breaking).
30: JsonSchemaReward docs updated to accurately describe brace-matching
behavior. Name kept for backward compatibility, but docs now say
"does NOT parse JSON or validate against a JSON Schema."
31: Remove non-functional EntropyFilteringConfig export and dead
grpo-entropy.ts file. The config was exported but never wired to
any training path.
32: Delete dead callbacks.rs (84-line placeholder with "future
enhancement" comments, never used by any module).
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
33: Profiling mutex — .lock().unwrap() replaced with .unwrap_or_else(|e|
e.into_inner()) to recover from poison instead of crashing Node.js.
Profiling is non-critical; a poisoned mutex should not take down the
process.
34: validate_data_shape — now checks for negative dimensions and uses
checked_mul to detect overflow before allocation. Previously, a
negative i64 dim would cast to a huge usize via wrapping.
35: DecodeProfiler TTFT — duration_since replaced with
saturating_duration_since to avoid panic if Instants are unexpectedly
ordered (returns Duration::ZERO instead).
36: Qwen3 get_parameters — three .expect() on RwLock read locks replaced
with .map_err()?. Return type changed from HashMap to Result<HashMap>.
All callers updated (production code uses ?, test code uses .unwrap()).
37: vision_cache.lock().unwrap() in vlm_prepare_vision_features replaced
with .lock().map_err()? to propagate error instead of panicking.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
38: Qwen3 max_new_tokens default raised from 100 to 2048, matching Qwen3.5.
Updated GenerationConfig::default(), all unwrap_or(100) call sites, and
the doc comment. 100 tokens was far too low for most use cases.
39: Removed silent top_k=20 injection in Qwen3.5 Dense and MoE chat/chatStream.
Previously, config.top_k.or(Some(20)) injected top_k=20 even when users
left it unset (expecting no top-k filtering). Now passes config.top_k
through directly — users who want top_k=20 can set it explicitly.
40: Added enable_thinking field to ChatConfig. Previously hardcoded to None
in all chat()/chatStream() calls, preventing users from controlling
Qwen3's <think> tag behavior. Now wired through to
apply_chat_template_sync in all three model variants (Qwen3, Qwen3.5
Dense, Qwen3.5 MoE).
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
41: SFT trainer now installs SIGTERM/SIGINT handlers that save an
emergency checkpoint before exit. Previously, interrupted SFT
training lost all progress since the last periodic checkpoint.
Mirrors the existing GRPO trainer signal handling.
42: GRPO engine no longer increments step counter on NaN skip.
Previously, all 3 train_step variants (trainStep, trainStepAuto,
trainStepWithGenerations) incremented state.step on NaN loss or
NaN gradient paths, causing step count drift vs actual training
progress. Now step only increments on successful gradient
application, matching SFT behavior.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The V2 paged attention kernel writes partitioned outputs in float16 (the I/O type), but tmp_out was allocated using dtype.size() which returns 1 byte for FP8 (UChar) cache mode instead of 2 bytes for float16. This caused a GPU buffer overrun when the Metal kernel wrote 2-byte float16 values into a 1-byte-per-element buffer. Fixed by using MetalDtype::Float16.size() (always 2 bytes) for tmp_out allocation, matching the actual kernel output type. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Replace "Phase 4"/"Phase 5" roadmap comments with neutral descriptions of current limitations. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Paged attention: command queue now created once in MetalState::init() and reused across all kernel dispatches. Previously, every dispatch (reshape_and_cache, paged_attention V1/V2, copy_blocks, swap_blocks) created a new command queue — an expensive Metal API call. - apply_sampling: when no filters are active (temperature=1, top_k=0, top_p=1, min_p=0), return a lazy clone instead of GPU copy. The previous logits.copy() triggered an unnecessary Metal copy kernel on every unfiltered sample call. - TextRecModel.recognize_batch: clarified that sequential processing is intentional (variable-width crops prevent true batching without padding). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- MoE decode loops now use synchronize_and_clear_cache() matching Dense. Previously MoE used weaker clear_cache() which skips synchronization, risking memory accumulation under sustained generation. - Removed MxArray, convertModel, convertParquetToJsonl re-exports from @mlx-node/trl. These belong in @mlx-node/core (where they originate). Re-exporting from the training package created multiple-package export confusion. Import from @mlx-node/core directly. Skipped (not worth the breaking change): - SFT snake_case vs GRPO camelCase config — established conventions - from_weight vs from_weights — intentional (singular vs multiple params) - eprintln! — 2 of 3 are debug_assertions only, 1 is intentional stderr - MxArray in @mlx-node/vlm — legitimately needed for vision pipeline users Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
SFT config now uses camelCase (TypeScript convention) matching GRPO: model_name → modelName, learning_rate → learningRate, batch_size → batchSize, num_epochs → numEpochs, etc. TOML config files and CLI overrides still accept snake_case — the loader converts via snakeToCamel() before matching config keys. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Enable declarationMap in root tsconfig so editors jump to .ts source instead of .d.ts stubs when navigating across packages. - Unpin @napi-rs/image from exact 1.12.0 to ^1.12.0 for patch updates. - Document formatToolResponse's Qwen3-specific XML format in comment. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…r → loadModel() Rename `loadPretrained` to `load` across all model classes (Rust NAPI + TS wrappers) for consistency with VLM/document models. Replace the `ModelLoader` class with a standalone `loadModel()` function that auto-detects architecture. Define shared `TrainableModel` type and typed `ModelType` union so trainers consume `loadModel()` instead of duplicating dispatch logic. Breaking changes: `ModelLoader` class removed, `loadPretrained` renamed to `load` on Qwen3Model, Qwen35Model, Qwen35MoeModel. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (2)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughRenames model-loading APIs (ModelLoader → loadModel, loadPretrained → load), migrates SFT config keys to camelCase, adds vision-feature caching and shared VLM prep, standardizes finish reasons ("eos" → "stop"), converts many Rust FFI callbacks to extern "C-unwind", removes GRPO config artifacts, and updates documentation and package metadata. Changes
Sequence Diagram(s)sequenceDiagram
participant App as JS App
participant LM as `@mlx-node/lm`
participant Core as `@mlx-node/core` (NAPI)
participant Rust as mlx-core (Rust)
participant VisionCache as VisionCache (Rust)
App->>LM: call loadModel(modelPath)
LM->>Core: forward load request (load or detectModelType)
Core->>Rust: NAPI -> spawn async load(modelPath)
Rust->>VisionCache: compute_image_cache_key(all_images?) / check cache
VisionCache-->>Rust: cache hit? / miss
alt cache miss
Rust->>VisionCache: vlm_prepare_vision_features(...) -> compute features
VisionCache-->>Rust: insert computed features
end
Rust-->>Core: return Model handle / Promise
Core-->>LM: resolved TrainableModel
LM-->>App: return model instance
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1573e53b86
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
Actionable comments posted: 15
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
crates/mlx-core/src/autograd.rs (2)
54-65:⚠️ Potential issue | 🟡 MinorDoc comment is now stale after ABI change.
The comment at lines 57-60 states "Any panics would cross FFI boundary which is UB", but
extern "C-unwind"now makes unwinding defined behavior. The comment should be updated to reflect this.📝 Suggested doc update
/// # Safety -/// This function is called from C++, so we must be careful with error handling. -/// Any panics would cross FFI boundary which is UB. +/// This function is called from C++. Uses C-unwind ABI so panics can safely +/// unwind across the FFI boundary when the C++ side is compiled with exceptions. extern "C-unwind" fn loss_function_callback(🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/autograd.rs` around lines 54 - 65, The doc comment for loss_function_callback is stale: update the safety note to reflect that the function uses extern "C-unwind" so unwinding across the FFI boundary is defined rather than UB; change the sentence about panics crossing FFI boundary and UB to explain that unwinding is supported under extern "C-unwind" and describe any remaining safety concerns (e.g., ensure C++ callers are prepared for Rust unwinds or prefer catching unwinds), keeping the reference to the function signature extern "C-unwind" fn loss_function_callback(...) and the requirement to handle errors safely when called from C++.
312-322:⚠️ Potential issue | 🟡 MinorAdd
[MLX]prefix logging to exception handling inmlx_checkpoint_apply's C++ callback wrapper.The C++ side does wrap the Rust callback invocation (
layer_fn) in try-catch, but re-throws the exception without logging. This diverges from the established pattern in other FFI functions (e.g.,mlx_stream.cpp,mlx_qwen35.cpp) which log caught exceptions to stderr with an[MLX]prefix before action. Update the exception handler in thelayer_wrapperlambda to log the error details before re-throwing.The build configuration supports exception handling (C++17, clang++, no
-fno-exceptionsflag), soextern "C-unwind"unwinding is properly supported.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/autograd.rs` around lines 312 - 322, The C++ callback wrapper inside mlx_checkpoint_apply's layer_wrapper lambda currently catches exceptions and rethrows them without logging; modify that catch block to write the exception details to stderr prefixed with "[MLX]" before rethrowing (use the caught std::exception::what() when available and a generic message for unknown exceptions), so that errors from invoking layer_fn are logged consistently with other FFI wrappers.__test__/models/qwen3.test.ts (1)
109-143:⚠️ Potential issue | 🟡 MinorUpdate the finish-reason assertion to match the new contract.
This block still allows
'eos', but the generation APIs in this PR now report EOS termination as'stop'. As written, the test will fail on valid EOS completions.💡 Suggested tweak
- expect(['eos', 'length']).toContain(result.finishReason); + expect(['stop', 'length']).toContain(result.finishReason);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@__test__/models/qwen3.test.ts` around lines 109 - 143, The test "should generate text from prompt (requires model files)" asserts allowed finish reasons using result.finishReason; update that assertion to match the new contract by replacing the allowed values array ['eos','length'] with ['stop','length'] so valid EOS completions (now reported as 'stop') pass; locate the assertion that calls expect(['eos', 'length']).toContain(result.finishReason) and change it accordingly in the block after model.generate(...) that verifies result properties.
🧹 Nitpick comments (5)
crates/mlx-core/src/array/creation.rs (1)
15-20: Consider usingusize::try_from()for defensive type safetyWhile the negative dimension check at line 9 ensures
d >= 0before the cast at line 15, usingusize::try_from(d)after the negativity check would be more explicit and aligns with defensive coding practices. This pattern is repeated throughout the codebase (e.g.,safetensors.rs:343,foreign_weights.rs:575), so this is a suggestion for consistency rather than a functional fix. Given that the codebase targets only 64-bit platforms where positivei64values always fit inusize, the practical risk is minimal.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/array/creation.rs` around lines 15 - 20, Replace the unchecked cast "d as usize" in the multiplication into a defensive conversion using usize::try_from(d) (after the existing d >= 0 check) so that the multiplication uses expected.checked_mul(usize::try_from(d)? ) with an explicit error mapped into the same Error::from_reason pattern; update the conversion in the same function (and mirror the same change at other similar sites) to match the safetensors.rs/foreign_weights.rs style for consistent defensive type handling.crates/mlx-core/src/utils/gguf.rs (1)
339-344: Consider element-size-aware bounds for array allocation.The check uses
MAX_GGUF_ALLOC(256M) as an element count limit, but for string arrays, each element can itself be up to 256 MB perread_string. This creates a theoretical worst-case of 256M × 256MB. For primitive arrays (u32, f32), this is overly conservative since actual memory islen × 4bytes.This is unlikely to be exploited in practice (string arrays of that size would time out), but for defense-in-depth you could scale the limit by element size.
🤖 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 339 - 344, The current check uses MAX_GGUF_ALLOC as an element-count limit regardless of element byte-size; instead compute a byte-budget and compare len * element_size against it. In the array-reading routine (the block using len and MAX_GGUF_ALLOC and where read_string is used), determine element_size: for primitives use std::mem::size_of::<T>() (e.g., 4 for u32/f32), and for string arrays use the known per-element max (e.g., 256 MiB as used by read_string). Then ensure len.checked_mul(element_size) is <= MAX_GGUF_ALLOC (or compute max_len = MAX_GGUF_ALLOC / element_size and check len <= max_len), handling checked arithmetic to avoid overflow and treating element_size == 0 defensively. Update the error message to report the computed byte request and the MAX_GGUF_ALLOC limit and keep using MAX_GGUF_ALLOC constant and read_string symbol references to locate the string-case logic.crates/mlx-core/src/models/paddleocr_vl/chat.rs (1)
169-199: Consider handling the newToolrole informat_vlm_chat.The
Toolvariant was added toChatRole, butformat_vlm_chatonly handlesUser,Assistant, andSystemroles. Tool messages are currently skipped (neither formatted nor errored).If tool responses should be included in VLM chat formatting, add handling logic. Otherwise, consider adding a comment clarifying that tool messages are intentionally unsupported for VLM chat templates.
🤖 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/chat.rs` around lines 169 - 199, format_vlm_chat currently ignores the new ChatRole::Tool variant, so tool messages are silently dropped; update the message-processing loop in format_vlm_chat to handle ChatRole::Tool explicitly—either add a branch that formats tool messages (e.g., prefix like "Tool: " then include content and appropriate image-placeholder behavior similar to User) if tool outputs belong in VLM templates, or add a clear comment and/or an explicit continue/placeholder branch for ChatRole::Tool to document intentional omission; reference the loop that checks msg.role and the enums ChatRole::Tool, ChatRole::User, and ChatRole::Assistant when making the change.crates/mlx-core/src/models/qwen3_5_moe/model.rs (1)
732-745: Whole-batch cache keys lose reuse in multi-image chats.
compute_image_cache_key(&all_images)turns the entire image list into one cache entry, so a later turn that reuses image A but adds image B will still miss and re-encode A. If the cache is meant to avoid re-encoding repeated images, cache per-image features (or update the cache/docs to reflect “same image set” semantics instead).Also applies to: 1285-1300
🤖 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 732 - 745, The code currently builds a single cache key with compute_image_cache_key(&all_images) which prevents reuse when image sets change; replace that with per-image cache keys (e.g., compute_image_cache_keys(&all_images) -> Vec<ImageCacheKey>) and use those keys when calling vlm_prefill_moe so previously encoded images can be reused. Update the compute_image_cache_key function into a per-image implementation (or add a new compute_image_cache_keys) and adjust all call sites (including the other occurrence around lines 1285-1300) and the vlm_prefill_moe signature/handling to accept per-image keys (or iterate and fetch/merge cached features) instead of a single combined key. Ensure token_history/final_tokens logic is unchanged and that the new per-image cache lookup/encoding preserves ordering and determinism.crates/mlx-core/src/models/qwen3/model.rs (1)
3676-3680: Silently returning 0 on error may mask issues during debugging.When
get_parameters()fails (e.g., lock poisoning), this returns 0 which causesWiredLimitContextto operate with incorrect memory estimates. While this won't crash, it could lead to suboptimal memory management that's hard to diagnose.Consider logging a warning when this fallback is triggered:
📝 Suggested improvement
pub fn calculate_memory_size(&self) -> usize { let params = match self.get_parameters() { Ok(p) => p, - Err(_) => return 0, + Err(e) => { + warn!("Failed to calculate memory size: {}", e); + return 0; + } }; params.values().map(|p| p.nbytes()).sum() }🤖 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 3676 - 3680, The match arm that handles get_parameters() failure currently swallows the error and returns 0; change it to capture the error (e.g., Err(e)) and emit a warning log with the error details and context (mentioning the function/method and that memory estimation fell back to 0) before returning 0 so failures like lock poisoning are visible; update the match in the code that calls self.get_parameters() (the block computing params.values().map(|p| p.nbytes()).sum()) to use a logging macro (e.g., tracing::warn! or log::warn!) and include e in the message.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@crates/mlx-core/src/grpo/rewards.rs`:
- Line 359: The doc comment incorrectly claims a "top-level" check while the
implementation merely searches for the string "field" anywhere in the extracted
JSON text; either remove "top-level" from the comment or change the
implementation to parse the JSON and check only the root object's keys. Update
the code that currently looks for the literal "field" substring to instead parse
with serde_json::from_str into a serde_json::Value and then verify each required
key exists in value.as_object().unwrap_or_default() (or update the comment above
the check to drop "top-level") so the behavior matches the wording; refer to the
literal "field" string and the block where required-field presence is tested
when making the change.
In `@crates/mlx-core/src/models/qwen3_5_moe/model.rs`:
- Around line 2555-2559: The error message returned when self.tokenizer is None
is misleading; instead of "Tokenizer not loaded - call load() first" update the
Error constructed in the tokenizer lookup (the ok_or_else call) to state that no
tokenizer was packaged/loaded (e.g. "Tokenizer not available; tokenization data
(tokenizer.json) was not found or not loaded") so callers know load() may have
succeeded without a tokenizer; keep reference to the same symbols
(self.tokenizer, load(), Error::from_reason and the subsequent
apply_chat_template_sync call) so the change is localized to the tokenizer
lookup error message.
In `@crates/mlx-core/src/models/qwen3/generation.rs`:
- Line 125: The inline comment for the struct field finish_reason currently
lists only "stop" and "length" while the public accessor exposes 'stop' |
'length' | 'repetition'; update the comment on pub(crate) finish_reason: String
(and the analogous comment at the other occurrence mentioned) to enumerate all
allowed values including "repetition" so docs match the exposed union and avoid
confusion for maintainers and API consumers.
In `@crates/mlx-core/src/tokenizer.rs`:
- Around line 542-558: The current call to sanitize_messages(&messages) runs for
both template and ChatML paths but rewrites roles to "user" and doesn't sanitize
non-content fields, which breaks template roles and allows raw tokens into
template context; change the call site so sanitize_messages is only used for the
ChatML fallback (keep the existing sanitize_messages ->
format_chatml_presanitized flow), and add a new sanitizer used before
render_chat_template_jinja2 (e.g., sanitize_messages_for_template or extend
render_chat_template_jinja2 to sanitize incoming context) that preserves
original message.roles and sanitizes every string field that will be passed into
the template (content, reasoning_content, tool_call_id, and each tool_calls[*]
string fields). Update the call in the code snippet to pass the original
messages (or a role-preserving sanitized copy) into render_chat_template_jinja2
and ensure render_chat_template_jinja2 receives only sanitized strings while
leaving roles intact.
In `@examples/grpo/train-github-tool.ts`:
- Line 82: The CLI usage/docs string still references qwen3-1.7b-mlx-bf16 while
the runtime default constant DEFAULT_MODEL_PATH was changed to
qwen3-0.8b-mlx-bf16; update the CLI/help text or any documented default model
name (the usage string near the top of train-github-tool.ts) to match the new
DEFAULT_MODEL_PATH value so docs and runtime default stay in sync.
In `@examples/lm.ts`:
- Line 9: The usage text in examples/lm.ts currently shows the flag "--image"
but the argument parser checks for "--ocr"; update the usage string to reference
"--ocr" so it matches the parser (or alternatively change the parser to accept
"--image"); locate the usage line that prints "oxnode examples/lm.ts
<model-name> [--image <path>]" and make it consistent with the flag handling
code that looks for "--ocr".
In `@packages/cli/src/cli.ts`:
- Line 3: The JSON import using "with { type: 'json' }" in
packages/cli/src/cli.ts (importing into symbol pkgJson) requires Node >=20.10;
either declare that runtime constraint by adding "engines": { "node": ">=20.10"
} to packages/cli/package.json, or replace the JSON import with a runtime-read
approach: read the ../package.json file (e.g., using fs.readFileSync and new
URL(import.meta.url) or fs.promises.readFile) and JSON.parse its contents, then
assign the result to pkgJson so the CLI works on older Node versions.
In `@packages/cli/src/commands/convert.ts`:
- Line 62: The mmproj argument is validated but only used when inputPath
endsWith('.gguf'), so when inputPath is a directory the mmproj is ignored;
update the convert flow to accept and forward mmproj for directory inputs by (1)
extending convertModel (and any callers) to accept an optional mmproj parameter,
(2) ensure the earlier mmproj validation (where mmproj is parsed) remains and
its value is passed into convertModel when inputPath is a directory, and (3)
keep convertGgufToSafetensors behavior unchanged (still accept mmproj) so both
convertGgufToSafetensors and convertModel honor mmproj consistently. Include
references to inputPath, convertGgufToSafetensors, convertModel, and mmproj when
making the changes.
In `@packages/core/README.md`:
- Around line 33-50: The fenced architecture block in the README is missing a
language tag which triggers MD040; update the triple-backtick fence around the
diagram in packages/core/README.md to include a language identifier (e.g.,
change ``` to ```text) so the block is treated as text by markdownlint and the
warning is resolved.
In `@packages/lm/README.md`:
- Around line 129-136: The README lists loadModel() under a "Classes" header
which is incorrect; update the documentation to separate functions and classes
(or rename the "Classes" heading to "API") so that loadModel() is presented
under a "Functions" or "API" section while keeping Qwen3Model, Qwen35Model, and
Qwen35MoeModel under "Classes"; edit the table and/or headings to reflect this
change and ensure loadModel() is described as a function (with its signature)
and the other three remain listed as classes.
In `@packages/lm/src/models/model-loader.ts`:
- Around line 35-47: The detectModelType function currently hides all errors
behind a generic "config.json not found" message; change its catch to only
convert ENOENT (file-not-found) into that friendly message while rethrowing
Unsupported model_type errors and preserving or wrapping any other errors with
their original message; specifically, in detectModelType (which reads
join(modelPath, 'config.json') and checks SUPPORTED_MODEL_TYPES), detect e.code
=== 'ENOENT' to throw the friendly not-found error, rethrow errors that start
with 'Unsupported model_type', and for any other error include the original
error.message (or the error itself) in the thrown Error so callers like
loadModel can see the real failure reason.
In `@packages/trl/src/index.ts`:
- Around line 11-15: The JSDoc example imports a non-exported symbol GRPOConfig,
which breaks the sample; remove GRPOConfig from the import list and update the
example to import only exported symbols (e.g., GRPOTrainer,
loadLocalGsm8kDataset) and keep the existing usage of GRPOTrainer.create (and
loadModel) so the snippet reflects actual exported API; update the example
import line and any references to GRPOConfig accordingly.
In `@packages/trl/src/trainers/sft-trainer.ts`:
- Around line 267-273: The logger is constructed in create() using
config.tuiMode before the class constructor applies the environment-based
tuiMode fallback, so console logging can remain enabled even when MLX_TUI_MODE
should disable it; update create() to derive the effective TUI mode the same way
the constructor does (use the same fallback logic for config.tuiMode /
MLX_TUI_MODE) and pass that computed boolean into createTrainingLogger (the
logger variable) instead of the raw config.tuiMode so createTrainingLogger/
logger respects the runtime TUI setting consistently.
- Around line 160-188: The signal handler currently installed by
setupSignalHandlers uses process.exit(0) and never detaches handlers, which can
prematurely terminate host applications and leak handlers across trainer
lifecycles; modify setupSignalHandlers to store references to the installed
callbacks (e.g., keep SIGTERM and SIGINT handler functions on the instance),
remove the hard call to process.exit(0) inside gracefulShutdown so it only sets
this.stopRequested and performs the emergency checkpoint logic, add a new
teardownSignalHandlers() method that removes the stored listeners via
process.off/removeListener and resets signalHandlersInstalled, and ensure
teardownSignalHandlers() is invoked from the end of train() cleanup so handlers
are detached when training finishes.
In `@packages/vlm/README.md`:
- Around line 58-75: The README's ASCII diagram fenced code block lacks a
language identifier; update the opening fence for that diagram from ``` to
```text (or ```plaintext) so linters/renderers recognize it as plain text—modify
the fenced block containing the diagram (the lines starting with "Input Image"
and the arrows) to use ```text as the opening fence.
---
Outside diff comments:
In `@__test__/models/qwen3.test.ts`:
- Around line 109-143: The test "should generate text from prompt (requires
model files)" asserts allowed finish reasons using result.finishReason; update
that assertion to match the new contract by replacing the allowed values array
['eos','length'] with ['stop','length'] so valid EOS completions (now reported
as 'stop') pass; locate the assertion that calls expect(['eos',
'length']).toContain(result.finishReason) and change it accordingly in the block
after model.generate(...) that verifies result properties.
In `@crates/mlx-core/src/autograd.rs`:
- Around line 54-65: The doc comment for loss_function_callback is stale: update
the safety note to reflect that the function uses extern "C-unwind" so unwinding
across the FFI boundary is defined rather than UB; change the sentence about
panics crossing FFI boundary and UB to explain that unwinding is supported under
extern "C-unwind" and describe any remaining safety concerns (e.g., ensure C++
callers are prepared for Rust unwinds or prefer catching unwinds), keeping the
reference to the function signature extern "C-unwind" fn
loss_function_callback(...) and the requirement to handle errors safely when
called from C++.
- Around line 312-322: The C++ callback wrapper inside mlx_checkpoint_apply's
layer_wrapper lambda currently catches exceptions and rethrows them without
logging; modify that catch block to write the exception details to stderr
prefixed with "[MLX]" before rethrowing (use the caught std::exception::what()
when available and a generic message for unknown exceptions), so that errors
from invoking layer_fn are logged consistently with other FFI wrappers.
---
Nitpick comments:
In `@crates/mlx-core/src/array/creation.rs`:
- Around line 15-20: Replace the unchecked cast "d as usize" in the
multiplication into a defensive conversion using usize::try_from(d) (after the
existing d >= 0 check) so that the multiplication uses
expected.checked_mul(usize::try_from(d)? ) with an explicit error mapped into
the same Error::from_reason pattern; update the conversion in the same function
(and mirror the same change at other similar sites) to match the
safetensors.rs/foreign_weights.rs style for consistent defensive type handling.
In `@crates/mlx-core/src/models/paddleocr_vl/chat.rs`:
- Around line 169-199: format_vlm_chat currently ignores the new ChatRole::Tool
variant, so tool messages are silently dropped; update the message-processing
loop in format_vlm_chat to handle ChatRole::Tool explicitly—either add a branch
that formats tool messages (e.g., prefix like "Tool: " then include content and
appropriate image-placeholder behavior similar to User) if tool outputs belong
in VLM templates, or add a clear comment and/or an explicit continue/placeholder
branch for ChatRole::Tool to document intentional omission; reference the loop
that checks msg.role and the enums ChatRole::Tool, ChatRole::User, and
ChatRole::Assistant when making the change.
In `@crates/mlx-core/src/models/qwen3_5_moe/model.rs`:
- Around line 732-745: The code currently builds a single cache key with
compute_image_cache_key(&all_images) which prevents reuse when image sets
change; replace that with per-image cache keys (e.g.,
compute_image_cache_keys(&all_images) -> Vec<ImageCacheKey>) and use those keys
when calling vlm_prefill_moe so previously encoded images can be reused. Update
the compute_image_cache_key function into a per-image implementation (or add a
new compute_image_cache_keys) and adjust all call sites (including the other
occurrence around lines 1285-1300) and the vlm_prefill_moe signature/handling to
accept per-image keys (or iterate and fetch/merge cached features) instead of a
single combined key. Ensure token_history/final_tokens logic is unchanged and
that the new per-image cache lookup/encoding preserves ordering and determinism.
In `@crates/mlx-core/src/models/qwen3/model.rs`:
- Around line 3676-3680: The match arm that handles get_parameters() failure
currently swallows the error and returns 0; change it to capture the error
(e.g., Err(e)) and emit a warning log with the error details and context
(mentioning the function/method and that memory estimation fell back to 0)
before returning 0 so failures like lock poisoning are visible; update the match
in the code that calls self.get_parameters() (the block computing
params.values().map(|p| p.nbytes()).sum()) to use a logging macro (e.g.,
tracing::warn! or log::warn!) and include e in the message.
In `@crates/mlx-core/src/utils/gguf.rs`:
- Around line 339-344: The current check uses MAX_GGUF_ALLOC as an element-count
limit regardless of element byte-size; instead compute a byte-budget and compare
len * element_size against it. In the array-reading routine (the block using len
and MAX_GGUF_ALLOC and where read_string is used), determine element_size: for
primitives use std::mem::size_of::<T>() (e.g., 4 for u32/f32), and for string
arrays use the known per-element max (e.g., 256 MiB as used by read_string).
Then ensure len.checked_mul(element_size) is <= MAX_GGUF_ALLOC (or compute
max_len = MAX_GGUF_ALLOC / element_size and check len <= max_len), handling
checked arithmetic to avoid overflow and treating element_size == 0 defensively.
Update the error message to report the computed byte request and the
MAX_GGUF_ALLOC limit and keep using MAX_GGUF_ALLOC constant and read_string
symbol references to locate the string-case logic.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: f7bbda6e-2e7f-4eae-90b1-68931ed4a368
⛔ Files ignored due to path filters (1)
yarn.lockis excluded by!**/yarn.lock,!**/*.lock
📒 Files selected for processing (104)
CLAUDE.mdLICENSEREADME.md__test__/models/qwen3-chat.test.ts__test__/models/qwen3-chunked-prefill.test.ts__test__/models/qwen3-generate-batch-parallel.test.ts__test__/models/qwen3-generate-batch.test.ts__test__/models/qwen3.test.ts__test__/models/speculative-decoding.test.ts__test__/tokenization/qwen3-tokenizer.test.ts__test__/trainers/grpo-config.test.ts__test__/trainers/sft-config.test.ts__test__/trainers/smoke_test.toml__test__/utils/dataset.test.tscrates/mlx-core/src/array/creation.rscrates/mlx-core/src/autograd.rscrates/mlx-core/src/decode_profiler.rscrates/mlx-core/src/gradients/mod.rscrates/mlx-core/src/grpo/callbacks.rscrates/mlx-core/src/grpo/engine.rscrates/mlx-core/src/grpo/loss.rscrates/mlx-core/src/grpo/mod.rscrates/mlx-core/src/grpo/rewards.rscrates/mlx-core/src/models/paddleocr_vl/chat.rscrates/mlx-core/src/models/paddleocr_vl/processing.rscrates/mlx-core/src/models/pp_text_rec/model.rscrates/mlx-core/src/models/qwen3/generation.rscrates/mlx-core/src/models/qwen3/model.rscrates/mlx-core/src/models/qwen3/persistence.rscrates/mlx-core/src/models/qwen3_5/model.rscrates/mlx-core/src/models/qwen3_5/persistence.rscrates/mlx-core/src/models/qwen3_5/processing.rscrates/mlx-core/src/models/qwen3_5/vision.rscrates/mlx-core/src/models/qwen3_5_moe/model.rscrates/mlx-core/src/models/qwen3_5_moe/persistence.rscrates/mlx-core/src/models/training_generate.rscrates/mlx-core/src/profiling.rscrates/mlx-core/src/sampling.rscrates/mlx-core/src/sft/engine.rscrates/mlx-core/src/tokenizer.rscrates/mlx-core/src/training_model.rscrates/mlx-core/src/utils/functional.rscrates/mlx-core/src/utils/gguf.rscrates/mlx-core/src/utils/pickle.rscrates/mlx-core/src/utils/safetensors.rscrates/mlx-paged-attn/Cargo.tomlcrates/mlx-paged-attn/src/metal/copy_blocks.rscrates/mlx-paged-attn/src/metal/paged_attention.rscrates/mlx-paged-attn/src/metal/reshape_and_cache.rscrates/mlx-paged-attn/src/metal/state.rscrates/mlx-paged-attn/src/metal/swap_blocks.rscrates/mlx-sys/src/lib.rscrates/mlx-sys/src/mlx_qwen35_vlm.cppdocs/AUTOGRAD_INTEGRATION.mddocs/DEVELOPMENT_HISTORY.mddocs/FEATURE_ALIGNMENT_SESSION.mddocs/PERFORMANCE_FIX.mddocs/PERFORMANCE_INVESTIGATION.mddocs/PERFORMANCE_OPTIMIZATIONS.mddocs/README.mddocs/SAFETENSORS_LOADER.mddocs/VLM_GUIDE.mddocs/causal-mask-bug-fix.mddocs/causal-mask-root-cause.mddocs/grpo/README.mddocs/grpo/algorithm.mddocs/grpo/architecture.mddocs/grpo/implementation-plan.mddocs/grpo/implementation-review.mdexamples/README.mdexamples/grpo/train-github-tool.tsexamples/lm.tsexamples/sft/sft-octokit.tsexamples/tool-use-example.tspackages/cli/README.mdpackages/cli/package.jsonpackages/cli/src/cli.tspackages/cli/src/commands/convert.tspackages/cli/src/commands/download-dataset.tspackages/cli/src/commands/download-model.tspackages/cli/tsconfig.jsonpackages/core/README.mdpackages/core/index.d.ctspackages/core/package.jsonpackages/lm/README.mdpackages/lm/package.jsonpackages/lm/src/index.tspackages/lm/src/interfaces.tspackages/lm/src/models/model-loader.tspackages/lm/src/stream.tspackages/lm/src/tools/types.tspackages/trl/README.mdpackages/trl/package.jsonpackages/trl/src/index.tspackages/trl/src/trainers/grpo-config.tspackages/trl/src/trainers/grpo-entropy.tspackages/trl/src/trainers/grpo-trainer.tspackages/trl/src/trainers/sft-config.tspackages/trl/src/trainers/sft-trainer.tspackages/trl/src/types.tspackages/vlm/README.mdpackages/vlm/package.jsonpackages/vlm/src/pipeline/structure-v3.tstsconfig.json
💤 Files with no reviewable changes (22)
- crates/mlx-core/src/grpo/mod.rs
- docs/causal-mask-root-cause.md
- docs/DEVELOPMENT_HISTORY.md
- docs/PERFORMANCE_INVESTIGATION.md
- crates/mlx-core/src/grpo/callbacks.rs
- docs/README.md
- docs/FEATURE_ALIGNMENT_SESSION.md
- docs/AUTOGRAD_INTEGRATION.md
- packages/trl/src/trainers/grpo-entropy.ts
- docs/grpo/architecture.md
- docs/grpo/algorithm.md
- docs/PERFORMANCE_FIX.md
- docs/VLM_GUIDE.md
- docs/grpo/implementation-plan.md
- test/trainers/smoke_test.toml
- docs/causal-mask-bug-fix.md
- docs/grpo/README.md
- docs/SAFETENSORS_LOADER.md
- docs/PERFORMANCE_OPTIMIZATIONS.md
- packages/trl/src/trainers/grpo-config.ts
- docs/grpo/implementation-review.md
- test/trainers/grpo-config.test.ts
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 3 potential issues.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
| reasoning_content: msg.reasoning_content.clone(), | ||
| images: None, | ||
| }) | ||
| .collect() |
There was a problem hiding this comment.
Sanitize drops images, breaking Jinja2 template rendering for VLM
Medium Severity
The sanitize_messages function hardcodes images: None for all messages. While the comment says "images are not cloned as they are not used in template formatting," the sanitized messages are passed to render_chat_template_jinja2 which serializes messages to JSON. If the Jinja2 template references image-related fields (e.g., for injecting image tokens), this could cause incorrect template output for VLM chat paths that go through the tokenizer's apply_chat_template_sync. The VLM models call apply_chat_template_sync which now sanitizes and drops images before Jinja2 rendering.
| let state = state_arc.read().map_err(|_| { | ||
| Error::new(Status::GenericFailure, "Failed to acquire state read lock") | ||
| })?; | ||
| state.step += 1; |
There was a problem hiding this comment.
Step not incremented on NaN loss skip changes metrics
Medium Severity
The NaN/invalid loss skip paths now use a read lock instead of a write lock and no longer increment state.step. While this may be intentional ("step NOT incremented on NaN skip"), it means the returned EngineStepMetrics.step reports the same step number repeatedly during consecutive NaN losses. Callers that use the step number for logging, checkpointing, or progress tracking may enter infinite loops or never advance if NaN losses persist.
Additional Locations (2)
There was a problem hiding this comment.
💡 Codex Review
mlx-node/packages/trl/src/trainers/sft-config.ts
Lines 193 to 196 in 06fa426
For callers that still pass the previous public field names like model_name or learning_rate directly in JS/TS, this loop now rejects or ignores them because only exact camelCase keys are accepted here. loadSFTTomlConfig() and applySFTOverrides() already call camelCase(...), so TOML/CLI inputs remain backward-compatible, but SFTTrainer.create()/new SFTTrainer(...) now either throw (modelName missing) or silently fall back to defaults for the other legacy fields. That makes the camelCase rename a breaking change for existing training scripts rather than just a type-level cleanup.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


Note
Medium Risk
Medium risk due to broad public API renames (
loadPretrained→load, finish reasoneos→stop, config key casing) and behavioral defaults (generation token limits, GRPO loss default) that can break downstream callers and alter training/inference outcomes.Overview
Standardizes the public inference/training APIs by renaming model loading to
load()/loadModel()(replacingloadPretrained/ModelLoader) across docs and tests, expanding chat config withenableThinking, and normalizing finish reasons to"stop"(was"eos"). SFT config expectations are updated to camelCase, and a GRPO config smoke test + fixture are removed.Hardens native code paths: adds overflow/negative-dimension checks when creating arrays, switches multiple FFI callbacks and
mlx-sysextern blocks to"C-unwind", makes decode TTFT timing use saturating duration, and avoids panics/poisoned-lock crashes in profiling and pickle handling. GGUF parsing is constrained to prevent oversized allocations and now errors on unsupported tensor types.Improves VLM/paged-attention internals by extracting shared image aggregation, refactoring Qwen3.5(-MoE) VLM prefill to reuse preprocessed images and a single computed vision cache key, and fixing cache pointer ownership (heap allocate + explicit delete) to avoid UAF/leaks. Metal paged-attention now reuses a global command queue and fixes a temporary buffer sizing bug for FP8 caches; sampling avoids unnecessary GPU copies when no filters are applied.
Written by Cursor Bugbot for commit 06fa426. This will update automatically on new commits. Configure here.
Summary by CodeRabbit
New Features
API Changes
Improvements
Documentation