Repository navigation
feat: add mlx-lm feature parity (chunked prefill, quantized KV cache,… - #11
Conversation
📝 WalkthroughWalkthroughAdds speculative decoding and chunked prefill to Qwen3, implements a quantized KV cache and quantization FFI, introduces batch optimizer APIs and KVCache trimming, removes XTC sampling, hardens tokenizer/chat template security, adds path-security utilities, enhances NaN/Inf detection, and updates many tests and public APIs. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Tokenizer
participant DraftModel as Draft Model
participant TargetModel as Target Model
participant KVCache
Client->>Tokenizer: tokenize(input)
Tokenizer-->>Client: input_ids
Client->>DraftModel: forward(input_ids)
DraftModel-->>Client: draft_tokens, draft_probs
Client->>TargetModel: forward(input_ids + draft_tokens)
TargetModel-->>Client: target_logits
Client->>Client: verify_draft_tokens(draft_tokens, draft_probs, target_logits)
alt all accepted
Client->>KVCache: append accepted tokens
else some rejected
Client->>Client: resample from adjusted target distribution
Client->>KVCache: rewind/trim caches (trim_kv_caches)
end
sequenceDiagram
participant Caller
participant GRPOTrainer
participant RewardFunction
participant TimeoutHandler
Caller->>GRPOTrainer: trainStepAuto(...)
GRPOTrainer->>TimeoutHandler: withTimeout(rewardFunction, rewardTimeout)
TimeoutHandler->>RewardFunction: execute()
alt within timeout
RewardFunction-->>TimeoutHandler: rewards
TimeoutHandler-->>GRPOTrainer: rewards
else timeout
TimeoutHandler-->>GRPOTrainer: RewardTimeoutError
GRPOTrainer->>GRPOTrainer: log and skip/handle batch
end
GRPOTrainer->>GRPOTrainer: apply rewards, update state, persist checkpoint if needed
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This PR adds significant feature parity with mlx-lm, including chunked prefill, quantized KV cache, and speculative decoding, along with critical performance fixes and security improvements.
Changes:
- Removed unnecessary eval()/synchronize() calls in C++ FFI that destroyed MLX's lazy evaluation (4x performance improvement: 37→140 tok/s)
- Added chunked prefill for long prompts with configurable chunk sizes (default 2048 tokens)
- Implemented quantized KV cache with 4-bit and 8-bit support (44-69% memory reduction)
- Added speculative decoding for 2-3x speedup with draft models
- Introduced path security utilities to prevent directory traversal attacks in dataset loading
- Fixed GRPO loss computation bugs (overflow handling, Dr.GRPO normalization)
- Enhanced tokenizer security with role validation and content sanitization
- Added batch optimizer updates to reduce FFI overhead
Reviewed changes
Copilot reviewed 59 out of 59 changed files in this pull request and generated 13 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/mlx-sys/src/mlx.cpp | Removed eval/sync calls, added quantization FFI, epsilon stability fixes |
| crates/mlx-sys/src/lib.rs | Added quantization FFI declarations |
| crates/mlx-core/src/models/qwen3/* | Added speculative decoding, parameter validation, chunked prefill |
| crates/mlx-core/src/transformer/* | Added quantized KV cache, trim operation for speculative decoding |
| crates/mlx-core/src/grpo/loss.rs | Fixed overflow handling, corrected Dr.GRPO normalization |
| crates/mlx-core/src/tokenizer.rs | Added security documentation, role validation, content sanitization |
| crates/mlx-core/src/optimizers/* | Added batch update methods, optimizer state get/set for checkpointing |
| packages/trl/src/utils/path-security.ts | New path traversal protection utilities |
| packages/trl/src/data/* | Integrated path security, special token ID derivation |
| test/* | Comprehensive new test suites for all features |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.
There was a problem hiding this comment.
Actionable comments posted: 15
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (6)
examples/test-mlx-lm-speed.py (1)
16-19:⚠️ Potential issue | 🟡 MinorUpdate setup instructions to match the new model path.
The
MODEL_PATHon line 36 now referencesqwen3-1.7b-mlx-bf16, but the setup instructions in the docstring still reference the oldQwen3-0.6B-Instructmodel andqwen3-0.6b-mlx-bf16path. This inconsistency will cause the script to fail for users following the documented setup.📝 Proposed fix to align documentation with code
Setup: # Convert HuggingFace model to MLX format (if not already done) python -m mlx_lm.convert \ - --hf-path Qwen/Qwen3-0.6B-Instruct \ - --mlx-path .cache/models/qwen3-0.6b-mlx-bf16 \ + --hf-path Qwen/Qwen3-1.7B \ + --mlx-path .cache/models/qwen3-1.7b-mlx-bf16 \ --dtype float32Also applies to: 36-36
crates/mlx-core/src/optimizers/adam.rs (1)
117-130:⚠️ Potential issue | 🟠 MajorVerify step counter increment behavior in batch updates.
The
stepcounter is incremented insideupdate_single_internal(line 130), meaning a batch update with N parameters will incrementstepN times. This differs from typical Adam implementations where step increments once per optimizer step (regardless of parameter count).If bias correction is enabled, this will produce incorrect correction factors. Consider incrementing step once in
update_batchrather than per-parameter.🐛 Proposed fix to increment step once per batch
pub fn update_batch( &mut self, param_names: Vec<String>, params: Vec<&MxArray>, grads: Vec<&MxArray>, ) -> Result<Vec<MxArray>> { if param_names.len() != params.len() || params.len() != grads.len() { return Err(Error::new( Status::InvalidArg, format!( "Mismatched lengths: {} names, {} params, {} grads", param_names.len(), params.len(), grads.len() ), )); } + // Increment step once for the entire batch + self.step += 1; + let mut updated_params = Vec::with_capacity(params.len()); for ((name, param), grad) in param_names .into_iter() .zip(params.into_iter()) .zip(grads.into_iter()) { - let updated = self.update_single_internal(name, param, grad)?; + let updated = self.update_single_internal_no_step(name, param, grad)?; updated_params.push(updated); } Ok(updated_params) }This requires splitting
update_single_internalinto two variants or adding a flag to control step increment.packages/trl/src/trainers/grpo-trainer.ts (1)
567-573:⚠️ Potential issue | 🟠 MajorMark graceful-shutdown checkpoints as emergency.
saveCheckpoint()now treats non-emergency saves as “last known good.” The signal handler calls it without{ isEmergency: true }, so a crash snapshot can overwrite the last-good checkpoint and undermine recovery.🔧 Proposed fix
- await this.saveCheckpoint(`emergency-${this.currentStep}`); + await this.saveCheckpoint(`emergency-${this.currentStep}`, { isEmergency: true });crates/mlx-core/src/transformer/mod.rs (1)
21-39:⚠️ Potential issue | 🟠 MajorAdd
#[napi]annotations toUnifiedKVCacheandcreate_unified_caches.The
QuantizedKVCacheandQuantizedKVCacheConfigexports are correctly annotated, butUnifiedKVCache(enum at line 389) andcreate_unified_caches(function at line 458) lack#[napi]annotations. Since both are publicly re-exported in mod.rs, they must be annotated for proper Node.js bindings and TypeScript type generation.crates/mlx-core/src/tokenizer.rs (1)
495-510:⚠️ Potential issue | 🟠 MajorChat templates are skipped when tools are absent.
The current guard requires
tools.is_some()and a template, so a tokenizer_config template is ignored for normal chats. Render the template whenever it exists, passingtoolsasNonewhen unavailable.✅ Suggested fix
- let formatted = if tools.is_some() - && let Some(chat_template) = chat_template + let formatted = if let Some(chat_template) = chat_template { Self::render_chat_template_jinja2( &chat_template, &messages, tools.as_deref(), add_prompt, enable_thinking, ) .map_err(Error::from_reason)? } else { // Fallback to simple ChatML for backward compatibility Self::format_chatml(&messages, add_prompt) };- let formatted = if tools.is_some() - && let Some(chat_template) = &self.chat_template + let formatted = if let Some(chat_template) = &self.chat_template { Self::render_chat_template_jinja2( chat_template, messages, tools, add_prompt, enable_thinking, ) .map_err(Error::from_reason)? } else { // Fallback to simple ChatML for backward compatibility Self::format_chatml(messages, add_prompt) };Also applies to: 938-952
packages/trl/src/data/sft-dataset.ts (1)
323-352:⚠️ Potential issue | 🟡 MinorHandle missing
"assistant"token ID explicitly.
tokenToId('assistant')can returnnull; without a guard, assistant spans are never detected and labels remain masked. Consider failing fast with a clear error.✅ Suggested fix
// Get "assistant" token ID (it's a single token in Qwen3) const assistantTokenId = this.tokenizer.tokenToId('assistant'); + if (assistantTokenId === null) { + throw new Error('Tokenizer is missing the "assistant" token needed for ChatML masking.'); + }
🤖 Fix all issues with AI agents
In `@__test__/core/numerical-consistency.test.ts`:
- Around line 395-527: The test uses a brittle hard timing assertion
(expect(elapsed).toBeLessThan(100)) in the "should work on large arrays
efficiently" case which will fail on slower CI/GPU; update that test (the one
that creates size/ data, calls hasNanOrInf(x), and measures start/elapsed) to
avoid strict wall-clock checks—either remove the
expect(elapsed).toBeLessThan(100) assertion, replace it with a relaxed/gated
check (e.g., a much higher threshold like 1000ms) or guard it behind an env flag
(e.g., only assert fast timing when process.env.PERF_TESTS is set), and keep the
functional assertion expect(result).toBe(true) intact.
In `@__test__/transformer/quantized-kv-cache.test.ts`:
- Around line 78-100: The current try/catch around cache.updateAndFetch swallows
all errors; change it to only swallow/retry when the thrown error clearly
indicates quantization is unsupported (e.g., message includes "not supported" or
a specific QuantizationError type) and rethrow any other errors so regressions
aren't hidden; update the block that calls cache.updateAndFetch (and the
analogous try/catch blocks in this test file) to inspect e.message or e.name and
only log+skip for the explicit unsupported case, otherwise throw e.
In `@crates/mlx-core/src/models/qwen3/model.rs`:
- Around line 2064-2078: The speculative decoding path currently applies
repetition_penalty only to the initial logits (see repetition_penalty and
apply_repetition_penalty usage) but not to the subsequent draft or verification
logits sampled via sample_and_logprobs (first_token_result and the draft/verify
sampling blocks), causing divergence from generate() when repetition_penalty !=
1.0; fix by invoking apply_repetition_penalty on the draft logits before calling
sample_and_logprobs for the draft step and again on the verification logits
before acceptance/resampling so both draft sampling and verification resampling
honor repetition_penalty (or alternatively document that repetition_penalty is
intentionally ignored in speculative steps).
- Around line 2158-2173: The draft_probs are computed from a plain temperature
softmax (scaled_logits + Activations::softmax) but sampling uses sample(...)
with sampling_config (top_k/top_p/min_p and special handling for
temperature==0), so the two distributions diverge; update the code so the same
sampling filters are applied to draft_last_logits before calling
Activations::softmax (or alternatively compute per-token logprobs under the
actual sampling distribution). Concretely, reuse the same preprocessing that
sample(&draft_last_logits, Some(sampling_config)) uses (or extract that logic
into a helper) to produce filtered_logits, then call
Activations::softmax(&filtered_logits, Some(-1)) and push that into draft_probs
so draft_probs matches the sampling distribution used by sample; keep uses of
draft_current_token, draft_tokens, sampling_config, scaled_logits and sample
consistent.
- Around line 2218-2222: The verification logits slice drops the prediction for
the first draft token by starting at position 1; update the logic around
target_logits and verification_logits so the slice begins at position 0 (i.e.,
include the logits that predict the first draft token) and handle the final
"bonus" logit separately (retain any trailing logits into a separate variable if
needed) to keep draft-token-to-logit alignment; locate the code that defines
verification_logits (the slice on target_logits and the use of
verify_seq_len/vocab_size) and adjust the slice indices and downstream uses
accordingly.
- Around line 1871-1891: The function generate_speculative_sync is currently
declared pub but is only invoked internally by the N-API wrapper
generate_speculative_sync_napi; change its visibility to pub(crate) so it's
internal to the crate (update the signature of the generate_speculative_sync
method accordingly) to reflect it is not part of the public API while leaving
generate_speculative_sync_napi public for external use.
In `@crates/mlx-core/src/models/qwen3/speculative.rs`:
- Around line 171-270: The code currently increments num_accepted for
resampled/final tokens causing VerificationResult.num_accepted to reflect
accepted_tokens.len() (which may include the extra final token); change the
logic so num_accepted counts only accepted draft tokens: remove the num_accepted
+= 1 in the resample/rejection branch and do not increment num_accepted when
pushing the "bonus" final token (the block that samples when num_accepted ==
num_draft), ensure num_accepted is incremented only where draft tokens from the
loop are accepted, and set VerificationResult.num_accepted = num_accepted (use
the existing num_accepted variable instead of accepted_tokens.len()) so cache
trimming relies on the draft-only count.
- Around line 108-145: Before the loop, validate shapes and bounds to avoid
panics: ensure draft_tokens.len() == num_draft and draft_probs.len() ==
num_draft, assert target_logits.shape_at(0)? == num_draft and set vocab_size
from target_logits.shape_at(1)?; then inside the per-token loop check
draft_token as usize < vocab_size and that target_probs_data.len() >= (i *
vocab_size + draft_token as usize) and that draft_probs[i] exists and its
flattened length > draft_token as usize; return a proper error (using ?/Err)
instead of letting indexing panic. Reference the variables draft_tokens,
draft_probs, target_logits, target_probs_data, target_logprobs_data, draft_token
and vocab_size when adding these guards.
In `@crates/mlx-core/src/optimizers/adamw.rs`:
- Around line 76-119: The batch updater update_batch is causing the optimizer
step to increment multiple times because update_single_internal increments the
internal step counter; change the logic so a single step increment happens per
batch: remove or disable per-call step increments inside update_single_internal
(or add a boolean parameter like increment_step) and instead increment self.step
exactly once in update_batch after processing all parameters; update references
in update_single_internal (and any bias-correction math) to use the
passed-in/current step value rather than mutating it per-item so bias correction
is computed using the correct single-step count.
In `@crates/mlx-core/src/transformer/quantized_kv_cache.rs`:
- Around line 171-213: The current update uses MxArray::concatenate on each
update (seen in the concatenation of keys_quantized, values_quantized, k_scales,
k_biases, v_scales, v_biases), which causes O(N²) reallocations; change
update_and_fetch to pre-allocate capacity and write in-place. Specifically, when
first initializing allocate buffers with the full sequence-capacity (use the
same shape/step logic as kv_cache.rs), store that as
keys_quantized/values_quantized/k_scales/k_biases/v_scales/v_biases, and on
subsequent updates avoid MxArray::concatenate: compute the destination slice
using the current self.offset and seq_len and call slice_assign_axis_inplace (or
equivalent) to copy k_quant/v_quant/k_scales/... into the preallocated arrays at
axis 2; update self.offset accordingly and only reallocate if capacity exceeded.
Ensure you reference and reuse the same axis (axis 2) and the fields
keys_quantized, values_quantized, k_scales, k_biases, v_scales, v_biases when
implementing this change.
In `@crates/mlx-sys/src/mlx.cpp`:
- Around line 4400-4436: The docstring for mlx_dequantize incorrectly lists
out_dtype values 5 and 6 (bfloat16/float16) which to_mlx_dtype does not handle;
update the comment to match BridgeDType mappings actually accepted by
to_mlx_dtype (e.g., 0=float32, 1=float64, 2=int32, 3=... or whatever the
BridgeDType enum defines) or explicitly note that only BridgeDType values
recognized by to_mlx_dtype are valid; ensure the mlx_dequantize param
description for out_dtype mentions that unrecognized values default to input
dtype/float32 and reference the to_mlx_dtype conversion and BridgeDType enum to
avoid silent dtype changes.
In `@packages/core/index.d.cts`:
- Around line 783-797: The trim(newLen: number) doc is ambiguous about
out-of-range values; update the JSDoc for the trim method to explicitly state
that negative newLen values are clamped to 0 and that newLen values greater than
the current offset are treated as a no-op (i.e., the cache is unchanged), and
keep the existing note that this only updates the internal offset and does not
deallocate memory; reference the method name trim(newLen: number) and "current
offset" when adding these explicit behaviors.
In `@packages/trl/src/data/dataset.ts`:
- Around line 95-108: The current resolveBasePath uses DEFAULT_BASE_PATH
(process.cwd() + '/data/gsm8k') which may lie outside a custom allowedRoot;
update resolveBasePath to, when optionPath is undefined, construct the default
base inside the allowedRoot (e.g., join allowedRoot with the relative default
segment like 'data/gsm8k'), then validate that constructed path with
validatePathContainment and return it; keep existing logic for when optionPath
is provided (use resolvePath and validatePathContainment). Ensure you reference
resolveBasePath, DEFAULT_BASE_PATH, getAllowedRoot, validatePathContainment, and
resolvePath when making the change.
In `@packages/trl/src/trainers/grpo-trainer.ts`:
- Around line 355-369: computeDatasetHash currently only hashes ex.prompt so
metadata/labels changes are ignored; update computeDatasetHash (and the content
construction) to include relevant fields from DatasetExample (e.g., metadata,
label, expectedAnswer) when building the fingerprint—simplest fix: stringify the
entire example (JSON.stringify(ex)) or build a stable concatenation of prompt +
metadata + label before hashing, keeping sampleSize behavior and returning the
same 16-char hex digest.
In `@packages/trl/src/utils/path-security.ts`:
- Around line 31-55: validatePathContainment and resolveAndValidatePath must
resolve allowedRoot to an absolute path and use a robust traversal check: in
resolveAndValidatePath, call resolvePath/resolve on allowedRoot (not just
resolvedPath) so both resolvedPath and allowedRoot are absolute; in
validatePathContainment, compute relative = relative(absAllowedRoot,
absResolvedPath) and consider the path escaped only if relative === ''? no —
instead detect traversal by splitting the relative using path.sep and checking
if the first path segment is exactly '..' or any segment equals '..' (or if
isAbsolute(relative) is true); throw PathTraversalError(resolvedPath,
allowedRoot) when that condition is met. Update references to
validatePathContainment, resolveAndValidatePath and PathTraversalError
accordingly.
🧹 Nitpick comments (13)
crates/mlx-core/src/stream.rs (1)
149-158: Consider logging when Metal device info is unavailable.Returning a no‑op context is safe, but a warning would make Metal init failures easier to diagnose in the field.
🔧 Suggested change
if device_info_ptr.is_null() { + tracing::warn!( + "[wired_limit] Metal device info unavailable; skipping wired limit adjustment." + ); return Self { old_limit: 0, streams: Vec::new(), }; }examples/test-converted-model.ts (1)
12-12: Consider making the model path configurable.For improved flexibility and reusability, the model path could be read from an environment variable or CLI argument.
💡 Optional: Make path configurable
-const MODEL_PATH = resolve(process.cwd(), '.cache', 'models', 'qwen3-1.7b-mlx-bf16'); +const MODEL_PATH = resolve( + process.cwd(), + process.env.MLX_MODEL_PATH ?? '.cache/models/qwen3-1.7b-mlx-bf16' +);packages/trl/src/trainers/grpo-trainer.ts (1)
253-279: Prefer TypedArrays for processed-batch tracking.
processedBatchIndicesand its serialized form useSet<number>/number[]. To align with the TypedArray-first guideline, consider aUint8Arraybitmap orInt32Arraystorage and convert to a plain array only at JSON serialization boundaries.As per coding guidelines: Use TypedArrays (Float32Array, Int32Array, BigInt64Array) for all array data and shape handling instead of JavaScript objects.
Also applies to: 456-459, 1613-1647, 1828-1839
__test__/models/speculative-decoding.test.ts (1)
8-11: Use@mlx-node/trlre-exports instead of@mlx-node/core.
Tests should exercise the public surface;@mlx-node/coreis internal.As per coding guidelines: Re-export APIs cleanly through index.ts files; users should import from
@mlx-node/lmor@mlx-node/trl, never directly from@mlx-node/corewhich is internal.🔧 Suggested change
-import { MxArray, KVCache } from '@mlx-node/core'; +import { MxArray, KVCache } from '@mlx-node/trl';__test__/core/optimizers.test.ts (2)
1-3: Use public entrypoints instead of importing from@mlx-node/core.These tests currently import optimizers/utilities from the internal package. Please re-export these symbols from
@mlx-node/trl(or@mlx-node/lm) and switch the import so tests exercise the public API surface.♻️ Suggested update (after re-exporting from a public package)
-import { Adam, AdamW, SGD, RMSprop, GradientUtils, LRScheduler } from '@mlx-node/core'; +import { Adam, AdamW, SGD, RMSprop, GradientUtils, LRScheduler } from '@mlx-node/trl';As per coding guidelines,
**/*.ts: Re-export APIs cleanly through index.ts files; users should import from@mlx-node/lmor@mlx-node/trl, never directly from@mlx-node/corewhich is internal.
464-469: Batch update assertions only sample elements—compare full tensors.Right now only a subset of indices are checked, which can miss mismatches in other positions. Consider comparing entire Float32Array outputs (and reuse the helper for the other batch-update tests).
✅ More complete comparison
- expect(batchResults[0].toFloat32()[0]).toBeCloseTo(single1.toFloat32()[0], 5); - expect(batchResults[0].toFloat32()[1]).toBeCloseTo(single1.toFloat32()[1], 5); - expect(batchResults[1].toFloat32()[0]).toBeCloseTo(single2.toFloat32()[0], 5); - expect(batchResults[2].toFloat32()[0]).toBeCloseTo(single3.toFloat32()[0], 5); + const expectArrayClose = (a: Float32Array, b: Float32Array) => { + expect(a.length).toBe(b.length); + for (let i = 0; i < a.length; i++) expect(a[i]).toBeCloseTo(b[i], 5); + }; + expectArrayClose(batchResults[0].toFloat32(), single1.toFloat32()); + expectArrayClose(batchResults[1].toFloat32(), single2.toFloat32()); + expectArrayClose(batchResults[2].toFloat32(), single3.toFloat32());__test__/models/qwen3-chunked-prefill.test.ts (1)
1-3: Prefer public@mlx-node/lm/@mlx-node/trl entrypoints for model APIs.This test imports Qwen3Model/Qwen3Tokenizer from the internal
@mlx-node/corepackage. Please re-export these symbols from@mlx-node/lm(preferred for model APIs) and update the import to keep tests aligned with the supported public surface.♻️ Suggested update (after re-exporting from `@mlx-node/lm`)
-import { Qwen3Model, MxArray, Qwen3Tokenizer, type ChatMessage } from '@mlx-node/core'; +import { Qwen3Model, MxArray, Qwen3Tokenizer, type ChatMessage } from '@mlx-node/lm';As per coding guidelines,
**/*.ts: Re-export APIs cleanly through index.ts files; users should import from@mlx-node/lmor@mlx-node/trl, never directly from@mlx-node/corewhich is internal.__test__/core/optimizers-extended.test.ts (1)
1-3: Use public entrypoints instead of importing from@mlx-node/core.These tests should exercise the public API surface. Please re-export the optimizer classes from
@mlx-node/trl(or@mlx-node/lm) and update this import accordingly.♻️ Suggested update (after re-exporting from a public package)
-import { MxArray, Adam, AdamW, SGD, RMSprop, GradientUtils } from '@mlx-node/core'; +import { MxArray, Adam, AdamW, SGD, RMSprop, GradientUtils } from '@mlx-node/trl';As per coding guidelines,
**/*.ts: Re-export APIs cleanly through index.ts files; users should import from@mlx-node/lmor@mlx-node/trl, never directly from@mlx-node/corewhich is internal.__test__/trainers/grpo-reward-timeout.test.ts (1)
55-63: Avoid invoking the slow reward function twice in the timeout test.Calling
scoreGenerationstwice spins up two slow reward executions. Capture the error once and assert both the type and message to keep the test faster and avoid extra timers.✅ Single-call assertion
- // Should throw RewardTimeoutError - await expect(trainer.scoreGenerations(promptMessages, genResult.completionTexts, [null], 2)).rejects.toThrow( - RewardTimeoutError, - ); - - // Verify error message contains timeout info - await expect(trainer.scoreGenerations(promptMessages, genResult.completionTexts, [null], 2)).rejects.toThrow( - /timed out after 100ms/, - ); + let err: unknown = null; + try { + await trainer.scoreGenerations(promptMessages, genResult.completionTexts, [null], 2); + } catch (e) { + err = e; + } + expect(err).toBeInstanceOf(RewardTimeoutError); + expect((err as Error).message).toMatch(/timed out after 100ms/);crates/mlx-core/src/tokenizer.rs (1)
640-830: Cache compiled Jinja2 templates to avoid per-call parsing.
Environmentcreation + template parsing on every call can become a hot‑path cost. Consider caching a compiled template/Environment inQwen3Tokenizer(e.g.,OnceCell<Environment>orArc<Template>) and reusing it across calls.
Based on learnings Integrate HuggingFace tokenizers with Jinja2 template support for chat formatting; pre-compile templates and cache tokenizers for performance.crates/mlx-core/src/models/qwen3/speculative.rs (1)
70-107: Public speculative helpers should be NAPI‑exported or crate‑private.These items are
pubbut lack#[napi]. If they’re intended for JS bindings, add the macro (and JS‑friendly types); otherwise considerpub(crate)to avoid exposing an unsupported API surface.
As per coding guidelines Export all public operations using #[napi] attribute for seamless Node.js bindings with TypeScript type generation.crates/mlx-core/src/transformer/quantized_kv_cache.rs (2)
269-355: Wrapmlx_quantize/dequantizebehind safe MxArray helpers.Calling raw
sys::mlx_*inmlx-corewidens the unsafe surface area. Consider adding safe wrappers in the array module and using them here to keep FFI access centralized.
Based on learnings Use type-safe wrappers for array operations, avoiding raw FFI calls outside of mlx-sys; leverage MLX's lazy evaluation for operation fusion.
389-462: Public UnifiedKVCache/create_unified_caches should be NAPI‑exported or crate‑private.They’re
pubbut lack#[napi]. If they’re meant for JS consumption, add#[napi]with JS‑friendly types; otherwise considerpub(crate)to avoid leaking internal API.
As per coding guidelines Export all public operations using #[napi] attribute for seamless Node.js bindings with TypeScript type generation.
… speculative decoding) - Remove unnecessary eval()/synchronize() calls in C++ FFI that were destroying MLX's lazy evaluation pipeline (4x performance regression fix: 37 → 140 tok/s) - Align periodic cleanup interval to 256 tokens (matching mlx-lm) - Process long prompts in configurable chunks (default: 2048 tokens) - Reduces peak memory usage for long sequences - Enables async pipelining during prefill - New config: `prefillStepSize` - 4-bit and 8-bit cache compression via group-wise affine quantization - Memory reduction: 44% (8-bit) to 69% (4-bit) - New FFI: mlx_quantize(), mlx_dequantize() - New config: `kvCacheBits`, `kvCacheGroupSize` - Draft model acceleration for 2-3x speedup - Rejection sampling acceptance criterion (more correct than exact comparison) - KV cache trimming for rejected tokens - New method: generateSpeculativeSync() - New config: `numDraftTokens` - loadParameters now throws when use_qk_norm=true but QK norm weights missing - Fix clippy warning in quantized_kv_cache.rs (unnecessary_unwrap) - New test suites: chunked-prefill, quantized-kv-cache, speculative-decoding, qwen3-parameter-validation Co-Authored-By: Claude Opus 4.5 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
crates/mlx-core/src/grpo/engine.rs (1)
1328-1328:⚠️ Potential issue | 🟡 MinorInconsistent threshold comparison:
>vs>=across methods.This line uses
>(greater than) while Line 696 intrain_stepuses>=(greater than or equal) for the same check. Both occur after incrementingnan_gradient_count, causing different stopping behavior:
train_step: stops when count reachesmax_nan_gradientstrain_step_with_generations: stops when count exceedsmax_nan_gradients(allows one extra NaN)🔧 Suggested fix for consistency
- if state.nan_gradient_count > max_nan { + if state.nan_gradient_count >= max_nan {
🤖 Fix all issues with AI agents
In `@crates/mlx-core/src/models/qwen3/model.rs`:
- Around line 2270-2291: The code advances target_cache_idx and draft_cache_idx
to include the current_token, but verify_input expects cache indices pointing to
the position before current_token; adjust the indices by subtracting 1 to
exclude current_token: compute new_target_cache_len as before but set
target_cache_idx = new_target_cache_len - 1 and draft_cache_idx =
new_target_cache_len - 1 (ensure non-negative), update target_rope_offsets and
draft_rope_offsets from those adjusted indices, and when computing
rejection_point from draft_start_cache_idx + verification_result.num_accepted
ensure that it also references the position before the next current_token (e.g.,
rejection_point = draft_start_cache_idx + accepted_count - 1) before calling
trim_kv_caches (and guard against underflow).
In `@crates/mlx-core/src/tools/mod.rs`:
- Around line 210-226: The string-encoded arguments branch should sanitize the
string before parsing: when matching Value::String(s) call
sanitize_json_string(s) to produce a sanitized string, then run
serde_json::from_str::<Value>(&sanitized) and on success return
ToolCallResult::ok(name, parsed_args, raw_content.to_string()); on failure
return ToolCallResult::parse_error(name, sanitized.clone(), format!("Failed to
parse arguments string as JSON: {}", e), raw_content.to_string()). This keeps
parsing consistent with the outer JSON sanitization and references the
Value::String(s) match arm and ToolCallResult::ok/parse_error call sites.
🧹 Nitpick comments (14)
examples/test-converted-model.ts (1)
12-12: Consider making MODEL_PATH configurable for easier testing.For improved flexibility, the model path could accept an environment variable or command-line argument fallback. This would make the example easier to use with different models without editing the source.
💡 Optional enhancement
-const MODEL_PATH = resolve(process.cwd(), '.cache', 'models', 'qwen3-1.7b-mlx-bf16'); +const MODEL_PATH = process.env.MODEL_PATH + ?? process.argv[2] + ?? resolve(process.cwd(), '.cache', 'models', 'qwen3-1.7b-mlx-bf16');__test__/trainers/grpo-reward-timeout.test.ts (1)
55-63: Consider consolidating duplicate async calls for efficiency.The test makes two separate
scoreGenerationscalls, each triggering a full timeout cycle (totaling ~200ms minimum wait). Consider using a single try/catch block to verify both the error type and message:♻️ Suggested refactor
- // Should throw RewardTimeoutError - await expect(trainer.scoreGenerations(promptMessages, genResult.completionTexts, [null], 2)).rejects.toThrow( - RewardTimeoutError, - ); - - // Verify error message contains timeout info - await expect(trainer.scoreGenerations(promptMessages, genResult.completionTexts, [null], 2)).rejects.toThrow( - /timed out after 100ms/, - ); + // Should throw RewardTimeoutError with timeout info in message + try { + await trainer.scoreGenerations(promptMessages, genResult.completionTexts, [null], 2); + expect.fail('Should have thrown RewardTimeoutError'); + } catch (error) { + expect(error).toBeInstanceOf(RewardTimeoutError); + expect((error as Error).message).toMatch(/timed out after 100ms/); + }__test__/trainers/grpo-resume-validation.test.ts (2)
154-155: Use existing import instead of inlinerequire.The file already imports
readFileSyncfromnode:fsat Line 2. Consider using that import or addingreadFileSyncto the import statement instead of usingrequire('node:fs').♻️ Suggested refactor
// Read the training state const statePath = join(checkpointPath, 'training_state.json'); - const stateContent = require('node:fs').readFileSync(statePath, 'utf-8'); + const stateContent = readFileSync(statePath, 'utf-8'); const state: TrainingState = JSON.parse(stateContent);
232-236: Same inlinerequirepattern could be refactored.This block uses
require('node:fs')forcopyFileSyncandreaddirSync. Consider adding these to the import at Line 2.♻️ Suggested refactor
At line 2, add the needed imports:
-import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs'; +import { mkdirSync, writeFileSync, rmSync, existsSync, readFileSync, copyFileSync, readdirSync } from 'node:fs';Then use the imports directly:
- const { copyFileSync, readdirSync } = require('node:fs'); - const modelFiles = readdirSync(tempModel.modelPath); + const modelFiles = readdirSync(tempModel.modelPath);crates/mlx-core/src/tokenizer.rs (2)
182-229: Consider logging template safety warnings in release builds.The template safety validation (lines 221-226) only emits warnings in debug builds via
#[cfg(debug_assertions)]. In release builds, the warning is silently discarded withlet _ = warning;.This design choice means production deployments won't see any indication when a template has suspicious patterns. Consider whether a release-mode log (e.g., via
tracingorlogcrate) would be appropriate for operational visibility.That said, the current approach is reasonable if the goal is purely defense-in-depth without affecting user experience.
560-598: Role validation allocates unnecessarily for comparison.The
validate_chatml_rolefunction allocates aStringviato_lowercase()for every role validation, even though roles are typically short and comparisons could be done case-insensitively without allocation.This is a minor performance concern since role validation happens per-message, and messages are typically few. However, for high-throughput scenarios, consider using
eq_ignore_ascii_case:♻️ Proposed optimization to avoid allocation
fn validate_chatml_role(role: &str) -> &'static str { - // Normalize: trim whitespace and convert to lowercase for comparison - let normalized = role.trim().to_lowercase(); + let trimmed = role.trim(); // Check against whitelist for &valid_role in VALID_CHATML_ROLES { - if normalized == valid_role { + if trimmed.eq_ignore_ascii_case(valid_role) { return valid_role; } }crates/mlx-core/src/models/qwen3/persistence.rs (1)
660-698: Consider more explicit error handling for missing config values.The
unwrap_ordefaults (1024 for hidden_size, 16 for num_heads) could silently mask a malformed config file. If the config is missing these critical fields, it might be better to fail early with a clear error rather than use defaults that could lead to subtle shape mismatches later.♻️ Suggested improvement
// Otherwise, calculate from hidden_size / num_heads with validation - let hs = raw_config["hidden_size"] + let hs = match raw_config["hidden_size"] .as_i64() .or_else(|| raw_config["hiddenSize"].as_i64()) - .unwrap_or(1024) as i32; - let nh = raw_config["num_attention_heads"] + { + Some(v) => v as i32, + None => return Err(Error::new( + Status::InvalidArg, + "hidden_size is required when head_dim is not specified", + )), + }; + let nh = match raw_config["num_attention_heads"] .as_i64() - .or_else(|| raw_config["numAttentionHeads"].as_i64()) - .unwrap_or(16) as i32; + .or_else(|| raw_config["num_heads"].as_i64()) + .or_else(|| raw_config["numAttentionHeads"].as_i64()) + { + Some(v) => v as i32, + None => return Err(Error::new( + Status::InvalidArg, + "num_attention_heads is required when head_dim is not specified", + )), + };crates/mlx-core/src/models/qwen3/speculative.rs (1)
273-292: Consider whether_kv_valuesparameter is intentionally unused.The
trim_kv_cachesfunction takeskv_valuesbut only useskv_keys.len()for logging. If values don't need trimming separately, consider documenting why, or remove the unused parameter if it's not needed.__test__/models/speculative-decoding.test.ts (1)
130-134: This test is a placeholder that doesn't verify anything.The test claims to verify
SpeculativeStatsis exported but only assertsexpect(true).toBe(true). Consider either removing it or actually importing and checking the export.♻️ Suggested improvement
it('should export SpeculativeStats', async () => { - // The SpeculativeStats struct should be accessible - // This is a compile-time check that the module exports are correct - expect(true).toBe(true); + // Verify SpeculativeStats is exported from core + const { SpeculativeStats } = await import('@mlx-node/core'); + expect(SpeculativeStats).toBeDefined(); });Or if
SpeculativeStatsis not directly exported (it may be internal to Rust), remove the test entirely since it provides no value.crates/mlx-core/src/grpo/engine.rs (1)
770-797: Consider extracting common NaN/Inf handling into a helper function.The
AccumulationResulthandling logic is repeated acrosstrain_step,train_step_with_generations, andtrain_step_autowith identical patterns for:
- Incrementing counters on invalid gradients
- Emergency save threshold checking
- Resetting consecutive count on success
This could be extracted into a helper function to reduce duplication and ensure consistent behavior.
💡 Potential helper function
fn handle_accumulation_result( state: &mut EngineState, result: &AccumulationResult, emergency_threshold: u32, ) { if result.had_invalid_gradients { state.consecutive_nan_count += 1; state.nan_gradient_count += result.invalid_param_count as u64; warn!( "Found {} parameters with NaN/Inf during accumulation: {:?} (consecutive: {})", result.invalid_param_count, result.invalid_param_names, state.consecutive_nan_count ); if state.consecutive_nan_count >= emergency_threshold && !state.needs_emergency_save { state.needs_emergency_save = true; warn!( "Emergency save triggered: {} consecutive steps with NaN/Inf gradients", state.consecutive_nan_count ); } } else { state.consecutive_nan_count = 0; } }Also applies to: 1365-1392, 2027-2054
__test__/models/qwen3-chunked-prefill.test.ts (1)
1-2: Use the public entrypoint instead of@mlx-node/core.These tests should consume the public API surface. Prefer importing from
@mlx-node/lm(or@mlx-node/trl) rather than the internal core package.🔧 Suggested change
-import { Qwen3Model, Qwen3Tokenizer, type ChatMessage } from '@mlx-node/core'; +import { Qwen3Model, Qwen3Tokenizer, type ChatMessage } from '@mlx-node/lm';As per coding guidelines: Re-export APIs cleanly through index.ts files; users should import from
@mlx-node/lmor@mlx-node/trl, never directly from@mlx-node/corewhich is internal.__test__/core/optimizers.test.ts (1)
438-546: Route optimizer test imports through the public package entrypoint.These batch-update tests exercise the public optimizer API; please import from
@mlx-node/trl(or@mlx-node/lm) rather than@mlx-node/coreso the tests reflect the supported entrypoint.🔧 Suggested import change
-import { Adam, AdamW, SGD, RMSprop, GradientUtils, LRScheduler } from '@mlx-node/core'; +import { Adam, AdamW, SGD, RMSprop, GradientUtils, LRScheduler } from '@mlx-node/trl';As per coding guidelines, users should import from
@mlx-node/lmor@mlx-node/trl, never directly from@mlx-node/corewhich is internal.crates/mlx-core/src/transformer/quantized_kv_cache.rs (2)
108-117: Consider using proper logging or returning a Result for invalid bits.Using
eprintln!for error reporting in library code is not ideal since it bypasses any logging framework the consumer might use. However, this is a minor concern given the validation is defensive.
269-296: Consider moving raw FFI calls to mlx-sys with type-safe wrappers.The
quantize_tensoranddequantize_tensormethods invokesys::mlx_quantizeandsys::mlx_dequantizedirectly. Based on learnings, raw FFI calls should be confined tomlx-syswith type-safe wrapper abstractions exposed for use inmlx-core.This works correctly but could improve maintainability by encapsulating the FFI boundary.
#11) … speculative decoding) - Remove unnecessary eval()/synchronize() calls in C++ FFI that were destroying MLX's lazy evaluation pipeline (4x performance regression fix: 37 → 140 tok/s) - Align periodic cleanup interval to 256 tokens (matching mlx-lm) - Process long prompts in configurable chunks (default: 2048 tokens) - Reduces peak memory usage for long sequences - Enables async pipelining during prefill - New config: `prefillStepSize` - 4-bit and 8-bit cache compression via group-wise affine quantization - Memory reduction: 44% (8-bit) to 69% (4-bit) - New FFI: mlx_quantize(), mlx_dequantize() - New config: `kvCacheBits`, `kvCacheGroupSize` - Draft model acceleration for 2-3x speedup - Rejection sampling acceptance criterion (more correct than exact comparison) - KV cache trimming for rejected tokens - New method: generateSpeculativeSync() - New config: `numDraftTokens` - loadParameters now throws when use_qk_norm=true but QK norm weights missing - Fix clippy warning in quantized_kv_cache.rs (unnecessary_unwrap) - New test suites: chunked-prefill, quantized-kv-cache, speculative-decoding, qwen3-parameter-validation <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Mostly documentation, CI, and test-suite churn, but it changes the CI test command and significantly reshapes coverage (removing several gradient/backprop suites while adding new ones), which could let regressions slip or surface new flaky integration tests. > > **Overview** > Updates CI to run JS tests via `yarn vite run test`. > > Refreshes docs to **remove XTC sampling mentions** and adds a **tokenizer security note** about trusted `tokenizer_config.json` Jinja templates. > > Significantly refactors the test suite: removes several manual backprop/VJP/basic-training tests, adds GPU-native NaN/Inf detection checks, and introduces new integration/unit tests around Qwen3 generation features (chunked prefill, speculative decoding, quantized KV cache), optimizer batch/state checkpoint behaviors, GRPO resume validation and reward timeouts, SFT special token ID handling, and path traversal protections. Also adds `rand` as a workspace dependency. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit b9386da. 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** * Speculative decoding with draft models for faster generation * Quantized KV cache (4-bit/8-bit) and unified cache option to reduce memory * Chunked prefill for long-context handling * Parameter validation on model load * Reward-function timeout and optimizer checkpoint/restore for safer training * Path-security checks to prevent directory-traversal issues * Batch optimizer updates for performance * **Bug Fixes** * Better NaN/Inf detection (GPU-native) and numerical stability improvements * Safer device initialization (null-pointer handling) * **Removals** * XTC sampling feature * computeGradientNorm utility <sub>✏️ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.5 <[email protected]>
…oad gate, job dismissal - G2: require config.json AND >=1 weight file before a model counts as installed (download.hasModelPayload OR->AND; models.isModelInstalled marker validation; shared isWeightFile moved to models.ts) - G3: replace a changed trace file's rows transactionally (delete-by-source -> reinsert -> watermark upsert, rollback-safe) so stale rows can't linger - G4: reconcile session rows against the discoverable set so a --session-dir switch drops out-of-root rows - G5: create the per-day chart row before the null check so a null metric leaves a gap instead of bridging neighbours into false continuity - G6: let a terminal (error/cancelled/done) download be dismissed — cancel() evicts it, the UI issues DELETE on error; api.ts comment + committing wire type reconciled - G1: document the cold-tier quota as a per-process best-effort cap (docs + code comment); strict cross-process locking is out of scope for v1 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
…oad gate, job dismissal - G2: require config.json AND >=1 weight file before a model counts as installed (download.hasModelPayload OR->AND; models.isModelInstalled marker validation; shared isWeightFile moved to models.ts) - G3: replace a changed trace file's rows transactionally (delete-by-source -> reinsert -> watermark upsert, rollback-safe) so stale rows can't linger - G4: reconcile session rows against the discoverable set so a --session-dir switch drops out-of-root rows - G5: create the per-day chart row before the null check so a null metric leaves a gap instead of bridging neighbours into false continuity - G6: let a terminal (error/cancelled/done) download be dismissed — cancel() evicts it, the UI issues DELETE on error; api.ts comment + committing wire type reconciled - G1: document the cold-tier quota as a per-process best-effort cap (docs + code comment); strict cross-process locking is out of scope for v1 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
…oad gate, job dismissal - G2: require config.json AND >=1 weight file before a model counts as installed (download.hasModelPayload OR->AND; models.isModelInstalled marker validation; shared isWeightFile moved to models.ts) - G3: replace a changed trace file's rows transactionally (delete-by-source -> reinsert -> watermark upsert, rollback-safe) so stale rows can't linger - G4: reconcile session rows against the discoverable set so a --session-dir switch drops out-of-root rows - G5: create the per-day chart row before the null check so a null metric leaves a gap instead of bridging neighbours into false continuity - G6: let a terminal (error/cancelled/done) download be dismissed — cancel() evicts it, the UI issues DELETE on error; api.ts comment + committing wire type reconciled - G1: document the cold-tier quota as a per-process best-effort cap (docs + code comment); strict cross-process locking is out of scope for v1 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
… speculative decoding)
Remove unnecessary eval()/synchronize() calls in C++ FFI that were destroying MLX's lazy evaluation pipeline (4x performance regression fix: 37 → 140 tok/s)
Align periodic cleanup interval to 256 tokens (matching mlx-lm)
Process long prompts in configurable chunks (default: 2048 tokens)
Reduces peak memory usage for long sequences
Enables async pipelining during prefill
New config:
prefillStepSize4-bit and 8-bit cache compression via group-wise affine quantization
Memory reduction: 44% (8-bit) to 69% (4-bit)
New FFI: mlx_quantize(), mlx_dequantize()
New config:
kvCacheBits,kvCacheGroupSizeDraft model acceleration for 2-3x speedup
Rejection sampling acceptance criterion (more correct than exact comparison)
KV cache trimming for rejected tokens
New method: generateSpeculativeSync()
New config:
numDraftTokensloadParameters now throws when use_qk_norm=true but QK norm weights missing
Fix clippy warning in quantized_kv_cache.rs (unnecessary_unwrap)
New test suites: chunked-prefill, quantized-kv-cache, speculative-decoding, qwen3-parameter-validation
Note
Medium Risk
Mostly documentation, CI, and test-suite churn, but it changes the CI test command and significantly reshapes coverage (removing several gradient/backprop suites while adding new ones), which could let regressions slip or surface new flaky integration tests.
Overview
Updates CI to run JS tests via
yarn vite run test.Refreshes docs to remove XTC sampling mentions and adds a tokenizer security note about trusted
tokenizer_config.jsonJinja templates.Significantly refactors the test suite: removes several manual backprop/VJP/basic-training tests, adds GPU-native NaN/Inf detection checks, and introduces new integration/unit tests around Qwen3 generation features (chunked prefill, speculative decoding, quantized KV cache), optimizer batch/state checkpoint behaviors, GRPO resume validation and reward timeouts, SFT special token ID handling, and path traversal protections. Also adds
randas a workspace dependency.Written by Cursor Bugbot for commit b9386da. This will update automatically on new commits. Configure here.
Summary by CodeRabbit
New Features
Bug Fixes
Removals
✏️ Tip: You can customize this high-level summary in your review settings.