ds4 icon indicating copy to clipboard operation
ds4 copied to clipboard

Implemented `--cpu-moe` and `--prefill-metal-phases` to run the Q4 model on a 128 GB Mac

Open tkhr-sait opened this issue 6 months ago • 7 comments

TL;DR

Sharing two experimental fork additions that let DeepSeek-V4 Flash Q4 GGUF (~153 GiB) run on a 128 GB Mac (alpha quality, like the rest of the fork). Not proposing this for upstream — the approach relies on a CPU path (a custom Q4_K NEON kernel) that's outside this project's supported scope, so it doesn't really belong in the main codebase to maintain. Just leaving it here in case it's useful.

  1. --cpu-moe / --n-cpu-moe N — routes MoE expert matmuls to the CPU; the 145 GiB of routed experts stay out of the Metal residency set.
  2. --prefill-metal-phases auto|N — during prefill only, splits the routed experts into N Metal-resident phases and runs the matmul on GPU; generation falls back to cpu-moe. ~7.8× prefill at 16k context.

Fork: https://github.com/tkhr-sait/ds4 Relevant commits:

  • metal: run routed MoE on CPU to fit 153 GiB model on 128 GB Mac

  • cpu: i8mm 2x2 GEMM for routed Q4_K MoE prefill

  • metal: prefill in Metal-resident phases with cpu-moe fallback for gen

    Update (2026-06): Added --routed-metal-dynamic (gen experts on GPU via a dynamic LRU residency) and F_RDADVISE prefetch across all paths — ~2× the cpu-moe gen baseline and prefill 1.6–2.0×. Measurements in the follow-up comment / full writeup.

Goal

  • On a 128 GB Mac, only Q2 (~81 GiB) fits today.
  • I'd like to run Q4 (~153 GiB) for better quality.
  • ~145 GiB of that is routed MoE experts → if I move just those to CPU, the remaining ~8 GiB fits comfortably in Metal residency.

What I did

Everything below is experimental. It runs, but edge cases, error handling, and long-running / crash-recovery behavior are not exercised.

  • Added --cpu-moe / --n-cpu-moe N flags (naming mirrors llama.cpp).
  • Excluded the routed-expert byte ranges from the Metal residency set.
  • Skipped those ranges in model_warm_weights to avoid wasted startup I/O.
  • Added a Q4_K CPU NEON kernel (dotprod / i8mm 2x2) and routed gate/up/down through it.
  • Added --prefill-metal-phases auto|N: during prefill only, partitions the routed experts into N Metal-resident phases and swaps residency between phases; generation falls back to cpu-moe.
    • auto derives N from sysctl iogpu.wired_limit_mb and hw.memsize so each phase fits the Metal wired-memory cap.
    • Env overrides: DS4_PREFILL_METAL_PHASES_WIRED_LIMIT_MIB, _HEADROOM_MIB (default 14336), _MIN_TOKENS (default 1500).

How to run

See the fork README for build and model download. --cpu-moe / --n-cpu-moe N behave the same as in llama.cpp, so I'll skip those. Once you have the Q4 GGUF and have run make, the new --prefill-metal-phases flag is used like this (the same flag is accepted by ds4-bench and ds4-server):

# Prefill in N Metal-resident phases (gen falls back to cpu-moe)
# auto: derive N from sysctl iogpu.wired_limit_mb
./ds4 --prefill-metal-phases auto -c 16384 --prompt-file prompt.txt

If auto complains about the wired-memory budget, raise it:

sudo sysctl iogpu.wired_limit_mb=112640
# or just override what ds4 sees
DS4_PREFILL_METAL_PHASES_WIRED_LIMIT_MIB=112640 ./ds4 --prefill-metal-phases auto ...

Memory picture and benchmark (Apple M4 Max, 128 GiB)

With --cpu-moe alone, prefill is CPU NEON-bound (~17 t/s). Observing that the Q4 routed experts don't fit in Metal residency in one go but do fit when split in half, --prefill-metal-phases partitions the routed experts into Metal-resident phases and runs the matmul on the GPU during prefill only. Generation falls back to cpu-moe (loading the full set into Metal residency for gen would exceed 128 GB).

