Skip to content

refactor: acquire locks once in Qwen3.5 dense generate/chat - #26

Merged
Brooooooklyn merged 6 commits into
mainfrom
refactor/qwen35-acquire-locks-once
Mar 6, 2026
Merged

Brooooooklyn merged 6 commits into
mainfrom
refactor/qwen35-acquire-locks-once

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

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

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.

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

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.

@coderabbitai

coderabbitai Bot commented Mar 5, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Serialize 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 (forward_inner, eval_token_and_caches_inner), update call sites, add MoE mutex handling, bump MLX submodule, and add CI netrc step.

Changes

Cohort / File(s) Summary
Qwen3.5 Lock/Forward Refactor
crates/mlx-core/src/models/qwen3_5/model.rs
Add a process-wide compiled mutex; switch to acquiring required locks once for prefill+decode; add internal forward_inner(...) and eval_token_and_caches_inner(...) (mutable refs, no Arc/RwLock inside); add forward_compiled and update compiled vs Rust fallback flows and call sites.
Qwen3.5 MoE Mutex
crates/mlx-core/src/models/qwen3_5_moe/model.rs
Introduce MOE_COMPILED_MUTEX (Tokio mutex) and move C++ MoE path detection earlier; guard MoE compiled init/decode under the mutex; adjust lock lifetimes and cache ownership during C++ handoff.
Submodule Pointer
crates/mlx-sys/mlx
Update mlx submodule commit pointer only (no source/API changes).
CI: CMake Auth Step
.github/workflows/ci.yml
Add step to populate ~/.netrc with GITHUB_TOKEN for authenticated CMake downloads in build/test/lint jobs.
Manifest / Other
Cargo.toml, workspace manifest, ... (lines changed noted in PR)
Manifest lines changed (+256/-227) to reflect internal edits and signature changes across the crate(s).

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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰
I hold one mutex with careful cheer,
Locks gathered once, the path grows clear.
No Arc to gnaw, just mutable ground,
Compiled waits — then hops profound. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: acquire locks once in Qwen3.5 dense generate/chat' directly summarizes the main change: refactoring the lock acquisition strategy in Qwen3.5 dense model to use an acquire-once pattern instead of per-call locking.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/qwen35-acquire-locks-once

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
crates/mlx-core/src/models/qwen3_5/model.rs (1)

424-501: Reduce decode-flow duplication to prevent behavior drift.

generate and chat now 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

📥 Commits

Reviewing files that changed from the base of the PR and between 70f2d50 and a8f86e1.

📒 Files selected for processing (2)
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/mlx-sys/mlx

@Brooooooklyn
Brooooooklyn force-pushed the refactor/qwen35-acquire-locks-once branch from a8f86e1 to 4b878d4 Compare March 5, 2026 16:28

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
crates/mlx-core/src/models/qwen3_5/model.rs (1)

391-396: ⚠️ Potential issue | 🔴 Critical

Serialize 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/chat calls can interleave mlx_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.rs

As 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

📥 Commits

Reviewing files that changed from the base of the PR and between a8f86e1 and 4b878d4.

📒 Files selected for processing (2)
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/mlx-sys/mlx
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/mlx-sys/mlx

Brooooooklyn and others added 3 commits March 6, 2026 15:04
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]>
@Brooooooklyn
Brooooooklyn force-pushed the refactor/qwen35-acquire-locks-once branch from 8de836a to 5575e0a Compare March 6, 2026 07:04

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
crates/mlx-core/src/models/qwen3_5/model.rs (1)

934-943: Refresh the forward_inner contract 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b878d4 and 8de836a.

📒 Files selected for processing (2)
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 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_inner and eval_token_and_caches_inner now mirror crates/mlx-core/src/models/qwen3_5_moe/model.rs:937-1008 almost 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

📥 Commits

Reviewing files that changed from the base of the PR and between 8de836a and 8f28b27.

📒 Files selected for processing (3)
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/mlx-core/src/models/qwen3_5_moe/model.rs
  • crates/mlx-sys/mlx
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/mlx-sys/mlx

Brooooooklyn and others added 2 commits March 6, 2026 16:48
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]>
@Brooooooklyn
Brooooooklyn merged commit b8b4691 into main Mar 6, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the refactor/qwen35-acquire-locks-once branch March 6, 2026 10:18
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant