Skip to content

perf(lfm2): compiled paged decode (~2× / ~1.5×) + paged-prefill last-token slice (~10% TTFT) - #66

Merged
Brooooooklyn merged 7 commits into
mainfrom
feat/lfm2-compiled-paged
Jun 3, 2026
Merged

Brooooooklyn merged 7 commits into
mainfrom
feat/lfm2-compiled-paged

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Ports 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 (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 (compiled prefill is a separate effort, exactly like qwen).
  • Dense + MoE in one decode fn; bf16/f16 only (quantized stays eager, same gate as the flat path).
  • Gated default-ON with eager fallback on first-step init/forward failure.

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

checkpoint old pure-Rust new compiled-paged ratio
1.2B dense ~42 ~149 (med) ~1.96×
8B MoE ~35 ~70 (med) ~1.47×

sendStream rides the same compiled graph as send (within ~3% noise). Absolute numbers swing ±15–20% with thermal; the interleaved ratio is the stable figure.

Note: the flat compiled port was parity (flat-eager is already atomic C++). This paged port is the real win because paged-eager was pure-Rust layer-by-layer.

Both paged loops wired + measured

lfm2 has two paged decode loops — chat_sync_core_paged_inner (non-streaming, ChatSession.send()) and chat_stream_sync_core_paged_inner (streaming, ChatSession.sendStream()). Both now share paged_compiled_decode_setup / paged_compiled_decode_step.

Validation

  • eager-paged ≡ compiled-paged byte-identical (greedy) on 1.2B dense + 8B MoE
  • streaming ≡ non-streaming byte-identical
  • counter-based engagement assertions (no thermal-noise dependence)
  • lfm2 compiled e2e 13/13 + eager 13/13; +2 bf16-gate unit tests; +gemma4 collision regression
  • cargo clippy --all-targets -- -D warnings clean, cargo fmt --check clean, yarn build:native clean

Codex adversarial review (3 rounds) — all findings resolved

Finding Fix
F1 streaming bypassed compiled-paged shared paged_compiled_decode_setup/step; Lfm2PagedCompiledState RAII guards declared reset → 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 too narrow authoritative load-time all_float_weights_bf16 flag 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 → 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.

Files

  • crates/mlx-sys/src/mlx_lfm2_common.h — lfm2_attn_pure_fn_arr_paged
  • crates/mlx-sys/src/mlx_lfm2_moe.cpp — lfm2_decode_fn_paged, paged globals, init/forward/reset/counter
  • crates/mlx-sys/src/lib.rs — FFI decls
  • crates/mlx-core/src/models/lfm2/{model,persistence}.rs — session, per-step wrapper, registration-gate widening, bf16 flag
  • crates/mlx-core/src/models/gemma4/persistence.rs — F5 deletion + regression test
  • crates/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 through paged_compiled_decode_setup / paged_compiled_decode_step in 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_cpp removed) so loads no longer mlx_clear_weights or publish colliding model ids against qwen/LFM2; regression test added.

Prefill (default ON): slice to the last token before output norm + lm_head in eager paged prefill; toggle MLX_LFM2_DISABLE_LAST_TOKEN_SLICE.

E2E tests cover compiled-paged engagement, eager vs compiled-paged byte parity, streaming parity, and warm-cache fixes (raw_text echo). New paired perf harness scripts under examples/.

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.

Measurement note: cross-invocation tok/s drifts ~15% on M5 Max (thermal). The A/B orchestrator (examples/lfm2-perf-pair.py) interleaves baseline/optimized arms back-to-back, takes the median of per-pair ratios (drift-canceling), and gates a "real win" on a control band measured from a no-op run (validated: a no-op toggle reads +0.79%, real_win=false; robust floor ≈1.5–2.2%).

Kept (proven)

perf(lfm2): project lm_head on T=1 in paged prefill — the eager paged prefill ran embedding_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.

  • Byte-identical at T=0 (toggle on==off on 1.2B + 8B; full lfm2_compiled_e2e 13/13 on both compiled and MLX_NO_COMPILE arms).
  • Measured TTFT median ratio 1.0965 (+9.65%, 1.2B) / 1.1194 (+11.94%, 8B) vs control band ±1.5/2.2%. The win is fully attributable to the output projection (prefill ratio == total ratio).
  • Gated by 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, reportPerformance metrics) + examples/lfm2-perf-pair.py (paired orchestrator + verdict).

Not in this PR (bigger follow-ups)

  • Quantized compiled-paged decode (~1.4–1.9× for the realistic quantized deployment shape) — blocked today by a one-line .scales gate; kernels (quantized_matmul/gather_qmm) + the qwen3_5_moe registry template already exist.
  • Decode lookahead (async_eval pipelining) — needs the on-device-token enabler first.

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]>
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b0c4dc82-2202-4d8c-bfc4-46948533401a

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/lfm2-compiled-paged

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.

Brooooooklyn and others added 2 commits June 3, 2026 16:05
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]>
@Brooooooklyn Brooooooklyn changed the title perf(lfm2): compiled paged decode — ~2× (1.2B dense) / ~1.5× (8B MoE) perf(lfm2): compiled paged decode (~2× / ~1.5×) + paged-prefill last-token slice (~10% TTFT) Jun 3, 2026

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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]>

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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]>

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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]>

@cursor cursor 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.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ 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]>
@Brooooooklyn
Brooooooklyn merged commit 3360e4f into main Jun 3, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/lfm2-compiled-paged branch June 3, 2026 12:54
Brooooooklyn added a commit that referenced this pull request Jun 4, 2026
… 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]>
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