Skip to content

perf(qwen4): optimize Qwen 3.8 Flash Next prefill, decode, DFlash2 & prefix caching end-to-end - #465

Merged
Brooooooklyn merged 6 commits into
mainfrom
perf/qwen4-flash-next
Dec 1, 2026
Merged

Brooooooklyn merged 6 commits into
mainfrom
perf/qwen4-flash-next

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Contributor

Summary

End-to-end Metal 4 / Apple Silicon inference optimization for Qwen 3.8 Flash Next (qwen4_exp), bringing real 104 GiB UD-Q4_K_XL + DFlash2 performance into Splash / TensorFold territory while preserving bit-exact greedy parity and persistent PagedAttention RAM + SSD prefix caching.

flowchart LR
  subgraph Prefill["Prefill Overhaul (1.8x–5.2x faster TTFT)"]
    P1["In-place Tiled64 Q8_0 repack<br/>Zero TG/barriers INT8 NAX GEMM"]
    P2["AOT Unified MoE Prefill (BM=32)<br/>bfloat x half NAX, 8 KiB stage, shared fused"]
    P3["AOT Sparse QSA + GDN Prefill + PLE<br/>Fused block indexer Q/K & bank-coalesced PLE"]
  end
  subgraph Decode["Decode & Speculation (1.3x–3.6x faster)"]
    D1["Tiled64 M=1..2 col & M=3..64 mat<br/>Zero JIT CustomKernels, budget=0"]
    D2["Fused hc_down+hc_inject+2*sig(w/4)<br/>Fused QSA QKV prep+store & gated attn"]
    D3["DFlash2 M=8 + Metal Tree Verify (T<=16)<br/>Spanned vocab + Q4 head + kv_mode=4"]
  end
  subgraph Serving["Serving, Memory & Prefix Cache"]
    S1["INT8 GDN prefix states (110->31 MiB)<br/>Q4PS v5 + persistent SSD reload"]
    S2["1|4|24 flush schedule (0ms Bubble #2)<br/>Host-gate, KV growth cliff & 4-lane fairness"]
  end
Loading

