Skip to content

perf(gemma4): accelerate long-context decode - #111

Merged
Brooooooklyn merged 10 commits into
mainfrom
perf/gemma4-long-context-decode
Aug 1, 2026
Merged

Brooooooklyn merged 10 commits into
mainfrom
perf/gemma4-long-context-decode

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • route supported Gemma4 BF16 D512 decode through an optimized grouped Metal path with direct paged-KV reads and a measured long-context stripe policy
  • reuse decode metadata by block-table revision and bypass the single-slot KV max reduction while keeping request release/reuse cache-safe
  • cache plain E4M3 reconstructed-weight transposes at load time and honor composed model maxTokens limits when a turn has no explicit override
  • add route, parity, lifecycle, benchmark, and agent configuration coverage plus diagnostic documentation

Why

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 ForceD512Staged internal 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.

  • 128-stripe policy: +5.8% weighted decode throughput across three repeated A/B runs
  • direct D512 reads: five-layer median 18.715 ms -> 9.653 ms (-48.4%, 1.94x), with byte-exact deterministic parity
  • advancing decode metadata: 24.087 us -> 0.582 us per token; same-token reuse: 4.593 us -> 0.004 us
  • single-slot KV scheduling: 14.921 ms -> 0.742 ms over 128 tokens x five layers; total 47.442 ms -> 28.134 ms
  • cached FP8 transpose, five alternating pairs with identical checksums:
    • FP8 graph construction: -32.9%
    • full-token graph construction: -17.4%
    • FP8 materialized execution: -1.8%
    • full-token materialized execution: -3.0%

Rejected alternatives:

  • contiguous hot KV: 9.958 ms versus 8.216 ms for paged direct, plus 74.8 ms hydration and about 1.75 GiB of extra memory
  • centralized reducer: 3.37% slower
  • typed quant dispatch: about 0.14%, statistically inconclusive
  • trusted block scan bypass and host bookkeeping changes: too small to retain

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-lm at e5baded8c1d286754edb479ffbde4655a68e2758.

Validation

  • cargo test --release -p mlx-core --lib (2,593 passed, 58 ignored)
  • cargo clippy --release -p mlx-core --lib --tests -- -D warnings
  • cargo fmt --all --check
  • yarn test packages/agent/__test__/chat-config.test.ts packages/agent/__test__/stream-adapter.test.ts (55 passed)
  • yarn build:ts
  • yarn lint
  • git diff --check origin/main..HEAD

Note

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_plan policy 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, PagedDecodeRouteHint so model-level choices are not overridden by env Auto, and richer route/fallback telemetry.

PagedKVCacheAdapter caches decode planning per context bucket, reuses block-table metadata across token advances via physical_revision, passes route hints through graph and raw Metal gather, and hardens release_request when the allocator is poisoned or the table is already gone. SequenceBlockTable bumps 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.

QuantizedLinear plain 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.

@coderabbitai

coderabbitai Bot commented Jul 31, 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 Plus

Run ID: 75656b26-d234-4853-b1a4-5a8faa812ccb

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

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.

@cursor

cursor Bot commented Jul 31, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

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

@Brooooooklyn
Brooooooklyn merged commit 96d5656 into main Aug 1, 2026
7 checks passed
@Brooooooklyn
Brooooooklyn deleted the perf/gemma4-long-context-decode branch August 1, 2026 01:02
robert-johansson pushed a commit to robert-johansson/mlx-node that referenced this pull request Aug 2, 2026
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]>
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