Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
152 commits
Select commit Hold shift + click to select a range
6030455
[compressed-tensors] dequantize while loading through the conversion …
ArthurZucker Nov 2, 2026
ac8b3c9
[compressed-tensors] dequantize=True drops w8a8 activation quantizati…
ArthurZucker Nov 2, 2026
eaadfac
[compressed-tensors] dequantize is the user's flag: base picks the lo…
ArthurZucker Nov 2, 2026
0501fe0
[compressed-tensors] static serialized names and load op, op resolves…
ArthurZucker Nov 2, 2026
93b1133
[compressed-tensors] deserialize through the conversion mapping: weig…
ArthurZucker Nov 2, 2026
6309e6e
[quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpo…
ArthurZucker Nov 2, 2026
387320f
[quantization] plan: TypeGuard for the plans
ArthurZucker Nov 2, 2026
749a263
[quantization] no left name boundary: own-name converters use 3 name …
ArthurZucker Nov 2, 2026
14796da
[compressed-tensors] dequantize while loading through the conversion …
ArthurZucker Nov 2, 2026
81ff283
[compressed-tensors] dequantize=True drops w8a8 activation quantizati…
ArthurZucker Nov 2, 2026
3acfe14
[compressed-tensors] dequantize is the user's flag: base picks the lo…
ArthurZucker Nov 2, 2026
acc40ca
[compressed-tensors] static serialized names and load op, op resolves…
ArthurZucker Nov 2, 2026
20b3c02
[compressed-tensors] deserialize through the conversion mapping: weig…
ArthurZucker Nov 2, 2026
7cf9e8a
[compressed-tensors] keep weights compressed unless dequantize=True
ArthurZucker Nov 4, 2026
142380e
[quantization] quantize on the fly through a "quantize" load operation
ArthurZucker Nov 2, 2026
1a3ccb5
[quantization] bnb dequantizes through the "dequantize" load operatio…
ArthurZucker Nov 2, 2026
9cad2c3
[quantization] every config takes `dequantize`, a loading attribute o…
ArthurZucker Nov 2, 2026
1f799fc
[quantization] gemma dequantizes through the "dequantize" load operation
ArthurZucker Nov 2, 2026
4e221eb
[quantization] remove post-load model.dequantize(): load with dequant…
ArthurZucker Nov 2, 2026
8c93f47
[quantization] "dequantize" load operation for every quantizer
ArthurZucker Nov 2, 2026
d621a7c
[loading] source patterns start on a name boundary; don't dequantize …
ArthurZucker Nov 2, 2026
ae15396
[quantization] saving goes through the "serialize" load operation (to…
ArthurZucker Nov 2, 2026
cfccc9c
[quantization] hqq "quantize" op; higgs repacks in "deserialize"; fbg…
ArthurZucker Nov 2, 2026
baf46a1
[loading] non-persistent buffers holding a value keep it when moved o…
ArthurZucker Nov 2, 2026
d07429e
[quantization] sinq saves through "serialize"; fbgemm input_scale_ub …
ArthurZucker Nov 2, 2026
cbb64d8
[quantization] dequantize fused params stored under their own name; n…
ArthurZucker Nov 2, 2026
2e7276f
[quantization] quantizers import without torch; doc headings without …
ArthurZucker Nov 2, 2026
47e4ec2
[quantization] review: `dequantizing` property, one FP4 table, leftov…
ArthurZucker Nov 2, 2026
0e4799d
[quantization] `dequantizing` holds for configs without the attribute
ArthurZucker Nov 2, 2026
104943c
[quantization] get_weight_conversions reads `dequantizing`
ArthurZucker Nov 2, 2026
a5fcfdf
[quantization] leave NVFP4, fused-experts dequantize, the fp8 chain f…
ArthurZucker Nov 2, 2026
0e162f0
[loading] keep WeightTransform.quantization_operation for peft
ArthurZucker Nov 2, 2026
9311c92
[quantization] port bnb dequantize tests to dequantize=True
ArthurZucker Nov 4, 2026
4f11091
[quantization] bnb dequantize: undo Conv1D transpose, cast to the den…
ArthurZucker Nov 4, 2026
c1884c2
[compressed-tensors] test the default load keeps the compressed forma…
ArthurZucker Nov 4, 2026
fec5a1f
[quantization] say dequantized / unquantized instead of dense
ArthurZucker Nov 4, 2026
3d0dd75
[hqq] swap in empty HqqLinear before loading, load ops fill it in place
ArthurZucker Nov 4, 2026
103d28b
[quantization] swap modules in one pass through a per-quantizer `quan…
ArthurZucker Nov 4, 2026
ac06ef5
[compressed-tensors] docs: default load keeps the compressed format a…
ArthurZucker Nov 4, 2026
dbfba36
Merge remote-tracking branch 'origin/compressed-tensors-dequantize-on…
ArthurZucker Nov 4, 2026
5e2c847
[quantization] plan: one update_weight_conversions, quantizer sets ea…
ArthurZucker Nov 4, 2026
165c1f4
[quantization] plan: delegate after-load hooks, drop dequantized patt…
ArthurZucker Nov 5, 2026
5e01aa6
[eetq] dequantize without the kernel: undo the CUTLASS layout in torc…
ArthurZucker Nov 5, 2026
33194b4
[quantization] quantizer_for -> get_quantizer
ArthurZucker Nov 5, 2026
5ac253a
[quantization] dequantize without kernels: torch bnb 4-bit dequant, s…
ArthurZucker Nov 5, 2026
49d2343
Merge remote-tracking branch 'origin/compressed-tensors-dequantize-on…
ArthurZucker Nov 5, 2026
546564b
Merge remote-tracking branch 'origin/quantize-load-operation' into HEAD
ArthurZucker Nov 5, 2026
e5314e7
[fp8] bring back replace_with_fp8_embedding
ArthurZucker Nov 5, 2026
9692337
[fp8] drop replace_with_fp8_embedding again: quantized_module swaps t…
ArthurZucker Nov 5, 2026
d27969b
[quantization] load ModelOpt per-layer checkpoints (NVFP4, FP8, MXFP4…
ArthurZucker Nov 5, 2026
8333cb2
[quantization plan] cleanup: core back near main, NVFP4 experts forwa…
ArthurZucker Nov 5, 2026
4172233
Merge quantize-load-operation (#50240): quantize is a load operation,…
ArthurZucker Nov 5, 2026
959185c
Merge main into mixed-nvfp4-fp8-plan
ArthurZucker Nov 5, 2026
4d4e8b8
Split: quantize / dequantize as load operations move to their own PR …
ArthurZucker Nov 5, 2026
c8e86f5
[docs] add a quantized format: from a FineGrainedFP8 config to a new …
ArthurZucker Nov 5, 2026
a2ae59f
[fp8] deserialize ue8m0 scales saved as bytes by their bits (MXFP8)
ArthurZucker Nov 5, 2026
6e4953a
[quantization] docs follow the plan; ModelOpt single quant_algo loads…
ArthurZucker Nov 10, 2026
3a23dd5
human text
ArthurZucker Nov 10, 2026
706bebd
not a fan yes of this shit
ArthurZucker Nov 10, 2026
034c0c3
nits
ArthurZucker Nov 10, 2026
809e9e7
unbloat the fuck up
ArthurZucker Nov 10, 2026
0377ebe
more unbloat
ArthurZucker Nov 10, 2026
8d3639d
is it simpler?
ArthurZucker Nov 10, 2026
2e6066a
one line
ArthurZucker Nov 10, 2026
2431bfe
trying to simplify
ArthurZucker Nov 10, 2026
adb262b
simplify ?
ArthurZucker Nov 10, 2026
5e175d0
nits
ArthurZucker Nov 10, 2026
a4f26d2
will this work?
ArthurZucker Nov 10, 2026
8bc1530
cleanup?
ArthurZucker Nov 10, 2026
5243cca
this should make it simpler overall
ArthurZucker Nov 11, 2026
035a195
reject stuffs that need more work for now
ArthurZucker Nov 11, 2026
d5141f8
nits
ArthurZucker Nov 11, 2026
647fb5e
renames
ArthurZucker Nov 11, 2026
aca0192
nit
ArthurZucker Nov 11, 2026
85c8e9e
super nit
ArthurZucker Nov 11, 2026
efa360a
doc and rename
ArthurZucker Nov 11, 2026
417f08d
space
ArthurZucker Nov 11, 2026
769a6ff
update
ArthurZucker Nov 11, 2026
488376e
up
ArthurZucker Nov 11, 2026
5564888
Update src/transformers/core_model_loading.py
ArthurZucker Nov 11, 2026
47a6551
Merge remote-tracking branch 'origin/main' into mixed-nvfp4-fp8-plan
ArthurZucker Nov 11, 2026
cf8a3e8
Merge remote-tracking branch 'origin/mixed-nvfp4-fp8-plan' into mixed…
ArthurZucker Nov 11, 2026
5e4d4fb
Sort the integrations init (init_isort)
ArthurZucker Nov 11, 2026
7b1faa5
Kimi-K2.5: name the qkv params its converter unfuses
ArthurZucker Nov 11, 2026
9490952
ai update for most review comments, cleaning up now
ArthurZucker Nov 12, 2026
94c9abc
Address review: plan out of Auto, schema readers, per-format experts …
ArthurZucker Nov 12, 2026
ef08fc2
FP8: drop the MXFP4 paths, MXFP4 experts run on their own interface
ArthurZucker Nov 12, 2026
3e87b6b
Rename renamed_names to checkpoint_renames; TODO for MiniMax M3's moe…
ArthurZucker Nov 12, 2026
baabd05
Shorten the FP8 DeepGEMM dispatch comments (noisy_comments)
ArthurZucker Nov 12, 2026
4cf548b
FP8 dequantize round trip (single format), NVFP4 experts via experts …
ArthurZucker Nov 12, 2026
04f6f81
cleanup some shit
ArthurZucker Nov 12, 2026
b9c1695
up
ArthurZucker Nov 12, 2026
5a25339
Dequantized models save unquantized again (TODO: quantize back)
ArthurZucker Nov 12, 2026
aabbd56
Merge remote-tracking branch 'origin/main' into mixed-nvfp4-fp8-plan
IlyasMoutawwakil Nov 12, 2026
bb5fc01
Quantization plan fixes: bitsandbytes loading, NVFP4 parallelism and …
IlyasMoutawwakil Nov 12, 2026
2baa90f
Docstrings, spacing and an NVFP4 limitations note; NVFP4 EP test runs…
IlyasMoutawwakil Nov 12, 2026
0907651
Stream MoE experts from the checkpoint through a device slot cache
ArthurZucker Nov 20, 2026
bebcd3f
experts offload: timing stats, count tied params once in the budget
ArthurZucker Nov 20, 2026
a4bec1a
experts offload: approximate LFU policy
ArthurZucker Nov 20, 2026
3885bec
experts offload: disk -> pinned RAM -> VRAM on a copy stream (CUDA), …
ArthurZucker Nov 20, 2026
8d64792
Metal gather_qmm experts (MetalExperts) streamed quantized; batched_m…
ArthurZucker Nov 20, 2026
6d58cb6
experts offload: device slot table + one miss op (compile / CUDA-grap…
ArthurZucker Nov 20, 2026
99cb904
experts offload: prompts run on a compact bank of the routed slots
ArthurZucker Nov 20, 2026
1e8bf79
Stream embedding rows from the checkpoint (device_map "disk" on an nn…
ArthurZucker Nov 20, 2026
1054c86
experts offload: safetensors prefetch loader for CUDA reads (one plan…
ArthurZucker Nov 20, 2026
6eb5894
MetalExperts: scales in the activations' dtype (no cast per call)
ArthurZucker Nov 20, 2026
822b0e1
Affine-quantized experts on CUDA (Triton gather_qmv, same layout as M…
ArthurZucker Nov 20, 2026
3665557
experts offload: opt-in phase tracing; never set a result on a cancel…
ArthurZucker Nov 20, 2026
bc3225b
experts offload: native stacked banks only, one row read copied into …
ArthurZucker Nov 20, 2026
ae71b99
experts offload: fix pinned-pool completeness and the op registry lea…
ArthurZucker Nov 20, 2026
1d38fd6
experts offload: one prefetch loader per file for a layer's rows (lis…
ArthurZucker Nov 20, 2026
affe295
Metal kernels: fake impls for gather_qmm / quantized_matmul so torch.…
ArthurZucker Nov 20, 2026
b1486d4
experts offload: benchmarks, diagnostics and bench log
ArthurZucker Nov 20, 2026
0413933
bench: import dense_quant lazily
ArthurZucker Nov 20, 2026
1790a91
experts offload: stream banks loaded through a quantizer's identity c…
ArthurZucker Nov 20, 2026
1470513
bench: print traceback on failure
ArthurZucker Nov 20, 2026
30871ab
experts offload: stream rows of a table collected under several patterns
ArthurZucker Nov 20, 2026
67c9d88
bench: local conversion on MPS, streamed verify
ArthurZucker Nov 20, 2026
b57d982
experts offload: streamed table rows apply their FP8 dequantization s…
ArthurZucker Nov 20, 2026
355ffa2
experts offload: no NaN from unfilled slots (MetalExperts masks senti…
ArthurZucker Nov 20, 2026
25462e5
MetalExperts: back to the weight product (where() broke compiled deco…
ArthurZucker Nov 20, 2026
ced4adf
StaticCache: create cumulative_length on the device (a 0-d .to() sync…
ArthurZucker Nov 20, 2026
27f1e72
experts offload: streamed embedding rows in the replaced embedding's …
ArthurZucker Nov 20, 2026
16ec765
generate: deferred stop check returns without waiting on the device w…
ArthurZucker Nov 20, 2026
22e80a0
Metal kernels for gated delta rule and causal conv1d on MPS; streamed…
ArthurZucker Nov 20, 2026
9cefc7b
qwen4_exp: vectorize the QSA indexer (no per-query loop, compiles ful…
ArthurZucker Nov 20, 2026
af6da62
bench: Qwen3.8 synthetic (real dims, random 4-bit weights saved once)…
ArthurZucker Nov 20, 2026
07ed97c
agent: Qwen3.8 on H200 task, streamed logs, per-iteration cap
ArthurZucker Nov 20, 2026
861295d
Metal: batch-1 4-bit matvec for thin matrices (Qwen3.8 synthetic deco…
ArthurZucker Nov 20, 2026
c09cf45
bench: Qwen3.8 synthetic Metal log + stub ablations
ArthurZucker Nov 20, 2026
da8eec5
bench: Qwen3.8 Metal negative results (vectorized qmv, fusion, specul…
ArthurZucker Nov 20, 2026
a61155f
Metal experts decode: down projection + routing sum in one kernel (Qw…
ArthurZucker Nov 21, 2026
52052d1
Metal: short-side batch-1 qmv (lanes per row 16/32) for hyper-connect…
ArthurZucker Nov 21, 2026
9a6ccae
Metal gated delta rule: advance the cache's float32 state in place (n…
ArthurZucker Nov 21, 2026
150b7ef
Metal gated delta rule: 4 threads per state column
ArthurZucker Nov 21, 2026
1b31fa8
Metal ops: dtype/contiguous casts outside the custom ops so compile f…
ArthurZucker Nov 21, 2026
97dab98
Metal: fuse sibling projections sharing an input (Qwen3.8 synthetic d…
ArthurZucker Nov 21, 2026
5ad6b7c
Metal gated delta rule: recurrent state in the activations' dtype (bf…
ArthurZucker Nov 21, 2026
29544cd
Metal: every batch-1 4-bit linear through qmv4 (Qwen3.8 synthetic 46.…
ArthurZucker Nov 21, 2026
8798ddb
Metal: 64-lane expert down kernel, scales cast to the activations' dt…
ArthurZucker Nov 21, 2026
0d3918a
experts offload: routing copy queued before pass 1, decode pass 2 ove…
ArthurZucker Nov 21, 2026
3f2ce59
experts offload on MPS: device waits on a Metal shared event while a …
ArthurZucker Nov 21, 2026
7ca1182
experts offload on MPS: pass 1 overlaps the host's miss check, misses…
ArthurZucker Nov 21, 2026
292d4f9
experts offload on MPS: host reads the slots pass 1 gathered, immedia…
ArthurZucker Nov 21, 2026
dbf8a20
experts offload: Metal kernels from the Hub (ArthurZ/metal-moe-decode…
ArthurZucker Nov 21, 2026
e6e0218
experts offload on MPS: misses read by safetensors prefetch straight …
ArthurZucker Nov 21, 2026
c49ae70
Qwen4 MoE: fused Metal router, deterministic top-k, and a safe offloa…
ArthurZucker Nov 24, 2026
f92836e
experts offload: decode profiling scripts and NO_COMPILE / DUMP_TOKEN…
ArthurZucker Nov 25, 2026
de8f59f
experts offload: honour MAX_AHEAD from the environment, add an in-pro…
ArthurZucker Nov 25, 2026
fb1e361
experts offload: measure the handshake, the guess, and the scalar syncs
ArthurZucker Nov 25, 2026
c9fd884
added a not about crashing
tarekziade Nov 25, 2026
0d784cf
Merge commit 'fb0b0bd018' into qwen3.8-metal-perf
tarekziade Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions benchmark_v2/experts_offload/BENCH_LOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Local Metal decode benchmark log

Goal: >= 60 tok/s sustained batch-1 decode, quantized, Apple Metal (M3 Max 30-core GPU, 96 GB).

Protocol (unless noted): `bench_experts_offload.py` (generate + streamer timing, no hand loop), greedy, batch 1,
4 different chat prompts x 128 new tokens each, median ms/token over all decode steps -> tok/s.
"Sustained" = a 1024-token generation's tok/s over the last 512 tokens (`--sustained`).
Prefill reported separately (1024-token prompt, one forward).

Model: Qwen3-30B-A3B (48 layers, 128 experts, top-8), experts Metal affine 4-bit g64 (`ArthurZ/Qwen3-30B-A3B-metal-experts-4bit`,
transformers format), dense layers bf16 unless noted.

| # | Date | Engine / config | Decode tok/s | Sustained tok/s | Prefill tok/s | Notes |
|---|---|---|---|---|---|---|
| 1 | 2026-11-20 | transformers eager, MPS, 4-bit Metal experts via offload store at cache 1.0, sdpa (`profile_offload.py ArthurZ/Qwen3-30B-A3B-metal-experts-4bit 1.0 sdpa`) | 7.17 | - | - | 139 ms/token: GPU drain ~88 ms (~1.6 ms/layer, ~10x over bandwidth), host ~54 ms, read waits 0.6 ms |
| 2 | 2026-11-20 | llama.cpp (brew, Metal) Qwen3-30B-A3B Q4_K_M, `llama-bench -p 512 -n 128,1024 -fa 1 -r 3 -ngl 99` | 53.10 (tg128) | 49.94 (tg1024) | 608 (pp512) | engine reference on this Mac |
| 3 | 2026-11-20 | transformers eager, MPS, 4-bit Metal experts, all on device (`device_map="mps"`, no offload), sdpa (`bench_experts_offload.py --configs full --new-tokens 64 --prompt-tokens 512`) | 31.32 | - | 372 | offload layer at 100% residency costs 4x (7.17): skip it when everything fits |
| 4 | 2026-11-20 | #3 + every nn.Linear but the router -> Metal affine 8-bit g64 (`--quantize-dense 8`) | 54.58 | - | 772 | dense bytes/token 2.4 -> 1.2 GB; ppl 2.2486 vs bf16-dense 2.2607 (quality kept) |
| 5 | 2026-11-20 | #3 + every nn.Linear but the router -> Metal affine 4-bit g64 (`--quantize-dense 4`) | 61.69 (62.13 rerun) | 56.80 | 787 (891 at 1024) | ppl 2.3651 (+4.6% vs 2.2607): quality NOT kept; decode slows with context (sdpa) |
| 6 | 2026-11-20 | #5 with metal-flash-sdpa attention (`--attn kernels-community/metal-flash-sdpa`) | 60.73 | 57.15 | 892 | no sustained gain over sdpa (56.80) |
| 7 | 2026-11-20 | always-on 4-bit g32, min-max (`--quantize-dense 4g32`) | 60.78 | 56.20 | 893 | ppl 2.2939 vs 2.2459 (+2.1%) |
| 8 | 2026-11-20 | quality only (`quality_check.py ... 4c 4g32c`): per-group MSE clipping search | - | - | - | ppl: 4c 2.3043 (+1.8%), **4g32c 2.2759 (+0.5%)** vs bf16 always-on 2.2642; same bytes as 4g32 |
| 9 | 2026-11-20 | #7 with always-on 4g32c + `generate(cache_implementation="static")` + torch.compile on MPS (`full+compile`) | ~~35.42~~ | ~~33.99~~ | ~~371~~ | INVALID: ran while mlx-lm install/downloads saturated the CPU; and generate never compiles on MPS (0 frames compiled, see #10) |
| 10 | 2026-11-20 | `diag_compile_mps.py` (4g32c): eager dynamic / eager static / static + generate's compile | 60.88 / 60.55 / 60.53 | - | - | generate's auto-compile is CUDA-only: 0 frames compiled on MPS; static cache costs nothing |
| 11 | 2026-11-20 | `diag_compile_mps.py`: explicit `torch.compile(model.forward)` + static cache, before fake ops | 60.52 (default) / 62.86 (max-autotune-no-cudagraphs) | - | - | 61 graph breaks/step: hub Metal ops (`gather_qmm`, `quantized_matmul`) had no fake impl |
| 12 | 2026-11-20 | + fake impls for the Metal ops (`_register_fake_kernels`): 0 graph breaks, 2 graphs | 88.30 (median step) | - | - | eager same run 57.75 |
| **13** | 2026-11-20 | **public API** `verify_generate.py`: 4-bit experts + always-on 4g32c, `generate(cache_implementation="static", compile_config=CompileConfig() w/ _compile_all_devices=True)`, Metal quantizer `is_compileable=True` | **86.17** (mean, 4 prompts x 128) | **79.47** (mean, tokens 512-1024) | - | greedy == eager 50/128 (bf16 fusion numerics); ppl compiled 2.2747 vs eager 2.2799 (no loss) |

**Qwen3-30B-A3B (stepping stone, not the goal):** 79.47 tok/s sustained on Metal, quantized, through `generate`, quality kept (ppl +0.5% vs bf16 always-on, compile -0.2%). **The goal is Qwen3.8-Flash-Next: not met yet.**
Reproduce: `PYTHONPATH=src python verify_generate.py ArthurZ/Qwen3-30B-A3B-metal-experts-4bit 4g32c` (M3 Max 30-core GPU, 96 GB, torch 2.15.0, kernels 0.18.2).
| 14 | 2026-11-20 | regression check after the NaN fix: MetalExperts `torch.where` sentinel mask | 54.42 | 49.59 | - | where() in MetalExperts broke compiled decode (152 extra aten::copy_/token); reverted to the weight product, NaN-safety kept by zero-initialized pools |
| 15 | 2026-11-20 | #13 config, current code (`verify_generate.py ... 4g32c`) | **88.26** | **81.98** | - | Qwen3-30B-A3B stepping stone; greedy == eager 27/128 (bf16 fusion numerics) |
| 16 | 2026-11-20 | `bench_generate_overhead.py`: StaticCache `cumulative_length` created on the device instead of `.to(device)` (was a sync per layer on MPS) | step 12.27 -> 11.67 ms | - | - | per-generate overhead 70.9 -> 53.4 ms (10-token prompt, 1 new token) |

## Qwen3.8-Flash-Next on M3 Max (synthetic weights at the real dims, `bench_qwen38_synthetic.py`)

Real config (48 layers: 36 gated-delta-net + 12 full attention with QSA indexer, hidden 2560, top-10 routing, vocab
248k), random weights, 64 experts instead of 512 (same work per token), 4-bit experts g64 + 4-bit dense g32, static
cache + compile, 256 greedy tokens. Weights generated once to `~/.cache/qwen38-synthetic-64e-all4bit.safetensors`.

| # | Date | Change | Decode tok/s (median) | ms/token | Notes |
|---|---|---|---|---|---|
| Q1 | 2026-11-20 | first run (scales float32: per-call cast of the expert scale banks) | 20.0 | 50.9 | build artefact |
| Q2 | 2026-11-20 | bf16 scales like a loaded checkpoint | 29.6 | 34.5 | GPU busy 99.8% (Metal System Trace) |
| Q3 | 2026-11-20 | thin linears (min dim <= 640) kept bf16 | 30.3 | 33.7 | +1.2 GB/token bf16 offsets the slow MLX thin qmv |
| Q4 | 2026-11-20 | all dense 4-bit + own batch-1 `qmv4` for out_features <= 1024 (`integrations/metal_qmv.py`) | **39.2** | 26.1 | MLX qmv: 4x10240 in 51-105 us |
| Q5 | 2026-11-20 | own gather qmv for experts (scalar, then 4-row vectorized) | 37.3 / 33.4 | | reverted: MLX `gather_qmm` faster; 4-row kernel starves thin matrices |

Stub ablations of Q4 (`diag_qwen38_ablate.py`, 25.0 ms/token): experts 7.97 ms (1.33 GB, 167 GB/s), linear_attn proj
6.67 ms (1.32 GB, 198 GB/s), hyper-connections 2.93 ms (0.40 GB, 137 GB/s), self_attn proj+indexer 2.85 ms (0.46 GB),
lm_head 1.77 ms (0.40 GB, 225 GB/s), shared expert 1.22 ms (0.15 GB); all matmuls 21.9 ms for 4.06 GB, the rest 3.1 ms.
Measured bandwidth: 250 GB/s read (`x.sum()`), so 4-bit single-token decode tops out near 4.06 GB / 250 GB/s + 3.1 ms
= 19.3 ms = **52 tok/s**. 100 tok/s needs <= ~1.7 GB/token, or several tokens per forward (speculative / MTP).
| Q6 | 2026-11-21 | vectorized `qmv4` (uint4 + float4) for thin linears; same for experts | 38.1 / 38.4 | | noise: thin matrices are latency-bound, MLX `gather_qmm` already at par |
| Q7 | 2026-11-21 | fuse sibling projections sharing an input (180 groups: linear_attn qkv+z+b+a, hyper down+inject, shared gate+up) | 39.6 | 25.7 | noise; stubbing all 216 tiny dispatches only saves 0.94 ms |
| Q8 | 2026-11-21 | speculative-verify proxy: decode step over a batch of k | k=4: 58.3 ms, k=8: 90.3 ms | | expert union grows with k: 100 tok/s would need 5.8 (k=4) / 9.0 (k=8) accepted per step |
| Q9 | 2026-11-21 | experts decode: MLX gate/up + own down projection with the routing sum in one kernel (`experts_down_sum`) | 41.2 | 24.7 | MLX down at 176 GB/s (short rows), ours 217 GB/s |
| Q10 | 2026-11-21 | short-side batch-1 `qmv4` (16/32 lanes per row, uint4 loads) for linears with a side <= 1024 | 42.5 | 24.0 | hyper up 22.3 -> 13.5 us, inject 42.2 -> 7.4 us |
| Q11 | 2026-11-21 | `fuse_sibling_linears`: projections sharing an input as one `MetalLinear` (192 groups) | 43.2 | 23.6 | small dispatches are latency-bound |
| Q12 | 2026-11-21 | gated delta rule advances the cache's float32 state in place (no clone, no copy back) | 44.4 | 22.5 | 12 MB/layer of state traffic gone |
| Q13 | 2026-11-21 | + attention q/k/v/indexer fusion, 4 threads per state column, casts outside the custom ops | **45.4** (256 tok), 45.0 (512 tok) | 22.4 | greedy == unfused on a tiny model |

Stub ablations of Q10 (24.15 ms): experts 6.81 ms, linear_attn proj 6.64, hyper-connections 3.08, self_attn+indexer 2.91,
lm_head 1.82, shared expert 1.14, rest 3.46.
| Q14 | 2026-11-21 | bf16 recurrent state (float32 compute, one rounding per token: 5.5e-3 rel. error, flat over 2048 tokens) | 46.6 | 21.8 | half the state traffic |
| Q15 | 2026-11-21 | every batch-1 4-bit linear through `qmv4` (large ones too) | **48.1** | 21.2 | MLX at par alone, slower in the model |
| Q16 | 2026-11-21 | tried: eager attention instead of sdpa / own gathered gate-up / 64-lane expert down / fused hyper-connection kernels | 42.3 / 46.9 / 48.1 / 47.6 | | kept only the 64-lane down kernel (239 vs 192 GB/s alone, neutral in the model) |

Fine stub ablation of Q15 (`diag_qwen38_ablate_fine.py`, 20.80 ms): linear_attn in_proj 3.56 (at peak), experts gate/up 3.66
(241 GB/s), experts down ~2.95 (150 GB/s; its stub also drops gate/up: 6.61 measured), linear_attn out_proj 1.77, lm_head 1.60
(250 GB/s), hyper up 1.58, hyper down+inject 1.47 (130 GB/s), attention qkv+indexer 1.27, sdpa 0.98, shared expert 0.63+0.49,
gated delta rule 0.53, conv 0.23. Per-dispatch Metal attribution is not available here: GPU counters are a time series
(default set: RT unit) and `torch.mps.profiler(wait_until_completed)` does not sync custom / hub Metal kernels.

## Streamed experts on MPS: Qwen3.8 synthetic, all 512 experts on disk (`make_qwen38_synthetic_ckpt.py`), cache 0.25

Router skew 0.6 (`sim_routing.py`, per-layer popularity: ~98.5% expert hit rate), static cache + compile, 4-bit dense.
All-resident reference (64-expert synthetic): 48.1 tok/s.

| # | Date | Change | Decode tok/s @0.25 | Notes |
|---|---|---|---|---|
| S1 | 2026-11-21 | baseline (uniform random routing) | 8.6 | hit rate ~ cache fraction, meaningless |
| S2 | 2026-11-21 | skew 0.6 | 8.6 | sync (device drain per layer) 74 ms/token, disk waits <1 ms |
| S3 | 2026-11-21 | lookahead 0 (guess reads starved the GIL), routing copy before pass 1, misses-only pass 2 | 11.7 | 48 host round trips/token, 170-260 us each on MPS |
| S4 | 2026-11-21 | **device waits on a Metal shared event, a host thread resolves misses** (`integrations/mps_events`, `_MPSHostRouter`): routing read from shared memory, misses `preadv`-ed straight into pool slots, slot table written in place | 15.2 | host never waits on the device mid-step |
| S5 | 2026-11-21 | memmove table updates, C++ hit path (no GIL) + stamp-based LRU | ~20 | Python on the host thread competed with issue for the GIL |
| S6 | 2026-11-21 | one command buffer per 2 layers (each costs device start-up + event resume) | **22.7 / 24.3 / 23.3** (3 runs) | exact: fp32 streamed == in-memory greedy tokens with the router asserted active |

Gotchas found on the way: Metal stops a queue past ~64 committed-but-blocked command buffers (host throttled to 32 layers
ahead); CPU writes into MPS memory race the caching allocator's queued writes of a previous owner (sync before the first
CPU write into a new buffer / pool); a device fill of a fresh buffer runs after the host reads it (CPU memset instead).
| S7 | 2026-11-21 | pass 1 (resident experts) before the wait, misses-only pass 2 (masked kernels), deferred table publication; wait op no longer declares the pool mutated (compile copied the whole pool around it per layer) | **37.0 / 38.5 / 40.2 / 40.7** (skew 0.6); 42.0 (skew 1.5, ~no misses) | exact (fp32 test); parallel `preadv` of misses tried: 34.5-35.7 (reader threads compete), reverted |
| S8 | 2026-11-21 | the host reads the slots pass 1 actually gathered (published with the routing), so installs publish at once (no deferral); next-layer guess published for read-ahead (off at lookahead 0) | **42.7 / 42.6 / 42.5** (skew 0.6, 3 runs, GPU idle) | exact: fp32 test; bf16 synthetic tokens match the host-sync path up to the same summation-order divergence (token 17); decode misses 0.3-0.4/token |

Note: another app (a browser tab) using ~65-70% of the GPU dropped the resident reference from 48.1 to ~38 tok/s and made
runs 32-41 tok/s; check `ioreg -r -c IOAccelerator | grep "Device Utilization"` is near 0 before benchmarking.
| S9 | 2026-11-21 | misses read by safetensors `prefetch(device="mps", out=slots)` (safetensors#996: its own threads, GIL released) instead of Python `preadv`; kernels from the Hub | **43.0 / 43.3 / 42.2** (skew 0.6, GPU idle) | exact (fp32 test); falls back to `preadv` without #996 |
13 changes: 13 additions & 0 deletions benchmark_v2/experts_offload/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Streamed MoE experts: benchmarks

- `bench_experts_offload.py`: decode / prefill tok/s and per-token streaming stats for `full`, `ours:<cache fraction>`
(`+compile`), on any checkpoint (local dir or Hub repo). `--router-skew` simulates routing locality on synthetic weights.
- `make_qwen38_synthetic_ckpt.py`: a loadable Qwen3.8-Flash-Next with all 512 experts and random weights (~80 GB),
to measure streaming on a Mac without the real checkpoint. `sim_routing.py`: the router skew.
- `bench_qwen38_synthetic.py`: the same architecture fully resident (64 experts, same work per token), the reference.
- `verify_generate.py`: public-API run on a real checkpoint (correctness vs eager, decode and sustained tok/s).
- `convert_metal_experts.py`: an FP8 / bf16 checkpoint -> 4-bit Metal experts in the transformers format.
- `dense_quant.py`, `quality_check.py`: 4-bit always-on layers on Metal and their perplexity.

Results and the experiment log: `BENCH_LOG.md`. Check the GPU is idle first
(`ioreg -r -c IOAccelerator | grep "Device Utilization"`): another app on the GPU skews every number.
58 changes: 58 additions & 0 deletions benchmark_v2/experts_offload/ablate_pass2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""How much of the 51 ms/token is the second expert pass? Zero `masked_decode` and re-time.
Diagnostic only: output is wrong on the ablated arm, so no correctness claim is made from it."""
import sys, time, torch
from dense_quant import quantize_dense
from transformers import AutoModelForCausalLM, AutoTokenizer

repo, spec, cache_gib = sys.argv[1], sys.argv[2], float(sys.argv[3])
N = int(sys.argv[4]) if len(sys.argv) > 4 else 128
tok = AutoTokenizer.from_pretrained(repo)
import glob
from safetensors import safe_open
resident = 0
for f_ in glob.glob(f"{repo}/*.safetensors"):
with safe_open(f_, "pt") as f:
for k in f.keys():
if ".experts." not in k and ".ngram_embedding." not in k:
resident += torch.Size(f.get_slice(k).get_shape()).numel() * 2
model = AutoModelForCausalLM.from_pretrained(
repo, dtype=torch.bfloat16, device_map={"": "mps", "experts": "disk", "ngram_embedding": "disk"},
max_memory={"mps": int(resident + cache_gib * 2**30)})
quantize_dense(model, spec)

layers = [m for m in model.modules()
if hasattr(m, "masked_decode") and getattr(m, "offload_store", None) is not None]
print(f"layers with masked_decode: {len(layers)}", flush=True)
real = [m.masked_decode for m in layers]

prompt = "Write a short story about a lighthouse keeper who finds a message in a bottle."
ids = lambda p: tok.apply_chat_template([{"role": "user", "content": p}], add_generation_prompt=True,
return_tensors="pt", return_dict=True, enable_thinking=False).input_ids.to("mps")

class S:
def __init__(self): self.t = []
def put(self, _): self.t.append(time.perf_counter())
def end(self): pass

def gen(n):
s = S()
with torch.inference_mode():
model.generate(ids(prompt), max_new_tokens=n, min_new_tokens=n, do_sample=False,
streamer=s, cache_implementation="static")
steps = [b - a for a, b in zip(s.t[2:], s.t[3:])]
return sum(steps) / len(steps)

gen(16); torch.mps.synchronize()
a = gen(N); torch.mps.synchronize()
print(f"baseline (pass 2 on) {a*1000:7.2f} ms/token {1/a:6.2f} tok/s", flush=True)

for m in layers:
m.masked_decode = lambda h, s, w, **k: torch.zeros_like(h)
b = gen(N); torch.mps.synchronize()
print(f"pass 2 zeroed {b*1000:7.2f} ms/token {1/b:6.2f} tok/s", flush=True)
print(f"pass-2 share {(a-b)*1000:7.2f} ms/token ({(a-b)/a*100:.1f}% of wall)", flush=True)

for m, f in zip(layers, real):
m.masked_decode = f
c = gen(N); torch.mps.synchronize()
print(f"restored (pass 2 on) {c*1000:7.2f} ms/token {1/c:6.2f} tok/s <- same-process control", flush=True)
Loading
Loading