Memory layout (--prefill-metal-phases 2)

flowchart LR
    subgraph S1["① Startup (cpu-moe baseline)"]
        direction TB
        M1["Metal residency<br/>~8 GiB<br/>shared expert + attention + KV"]
        P1["CPU mmap (lazy page-in)<br/>145 GiB<br/>all routed experts"]
    end
    subgraph S2["② Phase 0 prefill (layers 0..20)"]
        direction TB
        M2["Metal residency<br/>~82 GiB<br/>shared (~8) + Phase 0 routed (~74)"]
        P2["CPU mmap (untouched this phase)<br/>~71 GiB<br/>Phase 1 routed"]
    end
    subgraph S3["③ Phase 1 prefill (layers 21..42)"]
        direction TB
        M3["Metal residency<br/>~79 GiB<br/>shared (~8) + Phase 1 routed (~71)"]
        P3["CPU mmap (untouched this phase)<br/>~74 GiB<br/>Phase 0 routed"]
    end
    subgraph S4["④ Generation (cpu-moe fallback)"]
        direction TB
        M4["Metal residency<br/>~8 GiB<br/>shared expert + attention + KV"]
        P4["CPU mmap<br/>145 GiB<br/>all routed experts (matmul on CPU)"]
    end
    S1 -->|"engine_activate_prefill_phase(0)<br/>= map Phase 0 into residency"| S2
    S2 -->|"swap residency<br/>release Phase 0, map Phase 1"| S3
    S3 -->|"engine_restore_gen_routing()<br/>release routed, back to cpu-moe"| S4

    classDef metal fill:#cfe2ff,stroke:#0d6efd,color:#000;
    classDef mmap  fill:#fff3cd,stroke:#fd7e14,color:#000;
    class M1,M2,M3,M4 metal;
    class P1,P2,P3,P4 mmap;

Key points:

  • Metal residency cap drives the design: macOS iogpu.wired_limit_mb (default ~96 GiB on a 128 GiB M4 Max) is the hard ceiling for wired allocation. Phase 0 / Phase 1 are sized at ~82 / ~79 GiB so each fits; auto mode derives N from this sysctl value.
  • ②↔③ swap is the heaviest step: releasing Phase 0 from residency and registering Phase 1 means a new wired-memory request plus page touches, ~20–25 s each time.
  • Gen drops back to ① / ④ baseline: gen can't keep the routed set in residency (>128 GB), so it returns to the CPU NEON path. engine_restore_gen_routing() handles this.

Prefill

prompt tokens Q2 Metal (t/s) Q4 cpu-moe (t/s) Q4 phases=2 (t/s) phases=2 / cpu-moe
128 — — 8.45 —
1,024 — — 21.39 —
2,048 344 17.5 36.87 ~2.1×
4,096 — — 47.37 —
8,192 — — 89.71 —
16,384 277 16.1 125.39 ~7.8×
32,768 248 16.2 — —
65,536 205 16.3 — —

cpu-moe alone is ~15–20× slower than Q2 Metal but stays flat around 16 t/s up to 64k context. phases=2 wins bigger with longer prompts (the swap cost amortizes) — ~7.8× at 16k. For very short prompts (128 tok) a single swap can dominate and end up slower than cpu-moe alone.

Generation (ctx=2,048, temp=0)

gen tokens Q2 Metal (t/s) Q4 cpu-moe (t/s) Q4 gen after phases (t/s)
128 26.8 3.5 3.44
1,024 — 5.8 6.06
2,048 — 7.6 6.75
4,096 — 9.3 7.37
8,192 — 11.0 9.20
16,384 — 12.6 10.25

The increasing speed at longer generations is likely driven primarily by mmap'd expert pages accumulating in the OS page cache, reducing SSD reads each subsequent token. Gen after a phase-mode prefill is roughly on par with cpu-moe alone — within ~10–20 % for longer generations. Likely tail of the gen-side residency/page-cache restore; still observing.

Caveats for the phase path

  • Phase swap is expensive: each swap costs ~20–25 s of Metal residency setup plus up to ~27 s of page warmup. Measured 16k-prefill swap overhead totals ~40–70 s.
    • There's a ds4_gpu_set_skip_next_warmup() one-shot flag to skip the warmup pass on phase swaps (the initial residency + any explicit warmup still pay the cost). Trade-off: cold pages stretch the first chunk after the swap.
  • Short prompts lose: if the prompt is short, swap overhead dominates. auto mode disables phase splitting when the prompt is below DS4_PREFILL_METAL_PHASES_MIN_TOKENS (default 1500).

Limitations

  • Metal-only — CUDA backend is out of scope for this prototype.
  • --cpu-moe is effectively mandatory for Q4 — loading Q4 without it hangs (Metal residency registration exhausts unified memory).
  • Prefill is CPU NEON-bound (~16 t/s) — ANE (Apple Neural Engine) offload could help (refs: anemll, llama.cpp #10453).
  • MTP: Speculative decoding via the MTP head would be a natural way to boost generation speed, but the fork's current MTP path is experimental with only a slight speedup (also noted in the README). It does run together with --cpu-moe — just no real speed win yet.

Things that didn't work

I tried to break the CPU-NEON prefill bottleneck by offloading the routed-MoE matmul to other M4 accelerators. Both lost to CPU NEON i8mm. Recording the experiments here so others don't re-tread the same ground.

A. SME2 (Scalable Matrix Extension 2)

Tried accelerating Q4_K × Q8_K dot via Apple M4 SME2 instructions.

  • Stage 1 — streaming SVDOT (per-row dot in SVE2, worker-level batching): after stepping through several streaming-mode landmines (svaddv is not streaming-compatible, scalar FP without FEAT_SME_FA64 is UNDEFINED, the __arm_locally_streaming prologue's cntd faults because M4 has no standalone SVE, …), settled at 17.88 t/s vs NEON 18.00 t/s prefill (noise) with a 6% generation regression.
  • Stage 2 — smopa (16×16 outer-product accumulate) for int8×int8 GEMM via the ZA tile: got it working, but microbench showed it's 2-3× slower than NEON DOTPROD.
  • Why: M4's SME unit is an AMX-style independent coprocessor; effective smopa throughput on M4 is far below SIMD/NEON (rough estimate ~1/180 cycles).
  • Conclusion: SME2 on M4 can't beat NEON i8mm for this workload.

B. Metal GPU staging (run the routed MoE on the GPU)

Tried offloading the Q4_K expert matmul to the existing Metal g_moe_mul_mv_id_q4_k_*_pipeline kernels by staging the mmap'd weights into Metal-resident scratch (or via newBufferWithBytesNoCopy for zerocopy).

Optimization knobs explored:

  • memcpy mode (mmap → Metal-resident scratch) vs zerocopy mode (newBufferWithBytesNoCopy)
  • K=1..4 ping-pong scratch sets to keep the GPU command queue busy
  • ds4_gpu_flush_commands (async commit) to overlap CPU staging with GPU compute

Standalone microbench (M4 Max, 2048 tokens, 43 layers, pure compute time, no SSD I/O):

Mode per-layer Notes
memcpy + per-layer sync 120.8 ms memcpy 24 ms + GPU 97 ms
memcpy + flush K=4 93.9 ms async overlap hides memcpy
zerocopy + per-layer sync 96.7 ms no memcpy, GPU wait only
zerocopy + flush K=4 69.3 ms pure GPU kernel time

vs CPU NEON i8mm 2x2 (estimated ~20 ms/layer) — Metal is 3-4× slower.

  • Why: the Metal Q4_K kernel's compute density on M4 doesn't reach M4 NEON SMMLA's. No amount of staging / pipelining tweaking closes that gap.
  • Secondary issue: on real prefills (not the microbench), bytesNoCopy against cold mmap pages serializes GPU page faults through the kernel, making it even slower. Measured 512-tok prefill on real model: 2.82 t/s, 6× slower than the i8mm baseline (17.5 t/s).
  • Conclusion: GPU staging can't beat CPU NEON for this workload.

C. Async overlap of CPU MoE and Metal shared expert in the generation (decode) path

The prefill path already uses a cpu_moe_async_kick/join pattern: a worker thread runs the CPU routed MoE while the main thread encodes the Metal shared expert in parallel. I tried porting the same pattern into metal_graph_encode_decode_layer (n_tokens=1) to lift gen throughput.

  • What I did: replaced the gen sync handoff (direct cpu_routed_moe_batch_handoff_prealloc call) with cpu_moe_async_kick, and inserted two flush_commands + cpu_moe_async_join bridges — one right before the fused shared_down_hc_expand (which reads routed_out), one right before the non-fused add / hc_expand_add_split.
  • Result: gen 6.55 → 5.76 t/s (-12%), the opposite of the +3–7% I'd estimated.
  • Why (hypothesis):
    1. UMA DRAM bus contention — gen is per-token GEMV: both the CPU side (full read of Q2_K/IQ2_XXS routed expert weights) and the Metal side (full read of Q8_0 shared expert weights) are memory bound. Serial execution let them alternate on the bus and reach higher effective bandwidth; running them concurrently just starves both on bus access.
    2. Per-layer pthread_create overhead — 30 cpu_moe layers × ~50μs ≈ 1.5 ms/token of fixed cost.
    3. Extra Metal command buffer switches — added flush_commands cost per layer.
  • Why prefill is different: prefill (large n_tokens) is GEMM-heavy and compute-bound enough that the DRAM bus has slack — async overlap turns that slack into real savings. Gen is GEMV with both sides memory bound, so parallelism saturates the bus ceiling without any compute speedup.
  • Conclusion: reverted. Memory-bound × memory-bound parallelism on Apple Silicon UMA is generally a regression to be wary of, even when the same pattern wins on a compute-bound sibling path.

General observation (update: Metal was fixable, via phase staging)

The (B) conclusion that "the Metal Q4_K kernel can't match NEON SMMLA on compute density" turned out to be wrong: what dominated was the staging cost (mmap → residency copy, or bytesNoCopy against cold pages). With --prefill-metal-phases keeping the experts pre-resident in Metal, the same kernel reaches ~7.8× over NEON at 16k prefill (125 t/s vs 16 t/s, see the table above). The win is conditional on prompts long enough to amortize the phase swap, but the kernel itself is plenty fast.

SME2 (A) and gen-path async (C) still lose to NEON alone. ANE remains untried — different design (low-power inference), worth a separate investigation.

Sharing only

Sharing an experimental implementation. I'm not proposing this for upstream. The approach leans on a CPU code path — a custom Q4_K NEON kernel I added on the side — that's outside this project's supported scope, so it doesn't really belong in the main codebase to maintain. I'll keep it in my fork; posting here in case it's useful for anyone else trying to run the Q4 GGUF on a 128 GB Apple Silicon Mac.

tkhr-sait avatar May 16 '26 17:05 tkhr-sait

Interesting, thanks. Will leave this around and play with it in the future.

antirez avatar May 16 '26 17:05 antirez

i am running https://github.com/arozanov/mlx-lm/tree/feature/turboquant-kv-cache with https://huggingface.co/Thump604/DeepSeek-V4-Flash-MLX-Q3-mixed-gs128-affine which is 135gb total on m1 ultra with 128gb memory and when loaded its using only 70gb memory

badelon avatar May 17 '26 13:05 badelon

Lazy MLX load completed successfully on a 128GB Mac Studio. this is how can be achieved

badelon avatar May 17 '26 16:05 badelon

Tokens/sec when doing real work with Q4 using 128GB machines? Since the 2bit vs 4bit quality difference is not really big AFAIK: now that we have eval this is quite clear.

antirez avatar May 17 '26 16:05 antirez

~6 t/s with Q4 on real coding work (opencode). Wired memory ~13 GB. Cache management is currently left to macOS with no tuning — the mmap'd 145 GiB routed-expert range doesn't fit in cache, leaking ~200 MB/s of SSD reads.

Planned experiments:

  • Pin hot experts into Metal residency.
  • Page faults serialize and cap SSD at QD=1 (~25k IOPS); QD=32 would give 500k+ IOPS, so issue madvise(WILLNEED) on router top-K to raise queue depth.
  • MTP-batched gen. Speculative draft+verify batches N tokens' expert reads per forward pass. Infra (mtp_draft_tokens, metal_graph_verify_suffix_tops) exists; main work is wiring ds4_engine_mtp_draft_tokens() into the cpu-moe gen path.

Still iterating...

Details: https://github.com/tkhr-sait/ds4/tree/main/cpu-moe-memo/01-cpumoe-baseline#2026-05-18-ds4-server-cpu-moe-measurements

Image Image Image Image

tkhr-sait avatar May 19 '26 15:05 tkhr-sait

Follow-up (2026-06): --routed-metal-dynamic + F_RDADVISE across all paths

Since the original post I added a third path (gen experts on the GPU) and found the single biggest lever was prefetch. Same 153 GiB Q4 model, M4 Max / 128 GiB. Full writeup with charts (budget sweep, thermals, vm_stat): https://github.com/tkhr-sait/ds4/blob/main/cpu-moe-memo/02-routed-metal-dynamic/README.md

F_RDADVISE is the key lever (all three paths). On Darwin posix_madvise(WILLNEED) is only a vm hint and issues no I/O; F_RDADVISE issues a real read-ahead, so the SSD page-in overlaps compute. (Priority is encoded by repeat count, so the prefill lookahead deliberately re-hints the current layer.)

  • prefill (per-layer phases N=43 + next-layer prefetch): 111.9 → 182–222 t/s (1.6–2.0×)
  • CPU gen (prefetch the selected experts): 5.4 → ~10 t/s
  • GPU dynamic path: I/O cap lifted (per-expert make_buffer warmed)

--prefill-metal-phases auto now resolves to N=43 (one layer per phase, ~3.38 GiB swap each) with lookahead prefetch — instead of the old N=2 (two 82 GiB swaps, no prefetch).

New --routed-metal-dynamic (gen experts on GPU). Instead of the gen-time expert GEMV on CPU, wire only the experts the router actually selected (6 of 256, ≈13.5 MiB each on Q4) into a per-expert Metal residency set; an LRU keeps the recent working set resident up to a byte budget and evicts the tail. Reuses the existing mul_mv_id kernels. Requires --cpu-moe, Metal-only, default off; budget via DS4_ROUTED_METAL_BUDGET_MIB (default 40 GiB).

  • Q4 gen, 32 GiB budget: 10.58 (Normal) / 10.91 (High Power) t/s ≈ 2× the cpu-moe baseline (5.37)
  • Scales with budget via LRU hit%: 8→80 GiB = ~7.8→~12.6 t/s (High Power), hit% ~41→~94%

Thermals govern both CPU and GPU. gen t/s ≈ thermal headroom (cooling − accumulated heat). At a large budget dyn drives the GPU hard, so Normal throttles and High Power recovers +10–14% (72–80 GiB). Equalise the starting die temp when comparing runs, or most of the delta is thermal-history noise.

CPU vs GPU — opposite RAM trade-offs:

  • --cpu-moe: tiny wired (~13 GiB), rides the page cache → portable, runs on less RAM, no raised iogpu.wired_limit_mb; speed rides free-RAM-for-cache.
  • --routed-metal-dynamic: the wired budget is the speed knob (predictable, tunable t/s) but pins RAM and needs a raised iogpu.wired_limit_mb. Overshoot swaps — validate swap-out = 0 at your longest context, not a short prompt (80 GiB wires at the default limit).

Q2 (fits in RAM): dyn lands between full Metal (22.13) and cpu-moe (7.96) — 24–40 GiB ≈ 17 t/s (≈78% of full Metal). Even when the model fits, dyn is a useful cap on wired memory (most of full-Metal speed at a smaller footprint).

Tried, no effect here: MTP (speculative draft/verify) did not speed gen in this setup.

Still alpha quality / personal fork, Metal-only — sharing the measurements in case they're useful.

tkhr-sait avatar Jun 02 '26 23:06 tkhr-sait

Closing: main now ships SSD streaming for larger-than-RAM models (see README), a similar mechanism to what this fork explored. Fork stays up for reference.

tkhr-sait avatar Jun 06 '26 12:06 tkhr-sait