Repository navigation
refactor: acquire locks once in Qwen3.5 dense generate/chat - #26
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughSerialize compiled forward lifecycles with process-wide mutexes, replace per-step Arc/RwLock usage by holding required locks for entire prefill+decode sequences, introduce lock-free internals ( Changes
Sequence Diagram(s)sequenceDiagram
participant Controller
participant RustModel as Model (Rust)
participant Compiled as Compiled MLX (C++)
participant Caches as LayerCaches
Controller->>RustModel: acquire locks (layers, caches, norms, lm_head)
Controller->>RustModel: call prefill -> forward_inner(input_ids, ..., caches)
alt compiled backend available
RustModel->>Compiled: acquire process-wide compiled mutex
RustModel->>Compiled: forward_compiled / init (interact with C++ globals)
Compiled-->>RustModel: return logits / states
RustModel->>Compiled: release process-wide compiled mutex
else fallback
RustModel->>RustModel: execute forward_inner (mutable refs, no Arc/RwLock)
end
loop decode
Controller->>RustModel: eval_token_and_caches_inner(next_token, caches)
RustModel-->>Controller: token logits + updated caches
end
Controller->>RustModel: release locks (end of sequence)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
crates/mlx-core/src/models/qwen3_5/model.rs (1)
424-501: Reduce decode-flow duplication to prevent behavior drift.
generateandchatnow have large parallel compiled/fallback loops with already-divergent control flow. Extract a shared decode runner with hook points (e.g., repetition penalty/cutoff) to keep semantics aligned.Also applies to: 718-822
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/models/qwen3_5/model.rs` around lines 424 - 501, Duplicate compiled and fallback decode loops in generate/chat (the blocks using StreamContext, forward_compiled vs forward_inner, eval_token_and_compiled_caches vs eval_token_and_caches_inner, sampling and cache-syncing) risk drift; extract a single shared decode runner function (e.g., run_decode_loop) that accepts hook closures or trait objects for: (1) performing a forward+sampling step (call sites currently using forward_compiled + sample or forward_inner + sample and returning Option<next_y>), (2) evaluating/updating caches for the chosen path (currently eval_token_and_compiled_caches or eval_token_and_caches_inner), and (3) any per-step bookkeeping (pushing token into generated_tokens, eos detection, and calling crate::array::synchronize_and_clear_cache()); replace both loops with calls into this runner passing the appropriate forward/eval hooks to keep semantics aligned.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 391-396: The compiled C++ globals (g_compiled_caches,
g_compiled_offset, g_offset_int, g_compile_inited) are unsynchronized and can be
corrupted by concurrent generate/chat calls; serialize the compiled lifecycle by
adding a process-wide mutex around all compiled operations. Fix by either (A)
adding a static mutex in the C++ side and acquiring it in
mlx_qwen35_compiled_init_from_prefill, mlx_qwen35_forward_compiled, and
mlx_qwen35_eval_token_and_compiled_caches, or (B) adding a Rust-side
std::sync::Mutex<()> (e.g., a static OnceCell/Mutex) and lock it around the
entire compiled lifecycle (init → decode loop → reset) where the code drops
locks and enters the unsafe block that calls those C functions (the region after
drop(caches_guard)/drop(layers_guard)/drop(final_norm_guard)/drop(lm_head_guard));
ensure the lock covers all calls to the three C functions so concurrent
generation is serialized.
---
Nitpick comments:
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 424-501: Duplicate compiled and fallback decode loops in
generate/chat (the blocks using StreamContext, forward_compiled vs
forward_inner, eval_token_and_compiled_caches vs eval_token_and_caches_inner,
sampling and cache-syncing) risk drift; extract a single shared decode runner
function (e.g., run_decode_loop) that accepts hook closures or trait objects
for: (1) performing a forward+sampling step (call sites currently using
forward_compiled + sample or forward_inner + sample and returning
Option<next_y>), (2) evaluating/updating caches for the chosen path (currently
eval_token_and_compiled_caches or eval_token_and_caches_inner), and (3) any
per-step bookkeeping (pushing token into generated_tokens, eos detection, and
calling crate::array::synchronize_and_clear_cache()); replace both loops with
calls into this runner passing the appropriate forward/eval hooks to keep
semantics aligned.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: fd087bc3-7c9c-473a-8a2f-79f13d207597
📒 Files selected for processing (2)
crates/mlx-core/src/models/qwen3_5/model.rscrates/mlx-sys/mlx
a8f86e1 to
4b878d4
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
crates/mlx-core/src/models/qwen3_5/model.rs (1)
391-396:⚠️ Potential issue | 🔴 CriticalSerialize the compiled lifecycle across requests
At Line 391 and Line 685, locks are dropped before entering compiled mode, but decode continues with process-global compiled state and raw cache pointers (Line 424 and Line 718 regions). Concurrent
generate/chatcalls can interleavemlx_qwen35_compiled_init_from_prefill/mlx_qwen35_forward_compiled/mlx_qwen35_eval_token_and_compiled_caches/ reset and corrupt shared state.🔧 Suggested fix (Rust-side process-wide mutex around compiled lifecycle)
-use std::sync::{Arc, RwLock}; +use std::sync::{Arc, Mutex, OnceLock, RwLock}; +static QWEN35_COMPILED_LIFECYCLE_MUTEX: OnceLock<Mutex<()>> = OnceLock::new(); // ... inside generate/chat closure, before compiled init/decode: let use_compiled = unsafe { mlx_sys::mlx_qwen35_weight_count() } > 0; +let _compiled_lifecycle_guard = if use_compiled { + Some( + QWEN35_COMPILED_LIFECYCLE_MUTEX + .get_or_init(|| Mutex::new(())) + .lock() + .map_err(|_| Error::from_reason("Failed to acquire compiled lifecycle mutex"))?, + ) +} else { + None +}; let _compiled_guard = if use_compiled { Some(CompiledResetGuard) } else { None };#!/bin/bash set -euo pipefail echo "== Verify compiled globals and synchronization in C++ ==" fd 'mlx_qwen35\.cpp$' crates/mlx-sys/src rg -n -C3 'g_compiled_|std::mutex|std::lock_guard|std::scoped_lock|mlx_qwen35_compiled_init_from_prefill|mlx_qwen35_forward_compiled|mlx_qwen35_eval_token_and_compiled_caches|mlx_qwen35_compiled_reset' crates/mlx-sys/src/mlx_qwen35.cpp echo echo "== Verify Rust-side lifecycle serialization around compiled path ==" rg -n -C3 'QWEN35_COMPILED_LIFECYCLE_MUTEX|OnceLock<Mutex|drop\(caches_guard\)|drop\(layers_guard\)|mlx_qwen35_compiled_init_from_prefill|forward_compiled\(|eval_token_and_compiled_caches|CompiledResetGuard' crates/mlx-core/src/models/qwen3_5/model.rsAs per coding guidelines: "Handle Arc with thread-safe lifetime management; use Arc for shared ownership across threads."
Also applies to: 424-457, 685-689, 718-764
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/models/qwen3_5/model.rs` around lines 391 - 396, Concurrent requests can race when entering compiled mode because locks are dropped before calling into process-global compiled C++ routines (see the drop(caches_guard); drop(layers_guard); drop(final_norm_guard); drop(lm_head_guard); block), which lets other threads call mlx_qwen35_compiled_init_from_prefill / mlx_qwen35_forward_compiled / mlx_qwen35_eval_token_and_compiled_caches / compiled reset and corrupt shared state. Fix: introduce a process-wide Mutex (e.g., a OnceLock/OnceCell static named QWEN35_COMPILED_LIFECYCLE_MUTEX) and acquire its guard around the entire compiled lifecycle regions—wrap the compiled-init, forward_compiled, eval_token_and_compiled_caches calls and any compiled reset path with this mutex so the Rust-side code holds the global lock while using raw compiled caches/pointers; ensure you do not drop the per-model guards (caches_guard, layers_guard, final_norm_guard, lm_head_guard) or release the process mutex before returning from the compiled calls and also protect the compiled reset path (CompiledResetGuard / compiled_reset) with the same mutex.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 391-396: Concurrent requests can race when entering compiled mode
because locks are dropped before calling into process-global compiled C++
routines (see the drop(caches_guard); drop(layers_guard);
drop(final_norm_guard); drop(lm_head_guard); block), which lets other threads
call mlx_qwen35_compiled_init_from_prefill / mlx_qwen35_forward_compiled /
mlx_qwen35_eval_token_and_compiled_caches / compiled reset and corrupt shared
state. Fix: introduce a process-wide Mutex (e.g., a OnceLock/OnceCell static
named QWEN35_COMPILED_LIFECYCLE_MUTEX) and acquire its guard around the entire
compiled lifecycle regions—wrap the compiled-init, forward_compiled,
eval_token_and_compiled_caches calls and any compiled reset path with this mutex
so the Rust-side code holds the global lock while using raw compiled
caches/pointers; ensure you do not drop the per-model guards (caches_guard,
layers_guard, final_norm_guard, lm_head_guard) or release the process mutex
before returning from the compiled calls and also protect the compiled reset
path (CompiledResetGuard / compiled_reset) with the same mutex.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: b7a6e49f-67c7-4d0c-82c2-db541ef3c272
📒 Files selected for processing (2)
crates/mlx-core/src/models/qwen3_5/model.rscrates/mlx-sys/mlx
🚧 Files skipped from review as they are similar to previous changes (1)
- crates/mlx-sys/mlx
Replace per-call lock acquisition (forward_with_locks) with acquire-once pattern matching the MoE model. Locks are held for the entire prefill+decode sequence, eliminating per-step lock overhead. - Add forward_inner() taking direct refs instead of Arc<RwLock<...>> - Add eval_token_and_caches_inner() taking direct cache refs - Split decode loops into compiled (locks dropped) and Rust fallback (locks held) paths - Remove dead cache.reset() loops before immediate overwrite - Remove dead forward_with_locks/eval_token_and_caches wrappers Co-Authored-By: Claude Opus 4.6 <[email protected]>
Promise.all([model.chat(...), model.chat(...)]) races on C++ process-wide globals (g_compiled_caches, g_offset_int, etc.) because spawn_blocking dispatches to the tokio blocking thread pool. Add tokio::sync::Mutex acquired in async context before spawn_blocking to serialize the entire compiled lifecycle. Dense and MoE have separate mutexes (separate C++ anonymous namespaces). CompiledResetGuard/MoeResetGuard remain inside spawn_blocking for reset-on-drop cleanup. Co-Authored-By: Claude Opus 4.6 <[email protected]>
8de836a to
5575e0a
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
crates/mlx-core/src/models/qwen3_5/model.rs (1)
934-943: Refresh theforward_innercontract comment.The lead doc lines still say this helper acquires its own locks, but the new API requires the caller to hold them first. Tightening that comment will make the lock-lifetime contract clearer for future call sites.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/models/qwen3_5/model.rs` around lines 934 - 943, Update the doc comment for the free function forward_inner to remove lines implying it acquires locks itself and instead clearly state that the caller must acquire and hold the necessary locks for the entire prefill+decode sequence; mention that this is a lock-free forward pass variant that accepts direct mutable refs (not Arcs), that embedding_weight_t is an optional pre-transposed embedding for tied embeddings to avoid recomputing transposes, and that callers are responsible for lock lifetime and safety when calling forward_inner.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 397-410: The guards (caches_guard, layers_guard, final_norm_guard,
lm_head_guard) are being dropped before calling
mlx_qwen35_compiled_init_from_prefill()/the compiled decode while cache_ptrs
still point into self.caches; hold those guards across the compiled call so the
underlying buffers cannot be mutated by
reset_caches()/init_caches()/forward()/forward_with_cache() on the same model.
Fix by extending the guard lifetimes (e.g., bind them to a single tuple or keep
the guard variables in scope) and only drop them after the
compiled_init/compiled decode completes (ensure cache_ptrs remains valid for the
whole compiled call), referencing cache_ptrs, caches_guard, layers_guard,
final_norm_guard, lm_head_guard, mlx_qwen35_compiled_init_from_prefill, and the
compiled decode paths.
---
Nitpick comments:
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 934-943: Update the doc comment for the free function
forward_inner to remove lines implying it acquires locks itself and instead
clearly state that the caller must acquire and hold the necessary locks for the
entire prefill+decode sequence; mention that this is a lock-free forward pass
variant that accepts direct mutable refs (not Arcs), that embedding_weight_t is
an optional pre-transposed embedding for tied embeddings to avoid recomputing
transposes, and that callers are responsible for lock lifetime and safety when
calling forward_inner.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 8f512c70-3e67-4364-b984-cfa9b4dcc7bf
📒 Files selected for processing (2)
crates/mlx-core/src/models/qwen3_5/model.rscrates/mlx-core/src/models/qwen3_5_moe/model.rs
✅ Files skipped from review due to trivial changes (1)
- crates/mlx-core/src/models/qwen3_5_moe/model.rs
cache_ptrs contains raw pointers into MxArray handles owned by the Rust cache structs. Previously all RwLock guards were dropped before init_from_prefill, creating a window where concurrent reset_caches() could free the underlying arrays. Now caches_guard is held until after C++ has copied the arrays into its own globals (g_compiled_caches), then released. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
crates/mlx-core/src/models/qwen3_5/model.rs (1)
947-995: Extract the new lock-free decode helpers before dense/MoE drift apart.
forward_innerandeval_token_and_caches_innernow mirrorcrates/mlx-core/src/models/qwen3_5_moe/model.rs:937-1008almost line-for-line apart from the head type. Pulling the common mask/cache logic into one internal helper will make future decode fixes land once instead of twice.Also applies to: 1052-1071
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/mlx-core/src/models/qwen3_5/model.rs` around lines 947 - 995, forward_inner and eval_token_and_caches_inner duplicate the same mask/cache/loop logic; extract that into a small internal helper (e.g., compute_fa_mask_or_none and/or run_layers_lock_free) that (1) computes the fa_mask using create_causal_mask from seq_len and caches.as_ref().map(|c| c[fa_idx].offset()), (2) iterates layers and calls DecoderLayer::forward with the per-layer mask and caches.as_mut().map(|c| &mut c[i]) and returns the final hidden states; replace the duplicated blocks in forward_inner and eval_token_and_caches_inner (and the similar block around lines 1052-1071) to call this helper, preserving usage of final_norm, lm_head, embedding_weight_t and the Qwen3_5LayerCache types.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@crates/mlx-core/src/models/qwen3_5_moe/model.rs`:
- Around line 273-278: The current async MutexGuard from
MOE_COMPILED_MUTEX.lock().await has a non-'static lifetime and can be dropped
before the spawn_blocking closure uses it; replace the .lock().await call with
.lock_owned().await so you get an OwnedMutexGuard that can be moved into
napi::bindgen_prelude::spawn_blocking, e.g., keep the existing _moe_lock
variable but obtain it via MOE_COMPILED_MUTEX.lock_owned().await when use_cpp is
true; alternatively, if you prefer acquiring the lock inside the blocking
closure, move the MOE_COMPILED_MUTEX into the closure and call blocking_lock()
there.
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 302-307: The current code acquires DENSE_COMPILED_MUTEX with
.lock().await into _compiled_lock inside the async context, which can release
the guard if the async future is dropped and also cannot be moved into
spawn_blocking due to non-Send/non-'static MutexGuard; change the acquisition to
use lock_owned().await (producing an OwnedMutexGuard) and move that owned guard
(e.g., _compiled_lock) into the spawn_blocking closure (or alternatively pass
the Arc<Mutex<()>> into the closure and call blocking_lock() inside) so the
mutex lifetime ties to the blocking task and satisfies Send + 'static; update
both occurrences around the DENSE_COMPILED_MUTEX uses (including the other block
at lines ~591-596) and ensure the variable names (e.g., _compiled_lock) reflect
the owned guard.
---
Nitpick comments:
In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 947-995: forward_inner and eval_token_and_caches_inner duplicate
the same mask/cache/loop logic; extract that into a small internal helper (e.g.,
compute_fa_mask_or_none and/or run_layers_lock_free) that (1) computes the
fa_mask using create_causal_mask from seq_len and caches.as_ref().map(|c|
c[fa_idx].offset()), (2) iterates layers and calls DecoderLayer::forward with
the per-layer mask and caches.as_mut().map(|c| &mut c[i]) and returns the final
hidden states; replace the duplicated blocks in forward_inner and
eval_token_and_caches_inner (and the similar block around lines 1052-1071) to
call this helper, preserving usage of final_norm, lm_head, embedding_weight_t
and the Qwen3_5LayerCache types.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 060894f4-dd81-4a2a-a4a1-71221dcc6598
📒 Files selected for processing (3)
crates/mlx-core/src/models/qwen3_5/model.rscrates/mlx-core/src/models/qwen3_5_moe/model.rscrates/mlx-sys/mlx
🚧 Files skipped from review as they are similar to previous changes (1)
- crates/mlx-sys/mlx
MLX's CMakeLists.txt uses FetchContent to download nlohmann/json from GitHub Releases. Unauthenticated curl requests from CI runner IPs hit rate limits (403 Forbidden). Configure ~/.netrc so curl sends the GITHUB_TOKEN on requests to github.com and objects.githubusercontent.com. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace per-call lock acquisition (forward_with_locks) with acquire-once pattern matching the MoE model. Locks are held for the entire prefill+decode sequence, eliminating per-step lock overhead. - Add forward_inner() taking direct refs instead of Arc<RwLock<...>> - Add eval_token_and_caches_inner() taking direct cache refs - Split decode loops into compiled (locks dropped) and Rust fallback (locks held) paths - Remove dead cache.reset() loops before immediate overwrite - Remove dead forward_with_locks/eval_token_and_caches wrappers <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Touches the token generation hot path and concurrency/locking around C++ compiled globals; mistakes could cause deadlocks, reduced parallelism, or subtle generation regressions. > > **Overview** > **Improves Qwen3.5 generation concurrency safety and reduces lock overhead.** Dense `generate()`/`chat()` now acquire model/cache locks once for the full prefill+decode sequence via a new `forward_inner()`/`eval_token_and_caches_inner()` API, and split decode into a compiled C++ branch (dropping Rust locks after prefill) vs a Rust fallback branch (locks held throughout). > > **Prevents races in native compiled paths.** Adds process-wide Tokio mutexes to serialize dense and MoE compiled/C++ lifecycles when weights are loaded, avoiding concurrent `generate()`/`chat()` calls corrupting C++ global state. > > CI updates add a step to write `~/.netrc` with `GITHUB_TOKEN` so CMake downloads from GitHub can authenticate reliably. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 45d06ab. 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 * **Refactor** * Reduced runtime contention by centralizing lock management and holding required locks across prefill+decode sequences, improving throughput and latency consistency. * Added serialized coordination for native-accelerated and MoE execution paths to prevent races during compiled/C++ initialization and decoding. * Updated internal APIs to enable lock-minimized evaluation and decoding flow. * **Chores** * Updated upstream submodule/build integration and CI steps to enable authenticated CMake downloads. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
Replace per-call lock acquisition (forward_with_locks) with acquire-once pattern matching the MoE model. Locks are held for the entire prefill+decode sequence, eliminating per-step lock overhead.
Note
Medium Risk
Touches the token generation hot path and concurrency/locking around C++ compiled globals; mistakes could cause deadlocks, reduced parallelism, or subtle generation regressions.
Overview
Improves Qwen3.5 generation concurrency safety and reduces lock overhead. Dense
generate()/chat()now acquire model/cache locks once for the full prefill+decode sequence via a newforward_inner()/eval_token_and_caches_inner()API, and split decode into a compiled C++ branch (dropping Rust locks after prefill) vs a Rust fallback branch (locks held throughout).Prevents races in native compiled paths. Adds process-wide Tokio mutexes to serialize dense and MoE compiled/C++ lifecycles when weights are loaded, avoiding concurrent
generate()/chat()calls corrupting C++ global state.CI updates add a step to write
~/.netrcwithGITHUB_TOKENso CMake downloads from GitHub can authenticate reliably.Written by Cursor Bugbot for commit 45d06ab. This will update automatically on new commits. Configure here.
Summary by CodeRabbit
Refactor
Chores