Repository navigation
perf(gemma4): accelerate long-context decode - #111
Conversation
|
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 Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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 |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_336e9066-d824-4b39-a0d6-40a5ea93d6aa) |
Merge-forward of mirror/upstream (237ab8a, tag v0.0.10). 10 upstream commits: mlx-node#108/mlx-node#109 template-authoritative chat + continuation cache reuse, mlx-node#110 desktop control panel, mlx-node#111 gemma4 long-context decode, mlx-node#113 quantized inference fast paths. NOT a low-risk bump. crates/mlx-sys/src/lib.rs (+93), mlx_na_int8.cpp (+162), mlx_paged_*.cpp/.h (~550), and mlx_paged_stubs_linux.cpp (+24, our platform) all move; build.mjs rebuilds mlx-sys as a cargo dependency, so this reaches the binary GenMLX loads. 7 conflicts, then 38 rustc errors from API ripples that auto-merged cleanly into regions our fork also touches. Three ripple classes: mlx-node#113 Embedding refactor — project_logits_from_hidden and the forward/prefill family now take `embedding: &Embedding` instead of a raw weight + optional transposed twin. Adopted wholesale. inject_image_placeholders — now returns Result<Vec<u32>>; fork VLM call sites needed `?` (16 of the 38 errors, and NO resolver reported this class). ChatStreamChunk — gained three required fields; fork-added literals filled by mirroring the dense sibling's own values rather than blind-defaulting. THE TRANSPOSED EMBEDDING WEIGHT WAS NEVER OURS. It was flagged mid-merge as a lost fork perf patch; provenance says otherwise. The merge base already carried it (69 dense / 42 MoE occurrences), traced to upstream's own mlx-node#24, and upstream removed it in mlx-node#113. Our fork merely FOLLOWED that convention at call sites we added. Preserving it would have been a regression, not a rescue: Embedding documents `get_weight()` as a tripwire — "production inference must never call get_weight() on a packed embedding because that constructs a full [vocab, hidden] dequantization graph" — and mlx-node#113's `as_linear` routes packed checkpoints through mlx_quantized_matmul(transpose=true) so the dense table is never materialized. FORK PATCHES VERIFIED INTACT: genmlx-d3yn (one generation stream per model) — byte-exact. Stream::new sites 4/4 dense and 2/2 MoE vs HEAD; generation_stream refs 90/90 and 80/80. This is the patch most at risk of silent loss, and note it CANNOT be validated here: the leak is Metal-only (Stream::new collapses to the default stream without Metal), which is why it never reproduced on Thor. A green battery on a CUDA box proves nothing about it. mlx-cft4 (merged_qkvz in MoE weight loading) — was HALF-LOST and is restored. Upstream demoted apply_weights_moe_inner to a #[cfg(test)] wrapper and moved production loading into apply_weights_moe_inner_with_residency, which had no merged_qkvz param; our parameter survived only on the test-only wrapper while its consuming logic rode into the production body. Re-plumbed (:522, consumed :765). Left unfixed this would have silently corrupted MoE expert weight loading — no test would have caught it. genmlx-uhtp (mlx_report_error on paged-attn catch sites) — intact, rebased onto upstream's renamed context label. mlx gitlink UNCHANGED (fef8890f both sides — no nax replay needed). Superset invariant re-verified on freshly fetched refs after finding the first check ran against a stale up/main: `git cherry -v origin/main fef8890f up/main` -> 0 '+'. cargo check -p mlx-core --release: 0 errors. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Summary
maxTokenslimits when a turn has no explicit overrideWhy
At roughly 92K context, tracing showed decode time growing in the D512 attention path. The main avoidable costs were staged K/V copies, repeated decode metadata construction, a redundant max reduction for one-slot writes, and rebuilding plain-FP8 transpose graphs on every forward. Separately, normal Pi agent turns omitted a per-call token limit, so the composed model limit could be ignored and a session could stop earlier than configured. That correctness fix stays in this PR because it was required to reproduce and bound the original long-context agent workload reliably; it has independent focused coverage.
The paged pool remains the authoritative KV store. A contiguous hot-RAM mirror was benchmarked and rejected because it was slower for this geometry and would add substantial unified-memory pressure.
For compatibility, the legacy
ForceD512Stagedinternal route-hint spelling remains accepted but now selects the canonical direct-read backend. Existing Gemma4 diagnostic environment aliases are also preserved.Benchmarks
Exact Gemma4 geometry unless noted: BF16, Hq=16, Hkv=2, D=512, block size 16, context 91,795, five global layers.
Rejected alternatives:
A full-agent replay was used only as a sanity check, not formal benchmark evidence, because generated content diverged between numerical reduction paths and an unrelated background workload changed during the pair.
The upstream implementation audit used
mlx-lmate5baded8c1d286754edb479ffbde4655a68e2758.Validation
cargo test --release -p mlx-core --lib(2,593 passed, 58 ignored)cargo clippy --release -p mlx-core --lib --tests -- -D warningscargo fmt --all --checkyarn test packages/agent/__test__/chat-config.test.ts packages/agent/__test__/stream-adapter.test.ts(55 passed)yarn build:tsyarn lintgit diff --check origin/main..HEADNote
High Risk
Changes core Gemma4 decode routing, Metal kernel selection, and paged KV adapter lifecycle on the inference hot path; mis-routing or stale metadata could affect correctness or OOM behavior at long context.
Overview
Gemma4 paged decode is reworked around a
select_paged_decode_planpolicy that buckets context (4K), estimates multi-layer SDPA scratch from live headroom, and picks paged-pool SDPA only when headroom fits—otherwise paged attention, with explicit reasons and per-bucket SDPA failure latches. Grouped “D512” kernels replace the Gemma4-only naming: broader GQA geometries, measured ~92K crossovers, capability probes,PagedDecodeRouteHintso model-level choices are not overridden by envAuto, and richer route/fallback telemetry.PagedKVCacheAdaptercaches decode planning per context bucket, reuses block-table metadata across token advances viaphysical_revision, passes route hints through graph and raw Metal gather, and hardensrelease_requestwhen the allocator is poisoned or the table is already gone.SequenceBlockTablebumps revision on physical block changes only.Metal: production D512 grouped attention uses direct K/V reads (staged variant kept under a separate kernel name); stripe counts account for KV-head parallelism and Hq16/Hkv2 wide stripes at long context.
QuantizedLinearplain FP8 caches the[K,N]transpose at load so decode forwards skip per-call transpose graph work.Reviewed by Cursor Bugbot for commit 8013afa. Bugbot is set up for automated code reviews on this repo. Configure here.