Skip to content

[Engine] Qwen4-35B-A3B Apple Silicon Metal optimizations (16 GB partial-VRAM & full-VRAM) #472

Backlog

Description

@NightRain233

Problem

Profiling Qwen4-35B-A3B-UD-IQ2_XS on Apple Silicon Metal (v0.2.20-poly.10 / df2c3ff, Apple M5 Ultra 256 GB, both full VRAM and simulated 16 GB partial-VRAM budgets) surfaced four independent bottlenecks:

  1. PLE 11.52 GB n-gram table on macOS / Metal: per_layer_token_embd.weight (160M x 128 IQ4_NL, 72 B/row, 16 random rows/token) is whole-file mmap'd on Metal. With macOS 16 KiB VM pages, random mmap lookups pull at least 256 KiB/token into the unified buffer cache and thrash 16–24 GB Macs, while start_ple_warmer() has no macOS branch for 64–256 GB Macs. Related: [Engine] qwen4: read the PLE n-gram table row by row from disk through the Direct reader #440 and [Engine] qwen4: with --ple-direct, read PLE rows ahead: a decode window's while its guesses are drafted, a prompt's while its first layers run #465 (note [Engine] qwen4: read the PLE n-gram table row by row from disk through the Direct reader #440 currently falls back to mmap on Metal).
  2. Metal partial-VRAM host-GPU sync wall (router wait ~17–19 ms/tok): Engine::bell_on() returns false on Metal, disabling whole_rec_ / gr_deferred_write_ as soon as any expert is outside VRAM (!all_cached()) and forcing ~40 per-layer command buffer flushes + host waits per token.
  3. Missing Metal Qwen4 decode fusions: q4_gr_down_silu_quant (poly_mul_q8_0_k4 + q4_gr_silu_1_1 = 11.0% of full-VRAM decode GPU time) and q4_mul_sigmoid_q8_1 are skipped on Metal (#if !defined(STRATA_GPU_METAL)), and routed-expert gate_up still round-trips FP32 g_ before swiglu_rows_quantize_q8_1 (poly_quantize = 4.0% GPU time).
  4. 4K prefill QSA sparse attention hotspot: q4_qsa_attend_batch_q8_8 uses scalar per-element K/V reads and scalar FMAs, taking 515 ms (29.3% of total 4K prefill GPU time) at 1.34 TFLOP/s on M5 Ultra.

Split PRs (4 independent PRs, each against df2c3ff)

  1. [Engine] qwen4: extend --ple-direct to Metal (F_NOCACHE), async overlap, and macOS warmer #473 (Draft) — PLE Direct reader (F_NOCACHE) + async prefetch + macOS warmer (coordinates with [Engine] qwen4: read the PLE n-gram table row by row from disk through the Direct reader #440 / [Engine] qwen4: with --ple-direct, read PLE rows ahead: a decode window's while its guesses are drafted, a prompt's while its first layers run #465).
  2. [Engine] metal: add MTLSharedEvent doorbell with defer-rank and watchdog-safe CB chunking #474 (Draft) — Metal MTLSharedEvent partial-VRAM MoE doorbell + zero-bandwidth id < 0 skip.
  3. [Engine] qwen4/metal: fuse decode kernels, QSA score MMA, and overhaul Gated Residual #475 (Draft) — Metal Qwen4 decode fusions (260-TG q4_gr_down_silu_quant, q4_mul_sigmoid_q8_1, routed-expert SRAM gate_up + SwiGLU + Q8_1).
  4. [Engine] qwen4/metal: rewrite q4_qsa_attend_batch with simdgroup_matrix #476 (Ready) — Metal q4_qsa_attend_batch simdgroup_matrix rewrite (Metal-only 3 files; counterpart to CUDA [Engine] qwen4: QSA prompt attention for eight query heads a KV head from registers, the same bits #470).

Combined same-day A/B results (Apple M5 Ultra 256 GB, Qwen4-35B-A3B-UD-IQ2_XS, --kv q8_0 --lookup 0, df2c3ff vs combined 4-in-1)

Scenario Baseline (df2c3ff) Combined 4-in-1 Gain
Full VRAM --no-draft (192 tok) 92.27 tok/s 111.96 tok/s +21.3%
Full VRAM Embedded MTP (192 tok) 153.22 tok/s 154.52 tok/s +0.8%
Full VRAM 4K prefill (4096 tok) 2,488.2 tok/s 3,425.1 tok/s +37.7%
Sim 16 GB dynamic LRU --no-draft (5.3 GiB VRAM, 6 threads, --ple-direct) 23.08 tok/s 32.67 tok/s +41.6%
Sim 16 GB dynamic LRU MTP (5.2 GiB VRAM, 6 threads, --ple-direct) 25.39 tok/s 30.79 tok/s +21.3%
Sim 16 GB frozen 65% + --ram-experts-mib 0 --no-draft (6 threads, --ple-direct) 29.70 tok/s 46.97 tok/s +58.1%
Sim 16 GB frozen 62.4% + --ram-experts-mib 0 MTP (6 threads, --ple-direct) 40.63 tok/s 57.60 tok/s +41.8%
Sim 16 GB frozen 65% + --ram-experts-mib 0 4K prefill (4096 tok, --ple-direct) 2,039.5 tok/s 2,570.3 tok/s +26.0%

Limits / unverified

  • Hardware measurements above are on Apple M5 Ultra 256 GB (macOS, Release build); CUDA, HIP, SYCL, Windows, and Linux builds are not yet run. Physical 16 GB Apple M4 measurements will be added here once run.

Activity

  1. NightRain233 commented on Dec 6, 2026

    @NightRain233
    ContributorAuthor

    Status Update — Rounds 1–4 Complete, Rebased onto origin/main (0794bc5), Physical 16 GB M4 & Factorial Quality Verified

    Since opening this issue, #476 (QSA simdgroup_matrix batch attention, integrated in de0fe5b9f), #498 (high-BW short4/TG-LUT decode GEMV), and #504 (CI fixes) have landed on main, and upstream #464 added opt-in --ple-direct for CUDA/HIP.

    All 9 remaining Qwen4 / Metal PRs have been cleanly rebased onto origin/main (0794bc5, including #498 and #464), with zero merge conflicts (MERGEABLE), verified end-to-end on physical 16 GB Apple M4 (Mac16,12) and 256 GB Apple M5 Ultra, and audited with a 10-config factorial quality suite separating lossless defaults from opt-in approximate knobs.


    1. PR Status & Recommended Review / Merge Order

    Order PR Head Status Default Path Verified Checks (exact commit on 0794bc5)
    — #476, #498, #504 — Merged / Integrated — On main
    1 #511 — Lossless 256-K MMA256 (Q4_K/Q5_K/Q6_K/Q8_0), _fast_r2..r8, moe_sum_v4 b6ec657 Ready (MERGEABLE, pure engine/metal/) 100% lossless; Apple10 <2048-out k4 guarded M5 Ultra 51/51 ctest + standalone M5 Ultra & M4 A/B vs 0794bc5
    2 #513 — GPU cache-bias routing (kGateSoftmaxLogitAdd = 4) d38abe8 Ready (MERGEABLE) Opt-in (--cache-bias > 0); default unchanged M5 Ultra 51/51 ctest + factorial quality (CUDA/HIP kernels.cu awaits run-backends CI)
    3 #499 — Fix <= 24 GiB balanced Metal budget (XNU reclaimable VM + wired > 55% backoff) cc073b0 Draft (MERGEABLE) > 24 GiB Macs & non-Metal unchanged M5 Ultra 51/51 ctest, docs 6/6
    4 #473 — Extend #464 --ple-direct to Metal (F_NOCACHE, auto tight-RAM, layer-0 overlap, macOS warmer) 40478fe Draft (MERGEABLE) Preserves #464 CUDA/HIP opt-in 0 default M5 Ultra 51/51 ctest, settings_register, docs 6/6
    5 #475 — Lossless Qwen4 decode fusions, QSA score MMA (14.6×), Gated Residual overhaul 35a0e6a Draft (MERGEABLE) 100% lossless (≤ 1.5e-5 parity) M5 Ultra 51/51 ctest, docs 6/6
    6 #474 — Metal MTLSharedEvent doorbell, watchdog/AGX leak guard, CB chunking & opt-in --defer-rank 5a3b357 Draft (MERGEABLE) Default --defer-rank -1 strictly lossless M5 Ultra 51/51 ctest, settings_register, docs 6/6
    7 #500 — Native Metal BasinKV sparse KV offload (--basinkv, Quest/SphereIndex, WHT-INT4) 24ff792 Draft (MERGEABLE) Strictly opt-in (--basinkv) M5 Ultra 52/52 ctest (poly_basinkv_parity 0–10), test_setup_basinkv 6/6, docs 6/6
    8 #501 — Qwen4 opt-in --dense-requant <q4_k|...>[+head] with never-upsize guard 3cc75cd Draft (MERGEABLE) Strictly opt-in (--dense-requant) M5 Ultra 51/51 ctest, quantize_q4_K_ref memcmp == 0, factorial quality
    9 #512 — 1-slot Metal doorbell in Qwen4::draft_step + BasinKV blk.40 truncation f5a04a5 Draft (Depends on #474, MERGEABLE) Stacked cleanly on 5a3b357 M5 Ultra 51/51 ctest (incl. DraftBellEngine 5/5)

    2. Verified Hardware Results (Qwen4-35B-A3B-UD-IQ2_XS)

    A. Standalone #511 (b6ec657) Same-Day Interleaved A/B vs origin/main (0794bc5)

    B. Integrated Stack on Physical 16 GB Apple M4 (Mac16,12, fanless 13" MBA, 8-core Apple9, 120 GB/s)

    • Out-of-the-box --metal-memory balanced (ZERO manual --vram-reserve-mib flags):
    • Long-Context NIAH on Physical 16 GB Apple M4 (--metal-memory balanced --ple-direct --max-context 131072 --basinkv --basinkv-index sphere --basinkv-kv-quant wht_int4):
      • 128K capacity (131,072 tokens): GPU BasinKV 68.3 MiB (hot 44.0 + idx 23.4 + meta 1.0) + pinned RAM 726.0 MiB, while keeping 3,393 routed experts in VRAM.
      • True 16K BasinKV NIAH: 119.1 tok/s prefill, peak 8.39 GiB, 100% exact recall (AMBER-4921).
      • True 32K QSA NIAH: peak 8.82 GiB, 612 MiB PLE SSD reads (58.1% hit), 100% exact recall (ORCHID-8814).
      • True 64K (65,536 tokens) BasinKV NIAH (needle at ~50% depth): 60.1 tok/s prefill, 7.37 tok/s decode (9/9 MTP drafts accepted), peak memory footprint 9.56 GiB (8.47 GB max RSS, 0 swaps), PLE Direct 93.0% hit (246.30 MiB SSD reads, 699.8 ms collect wait), AGX gpu_inuse on exit 0.00 GiB, 100% exact recall (COBALT-7319).
      • True ~120K (122,880 tokens) BasinKV NIAH (needle at ~50% depth, token ~61,420): 28.6 tok/s prefill, 7.26 tok/s decode (7/8 MTP drafts accepted), peak memory footprint 9.57 GiB (8.51 GB max RSS, 0 swaps; RAM pressure guard smoothly released host buffers 3× without OOM), PLE Direct 95.1% hit (338.86 MiB SSD reads, 1,061.0 ms collect wait), AGX gpu_inuse on exit 0.00 GiB, 100% exact recall (QUARTZ-6042).

    3. Honest 10-Config Factorial Quality Evaluation (Apple M5 Ultra, Qwen4-35B-A3B-UD-IQ2_XS)

    Evaluated under a strict cold/low-hit partial-VRAM stress test (4,000 fixed experts from an M4 profile, 36–76% natural VRAM hit across tasks; 128-step teacher-forced Top-1/Top-5/GoldP vs full-VRAM lossless baseline + 6 end-to-end tasks with exact --eos-ids 248044,248046):

    Config Mode 128-Step Top-1 128-Step Top-5 Gold Mean Prob VRAM Hit (TF) Math Trap Logic Puzzle Python LRUCache Python edit_distance Zh QA 16K NIAH Score
    Full-VRAM baseline Lossless 100.00% 100.00% 0.7326 100.0% PASS PASS PASS PASS PASS PASS 6/6
    Partial-VRAM Metal Doorbell (--defer-rank -1) Default (Lossless) 99.22% 100.00% 0.7299 58.7% PASS PASS PASS PASS PASS PASS 6/6
    --dense-requant q4_k (full VRAM) Opt-in approx 89.06% 100.00% 0.7091 100.0% PASS PASS PASS PASS PASS PASS 6/6
    --dense-requant q4_k+head (full VRAM) Opt-in approx 89.06% 100.00% 0.7049 100.0% FAIL PASS PASS PASS PASS PASS 5/6
    GPU --cache-bias 0.5 (--defer-rank -1) Opt-in approx 87.50% 100.00% 0.6894 78.9% PASS PASS PASS PASS PASS PASS 6/6
    GPU --cache-bias 0.3 (--defer-rank -1) Opt-in approx 90.62% 100.00% 0.7158 69.4% FAIL FAIL PASS PASS PASS PASS 4/6
    GPU --cache-bias 1.0 (--defer-rank -1) Opt-in approx 78.12% 99.22% 0.6424 93.4% PASS FAIL PASS PASS PASS PASS 5/6
    --defer-rank 4 (partial VRAM) Opt-in approx 92.97% 100.00% 0.7129 53.0% PASS FAIL PASS PASS PASS PASS 5/6
    --defer-rank 0 (partial VRAM) Opt-in approx 79.69% 98.44% 0.6198 51.0% FAIL FAIL PASS PASS PASS PASS 4/6
    --cache-bias 0.5 + --defer-rank 0 Opt-in approx 78.12% 100.00% 0.5975 78.6% FAIL FAIL PASS PASS PASS PASS 4/6

    Key takeaway: Default Metal Doorbell (--defer-rank -1) is strictly lossless (99.22% Top-1, 100% Top-5, 6/6 PASS). All approximate speed knobs (--defer-rank >= 0, --cache-bias, --dense-requant) are kept strictly opt-in with honest trade-offs documented in each PR; in particular, --defer-rank 0 should not be treated as lossless when VRAM hit rate is low (~51%), and stacking --cache-bias with --defer-rank 0 compounds math/logic drift.


    4. Next Steps Needed from Maintainers

    Per CONTRIBUTING.md, PRs modifying shared cross-backend engine/src/poly/ files (#499, #473, #475, #474, #500, #501, #512) were built and tested on Apple Silicon macOS only (CUDA, HIP, SYCL, and MSVC builds were not run locally) and are therefore kept as Draft until maintainers confirm scope and indicate which PRs to flip Ready for Review for run-backends CI. Pure-Metal #511 is already Ready for Review (and #513 is Ready with a clear non-Metal kernels.cu CI caveat).

    (Companion Inkling-2-Mini 16 GB Apple Silicon optimization series is tracked in #456.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions