diff --git a/docs/benchmark_results/README.md b/docs/benchmark_results/README.md index cdda8b31f..e802291ea 100644 --- a/docs/benchmark_results/README.md +++ b/docs/benchmark_results/README.md @@ -30,6 +30,7 @@ These remain standalone because their reports leave a substantive measurement ga - [Scheduler-owned sequence state, decode rate on GB10](scheduler-owned-state-decode-gb10-2026-11-23.md): main against the #3254 branch for Gemma 3 and Qwen 3.5 with a null arm; no cell shows a decode regression. Gemma 3 at `B = 4` was 2% to 4% below main on a loaded host and is at or above main (+3% to +6%) on a quiet one. - [Turbo3Asym KV host readbacks and the on-device codec on GB10](turbo3-readback-share-gb10-2026-11-27.md): the readback share before #3274 (76% / 78% / 82% of a decode step) and decode after it (4.1x / 3.8x / 4.4x); no Apple Silicon run, and no batched (B>1) decode step was timed. - [CUDA graph commits per decode step on GB10](cuda-graph-commit-audit-gb10-2026-11-27.md): which launches pay the graph byte budget for a buffer they read part of (#3387), and the decode rate after the fused decode-MoE kernels stop paying it. MiniMax-M3 and `gemma4` were not measured on a checkpoint, the sparse path only at batch 1 on synthetic tensors, and Metal and ROCm not at all; the builtin gathers it found are left to a follow-up. +- [One-row MoE gathers on gather_qmv, GB10](moe-gather-one-row-qmv-gb10-2026-12-03.md): #2784 sends the one-row MoE gathers that ran `qmm_naive` to the per-pair `gather_qmv`: Gemma 4 26B A4B decode +23.0% at 4 clients and +7.7% at 8 (1 client unchanged), 8- to 127-token prefill 5% to 10% faster, Qwen3-30B-A3B 3-bit +17.8% to +31.7%, n = 3 with a null arm; kernel timings from 8 to 16384 pairs, and why a grouped read-each-expert-once kernel was not shipped (slower than the per-pair launch). Two checkpoints on one host; devices below sm_80 and the N1X host of #2796 were not run. - [Qwen3.8 snapshot capacity](qwen38-snapshot-capacity-default-2026-08-30.md): sizing unit tests are not a rerun of the Apple Silicon multi-turn benchmark. - [GB10 fused decode-MoE Dff crossover](fused-moe-dff-crossover-gb10-2026-11-11.md): the 8192 bound is confirmed by the decision rule, but no fused-path model has been measured between Dff 6400 and 14336, and the fast models' run-to-run spread is unexplained. - [ROCm flash prefill](sdpa-flash-prefill-gfx1151-2026-10-13.md): kernel timings exist, but model-level before/after was not measured. diff --git a/docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03.md b/docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03.md new file mode 100644 index 000000000..e4f2cd1c4 --- /dev/null +++ b/docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03.md @@ -0,0 +1,263 @@ +# One-row MoE gathers on gather_qmv instead of qmm_naive, GB10 (#2784) + +Batched decode of Gemma 4 26B A4B and Qwen3-30B-A3B (3-bit), Gemma 4 +short-prompt prefill, and kernel timings on one NVIDIA GB10 (sm_121, 121 GiB +unified memory), driver 580.178.04, CUDA 13.0.88, Ubuntu 24.04.5, before and +after the change. The baseline is mlxcel `9402cf893` (decode steps replayed as +CUDA graphs since #3714), MLX pinned to +`5a48f9cc2631804ea985c4289e34f0b1e4f66c60`. The main checkpoint is +`mlx-community/gemma-4-26b-a4b-it-4bit`, revision +`0d77464eeb233a2da68ebf9d7dc4edaac7db956d` (30 layers, 128 experts, top 8, +gate/up N = 704 K = 2816, down N = 2816 K = 704, affine 4-bit, group 64). + +## What runs where + +An expert projection hands `gather_qmm` one-row pairs: `[T, 1, 1, K]` against +`[T, top_k]` expert indices, or, from 64 pairs on, the same pairs flattened and +sorted by expert (SwitchGeGLU's sort). On the baseline `GatherQMM::eval_gpu` +ran such a gather on the per-pair `gather_qmv` below 8 pairs, and from 8 pairs +on on `qmm_sm80` where it applies (N a multiple of 128, 4 or 8 bits, sm_80 or +newer) and on `qmm_naive` everywhere else. Sorted gathers of at least +`8 * E` pairs take the dequantize + grouped GEMM path of #629 first. +`qmm_naive` spends a whole GEMM tile on each one-row pair. The change sends +those `qmm_naive` gathers to the per-pair `gather_qmv` instead, the kernel the +same gather already took below 8 pairs; `qmm_sm80` and #629 keep theirs. + +For Gemma 4 26B that is gate and up (N = 704) from 8 pairs to 1023: + +- batched decode from 2 clients on (16 pairs and up; 4 clients = 32 pairs, + 8 clients = 64, sorted); +- prefill of prompts, or final prefill chunks, of up to 127 tokens (up to + 1016 pairs). From 128 tokens (1024 pairs) #629 takes the gather, as before. + +One-token decode runs the fused GeGLU MoE kernel and reaches neither kernel. + +## Serving A/B + +`bench_moe.py` (in this directory) starts one `mlxcel-server` per arm +(`--parallel 8 --no-prompt-cache`, default flags otherwise, decode graphs on) +and sends 1, 4 or 8 concurrent streaming chat completions, each with a +different prompt (eight topics), greedy with `ignore_eos`, 512 tokens. The rate +is the aggregate over the window in which every row is streaming. Arms rotate +per round (main, new, main again), three rounds. Before each cell the driver +waited for a 1-minute load average of at most 4 and then for the GPU to cool +to 60 C (one Qwen3 cell started at load 4.7, which rose during the +temperature wait). No other GPU process was running when a run started. + +```sh +python3 bench_moe.py --main server-main --fix new=server-new \ + --model gemma-4-26b-a4b-it-4bit --rounds 3 --batches 1,4,8 --out result.json +``` + +Gemma 4 26B A4B: + +| Clients | main (6 runs), tok/s | new (3 runs), tok/s | Change | +|---:|---|---|---:| +| 1 | 73.12 (73.06 to 73.27) | 73.06 (72.97 to 73.09) | -0.1% | +| 4 | 90.20 (89.80 to 90.39) | 110.98 (110.56 to 111.12) | +23.0% | +| 8 | 155.12 (154.66 to 156.98) | 167.04 (166.89 to 167.21) | +7.7% | + +Medians, with ranges. The two main arms differ by 0.12 to 0.32% in median. +At 4 and 8 clients the new arm's range clears main's. The median SM clock was +2086 or 2093 MHz in every cell. The one-client decode rate is unchanged, but +the one-client text differs from main's in every round (`176c7e8499c4` against +`6f1cbc7620f7`): the prompt is prefilled through the changed gathers (see the +next section), and a one-token decode never reaches them. + +`mlx-community/Qwen3-30B-A3B-3bit`, revision +`6add5f3b9ef4219603698b4b996e20a6da6d8793` (48 layers, 128 experts, top 8, +hidden 2048, expert intermediate 768, every projection affine 3-bit, group +64), same driver and protocol. `qmm_sm80` takes only 4 and 8 bits, so on main +all three expert projections ran `qmm_naive` from 8 pairs on, and the fused +decode-MoE kernel declines 3-bit gate/up, so a one-client decode step gathers +8 pairs and is affected too: + +| Clients | main (6 runs), tok/s | new (3 runs), tok/s | Change | +|---:|---|---|---:| +| 1 | 69.88 (65.35 to 72.73) | 92.01 (90.82 to 92.42) | +31.7% | +| 4 | 111.72 (110.86 to 112.34) | 142.62 (142.28 to 143.17) | +27.7% | +| 8 | 124.02 (121.69 to 124.86) | 146.13 (144.56 to 146.20) | +17.8% | + +The two main arms differ by 0.26 to 0.73% in median; every new range clears +main's. The median SM clock was 2080 to 2093 MHz. The one-client text differs +from main's (`ca028e6b9d45` against `7e1bbb77b3f6`) and is the same in every +round within each arm. + +## Short-prompt prefill + +`ttft.py` (in this directory) starts one server per arm (default slots, +`--no-prompt-cache`) and times a non-streaming `/v1/completions` request with +`max_tokens` 1 (prefill plus one sampled token) for raw prompts of exactly L +tokens (`usage.prompt_tokens`), seven requests after one discarded, median per +server; arms rotate main, new, main over three rounds. + +```sh +python3 ttft.py --main server-main --new server-new \ + --model gemma-4-26b-a4b-it-4bit --lengths 8,16,32,64,96,127,128,256 --out result.json +``` + +| Prompt tokens | main (6 runs), ms | new (3 runs), ms | Change | +|---:|---|---|---:| +| 8 | 66.04 (65.61 to 66.63) | 60.05 (58.97 to 60.77) | -9.1% | +| 16 | 84.62 (83.94 to 85.60) | 76.26 (75.98 to 77.03) | -9.9% | +| 32 | 118.95 (118.30 to 119.71) | 109.98 (109.66 to 110.42) | -7.5% | +| 64 | 185.74 (184.89 to 186.52) | 174.39 (174.33 to 174.56) | -6.1% | +| 96 | 253.03 (251.94 to 254.57) | 238.97 (238.43 to 239.50) | -5.6% | +| 127 | 319.96 (319.26 to 321.89) | 302.56 (302.51 to 303.10) | -5.4% | +| 128 | 697.08 (692.15 to 699.42) | 697.19 (694.96 to 698.30) | 0.0% | +| 256 | 758.35 (756.08 to 760.07) | 758.35 (757.83 to 758.72) | 0.0% | + +Medians of the per-server medians, with ranges. The two main arms differ by +0.03 to 0.57%. Every length gave the same first token in both arms. 128 and +256 tokens take #629 in both arms and are controls. On both binaries a +128-token prompt takes 2.2 times as long as a 127-token one: from `8 * E` +sorted pairs #629 dequantizes the whole expert stack; that is unchanged here. + +## Kernel timings across pair counts + +To find where the per-pair `gather_qmv` might lose to `qmm_naive`, a temporary +probe (not committed) timed one `gather_qmm` on a synthetic expert stack per +pair count, unsorted (`[T, 1, 1, K]` against `[T, top_k]` distinct experts) +and sorted (below `8 * E` pairs), as the median of seven batches of +synchronous calls, in one binary with `MLXCEL_GATHER_QMM_ONE_ROW_QMV=0` +(`qmm_naive`) and unset, alternated twice. Single calls are 0.05 to 170 ms and +include a host synchronization each, so small gathers are noisy (the two runs +of one arm differ by up to 1.5x below about 0.3 ms). Ratio of means, +`gather_qmv` / `qmm_naive`: + +| Stack (E, top_k) | N | K | bits | 8 | 32 | 64 sorted | 256 sorted | 1016 sorted | 1016 | 4096 | 16384 | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| Gemma 4 gate/up (128, 8) | 704 | 2816 | 4 | 0.78 | 0.69 | 0.66 | 0.89 | 0.90 | 0.59 | 0.57 | 0.56 | +| Gemma 4 gate/up (128, 8) | 704 | 2816 | 8 | 0.46 | 0.80 | 0.89 | 0.88 | 0.75 | 0.83 | 0.83 | 0.83 | +| Qwen3-30B-A3B-like gate/up (128, 8) | 768 | 2048 | 3 | 0.73 | 0.81 | 0.74 | 0.85 | 0.89 | 0.70 | 0.65 | 0.64 | +| Qwen3-30B-A3B-like down (128, 8) | 2048 | 768 | 3 | 1.43 | 1.17 | 0.93 | 0.95 | 1.07 | 0.89 | 0.87 | 0.88 | +| Qwen3-30B-A3B-like gate/up (128, 8) | 768 | 2048 | 6 | 0.62 | 0.73 | 0.75 | 0.74 | 0.57 | 0.71 | 0.69 | 0.68 | +| Qwen3-30B-A3B-like down (128, 8) | 2048 | 768 | 6 | 0.85 | 0.73 | 0.78 | 0.90 | 0.77 | 0.69 | 0.67 | 0.66 | +| synthetic (128, 8) | 704 | 704 | 4 | 0.89 | 1.15 | 0.83 | 0.98 | 1.23 | 1.06 | 1.01 | 1.05 | + +Columns are pair counts, unsorted unless marked. Sorted gathers of 1024 pairs +or more take #629 on both arms and are left out. One-expert stacks with one +row per pair, as Qwen4-Exp's row-invariant projections run (K = 4096, 4-bit), +at 8 / 128 / 2048 / 8192 pairs: + +| N | 8 | 128 | 2048 | 8192 | +|---:|---:|---:|---:|---:| +| 1 | 0.13 | 0.06 | 0.08 | 0.12 | +| 32 | 0.12 | 0.24 | 0.48 | 0.41 | +| 64 | 0.16 | 0.65 | 0.57 | 0.53 | + +`gather_qmv` was faster almost everywhere, by up to about 2x on the 3-, 6- +and 8-bit stacks and up to 16x on the one-expert projections. Two places were +not. The synthetic 4-bit N = 704, K = 704 stack scatters around 1.0 in both +directions (0.83 to 1.23 below 1024 pairs, 1.01 to 1.06 above); no supported +model is known to run that shape off `qmm_sm80` (Gemma 4's K = 704 projection +is down, N = 2816, which keeps `qmm_sm80`). The 3-bit down at 8 and 32 +unsorted pairs is slower in both runs (0.17 against 0.12 ms at 8 pairs), while +the 3-bit gate and up at the same pair counts are faster by more than that; +Qwen3-30B-A3B-3bit, where those three gathers make up a decode step's MoE +layer, is measured end to end above. So the dispatch has no upper bound on the +pair count. + +## A grouped kernel that reads each expert once (not shipped) + +The issue proposed grouping the pairs of a gather by expert so a selected +expert is read once rather than once per pair. That was built first (a +`gather_qmv` variant whose blocks found the other pairs of their expert with +warp ballots and applied each dequantized tile to up to eight of them, used +for one-row gathers of 8 to 256 pairs that took `qmm_naive`) and measured on +the same host, base and protocol as above, with a third arm that sent exactly +the same gathers to the per-pair `gather_qmv`, n = 3: + +| Clients | main (6 runs) | grouped | per-pair `gather_qmv` | +|---:|---:|---:|---:| +| 1 | 74.62 | 74.49 (-0.2%) | 74.73 (+0.1%) | +| 4 | 87.85 | 100.89 (+14.9%) | 110.69 (+26.0%) | +| 8 | 155.75 | 159.55 (+2.4%) | 163.47 (+5.0%) | + +The two arms gave the same text in every round (every pair of the grouped +kernel had the per-pair bits), and the per-pair arm was faster by 8.9% at 4 +clients and 2.4% at 8: all of the gain came from leaving `qmm_naive`, and the +saved reads cost more than they saved. A bound in #2796's terms agrees that +they were never worth much: with this bench's prompts, a decode step's MoE +layer selects 27 distinct experts of 32 pairs at 4 clients and 45 of 64 at 8 +(median over 2850 layer-steps; #2796 found 28 and 45 on the N1X), so at most +15.6% of the gate/up reads at 4 clients could go, which with gathers about +54% of a layer and gate/up two thirds of the gathered bytes caps the gain at +about 5 to 6%. The grouped launch had a quarter of `gather_qmv`'s blocks per +pair; that was not profiled further. Grouping the `qmm_sm80` gathers (down) +too, and leaving 64-pair decode unsorted, were both slower in one-round +screens. + +## Numerics + +`examples/logit_trace` over `tests/fixtures/wikitext2_excerpt.txt`, top 8, +64-token chunks (4) and 16-token chunks (16), each arm traced with the change +on and off (`MLXCEL_GATHER_QMM_ONE_ROW_QMV=0`, main's `qmm_naive`) in one +binary, compared with `scripts/compare_logit_traces.py`. "Prefill" traces each +chunk from a forward at the chunk's width (64 tokens = 512 sorted pairs, 16 +tokens = 128 pairs: both take the changed gathers); "N rows" runs every +position as a width-one batched decode over N rows +(`MLXCEL_TRACE_BATCH_ROWS`). Top-1 disagreement, all positions and positions +the reference had decided (top-two gap at least 2): + +Qwen3-30B-A3B 3-bit: + +| Comparison | 64-token chunks | 16-token chunks | +|---|---|---| +| on vs off, prefill | 20/256 (7.8%), decided 0/91 | 21/256 (8.2%), decided 0/67 | +| on vs off, 1 row | 21/256 (8.2%), decided 0/92 | 22/256 (8.6%), decided 0/66 | +| on vs off, 4 rows | 17/256 (6.6%), decided 0/91 | 20/256 (7.8%), decided 0/67 | +| main: prefill vs 1 row | 17/256 (6.6%), decided 0/91 | 20/256 (7.8%), decided 0/67 | +| main: 1 row vs 4 rows | 12/256 (4.7%), decided 0/92 | 5/256 (2.0%), decided 0/66 | + +On Qwen3-30B-A3B 3-bit (perplexity on the excerpt 74 to 75 with 64-token +chunks and 232 to 240 with 16-token chunks, every arm within 3.5% of the +others, in both directions) the change disagrees with `qmm_naive` about as +often as main's own prefill and decode kernels disagree with each other, and +never where the reference had decided. Its one-token MoE step is a gather, so +its one-row traces differ on and off. + +On Gemma 4 26B A4B the one-row traces are byte-identical on and off: one-token +decode runs the fused GeGLU kernel and never reaches the changed gathers. That +makes the one-row trace (off) a reference the change does not touch, and each +arm is measured against it: + +| Against the 1-row trace | 64-token chunks | 16-token chunks | +|---|---|---| +| prefill, off (main's path) | 60/256 (23.4%), decided 6/115 (5.2%) | 69/256 (27.0%), decided 8/96 (8.3%) | +| prefill, on (this change) | 62/256 (24.2%), decided 5/115 (4.3%) | 70/256 (27.3%), decided 7/96 (7.3%) | +| 4 rows, off | 53/256 (20.7%), decided 4/115 (3.5%) | 73/256 (28.5%), decided 7/96 (7.3%) | +| 4 rows, on | 54/256 (21.1%), decided 6/115 (5.2%) | 65/256 (25.4%), decided 4/96 (4.2%) | +| 8 rows, off | 55/256 (21.5%), decided 6/115 (5.2%) | 61/256 (23.8%), decided 5/96 (5.2%) | +| 8 rows, on | 60/256 (23.4%), decided 5/115 (4.3%) | 62/256 (24.2%), decided 5/96 (5.2%) | + +Summed over the six cells, the change disagrees with the common reference on +32 of 633 decided positions (5.1%) and main's path on 36 of 633 (5.7%); the +change is closer in four cells, equal in one and farther in one (4 rows, +64-token chunks: 6 against 4). On all positions the two are 373 and 371 of +1536 (24.3% and 24.2%), and the largest logit move on the reference's choice +is 8.0 to 13.0 against 6.4 to 13.4. Compared directly, on against off, the +arms disagree more (decided positions, 64- and 16-token chunks: prefill +11/119 (9.2%) and 13/107 (12.2%), 4 rows 10/123 (8.1%) and 11/98 (11.2%), +8 rows 4/112 (3.6%) and 12/111 (10.8%)), because both arms of that comparison +changed the rounding, each in its own way, and two independent perturbations +tend to sit farther from each other than either sits from the reference. +Gemma 4 26B A4B is an instruct checkpoint run on raw text: its perplexity here +is 3600 to 4800 (64-token chunks) and 67000 to 110000 (16-token chunks) in +every arm, and main against itself disagrees on 21 to 29% of all positions +between batch sizes, so these traces cannot bound the change tightly; they +show it sits at main's own distance from the reference (closer in total). The +grouped kernel's direct on-against-off comparison at 4 and 8 rows (64-token +chunks) gave the same 10/123 and 4/112, as expected from identical bits. + +## Limits + +- Two checkpoints on one host for the end-to-end numbers. The kernel timings + cover other shapes and bit widths, but not on a checkpoint; no 6-bit or + mixed-precision MoE checkpoint and no Qwen4-Exp checkpoint was run. +- Expert gathers that take `qmm_sm80` (4- and 8-bit stacks with N a multiple + of 128: Qwen3-30B-A3B, Mixtral, Llama 4, ...) are unchanged and were not + re-measured. +- Devices below sm_80, where every one-row gather of 8 or more pairs ran + `qmm_naive`, were not measured. +- RTX Spark N1X, where #2796 measured, was not re-measured. diff --git a/docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03/bench_moe.py b/docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03/bench_moe.py new file mode 100644 index 000000000..9a03b20a4 --- /dev/null +++ b/docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03/bench_moe.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""Aggregate decode tok/s A/B for #2784: main-a / each --fix arm / main-b, rotated. + +One fresh server per (round, arm). Each cell sends B concurrent streaming chat +completions, each with a DIFFERENT prompt (so rows route to different +experts), greedy with ignore_eos, and reports the aggregate decode rate over +the window in which every row is streaming (latest first token to earliest +last token), as in docs/benchmark_results/issue-3385-qwen3-8b-gb10-2026-11-24. + +Clock gate: before each cell the GPU must be at or under GATE_TEMP_C (polled +up to 120 s), and nvidia-smi samples SM clock, power and temperature every +500 ms during the cell; the median SM clock is stored with the cell. +""" +import argparse +import hashlib +import json +import os +import signal +import socket +import statistics +import subprocess +import sys +import threading +import time +import urllib.request + +PROMPTS = [ + "Explain in detail how a modern CPU pipeline handles branch misprediction, with examples.", + "Write a long short story about a lighthouse keeper who discovers a message in a bottle.", + "Describe the history of the Roman Empire from its founding to the fall of the West.", + "Give a step-by-step recipe for a traditional Korean kimchi stew and explain each ingredient.", + "Write a Python tutorial that implements a binary search tree with insertion and deletion.", + "Compare the economic policies of Keynesian and Austrian schools of thought at length.", + "Explain how photosynthesis works at the molecular level, including the Calvin cycle.", + "Plan a two-week travel itinerary through Japan, with daily activities and food tips.", +] +GATE_TEMP_C = float(os.environ.get("GATE_TEMP_C", "60")) +# Host gate: the decode step's lazy graph is built on the host every step, so a +# busy host (another build) slows both arms by different amounts. Wait up to +# GATE_LOAD_MAX_S for the 1-minute load average to fall to GATE_LOAD. +GATE_LOAD = float(os.environ.get("GATE_LOAD", "4")) +GATE_LOAD_MAX_S = float(os.environ.get("GATE_LOAD_MAX_S", "1800")) + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def gpu_temp(): + out = subprocess.run(["nvidia-smi", "--query-gpu=temperature.gpu", "--format=csv,noheader,nounits"], + capture_output=True, text=True).stdout.strip() + return float(out.splitlines()[0]) + + +def gate(): + start = time.time() + while os.getloadavg()[0] > GATE_LOAD and time.time() - start < GATE_LOAD_MAX_S: + time.sleep(10) + t0 = time.time() + t = gpu_temp() + while t > GATE_TEMP_C and time.time() - t0 < 120: + time.sleep(2) + t = gpu_temp() + return round(time.time() - start, 1), t + + +class Sampler: + def __init__(self): + self.proc = subprocess.Popen( + ["nvidia-smi", "--query-gpu=clocks.sm,power.draw,temperature.gpu", + "--format=csv,noheader,nounits", "-lms", "500"], + stdout=subprocess.PIPE, text=True) + self.rows = [] + self.t = threading.Thread(target=self._read, daemon=True) + self.t.start() + + def _read(self): + for line in self.proc.stdout: + try: + self.rows.append([float(v) for v in line.strip().split(",")]) + except ValueError: + pass + + def stop(self): + self.proc.terminate() + self.proc.wait() + if not self.rows: + return {} + clk = [r[0] for r in self.rows] + pw = [r[1] for r in self.rows] + tp = [r[2] for r in self.rows] + return {"sm_mhz_median": statistics.median(clk), "sm_mhz_min": min(clk), + "power_w_median": statistics.median(pw), "temp_c_max": max(tp)} + + +def stream(port, prompt, max_tokens, out, idx): + body = json.dumps({ + "model": "default", "messages": [{"role": "user", "content": prompt}], + "max_tokens": max_tokens, "temperature": 0, "stream": True, + "stream_options": {"include_usage": True}, "ignore_eos": True, + }).encode() + req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}) + stamps, usage, text = [], None, [] + with urllib.request.urlopen(req, timeout=900) as resp: + for raw in resp: + line = raw.decode().strip() + if not line.startswith("data:"): + continue + payload = line[5:].strip() + if payload == "[DONE]": + break + obj = json.loads(payload) + if obj.get("usage"): + usage = obj["usage"] + if obj.get("choices"): + d = obj["choices"][0].get("delta", {}) + piece = (d.get("content") or "") + (d.get("reasoning_content") or "") + if piece: + stamps.append(time.perf_counter()) + text.append(piece) + out[idx] = (stamps, usage, "".join(text)) + + +def cell(port, batch, max_tokens, check=True): + out = [None] * batch + threads = [threading.Thread(target=stream, args=(port, PROMPTS[i], max_tokens, out, i)) + for i in range(batch)] + for t in threads: + t.start() + for t in threads: + t.join() + completion, digests = [], [] + for stamps, usage, text in out: + if usage is None or len(stamps) < 8: + raise RuntimeError("a row returned no usage or too few chunks") + completion.append(usage["completion_tokens"]) + digests.append(hashlib.sha256(text.encode()).hexdigest()[:12]) + lo = max(s[0] for s, _, _ in out) + hi = min(s[-1] for s, _, _ in out) + if check and hi - lo < 1.0: + raise RuntimeError(f"rows overlap for only {hi - lo:.2f} s") + rate = 0.0 + for stamps, usage, _ in out: + per_chunk = usage["completion_tokens"] / len(stamps) + inside = sum(1 for t in stamps if lo < t <= hi) + rate += inside * per_chunk / (hi - lo) + return rate, completion, digests, hi - lo + + +def start(binary, model, port, log, parallel, env=None): + cmd = [binary, "-m", model, "--host", "127.0.0.1", "--port", str(port), + "--parallel", str(parallel), "--no-prompt-cache"] + proc = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT, + env=dict(os.environ, **(env or {}))) + deadline = time.time() + 600 + while time.time() < deadline: + if proc.poll() is not None: + raise RuntimeError(f"server exited with {proc.returncode}") + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2) as r: + if r.status == 200: + return proc + except Exception: + time.sleep(1) + proc.kill() + raise RuntimeError("server did not become healthy") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--main", required=True) + ap.add_argument("--fix", action="append", required=True, + help="NAME=BINARY[:VAR=VAL[,VAR=VAL]]; repeatable") + ap.add_argument("--model", required=True) + ap.add_argument("--rounds", type=int, default=3) + ap.add_argument("--batches", default="1,4,8") + ap.add_argument("--max-tokens", type=int, default=512) + ap.add_argument("--out", required=True) + args = ap.parse_args() + batches = [int(b) for b in args.batches.split(",")] + fixes = [] + for spec in args.fix: + name, rest = spec.split("=", 1) + binary, _, envs = rest.partition(":") + env = dict(kv.split("=", 1) for kv in envs.split(",") if kv) + fixes.append((name, binary, env)) + arms = [("main-a", args.main, {})] + fixes + [("main-b", args.main, {})] + results = [] + log = open(args.out + ".server.log", "w") + for rnd in range(args.rounds): + r = rnd % len(arms) + order = arms[r:] + arms[:r] + for arm, binary, env in order: + port = free_port() + log.write(f"=== round {rnd} arm {arm} {binary} {env}\n") + log.flush() + proc = start(binary, args.model, port, log, max(batches), env) + try: + cell(port, 2, 32, check=False) # warm-up (prefill shapes, graph capture), discarded + for batch in batches: + cell(port, batch, 64, check=False) # per-batch warm-up so the cell replays captured graphs + waited, temp0 = gate() + load0 = os.getloadavg()[0] + s = Sampler() + rate, completion, digests, window = cell(port, batch, args.max_tokens) + clocks = s.stop() + clocks["load1_before"] = round(load0, 2) + clocks["load1_after"] = round(os.getloadavg()[0], 2) + row = {"round": rnd, "arm": arm, "batch": batch, + "decode_tok_s": round(rate, 2), "window_s": round(window, 2), + "completion_tokens": completion, "text_sha": digests, + "gate_wait_s": waited, "gate_temp_c": temp0, **clocks} + results.append(row) + print(json.dumps(row), flush=True) + finally: + proc.send_signal(signal.SIGTERM) + try: + proc.wait(timeout=60) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + summary = [] + for batch in batches: + def vals(arm): + return [r["decode_tok_s"] for r in results if r["batch"] == batch and r["arm"] == arm] + a, b = vals("main-a"), vals("main-b") + m = a + b + row = {"batch": batch, "main_a": a, "main_b": b, + "main_median": statistics.median(m), + "null_spread_pct": round(100 * abs(statistics.median(a) / statistics.median(b) - 1), 2)} + for name, _, _ in fixes: + f = vals(name) + row[name] = f + row[f"{name}_median"] = statistics.median(f) + row[f"{name}_vs_main_pct"] = round(100 * (statistics.median(f) / statistics.median(m) - 1), 2) + row[f"{name}_min_over_main_max"] = min(f) > max(m) + summary.append(row) + with open(args.out, "w") as fh: + json.dump({"rows": results, "summary": summary}, fh, indent=1) + for s in summary: + print(json.dumps(s), flush=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03/ttft.py b/docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03/ttft.py new file mode 100644 index 000000000..f11badda1 --- /dev/null +++ b/docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03/ttft.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Short-prompt prefill latency A/B for #2784: main-a / new / main-b, rotated. + +One fresh server per (round, arm), prompt cache off. For each target prompt +length L a raw /v1/completions prompt of exactly L tokens (usage.prompt_tokens, +calibrated per server) is sent with max_tokens=1, non-streaming; the request +wall time (prefill + one sampled token) is timed REPS times after one discarded +request, and the median is kept. Each L uses its own prompt text, the same in +every arm. +""" +import argparse +import json +import os +import signal +import socket +import statistics +import subprocess +import sys +import time +import urllib.request + +WORDS = ( + "the river bends around an old stone mill where the miller keeps a ledger of grain " + "brought by farmers from the valley each autumn and the children count the sacks " + "while the water turns the wheel slowly through the cold morning fog that hangs over " + "the fields until noon when the sun finally burns it away and the market opens in the " + "square with bread cheese apples honey wool rope candles and iron tools for sale to " + "travelers who come down from the mountain passes before the snow closes the roads " + "for the long winter months ahead of the spring thaw and the planting season begins " + "again with ploughs oxen seed and the songs of the workers in the wet brown earth" +).split() + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def gpu_temp(): + out = subprocess.run(["nvidia-smi", "--query-gpu=temperature.gpu", "--format=csv,noheader,nounits"], + capture_output=True, text=True).stdout.strip() + return float(out.splitlines()[0]) + + +def start(binary, model, port, log, env=None): + cmd = [binary, "-m", model, "--host", "127.0.0.1", "--port", str(port), "--no-prompt-cache"] + proc = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT, env=dict(os.environ, **(env or {}))) + deadline = time.time() + 600 + while time.time() < deadline: + if proc.poll() is not None: + raise RuntimeError(f"server exited with {proc.returncode}") + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2) as r: + if r.status == 200: + return proc + except Exception: + time.sleep(1) + proc.kill() + raise RuntimeError("server did not become healthy") + + +def text_for(n_words, offset): + return " ".join(WORDS[(offset + i) % len(WORDS)] for i in range(n_words)) + + +def request(port, prompt): + body = json.dumps({"model": "default", "prompt": prompt, "max_tokens": 1, "temperature": 0}).encode() + req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/completions", data=body, + headers={"Content-Type": "application/json"}) + t0 = time.perf_counter() + with urllib.request.urlopen(req, timeout=300) as resp: + obj = json.loads(resp.read()) + dt = time.perf_counter() - t0 + return dt, obj["usage"]["prompt_tokens"], obj["choices"][0].get("text", "") + + +def calibrate(port, target, offset): + """Word count whose prompt is exactly `target` tokens (or the closest below).""" + best = None + lo, hi = 1, target + while lo <= hi: + mid = (lo + hi) // 2 + _, n, _ = request(port, text_for(mid, offset)) + if n == target: + return mid, n + if n < target: + best = (mid, n) + lo = mid + 1 + else: + hi = mid - 1 + return best + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--main", required=True) + ap.add_argument("--new", required=True) + ap.add_argument("--model", required=True) + ap.add_argument("--rounds", type=int, default=3) + ap.add_argument("--lengths", default="8,16,32,64,96,127,128,256") + ap.add_argument("--reps", type=int, default=7) + ap.add_argument("--out", required=True) + args = ap.parse_args() + lengths = [int(x) for x in args.lengths.split(",")] + arms = [("main-a", args.main), ("new", args.new), ("main-b", args.main)] + rows = [] + log = open(args.out + ".server.log", "w") + calib = {} + for rnd in range(args.rounds): + order = arms[rnd % 3:] + arms[:rnd % 3] + for arm, binary in order: + t0 = time.time() + while gpu_temp() > 60 and time.time() - t0 < 120: + time.sleep(2) + port = free_port() + log.write(f"=== round {rnd} arm {arm} {binary}\n") + log.flush() + proc = start(binary, args.model, port, log) + try: + request(port, text_for(40, 0)) # warm-up, discarded + for li, L in enumerate(lengths): + offset = 7 * li + if L not in calib: + calib[L] = calibrate(port, L, offset) + words, ntok = calib[L] + prompt = text_for(words, offset) + request(port, prompt) # discarded + ts, texts = [], set() + for _ in range(args.reps): + dt, n, txt = request(port, prompt) + assert n == ntok, (n, ntok) + ts.append(dt * 1000) + texts.add(txt) + row = {"round": rnd, "arm": arm, "target": L, "prompt_tokens": ntok, + "ms_median": round(statistics.median(ts), 2), "ms_min": round(min(ts), 2), + "ms_max": round(max(ts), 2), "first_token": sorted(texts)} + rows.append(row) + print(json.dumps(row), flush=True) + finally: + proc.send_signal(signal.SIGTERM) + try: + proc.wait(timeout=60) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + summary = [] + for L in lengths: + def vals(a): + return [r["ms_median"] for r in rows if r["target"] == L and r["arm"] == a] + m = vals("main-a") + vals("main-b") + n = vals("new") + summary.append({"target": L, "prompt_tokens": calib[L][1], "main": m, "new": n, + "main_median": statistics.median(m), "new_median": statistics.median(n), + "new_vs_main_pct": round(100 * (statistics.median(n) / statistics.median(m) - 1), 2), + "null_spread_pct": round(100 * abs(statistics.median(vals("main-a")) / statistics.median(vals("main-b")) - 1), 2)}) + with open(args.out, "w") as fh: + json.dump({"rows": rows, "summary": summary, "calibration": calib}, fh, indent=1) + for s in summary: + print(json.dumps(s), flush=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/environment-variables.md b/docs/environment-variables.md index b21b1d9c5..ee0ca5258 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -868,6 +868,7 @@ recommended as normal deployment settings. | `MLXCEL_QMM_FOLD_MIN_ROWS` | integer `2` to `8`; anything else keeps the default | `5` on compute capability 12.1, `8` elsewhere | **CUDA only.** Rows from which a folded `M == 1` decode batch of a large weight (see `MLXCEL_QMM_FOLD_MIN_ELEMENTS`) leaves qmv for the GEMM kernels (issue #2690). From this width a batched row is no longer bitwise equal to the same row decoded alone. Verify blocks and prefill pieces (`M > 1`) always keep 8. Read once at first use. | | `MLXCEL_QMM_FOLD_MIN_ELEMENTS` | positive integer | `16777216` (2^24) | **CUDA only.** Weight size `N * K` from which `MLXCEL_QMM_FOLD_MIN_ROWS` applies. A smaller weight keeps qmv through 8 rows on compute capability 12.1 and through 7 elsewhere. Read once at first use. | | `MLXCEL_GATHER_QMM_GROUPED_MIN_ROWS` | positive integer | `8` | **CUDA only.** Amortization threshold for `MLXCEL_GATHER_QMM_GROUPED`: the fast path activates only once the sorted batch size `B` reaches `min_rows * E` (E = expert count), the point past which the one-time expert dequant traffic is cheaper than the legacy per-row re-reads. Lower it to trigger the fast path on smaller sorted batches (e.g. high-concurrency batched decode crossing the same sort gate); raise it to keep more traffic on the legacy path for tuning or rollback. | +| `MLXCEL_GATHER_QMM_ONE_ROW_QMV` | `0` disables; any other value or unset enables | on | **CUDA only.** Sends an affine `gather_qmm` whose pairs each have one row (MoE decode: `[T, 1, 1, K]` against `[T, top_k]` experts, or the same pairs flattened and sorted) to the per-pair `gather_qmv` where it would otherwise run `qmm_naive` (issue #2784): eight or more pairs whose expert N is not a multiple of 128, or whose bit width `qmm_sm80` does not take, or on a device below sm_80. Below eight pairs `gather_qmv` already ran, and gathers that take `qmm_sm80` or the sorted grouped GEMM (`MLXCEL_GATHER_QMM_GROUPED`) keep it. Every pair gets the bits a single-pair gather gives it (pinned by `gather_qmm_one_row_tests`), so against `qmm_naive` the rounding moves. Read once at first use. Set to `0` for `qmm_naive` (A/B, rollback). See `docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03.md`. | | `MLXCEL_CUDA_GRAPH_CAPTURE_BARRIER` | `0`/`false`/`off`/`no` disable (case-insensitive); `1`/`true`/`on`/`yes`, unset or any other value enables | on | **CUDA only.** Makes every captured child graph inside an MLX CUDA graph (a cuBLASLt matmul, a cuDNN convolution or attention, any other stream capture) a barrier: it joins every open branch of the graph before it and gates every node added after it, on top of the data dependencies MLX derives from buffers (`mlx/backend/cuda/device.cpp` overlay, issue #2462). Upstream orders a child graph only by the buffers it declares, which lets its kernels run alongside unrelated kernel nodes of the same graph, and on GB10 that overlap corrupted cuBLASLt f32 GEMMs in about 40% of fresh processes (the first run of a 12-layer DeBERTa-v2 encoder returned wrong hidden states from a random layer, every replay correct). Child graphs are also chained to each other, so independent cuBLASLt GEMMs no longer overlap; kernel nodes between two child graphs stay concurrent. Set to `0` for an A/B against upstream's ordering. | | `MLXCEL_CUDA_GRAPHS_DOT_VERBOSE` | `1`/`true`/`on`/`yes` enable (case-insensitive); `0`/`false`/`off`/`no`, unset or any other value leave it off | off | **CUDA only.** With MLX's `MLX_SAVE_CUDA_GRAPHS_DOT_FILE` set, `1` dumps each graph with `cudaGraphDebugDotFlagsVerbose`, so kernel and memset node parameters (grid, shared memory, memset target) appear next to the node types; that is what shows which buffers concurrent nodes touch (issue #2462). | | `MLXCEL_AUTOTUNE` | `1`/`true`/`on`/`yes` enable tuning; `cache`/`read`/`readonly`/`read-only` consume cached tactics only; `0`/`false`/`off`/`no` or unset disable | off | Shape-bucketed kernel autotuner (issue #906). Off by default and fully inert when off: no tactic-cache reads, no profiling, no filesystem access on the decode path, so cold-start latency and steady-state behavior are exactly what they were before #906. Set to `cache` to consume tactics an earlier `mlxcel tune` wrote without ever profiling at runtime, or to `1` to additionally profile the first use of a shape bucket that has no cached entry. Tuned tactics are keyed by `(op, kernel/runner identity, power-of-two shape bucket, dtype)` and stored one JSON file per key at `${MLXCEL_CACHE_DIR:-$HOME/.cache/mlxcel}/autotune/.json`, carrying the mlxcel version and the pinned MLX commit they were measured under; a mismatch in either discards the entry and re-tunes rather than applying a stale config, and a corrupt or unreadable file is warned about and ignored, never fatal. A shape outside the tuned matrix warns once and uses the op's default. Selection is min-latency over a median-of-N timing per candidate, where N scales with the measured per-launch cost (at least 5, and many more for a cheap launch, which is where run-to-run noise concentrates); candidates are sampled round-robin so drift over the sweep moves all of them together rather than favoring whichever was measured first. A candidate must beat the op's own default by more than 2% *and* by more than the two measurements' combined relative spread (scaled median absolute deviation over the repetitions), and two candidates that cannot be told apart collapse to whichever sits nearer the default. A win inside the host's noise floor is therefore not a win, so a noisy host converges back to the default instead of flapping; the spread and the threshold that was applied are recorded in the cache entry and printed by `mlxcel tune`. An explicitly-set variable for a tuned knob (`MLXCEL_PAGED_DECODE_SPLITS`, `MLXCEL_QMM_TILE_M`, `MLXCEL_QMV_MULTIROW`, `MLXCEL_QMV_MULTIROW_MAX_ROWS`) always wins over a tuned value and suppresses tuning for that knob. Only the v1 paged-decode `NumSplits` op is tuned lazily at runtime; the process-wide CUDA kernel knobs are tuned only by the offline `mlxcel tune` subcommand and applied at process start. | diff --git a/src/lib/mlxcel-core/src/gather_qmm_one_row_tests.rs b/src/lib/mlxcel-core/src/gather_qmm_one_row_tests.rs new file mode 100644 index 000000000..61ca6e80e --- /dev/null +++ b/src/lib/mlxcel-core/src/gather_qmm_one_row_tests.rs @@ -0,0 +1,427 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! One-row affine `gather_qmm` gathers on CUDA (issue #2784). +//! +//! MoE decode hands `gather_qmm` one-row pairs: `[T, 1, 1, K]` against an +//! `[E, N, K]` expert stack with `[T, top_k]` indices, or the same pairs +//! flattened and sorted. Below eight pairs `GatherQMM::eval_gpu` (the overlay in +//! `src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/quantized/quantized.cpp`) +//! always ran the per-pair `gather_qmv`; from eight pairs on, where `qmm_sm80` +//! does not apply (N not a multiple of 128), it ran `qmm_naive`. It now keeps +//! such gathers on `gather_qmv` at every pair count, so every pair of a gather +//! must equal the same pair gathered alone (a single-pair `gather_qmv`), bit +//! for bit: sorted or not, all pairs on one expert or each on its own, at the +//! smallest gather that used to take `qmm_naive` (eight pairs), at Gemma 4's +//! 4- and 8-client decode (32 and 64 pairs) and at prefill-sized gathers, and at +//! a K with a residue. `qmm_naive` rounds differently, so the first test fails +//! on the old dispatch. Below eight pairs, and from eight pairs on where +//! `qmm_sm80` applies, the kernels are unchanged and pinned too: below eight to +//! the single-pair bits, `qmm_sm80` to the reference. A dequantized reference +//! bounds every layout against a wrong answer that matches itself. +//! +//! cargo test -p mlxcel-core --features cuda --lib gather_qmm_one_row_tests + +use super::*; + +const GROUP: i32 = 64; +const BITS: i32 = 4; +/// A sorted gather of at least `8 * E` pairs takes the dequantize + grouped GEMM +/// prefill path (#629, `MLXCEL_GATHER_QMM_GROUPED_MIN_ROWS` at its default of +/// 8) before the one-row dispatch is reached. 64 experts keep every sorted +/// layout here below that 512-pair floor; Gemma 4 26B's 128 experts put it at +/// 1024. +const EXPERTS: i32 = 64; +/// Below this many pairs `gather_qmv` already ran (`M * B < 8`). +const QMV_BELOW: i32 = 8; + +fn randn(shape: &[i32], seed: u64) -> UniquePtr { + randn_as(shape, seed, dtype::BFLOAT16) +} + +fn randn_as(shape: &[i32], seed: u64, dt: i32) -> UniquePtr { + let key = random_key(seed); + // SAFETY: `key` lives across the call. + let x = unsafe { random_normal(shape, dtype::FLOAT32, key.as_ref().unwrap() as *const _) }; + astype(&x, dt) +} + +struct Stack { + w: UniquePtr, + scales: UniquePtr, + biases: UniquePtr, + n: i32, + k: i32, + bits: i32, + /// Activation (and scale) dtype. + dt: i32, +} + +fn stack(n: i32, k: i32) -> Stack { + stack_with(n, k, BITS, dtype::BFLOAT16) +} + +fn stack_with(n: i32, k: i32, bits: i32, dt: i32) -> Stack { + let w = multiply_scalar(&randn_as(&[EXPERTS, n, k], 3, dt), 0.02); + let q = quantize_weights(&w, GROUP, bits); + let s = Stack { + w: quantized_weights_w(&q), + scales: quantized_weights_scales(&q), + biases: quantized_weights_biases(&q), + n, + k, + bits, + dt, + }; + eval(&s.w); + eval(&s.scales); + eval(&s.biases); + s +} + +fn gather(x: &MlxArray, rhs: &MlxArray, s: &Stack, sorted: bool) -> UniquePtr { + // SAFETY: every pointer is owned by the caller for the whole call. + let y = unsafe { + gather_qmm( + x, + &s.w, + &s.scales, + s.biases.as_ref().unwrap() as *const _, + std::ptr::null(), + rhs as *const _, + true, + GROUP, + s.bits, + sorted, + "affine", + std::ptr::null(), + ) + }; + eval(&y); + y +} + +/// A pair layout: the token each pair reads and the expert it names. +struct Layout { + name: &'static str, + tokens: i32, + top_k: i32, + experts: Vec, + /// `true`: x is `[pairs, 1, K]` with `[pairs]` sorted indices (the + /// SwitchGLU sort); `false`: x is `[tokens, 1, 1, K]` with `[tokens, top_k]`. + sorted: bool, +} + +impl Layout { + fn pairs(&self) -> i32 { + self.tokens * self.top_k + } +} + +fn layouts() -> Vec { + let overlap = |tokens: i32, top_k: i32| -> Vec { + // Each token draws top_k distinct experts from a window that slides by + // three, so neighbouring tokens share some experts and not others. + (0..tokens) + .flat_map(|t| (0..top_k).map(move |j| ((t * 3 + j * 2) % EXPERTS) as u32)) + .collect() + }; + let mut sorted8 = overlap(8, 8); + sorted8.sort_unstable(); + let mut sorted257: Vec = (0..257).map(|p| ((p * 5) % EXPERTS) as u32).collect(); + sorted257.sort_unstable(); + let mut sorted511: Vec = overlap(64, 8)[..511].to_vec(); + sorted511.sort_unstable(); + vec![ + Layout { + name: "eight pairs, one expert", + tokens: 1, + top_k: 8, + experts: vec![5; 8], + sorted: false, + }, + Layout { + name: "nine pairs, one expert", + tokens: 9, + top_k: 1, + experts: vec![6; 9], + sorted: false, + }, + Layout { + name: "four tokens top-8 overlapping", + tokens: 4, + top_k: 8, + experts: overlap(4, 8), + sorted: false, + }, + Layout { + name: "eight tokens top-8 sorted", + tokens: 8, + top_k: 8, + experts: sorted8, + sorted: true, + }, + Layout { + name: "twenty pairs, one expert", + tokens: 20, + top_k: 1, + experts: vec![7; 20], + sorted: false, + }, + Layout { + name: "sixteen pairs, all distinct", + tokens: 2, + top_k: 8, + experts: (0..16).map(|e| e as u32).collect(), + sorted: false, + }, + Layout { + name: "257 pairs sorted", + tokens: 257, + top_k: 1, + experts: sorted257, + sorted: true, + }, + Layout { + name: "511 pairs sorted, one below the grouped GEMM floor", + tokens: 511, + top_k: 1, + experts: sorted511, + sorted: true, + }, + Layout { + name: "sixty-four tokens top-8 unsorted", + tokens: 64, + top_k: 8, + experts: overlap(64, 8), + sorted: false, + }, + ] +} + +/// Gathers below eight pairs, which took the per-pair `gather_qmv` before #2784. +fn small_layouts() -> Vec { + vec![ + Layout { + name: "one pair", + tokens: 1, + top_k: 1, + experts: vec![4], + sorted: false, + }, + Layout { + name: "two pairs, one expert", + tokens: 1, + top_k: 2, + experts: vec![5, 5], + sorted: false, + }, + Layout { + name: "seven pairs, three experts", + tokens: 7, + top_k: 1, + experts: vec![3, 9, 3, 3, 9, 1, 3], + sorted: false, + }, + ] +} + +/// x for `layout` and the `[pairs, K]` row each pair reads. +fn inputs(layout: &Layout, k: i32) -> (UniquePtr, UniquePtr, Vec) { + inputs_as(layout, k, dtype::BFLOAT16) +} + +fn inputs_as( + layout: &Layout, + k: i32, + dt: i32, +) -> (UniquePtr, UniquePtr, Vec) { + let pairs = layout.pairs(); + if layout.sorted { + let x = randn_as(&[pairs, 1, k], 11, dt); + eval(&x); + let rhs = from_slice_u32(&layout.experts, &[pairs]); + (x, rhs, (0..pairs).collect()) + } else { + let x = randn_as(&[layout.tokens, 1, 1, k], 9, dt); + eval(&x); + let rhs = from_slice_u32(&layout.experts, &[layout.tokens, layout.top_k]); + (x, rhs, (0..pairs).map(|p| p / layout.top_k).collect()) + } +} + +fn reference(x_rows: &MlxArray, layout: &Layout, s: &Stack) -> UniquePtr { + // SAFETY: every pointer is owned by `s` for the whole call. + let w = unsafe { + dequantize( + &s.w, + &s.scales, + s.biases.as_ref().unwrap() as *const _, + GROUP, + s.bits, + "affine", + ) + }; + let w = astype(&w, dtype::FLOAT32); + let rhs = from_slice_u32(&layout.experts, &[layout.pairs()]); + // [pairs, N, K] @ [pairs, K, 1] -> [pairs, N, 1] + let w_sel = take(&w, &rhs, 0); + let x = reshape(&astype(x_rows, dtype::FLOAT32), &[layout.pairs(), s.k, 1]); + reshape(&matmul(&w_sel, &x), &[layout.pairs(), s.n]) +} + +fn x_rows(x: &MlxArray, rows: &[i32], k: i32) -> UniquePtr { + let flat = reshape(x, &[-1, k]); + let idx: Vec = rows.iter().map(|&r| r as u32).collect(); + take(&flat, &from_slice_u32(&idx, &[rows.len() as i32]), 0) +} + +fn check_bitwise(layout: &Layout, s: &Stack) { + let pairs = layout.pairs(); + let (x, rhs, rows) = inputs_as(layout, s.k, s.dt); + let all = reshape(&gather(&x, &rhs, s, layout.sorted), &[pairs, s.n]); + eval(&all); + let all_bytes = array_to_raw_bytes(&all); + let row_nbytes = all_bytes.len() / pairs as usize; + let xr = x_rows(&x, &rows, s.k); + eval(&xr); + for p in 0..pairs { + // The same pair alone: one [1, 1, 1, K] row against a [1, 1] index, + // which is a single-pair `gather_qmv`. + let one_x = reshape(&slice(&xr, &[p, 0], &[p + 1, s.k]), &[1, 1, 1, s.k]); + let one_rhs = from_slice_u32(&[layout.experts[p as usize]], &[1, 1]); + let one = gather(&one_x, &one_rhs, s, false); + let one_bytes = array_to_raw_bytes(&one); + assert_eq!( + one_bytes.as_slice(), + &all_bytes[p as usize * row_nbytes..(p as usize + 1) * row_nbytes], + "{} (N={} K={}): pair {p} (expert {}) differs from the same pair gathered alone", + layout.name, + s.n, + s.k, + layout.experts[p as usize] + ); + } + let close = allclose( + &astype(&all, dtype::FLOAT32), + &reference(&xr, layout, s), + 2e-2, + 2e-2, + ); + eval(&close); + assert!( + item_bool(&close), + "{} (N={} K={}): gather strays from the dequantized reference", + layout.name, + s.n, + s.k + ); +} + +#[test] +fn one_row_gather_matches_each_pair_gathered_alone() { + if !default_device_is_gpu() { + eprintln!("skipping: no GPU default device"); + return; + } + // Gemma 4 26B A4B gate/up (N = 704 is not a multiple of 128, so eight or + // more pairs took qmm_naive), and the same N at K = 704, which leaves a + // residue after the 512-wide k-steps. + for (n, k) in [(704, 2816), (704, 704)] { + let s = stack(n, k); + for layout in layouts() { + assert!( + layout.pairs() >= QMV_BELOW, + "{}: below eight pairs", + layout.name + ); + check_bitwise(&layout, &s); + } + } +} + +#[test] +fn below_eight_pairs_and_qmm_sm80_shapes_keep_their_kernels() { + if !default_device_is_gpu() { + eprintln!("skipping: no GPU default device"); + return; + } + // Below eight pairs the per-pair `gather_qmv` runs, so every pair keeps the + // single-pair bits: at Gemma 4 26B A4B gate/up (N = 704) and down + // (N = 2816). + for (n, k) in [(704, 2816), (2816, 704)] { + let s = stack(n, k); + for layout in small_layouts() { + assert!( + layout.pairs() < QMV_BELOW, + "{}: not below eight pairs", + layout.name + ); + check_bitwise(&layout, &s); + } + } + // Down: N = 2816 is a multiple of 128, so from eight pairs on the gather + // stays on qmm_sm80 and only the reference applies. + let s = stack(2816, 704); + for layout in layouts() { + let (x, rhs, rows) = inputs(&layout, s.k); + let all = reshape(&gather(&x, &rhs, &s, layout.sorted), &[layout.pairs(), s.n]); + let xr = x_rows(&x, &rows, s.k); + let close = allclose( + &astype(&all, dtype::FLOAT32), + &reference(&xr, &layout, &s), + 2e-2, + 2e-2, + ); + eval(&close); + assert!( + item_bool(&close), + "{} (N=2816 K=704): strays from the dequantized reference", + layout.name + ); + } +} + +#[test] +fn other_bit_widths_and_f32_one_row_gathers_match_each_pair_gathered_alone() { + if !default_device_is_gpu() { + eprintln!("skipping: no GPU default device"); + return; + } + // `qmm_sm80` takes only 4 and 8 bits with bf16/f16 activations, so every + // one-row gather of a 3-, 5- or 6-bit stack, and every f32 one, took + // qmm_naive from eight pairs on and now takes `gather_qmv` at any N. Pin + // those to the single-pair bits and the reference too: Qwen3-30B-A3B's + // gate/up (N = 768, a multiple of 128) and down (N = 2048) at 3 and 6 bits, + // 5 bits at gate/up, 8 bits at N = 704 (off qmm_sm80 by N), and 4-bit f32. + let cases: [(i32, i32, i32, i32); 6] = [ + (768, 2048, 3, dtype::BFLOAT16), + (2048, 768, 3, dtype::BFLOAT16), + (768, 2048, 5, dtype::BFLOAT16), + (2048, 768, 6, dtype::BFLOAT16), + (704, 2816, 8, dtype::BFLOAT16), + (768, 2048, 4, dtype::FLOAT32), + ]; + for (n, k, bits, dt) in cases { + let s = stack_with(n, k, bits, dt); + // The smallest gather that took qmm_naive, Gemma 4's 4-client decode, + // and a sorted 8-client one. + for layout in layouts() + .into_iter() + .filter(|l| l.pairs() == 8 || l.pairs() == 32 || (l.sorted && l.pairs() == 64)) + { + check_bitwise(&layout, &s); + } + } +} diff --git a/src/lib/mlxcel-core/src/lib.rs b/src/lib/mlxcel-core/src/lib.rs index 5be0d0652..c0de8c0f8 100644 --- a/src/lib/mlxcel-core/src/lib.rs +++ b/src/lib/mlxcel-core/src/lib.rs @@ -5246,6 +5246,14 @@ mod qmm_naive_tile_tests; #[path = "qmm_fold_batch_tests.rs"] mod qmm_fold_batch_tests; +// One-row affine MoE gathers on CUDA keep the per-pair `gather_qmv` from eight +// pairs on (#2784): every pair agrees bit for bit with the same pair gathered +// alone, sorted or not, and every gather stays within a dequantized reference. +// Needs a GPU default device; skips otherwise. +#[cfg(all(test, feature = "cuda"))] +#[path = "gather_qmm_one_row_tests.rs"] +mod gather_qmm_one_row_tests; + // The pre-first-token phase breakdown (#1545) reported by // `MLXCEL_PROFILE_TTFT`. The phases are timed around GPU work, but whether // they account for the reported prefill is pure arithmetic, so it is pinned diff --git a/src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/quantized/quantized.cpp b/src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/quantized/quantized.cpp index eb547761b..50dacb3ed 100644 --- a/src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/quantized/quantized.cpp +++ b/src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/quantized/quantized.cpp @@ -12,7 +12,9 @@ // dispatch in decode and MLX exposes no hook for it, so the one-shot trace has // to be emitted from the dispatch site itself; (5) fold a batch that shares // one 2D weight into rows in QuantizedMatmul so batched decode reads the -// weight once instead of once per batch entry (lablup/mlxcel#2690). +// weight once instead of once per batch entry (lablup/mlxcel#2690); (6) send +// affine one-row GatherQMM gathers (MoE decode) that would take qmm_naive to +// the per-pair gather_qmv instead (lablup/mlxcel#2784). // // Modified from upstream MLX 5a48f9cc2631804ea985c4289e34f0b1e4f66c60 mlx/backend/cuda/quantized/quantized.cpp // @@ -113,6 +115,17 @@ array flat_view(const array& src, int64_t b0, int64_t bc) { return v; } +// `MLXCEL_GATHER_QMM_ONE_ROW_QMV=0` keeps one-row affine GatherQMM gathers of +// eight or more pairs on qmm_naive (lablup/mlxcel#2784). Read once: this is on +// the decode path. +bool gather_qmm_one_row_qmv_enabled() { + static const bool enabled = []() { + const char* e = std::getenv("MLXCEL_GATHER_QMM_ONE_ROW_QMV"); + return !(e && e[0] == '0' && e[1] == '\0'); + }(); + return enabled; +} + // Invoke call_one(x, out) split into row chunks so grid.y stays <= 65535 and // each chunk's m*n stays < 2^31. Only the unbatched 2D path (the case that // overflows) is chunked; batched weights keep M small and pass through. @@ -683,8 +696,22 @@ void GatherQMM::eval_gpu(const std::vector& inputs, array& out) { return; } + // [mlxcel #2784] A gather whose pairs each have one row (MoE decode: + // [T, 1, 1, K] against [T, top_k] experts, or the same pairs flattened and + // sorted) is B one-row GEMMs, and qmm_naive spends a whole tile on each. + // `gather_qmv` reads the same expert weights, once per pair as qmm_naive + // does, and is the kernel a gather below eight pairs already takes, so every + // pair gets the bits it gets when gathered alone. On GB10 this raised + // Gemma 4 26B A4B 4-client decode by about a quarter (gate/up, N = 704). + // qmm_sm80 (N a multiple of 128) keeps its gathers. A kernel that grouped + // the pairs by expert to read each selected expert once was slower than + // this per-pair launch at 4 and 8 clients. See + // docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03.md. + const bool one_row_qmv = mode_ == QuantizationMode::Affine && M == 1 && + supports(supports_qmv) && gather_qmm_one_row_qmv_enabled(); + if (can_use_qmm_naive) { - if (prefer_qmv) { + if (prefer_qmv || one_row_qmv) { call_qmv(); } else { call_qmm_naive();