Key Changes

  • Unified Tiled64 Dense Q8_0 (qwen4_tiled64_linear.metal, mlx_qwen4_tiled64.cpp, weights/): Load-time GPU repack of fixed q8_symmetric_128 banks (N%64==0, K%64==0, excluding output.weight and ffn_*_shexp) into Splash Tiled64 (plane0 + meta, dropping biases for ~5.6% runtime VRAM savings), powering zero-TG/zero-barrier INT8 NAX prefill (M>64), register-dequant matmul2d (M=3..64), coalesced col_m1/m2 (M=1..2), and fused hc_up + hc_mix with budget=0 (eliminating all 209 JIT CustomKernels in decode).
  • AOT Unified MoE Prefill (qwen4_moe_prefill.metal, mlx_qwen4_moe_prefill.cpp): Replaces JIT fast::metal_kernel prefill MoE (which ran FP32/TF32 down in 23 KiB TG SRAM and serialized shared experts across 2,511 size CB splits) with a single /32-budgeted AOT primitive using bfloat×half NAX, 8 KiB per-SG stage, simdgroup_barrier only, 4-bucket LPT indirect tiles, and unified shared-expert + combine fusion.
  • AOT Sparse QSA, GDN, Indexer, PLE & Hyper Fusion (qwen4_sparse_qsa.metal, qwen4_gdn_prefill.metal, qwen4_ple.metal, paged_indexer.metal, paged_qsa_attention.metal, qwen4_decode_ops.metal, qwen4_lm_head.metal):
    • Single-dispatch fused hc_down + hc_inject + 2*sigmoid(w/4) (-384 disps/step) and null-branch AOT inject_norm.
    • Fused QSA QKV prep+store (prefill, decode & tree verify), fused block-indexer Q-prep & K-pool+store, _gated paged QSA attention (sigmoid(gate) epilogue), 10× faster AOT radix11 Qwen4PagedIndexerSelect, and AOT Qwen4LmHeadQ8Argmax.
    • Bank-coalesced PLE lookup + single-dispatch qwen4_ple_gate_conv_bf16 & qwen4_ple_gate_conv_tree_bf16.
  • DFlash2 Speculation (dflash2/, draft_cycle/{mod,cost_model,tree_metal}.rs, packages/lm/): Auto-discovery with soft residency fallback, fast Q4 a4g64@t64 draft head with spanned vocab [0..148_288) ∪ [248_000..248_320), M=8 wave verify, Metal solo verify tree (T<=16) with exact sparse block-boundary top-k parity (HAS_PRE_TAIL_MASK) and kv_mode=4 token-major Int8 KV compaction, plus fixed WaveCostModel slope calibration.
  • Serving, Memory & Prefix Cache (state_codec.rs, prefix_disk.rs, hybrid_scheduler.rs, paged_kv_cache_adapter.rs, host.rs):
    • Per-32 symmetric INT8 GDN prefix states (110.3 -> 31.0 MiB/cell, STORED_STATES = 10, Q4PS v5 + MLX_QWEN4_PREFIX_STATE_FP32=1 opt-out bound into persistent fingerprint).
    • Host-gate compression-credit & rusage cap fixes, KV growth-cliff fix (single-extent cap before reclaim + index-plane accounting), 4-lane coalescing & 100 ms layer-sliced resumable prefill, 1|4|24 decode flush schedule (zeroing Host Bubble Welcome to mlx-node Discussions! #2), async cell_from_caches, and fallible cross-stream synchronization with fault latching.
    • Zero hardcoded GPU core counts (dynamically queried via mlx_gpu_core_count(), device.get_architecture_gen(), and metal::is_nax_available()).

Live E2E Benchmarks (Real 104 GiB Qwen3.8-Flash-Next-UD-Q4_K_XL on M5 Max 128 GB)

Autoregressive (AR) & Prefill

Case Before After Gain
title_450 (load → 1st turn) 6,325 ms (host-gate) 230 ms / 68.5 t/s (direct) 27.5× TTFT
chat_1.5k greedy (T=0.0) 4,522 ms (327 t/s) 877 ms (1,687 t/s) / 61.2 t/s 5.16× TTFT
chat_inc_4.5k (prefix hit) 5,388 ms / 40.5 t/s 1,599 ms (1,907 t/s) / 58.3 t/s 3.37× TTFT / +44% dec
work_cold_12k (9.5K) 11,522 ms (823 t/s) 5,107 ms (1,857 t/s) / 58.5 t/s 2.26× TTFT
work_cold_34k (38.7K) 39.8 s / 45.1 t/s 22.3 s (1,735 t/s) / 58.0 t/s 1.78× TTFT / +29% dec
work_cold_64k (75.8K) 82.5 s / 46.0 t/s 46.5 s (1,632 t/s) / 57.6 t/s 1.78× TTFT / +25% dec
work_inc_65k (79.5K) 5.89 s / 26.7 t/s (blk=5011) 2.42 s / 57.6 t/s (blk=2792) 2.43× TTFT / 2.16× dec
swarm_4L (165K, 4 concurrent) 172.8 s (0 hits, 34 mem drops) ~94 s (3 hits, 9 states, 0 drops) 1.84× wall
vision_chat_3k (2 JPGs) — 1,893 ms / 57.7 t/s clean

DFlash2 Speculative Decode (bit-exact with AR greedy)

Case Before After Gain
chat_1.5k greedy (T=0.0) 2,283 ms / 36.8 t/s 852 ms / 100.7 t/s 2.68× TTFT / 2.74× dec
chat_1.5k T=1 k=0 — 789 ms (1,874 t/s) / 110.5 t/s —
chat_1.5k DEF (T=1 k=20) 1,875 ms / 40.9 t/s 789 ms / 83.1 t/s 2.38× TTFT / 2.03× dec
work_cold_12k 14.6 s / 58.5 t/s 5.26 s (1,804 t/s) / 94.4 t/s 2.78× TTFT / 1.61× dec
work_cold_34k (38.7K) 62.2 s / 32.6 t/s 22.8 s (1,697 t/s) / 118.8 t/s 2.73× TTFT / 3.64× dec
swarm_4L (165K, 4 concurrent) 263.2 s 95.2 s (solo tail 91.4 t/s) 2.77× wall (-168 s)

PagedAttention RAM + Persistent SSD Prefix Cache (Q4PS v5)

Turn (9,485 tok, T=0.0) TTFT Speedup vs Cold Decode Notes
Cold 12K write 5,535 ms 1.0× 58.1 t/s SSD durable 3 states (97.8 MB), refused=0
Cross-owner RAM hit 138.2 ms 40.1× 60.3 t/s prefixRestored=3
Vision 2-JPG turn 1 → turn 2 1,837 → 375.9 ms 4.9× 58.2 t/s Multimodal continuation
Fresh process SSD reload 169.1 ms 32.7× 58.4 t/s adopted=5, diskRestored=1, droppedChain=0, bit-exact with RAM hit

Verification

  • cargo fmt --check & cargo clippy -p mlx-paged-attn -p mlx-sys -p mlx-core --lib --tests -- -D warnings: 0 warnings
  • bridge_metallib_names: 12/12 passed (all 152 qwen4_* Metal kernels verified present + compiling live pipelines)
  • mlx-paged-attn: 259 passed; kernels::qwen4: 18 passed (both Metal 4 NAX & MLX_QWEN4_FORCE_NON_NAX=1)
  • models::qwen4_exp: 543 passed; engine::hybrid_scheduler: 120 passed; engine::scheduler: passed
  • TS suites (packages/lm, inference-host, metallib-select): 11/11 files, 562/562 tests passed
  • crates/mlx-sys/mlx submodule verified 100% clean

@coderabbitai

coderabbitai Bot commented Dec 1, 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

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d5eec043-266c-4d2e-899f-423ff94ba129

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
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-01T19:30:51.198433Z 2d356e8 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Brooooooklyn
Brooooooklyn merged commit 1f5a775 into main Dec 1, 2026
22 checks passed
@Brooooooklyn
Brooooooklyn deleted the perf/qwen4-flash-next branch December 1, 2026 23:38
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