Repository navigation
perf(lfm2): compiled paged decode (~2× / ~1.5×) + paged-prefill last-token slice (~10% TTFT) - #66
Conversation
Port qwen3_5's compiled-paged decode to lfm2 + lfm2_moe so the DEFAULT paged decode runs inside an mlx::core::compile graph instead of the eager pure-Rust layer-by-layer loop. block_table / slot_mapping / offset are threaded as array INPUTS so the trace stays static across steps, and fast::paged_kv_write + fast::paged_attention run over the shared LayerKVPool Metal buffers. Decode-only (prefill stays eager paged, then seeds the compiled decode); covers dense + MoE in one fn; bf16/f16 only. Perf (interleaved A/B, warm, M5 Max) vs the old pure-Rust paged ceiling: 1.2B dense ~1.96×, 8B MoE ~1.47×. sendStream now rides the same compiled graph as send. Both paged loops wired + measured: chat_sync_core_paged_inner (non-streaming) and chat_stream_sync_core_paged_inner (streaming) share paged_compiled_decode_setup / paged_compiled_decode_step. Validation: eager-paged ≡ compiled-paged byte-identical on 1.2B + 8B MoE (greedy); streaming ≡ non-streaming byte-identical; counter-based engagement assertions. lfm2 compiled e2e 13/13 + eager 13/13. Codex adversarial review (3 rounds) — all findings resolved: - F1 streaming bypassed compiled-paged → shared setup/step helper; the Lfm2PagedCompiledState RAII guards are declared reset-guard → weight → lock so the C++ reset runs while the global locks are still held (Rust drops struct fields in declaration order). - F2 failed paged-init leaked mutated C++ globals → lfm2_reset_paged_globals() on every init error path + both catch blocks. - F3 bf16-only gate was too narrow → authoritative load-time all_float_weights_bf16 flag computed once over the whole registered param map (allows the intentional f32 *.expert_bias on MoE). - F4 MLX_DISABLE_COMPILE made the engagement counter lie → eager branch + test both honor the var. - F5 cross-family model-id collision: the compiled registry (g_weights + g_active_model_id) is ONE process-global owned by the last registrant; Gemma4 drew its id from a PRIVATE counter while publishing onto the shared atom, so its id could collide with lfm2/qwen and false-positive their gate (and its mlx_clear_weights evicted co-resident compiled models). Gemma4 has no compiled C++ forward path, so its registration was vestigial → DELETED. Every registry-sharing family now draws from the shared 1-based QWEN35_MODEL_ID_COUNTER. +race-free regression test. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ 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 |
Single-arm harness (reportPerformance metrics) + paired-process orchestrator that interleaves baseline/optimized arms back-to-back, takes median of per-pair ratios (cancels ~15% M5 thermal drift), and gates a real win on a control band. Tooling for the lfm2 perf-optimization workflow (prove-or-revert per step). Co-Authored-By: Claude Opus 4.8 <[email protected]>
The eager paged prefill ran embedding_norm + lm_head over the full [1,T,hidden] tensor then sliced the last token; now it slices BEFORE the projection so the largest matmul (lm_head, vocab 65536 x hidden 2048) runs on T=1 instead of all T prompt rows. Byte-identical at T=0 (verified toggle-on==toggle-off on 1.2B + 8B; full lfm2_compiled_e2e 13/13 on both compiled and MLX_NO_COMPILE arms). Thermally-fair paired A/B (median of per-pair ratios vs a control band): 1.2B dense: TTFT median ratio 1.0965 (+9.65%), control band +/-1.5% 8B MoE: TTFT median ratio 1.1194 (+11.94%), control band +/-2.2% The win is fully attributable to the output projection (prefill ratio == total ratio on both). Gated by MLX_LFM2_DISABLE_LAST_TOKEN_SLICE (default ON; set it to reproduce the old full-T projection for same-binary A/B). Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cbb08cea15
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…k + dedup compute_layer_kinds Addresses PR #66 inline review (cursor[bot] Medium + codex P2; cursor[bot] Low). paged_compiled_decode_setup acquires the process-wide COMPILED_LIFECYCLE_MUTEX + COMPILED_WEIGHTS_RWLOCK read guard to probe/seed the compiled-paged path, but on fallback (model_id eviction, block_size mismatch, or seed failure -> cpp_session_ready = false) it still moved both into Lfm2PagedCompiledState and held them for the ENTIRE pure-Rust eager decode loop -- starving register_weights_with_cpp's .write() and other compiled-decode startups' .lock() for the whole generation. Drop both guards when cpp_session_ready is false. Safe: that case always implies _paged_reset_guard is None (no seed armed), so the reset-while-locks-held drop-order invariant is vacuous on this path. The DIFFERENT first-step fallback in paged_compiled_decode_step (a seed DID run, reset_guard IS armed, locks MUST stay held until the reset) is deliberately untouched. The fix lives in the shared helper, so it covers both the non-streaming and streaming paged decode loops. Byte-identical output. Also dedup Lfm2Inner::compute_layer_kinds to delegate to the existing free fn compute_layer_kinds_for (byte-identical mapping; self.layers.len() == config.num_hidden_layers by construction). Codex adversarial review: approve, no material findings. lfm2_compiled_e2e 13/13 on both the compiled and MLX_NO_COMPILE (eager) arms; eager-paged == compiled-paged byte-identical. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c718bc968f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…review) Addresses the post-seed first-step fallback case (chatgpt-codex-connector P2). When the compiled-paged seed succeeded (reset guard armed, cross-family locks held) but the first forward_lfm2_cpp_paged returned null, paged_compiled_decode_step rerouted the rest of the turn to pure-Rust eager decode while `st` kept holding _paged_reset_guard, _weight_guard, and _compiled_lock until loop end -- needlessly pinning the process-wide COMPILED_LIFECYCLE_MUTEX + COMPILED_WEIGHTS_RWLOCK.read() across the whole eager tail, blocking weight registration (.write()) and other compiled-decode startups (.lock()). Now tear the session down at fallback time in the LOAD-BEARING order: drop the reset guard FIRST so mlx_lfm2_paged_reset() runs WHILE the locks are still held (per the Lfm2PagedCompiledState drop-order invariant), THEN release the weight read lock + lifecycle mutex. After this all three guards are None, so the struct's loop-end drop is a no-op (no double reset / double release). The eager tail uses run_paged_decode_step, which never touches the C++ paged session, and cpp_session_ready never re-enables -- so resetting + releasing early is safe. Symmetric to the setup-time fallback early-release (c718bc9). No code change for the cursor[bot] "High Severity" drop-order claim: it is incorrect. Struct fields drop in DECLARATION order (reverse-drop is the rule for LOCAL variables; verified by a standalone rustc program), so the existing reset->weight->lock field order already runs the reset while both locks are held. Reordering the fields would INTRODUCE the very race the comment guards against. Codex adversarial review: approve, no material findings. lfm2_compiled_e2e 13/13 on both compiled and MLX_NO_COMPILE arms; eager-paged == compiled-paged byte-identical. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bcb506bc3a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…y (PR #66 review) PR #66 widened the compiled-registration gate from flat-only (`use_block_paged_cache==Some(false) && !is_quantized`) to a bare `!is_quantized`, so the DEFAULT paged bf16 checkpoint also registers and uses the new compiled-PAGED decode. But that also let a non-quantized **f16** (float16, not bf16) lfm2 loaded with the default paged cache register and publish `model_id` into the single, process-global, cross-family compiled registry — even though `paged_compiled_decode_setup` immediately forces it onto eager paged (`!all_float_weights_bf16`, since compiled-PAGED is bf16-only). Net: merely loading an f16-paged lfm2 EVICTED any resident qwen/lfm compiled model from its single-owner slot (`compiled_path_active()` is an id-equality probe; a new id makes the evicted model's probe fail until reload) for ZERO benefit. Fix: compute the whole-model bf16-clean scan first, then register only when the model can actually take a compiled path — gated by a pure helper `should_register_compiled(is_quantized, is_flat, all_float_weights_bf16)`: * quantized -> never (unchanged) * flat (any dtype) -> register (compiled-flat is dtype-generic) * bf16 paged -> register (compiled-paged) * f16/f32 paged -> SKIP (eager paged, no eviction) `is_flat = use_block_paged_cache == Some(false)` is authoritative at load time: the paged adapter is built once in `Lfm2Inner::new` from that flag and decode dispatch keys on `paged_adapter.is_some()`; a model never switches flat<->paged mid-life. Skipping registration leaves `model_id` unpublished and `all_float_weights_bf16` at its default false, so `paged_compiled_decode_setup` cleanly uses eager paged with no eviction. The pre-registration bf16 scan only reads `weight.dtype()` over the same sanitized `params` the registrar consumes (the f32 `*.expert_bias` exception is preserved), so reordering it ahead of registration is inert. Adds `compiled_registration_gate_skips_only_f16_paged` asserting the full matrix. Codex adversarial review: SOUND, no material findings. cargo fmt --check + clippy -p mlx-core --all-targets -D warnings clean; all 29 lfm2 persistence unit tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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.
Reviewed by Cursor Bugbot for commit 74b0e24. Configure here.
…#66 review) cursor[bot] (Medium) flagged a symmetric hole in the `should_register_compiled` gate added by 74b0e24: that gate skips registering an f16 *paged* checkpoint (compiled-PAGED is bf16-only) to avoid a needless cross-family registry eviction, but compiled-PAGED ALSO hard-requires block_size == 16 (`paged_compiled_decode_setup` falls back to eager paged when `adapter.block_size() != CPP_PAGED_REQUIRED_BLOCK_SIZE`). The paged arm only checked dtype, so a bf16 paged checkpoint with `paged_block_size` 8 or 32 still registered — clearing `g_weights` and publishing `model_id` into the shared, process-global, cross-family `g_active_model_id` (evicting any resident qwen/lfm compiled model whose `compiled_path_active()` id-equality probe then fails until reload) — yet always ran eager paged. Pure-downside eviction, same class the dtype gate closed for f16. `paged_block_size` is a plain `#[serde(default)] Option<u32>` (settable to 8/32 via config.json; `PagedAttentionConfig::validate` accepts {8,16,32}), and the adapter block size is `config.paged_block_size.unwrap_or(16)` fixed once at `Lfm2Inner::new` and immutable after — so the load-time config authoritatively predicts the decode-time gate. Fix: extend the gate's paged arm with `paged_block_size_ok = config.paged_block_size.unwrap_or(16) == CPP_PAGED_REQUIRED_BLOCK_SIZE` (imported from the same `qwen3_5::model` path the runtime gate uses), registering iff `!is_quantized && (is_flat || (all_float_weights_bf16 && paged_block_size_ok))`. The flat arm stays block-agnostic (flat compiled is dtype/block-generic; a flat instance has `paged_adapter == None`, the exact complement of the `Some`-iff- `use_block_paged_cache != Some(false)` adapter construction), and the `unwrap_or(16)` matches the adapter so a `None` config still registers (None → 16-block adapter → arms compiled). This makes the load-time gate complete: {not-quantized, all-float-bf16, block16} is the full set of load-time-knowable compiled-paged preconditions; every remaining decline (model-id eviction race, seed-time pool failures, mid-cycle forward errors) is runtime-only and already handled by the lock-release + RAII reset fallback. Verified via a 4-lens + adversarial-refutation workflow (finding CONFIRMED real, fix complete, all refutations failed) and Codex adversarial review (SOUND, no material findings). Renames the gate unit test to `compiled_registration_gate_skips_f16_or_nonblock16_paged` and adds the bf16+paged+block!=16 → skip and flat-block-agnostic cases. Note (separate, pre-existing, out of scope): qwen3_5 / qwen3_5_moe register unconditionally and rely solely on the runtime block!=16 gate, so they carry the same needless eviction for non-16-block paged checkpoints; lfm2's gate is deliberately stricter. Tracked as a follow-up. cargo fmt --check + clippy -p mlx-core --all-targets -D warnings clean; all 29 lfm2 persistence unit tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… fix paged prefill-tps telemetry Quantized lfm2_moe checkpoints carry `.scales` tensors, so they can never register with the compiled-PAGED C++ path; with `use_block_paged_cache` defaulting ON they fell onto the eager-PAGED loop (~12 `synchronize_mlx()`/token, blocking `y.eval()`, no async double-buffering) — ~1.84× slower than the eager-FLAT path (in-graph KVCache + `async_eval_arrays`) on the measured mxfp8 LFM2.5-8B-A1B (74 → 131 tok/s on M5 Max, closing most of the gap vs oMLX's 187). Fix #1: resolve the `use_block_paged_cache` default in `Lfm2Inner::load_from_dir`, keyed on the authoritative `.scales` tensor signal (the SAME signal that gates compiled registration, so the two can't diverge for a checkpoint whose quantization block lacks top-level bits/mode) — quantized + unset → flat; bf16 → paged (PR #66 compiled-PAGED unaffected); an explicit config.json value always wins. The server auto-routes via `has_block_paged_cache()`, so batched / cross-request reuse is unaffected (bf16 stays paged; quantized moves to the warm-slot path the server already supports). Single-stream only. Fix #4: the paged prefill-throughput telemetry divided ttft by the attention SUFFIX (`tokens.len() - cached_prefix_len`), but paged prefill reprocesses the FULL prompt through the conv layers, so ttft is full-prompt scale — this under-reported prefill tok/s by the cache-hit ratio (~37 vs thousands on warm content-addressed prefix reuse). Use the full prompt count at both paged call sites. Qwen3.5's identical expression is correct (no conv reprocessing) and is left untouched. Deferred (plan only): quantized compiled-PAGED decode (#2, for batched serving) and a cross-family paged-loop wired_limit (#3a, no-op for the flat default on a 128GB host). Tests: pure-helper policy unit test; a parse_config-does-not-resolve contract test; a compute_performance_metrics divider test; and two #[ignore] real-weights regressions (quantized default load → flat via has_block_paged_cache(); paged warm-reuse prefill-tps is full-prompt scale). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Summary
Ports qwen3_5's compiled-paged decode to
lfm2+lfm2_moeso the default paged decode runs inside anmlx::core::compilegraph instead of the eager pure-Rust layer-by-layer loop.block_table/slot_mapping/offsetare threaded as array inputs (the trace stays static across steps), andfast::paged_kv_write+fast::paged_attentionrun over the sharedLayerKVPoolMetal buffers.Perf (the payoff)
Interleaved A/B, same binary, warm, temp 0, 256-tok, M5 Max — vs the old pure-Rust paged ceiling (~42/35 tok/s):
sendStreamrides the same compiled graph assend(within ~3% noise). Absolute numbers swing ±15–20% with thermal; the interleaved ratio is the stable figure.Both paged loops wired + measured
lfm2has two paged decode loops —chat_sync_core_paged_inner(non-streaming,ChatSession.send()) andchat_stream_sync_core_paged_inner(streaming,ChatSession.sendStream()). Both now sharepaged_compiled_decode_setup/paged_compiled_decode_step.Validation
cargo clippy --all-targets -- -D warningsclean,cargo fmt --checkclean,yarn build:nativecleanCodex adversarial review (3 rounds) — all findings resolved
paged_compiled_decode_setup/step;Lfm2PagedCompiledStateRAII guards declared reset → weight → lock so the C++ reset runs while the global locks are still held (Rust drops struct fields in declaration order)lfm2_reset_paged_globals()on every init error path + both catch blocksall_float_weights_bf16flag over the whole registered param map (allows the intentional f32*.expert_biason MoE)MLX_DISABLE_COMPILEmade the engagement counter lieg_weights+g_active_model_id) is ONE process-global owned by the last registrant. Gemma4 drew its id from a private counter while publishing onto the shared atom → its id could collide with lfm2/qwen and false-positive their gate (and itsmlx_clear_weightsevicted co-resident compiled models). Gemma4 has no compiled C++ forward path, so its registration was vestigial → deleted. Every registry-sharing family now draws from the shared 1-basedQWEN35_MODEL_ID_COUNTER. +race-free regression test.Files
crates/mlx-sys/src/mlx_lfm2_common.h—lfm2_attn_pure_fn_arr_pagedcrates/mlx-sys/src/mlx_lfm2_moe.cpp—lfm2_decode_fn_paged, paged globals, init/forward/reset/countercrates/mlx-sys/src/lib.rs— FFI declscrates/mlx-core/src/models/lfm2/{model,persistence}.rs— session, per-step wrapper, registration-gate widening, bf16 flagcrates/mlx-core/src/models/gemma4/persistence.rs— F5 deletion + regression testcrates/mlx-core/tests/lfm2_compiled_e2e.rs— parity + engagement tests🤖 Generated with Claude Code
Note
High Risk
Changes the primary LFM2 inference/decode path and process-global compiled weight/model-id state; cross-family registry bugs were real and fixes need careful co-residency testing.
Overview
Adds compiled-paged decode for LFM2/LFM2-MoE: new C++ graph (
lfm2_decode_fn_paged, paged KV ops, separate globals/FFI) and Rust hooks that seed from post-prefill paged pools + conv state, then run decode throughpaged_compiled_decode_setup/paged_compiled_decode_stepin both non-streaming and streaming paged loops, with locks, RAII reset, bf16/block-16 gates, and eager fallback on first-step failure.Load/registration now registers non-quantized bf16/f16 paged checkpoints into the shared compiled registry when weights are all bf16 and block size is 16 (
should_register_compiled,all_float_weights_bf16); flat path unchanged in spirit.Gemma4 stops calling into the shared compiled weight map (
register_gemma4_weights_with_cppremoved) so loads no longermlx_clear_weightsor publish colliding model ids against qwen/LFM2; regression test added.Prefill (default ON): slice to the last token before output norm +
lm_headin eager paged prefill; toggleMLX_LFM2_DISABLE_LAST_TOKEN_SLICE.E2E tests cover compiled-paged engagement, eager vs compiled-paged byte parity, streaming parity, and warm-cache fixes (
raw_textecho). New paired perf harness scripts underexamples/.Reviewed by Cursor Bugbot for commit 7b5b4be. Bugbot is set up for automated code reviews on this repo. Configure here.
Follow-up: prove-or-revert perf pass (decode → prefill)
After the compiled-paged decode landed, a deep-review of the lfm2 inference control flow surfaced further levers. Each candidate was implemented behind a
MLX_LFM2_DISABLE_*env toggle (same-binary A/B), then verified through a hard gate before being kept: build +clippy -D warnings+fmt→ byte-identical correctness (toggle-on == toggle-off at T=0) → thermally-fair paired perf A/B → keep only if the measured gain beats the noise floor, else revert.Kept (proven)
perf(lfm2): project lm_head on T=1 in paged prefill— the eager paged prefill ranembedding_norm+lm_head(vocab 65536 × hidden 2048) over the full[1,T,hidden]residual stream then sliced the last token; now it slices before the projection so the largest matmul runs on T=1.lfm2_compiled_e2e13/13 on both compiled andMLX_NO_COMPILEarms).MLX_LFM2_DISABLE_LAST_TOKEN_SLICE(default ON).Tested & rejected (honest — not a measured win)
drop the redundant post-prefill
synchronize— byte-identical, but measured +0.07%, inside the ±1.5% noise floor (inconsistent sign), so reverted rather than claimed.Tooling
examples/lfm2-perf-ab.ts(single-arm,reportPerformancemetrics) +examples/lfm2-perf-pair.py(paired orchestrator + verdict).Not in this PR (bigger follow-ups)
.scalesgate; kernels (quantized_matmul/gather_qmm) + the qwen3_5_moe registry template already exist.