Skip to content

[Metal] Add affine qmv_mma for 3-16 rows - #4787

Merged
zcbenz merged 3 commits into
ml-explore:mainfrom
ahuzmeza:pr/affine-qmv-mma-main
Nov 2, 2026
Merged

zcbenz merged 3 commits into
ml-explore:mainfrom
ahuzmeza:pr/affine-qmv-mma-main

Conversation

@ahuzmeza

@ahuzmeza ahuzmeza commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

On GPUs without NAX, affine quantized_matmul with 3–16 rows never uses qmv_mma, because use_qmv_mma returns false for affine (quantized.cpp L645-647).
Those shapes (batched decode, speculative decoding) fall back to qmv/qmv_wide or to qmm, whose 32-row tiles are mostly padding at this size. #4712 added qmv_mma for the fp formats only. This is the non-NAX side of the picture.

This PR ports #4712's fp_qmv_mma to affine for non-NAX GPUs:

  • dequantizes as q·scale + bias, with biases as an extra input
  • dispatches at 3–16 rows on gen 13/14 and 4–16 on gen 15+, for N·K ≥ 2^21 (not on Ultra or NAX)
  • uses wk 4 on every generation and bn 32 below gen 15 at ≤ 8 rows
  • covers 4 and 8 bits at group sizes 32, 64 and 128; all other dispatch paths are unchanged

Results

End to end on an M2 Pro, mlx-community/gemma-4-e4b-it-4bit, mlx_lm.benchmark -p 512 -g 128 -b 8 -n 2:
batch-8 decode goes from 70.0 to 202.1 tok/s (2.89×). Batch 1 remains unchanged.

Speedup over main, chained Qwen3-4B decoder shapes, bf16, group size 64 (95% intervals in the details below):

Rows 3 4 5 6 7 8 10 12 16
M2 Pro, affine8 1.15 1.46 1.77 3.00 3.08 3.15 1.97 1.95 1.92
M2 Pro, affine4 1.16 1.50 1.84 3.27 3.34 3.41 2.07 2.05 2.02
M4, affine8 off 1.02 1.03 1.10 1.26 1.46 1.56 1.88 1.83
M4, affine4 off 1.12 1.34 1.58 1.84 2.21 1.52 1.82 1.93

mxfp8 is the control and measures 1.00 throughout.

Part of the 6–8-row gain on the M2 Pro comes from main's own dispatch. On gen 13/14, main's batch limit sends the MLP projections to qmm, which is slower there than main's qmv. Measured against main with that limit raised, the gain at 6–8 rows is 2.09–2.84×, and batch-8 decode goes from 81.5 to 201.0 tok/s (2.47×).

Overlap with #4781

Both PRs use the same plumbing change. I'm happy to rebase onto #4781 if it lands first.

Measured on the M2 Pro (gen 14) and the M4 (gen 16).
Unmeasured: M1 (gen 13), M3 (gen 15) and A-series phones, enabled by generation.
Non-affine and NAX dispatches are unchanged.

95% intervals

M2 Pro (16-core), main VS. this branch, speedup [95% interval]

Rows 3 4 5 6 7 8 10 12 16
affine8 1.15
[1.14, 1.15]
1.46
[1.43, 1.46]
1.77
[1.74, 1.79]
3.00
[2.88, 3.00]
3.08
[3.05, 3.09]
3.15
[3.14, 3.15]
1.97
[1.96, 1.97]
1.95
[1.91, 1.96]
1.92
[1.88, 1.95]
affine4 1.16
[1.15, 1.18]
1.50
[1.50, 1.51]
1.84
[1.84, 1.86]
3.27
[3.27, 3.28]
3.34
[3.34, 3.34]
3.41
[3.41, 3.43]
2.07
[2.07, 2.08]
2.05
[2.05, 2.06]
2.02
[2.02, 2.02]
mxfp8 (control) 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00

M4 (10-core), same

Rows 3 4 5 6 7 8 10 12 16
affine8 1.00 (off) 1.02
[1.02, 1.03]
1.03
[1.03, 1.03]
1.10
[1.07, 1.11]
1.26
[1.23, 1.27]
1.46
[1.42, 1.47]
1.56
[1.56, 1.60]
1.88
[1.87, 1.89]
1.83
[1.82, 1.83]
affine4 1.00 (off) 1.12
[1.10, 1.13]
1.34
[1.33, 1.36]
1.58
[1.55, 1.60]
1.84
[1.81, 1.86]
2.21
[2.16, 2.22]
1.52
[1.52, 1.55]
1.82
[1.82, 1.85]
1.93
[1.92, 1.93]
mxfp8 (control) 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00
Method

Chained decoder forward pass on Qwen3-4B shapes, bf16, group size 64. 10 rounds per build in separate processes, alternating. (ratio of medians with a 95% bootstrap interval). mxfp8 is the control. Details are in the script below.

Benchmark script (to reproduce)

Install main and this branch in two venvs, then:

python affine_small_m_bench.py --base <main venv>/bin/python --other <branch venv>/bin/python
"""Chained-forward benchmark for quantized_matmul at few rows, comparing two MLX builds.

One forward = LAYERS decoder-shaped blocks (q/k/v/o, gate/up/down, rms_norm between), each layer's output
feeding the next, so the GPU cannot overlap one layer with the next (as in decode; see mlx #4265). Weights
cycle over 8 distinct layer sets so reads come from DRAM. The non-matmul ops are the same in every mode,
so differences between builds are matmul differences; mxfp8 serves as the control.

The two builds run as separate processes, alternating, for --rounds rounds. The figure per row count is
base/other as the ratio of the medians over rounds, with a 95% bootstrap interval (whole rounds resampled).

usage: python affine_small_m_bench.py --base <main venv>/bin/python --other <port venv>/bin/python
       [--rounds 10] [--rows 1,2,3,4,5,6,7,8,10,12,16] [--modes affine8,affine4,mxfp8] [--shape qwen3-4b]
"""
import argparse
import json
import os
import random
import statistics
import subprocess
import sys
import time

# (hidden, q_out, kv_out, intermediate, layers)
SHAPES = {"qwen3-4b": (2560, 4096, 1024, 9728, 36), "2b-class": (2048, 2048, 1024, 6144, 28)}
MODES = {"affine8": dict(group_size=64, bits=8, mode="affine"), "affine4": dict(group_size=64, bits=4, mode="affine"),
         "mxfp8": dict(mode="mxfp8"), "mxfp4": dict(mode="mxfp4")}
SETS, WARM, REPS = 8, 3, 15


def child(shape_name, modes, rows):
    import mlx.core as mx

    d, qo, kvo, inter, layers = SHAPES[shape_name]
    dims = {"q": (qo, d), "k": (kvo, d), "v": (kvo, d), "o": (d, qo), "g": (inter, d), "u": (inter, d),
            "dn": (d, inter)}

    def qweight(n, k, kw):
        w = (mx.random.normal((n, k)) / (k**0.5)).astype(mx.bfloat16)
        q = mx.quantize(w, **kw)
        b = q[2] if kw["mode"] == "affine" else None
        mx.eval(*[a for a in (q[0], q[1], b) if a is not None])
        return q[0], q[1], b

    def qmm(x, w, kw):
        return mx.quantized_matmul(x, w[0], w[1], w[2], transpose=True, **kw)

    def forward(h, sets, kw, norm_w):
        for li in range(layers):
            L = sets[li % SETS]
            x = mx.fast.rms_norm(h, norm_w, 1e-6)
            q, k, v = qmm(x, L["q"], kw), qmm(x, L["k"], kw), qmm(x, L["v"], kw)
            h = h + qmm(q + (k[:, :1] + v[:, :1]), L["o"], kw)  # k/v feed the chain, as attention would
            x = mx.fast.rms_norm(h, norm_w, 1e-6)
            g = qmm(x, L["g"], kw)
            h = h + qmm(g * mx.sigmoid(g) * qmm(x, L["u"], kw), L["dn"], kw)
        return h

    res = {"mlx": mx.__version__, "arch": mx.device_info().get("architecture"), "ms": {}}
    norm_w = mx.ones((d,), dtype=mx.bfloat16)
    for mode in modes:
        kw = MODES[mode]
        sets = [{name: qweight(n, k, kw) for name, (n, k) in dims.items()} for _ in range(SETS)]
        for M in rows:
            h0 = mx.random.normal((M, d)).astype(mx.bfloat16)
            mx.eval(h0, norm_w)
            for _ in range(WARM):
                mx.eval(forward(h0, sets, kw, norm_w))
            ts = []
            for _ in range(REPS):
                t = time.perf_counter()
                mx.eval(forward(h0, sets, kw, norm_w))
                ts.append((time.perf_counter() - t) * 1000)
            res["ms"][f"{mode}|{M}"] = statistics.median(ts)
        del sets
        mx.clear_cache()
    print(json.dumps(res))


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--base", required=True, help="python of the reference build (main)")
    p.add_argument("--other", required=True, help="python of the build under test")
    p.add_argument("--rounds", type=int, default=10)
    p.add_argument("--rows", default="1,2,3,4,5,6,7,8,10,12,16")
    p.add_argument("--modes", default="affine8,affine4,mxfp8")
    p.add_argument("--shape", default="qwen3-4b", choices=SHAPES)
    a = p.parse_args()
    cmd = [os.path.abspath(__file__), "--child", a.shape, a.modes, a.rows]
    runs = {"base": [], "other": []}
    for r in range(a.rounds):
        for arm in (("base", "other") if r % 2 == 0 else ("other", "base")):
            py = a.base if arm == "base" else a.other
            out = subprocess.run([py, *cmd], check=True, capture_output=True, text=True).stdout
            res = json.loads(out.strip().splitlines()[-1])
            runs[arm].append(res["ms"])
            print(f"round {r + 1}, {arm}: mlx {res['mlx']} {res['arch']}", file=sys.stderr, flush=True)
    rng = random.Random(0)
    n = a.rounds
    for mode in a.modes.split(","):
        print(f"[{a.shape}] {mode}   base ms  other ms   base/other  95% CI")
        for M in a.rows.split(","):
            k = f"{mode}|{M}"
            b = [x[k] for x in runs["base"]]
            o = [x[k] for x in runs["other"]]
            boot = []
            for _ in range(10000):
                pick = [rng.randrange(n) for _ in range(n)]
                boot.append(statistics.median(b[i] for i in pick) / statistics.median(o[i] for i in pick))
            boot.sort()
            ratio = statistics.median(b) / statistics.median(o)
            print(f"  M={M:>2}  {statistics.median(b):8.1f}  {statistics.median(o):8.1f}   {ratio:6.2f}x"
                  f"   [{boot[249]:.2f}, {boot[9749]:.2f}]")


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--child":
        child(sys.argv[2], sys.argv[3].split(","), [int(m) for m in sys.argv[4].split(",")])
    else:
        main()
  • ☑️ I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: Claude Code wrote the kernel, its dispatch, the tests and the benchmark script, investigated the dispatch paths and prior work, and ran the measurements, all under my direction

@ahuzmeza
ahuzmeza marked this pull request as ready for review October 29, 2026 00:09
@zcbenz

zcbenz commented Nov 1, 2026

Copy link
Copy Markdown
Member

This basically looks good to me, thanks for taking care of adding the kernel. Can you please rebase since now #4781 has been merged?

@ahuzmeza
ahuzmeza force-pushed the pr/affine-qmv-mma-main branch from 8f3f1c2 to a227bc1 Compare November 2, 2026 12:22
@ahuzmeza

ahuzmeza commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks! its been rebased

@zcbenz
zcbenz force-pushed the pr/affine-qmv-mma-main branch 2 times, most recently from 26ef220 to 1d8894a Compare November 2, 2026 21:33
@ahuzmeza

ahuzmeza commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the cleanup! I over-guarded the dispatch.

One question: the affine test always uses 19 rows, so the new kernel never runs. Intentional, or should it be x[:M]?

@zcbenz

zcbenz commented Nov 2, 2026

Copy link
Copy Markdown
Member

Thanks for checking! Yeah it should be x[:M].

@zcbenz
zcbenz force-pushed the pr/affine-qmv-mma-main branch from 1d8894a to 125e62c Compare November 2, 2026 22:04
@zcbenz
zcbenz merged commit ba8c005 into ml-explore:main Nov 2, 2026
47 of 48 checks passed
Augustas11 added a commit to Augustas11/mlx that referenced this pull request Nov 7, 2026
Port the affine qmv_mma kernel from ml-explore#4787 for non-NAX GPUs
without its row-count gate. Upstream sends 3..16 rows (4..16 on gen 15+)
to qmv_mma and fewer rows to qmv, so a row's bits would change with the
number of rows sharing the call. Each qmv_mma output sums K in an order
set only by the fixed simdgroup split (wk 4), the 128-wide K step and the
8x8 MMA; rows never read one another, and the row tile (tm) and column
tile (bn) only choose the threadgroup's coverage.

So the route reads the weight shape, type and device, never M: when the
shape qualifies, every row count from 1 up to the qmm route (at least 16)
takes qmv_mma, and grid y tiles rows 16 at a time above 16. Unaligned or
non-contiguous x is copied instead of falling back to qmv. Ultra is kept
on qmv_mma (upstream keeps it on qmv) so the lab window can measure it;
the exclusion depends only on the device, so restoring it stays
batch-invariant. qmm_splitk and qmv_wide stay off.

test_qmm_small_m_batch_invariant checks that rows of 2, 3, 4, 8 and 16-row
products equal the 1-row results bit for bit, for 4 and 8 bits at group
sizes 32 and 64.

The C++ test "test gpu small-M quantized matmul batch invariance" checks
the same for [M, K], [M, 1, K] and strided (non-contiguous) rows at group
sizes 32, 64 and 128 in float16, bfloat16 and float32.
jonathan308 added a commit to Layr-Labs/mlx that referenced this pull request Nov 9, 2026
On Ultra GPUs a 4-bit affine x @ w.T with 6 to 16 rows ran qmv_wide below
the vector limit and split-K qmm from it. These leave most cores idle or
read the weights more than once. Upstream's affine qmv_mma
(ml-explore#4787) keeps Ultra GPUs on the vector kernels.

affine_qmv_tile reads each weight once. 8 simdgroups compute 128 outputs
with float simdgroup MMAs from rows in threadgroup memory, and K is split
until about 240 threadgroups run. Up to 8 rows it applies the scale and
bias of each group once; 9 to 16 rows dequantize each weight.

MLX_QMV_TILE selects the route. The default uses it on Ultra GPUs from
gen 15, 1 uses it on each GPU without neural accelerators, and 0 turns it
off.

On an M3 Ultra in a Qwen3.8 27B (4-bit, bfloat16), an 8-token pass takes
57.0 ms instead of 84.4 ms, 12 to 16 tokens 91.8-94.4 ms instead of
135.3-136.1 ms, and a decode step of 16 streams 99.2 ms instead of
145.2 ms.

Co-Authored-By: Claude <[email protected]>
jeethu added a commit to numen-tech/mlx-swift that referenced this pull request Nov 17, 2026
…-explore/mlx#4787) behind MLX_QMV_MMA=1, off by default; tile-8 switch dropped; GPUFamilyRoute.qmvMMAVersion / qmvMMAEnvironmentKey and a route test (numen-tech/gemma4-qat#1701)
jeethu added a commit to numen-tech/mlx that referenced this pull request Nov 17, 2026
Carry ml-explore#4787 affine qmv_mma behind MLX_QMV_MMA=1, off by default (numen-tech/gemma4-qat#1701)
jeethu added a commit to numen-tech/mlx-swift that referenced this pull request Nov 17, 2026
Carry affine qmv_mma (ml-explore/mlx#4787) behind MLX_QMV_MMA=1, off by default (numen-tech/gemma4-qat#1701)
Lyxot added a commit to Lyxot/unsloth-zoo that referenced this pull request Nov 26, 2026
Pin `mlx==0.32.5` exactly. Code that served only 0.32.4 is now dead: re-pin it, or delete it where 0.32.5 fixes the bug upstream.

- Version-pinned mirrors of stock dispatch that is unchanged in 0.32.5 move from `"0.32.4"` to `"0.32.5"`, and their bitwise tests are re-gated.
- NAX small-row quantized matmul gap closed: 0.32.5's qmv_nax and split-K qmm_nax (ml-explore/mlx#4712, #4781) beat the route on an M5 Pro. int8 prefill and sorted gather keep the shared scope.
- Without NAX, the SIMD small-row route keeps only rows 17-24. Up to 16 rows, stock qmv_mma (ml-explore/mlx#4787) is faster.
- Remove workarounds that 0.32.5 fixes upstream:
  - the row-contiguous copy before cross-entropy (ml-explore/mlx#4702);
  - M1/M2 SDPA thread-limit routing (ml-explore/mlx#4708, #4719);
  - `toks_f + 0` in place of `stop_gradient` (ml-explore/mlx#4880).
- mlx now reads `MLX_ENABLE_TF32`, `MLX_SDPA_BLOCKS` and `MLX_SDPA_D512_MIN_KL` through `mx.config`, which caches the first read. Zoo's mirrors now read them the same way, with mlx's defaults, and tests use `mx.config.scoped_update`.
- 0.32.5's deeper stock `gelu_approx` exposes an `mx.compile(shapeless=True)` bug. A cache entry first traced inside a gradient, on inputs it does not track, later returns a stale batch shape. Zoo's installed `gelu_approx` keeps the plain formula for non-fp16 dtypes, and every trainer now installs it, not only `from_pretrained`.
- The native sliding-window route goes live on 0.32.5. Re-pin its fingerprint of the Gemma 4 compile patch's mask builder, which changed when that patch gained padding-free support.
Lyxot added a commit to Lyxot/unsloth-zoo that referenced this pull request Nov 26, 2026
Pin `mlx==0.32.5` exactly. Code that served only 0.32.4 is now dead: re-pin it, or delete it where 0.32.5 fixes the bug upstream.

- Version-pinned mirrors of stock dispatch that is unchanged in 0.32.5 move from `"0.32.4"` to `"0.32.5"`, and their bitwise tests are re-gated.
- NAX small-row quantized matmul gap closed: 0.32.5's qmv_nax and split-K qmm_nax (ml-explore/mlx#4712, #4781) beat the route on an M5 Pro. int8 prefill and sorted gather keep the shared scope.
- Without NAX, the SIMD small-row route keeps only rows 17-24. Up to 16 rows, stock qmv_mma (ml-explore/mlx#4787) is faster.
- Remove workarounds that 0.32.5 fixes upstream:
  - the row-contiguous copy before cross-entropy (ml-explore/mlx#4702);
  - M1/M2 SDPA thread-limit routing (ml-explore/mlx#4708, #4719);
  - `toks_f + 0` in place of `stop_gradient` (ml-explore/mlx#4880).
- mlx now reads `MLX_ENABLE_TF32`, `MLX_SDPA_BLOCKS` and `MLX_SDPA_D512_MIN_KL` through `mx.config`, which caches the first read. Zoo's mirrors now read them the same way, with mlx's defaults, and tests use `mx.config.scoped_update`.
- 0.32.5's deeper stock `gelu_approx` exposes an `mx.compile(shapeless=True)` bug. A cache entry first traced inside a gradient, on inputs it does not track, later returns a stale batch shape. Zoo's installed `gelu_approx` keeps the plain formula for non-fp16 dtypes, and every trainer now installs it, not only `from_pretrained`.
- The native sliding-window route goes live on 0.32.5. Re-pin its fingerprint of the Gemma 4 compile patch's mask builder, which changed when that patch gained padding-free support.
rcfa pushed a commit to cubiculum-ai/mlx that referenced this pull request Nov 26, 2026
Co-authored-by: Cheng <[email protected]>
osaurus-ai/mlx does not have the affine qmv_nax kernels (ml-explore#4781), so affine stays off this path on
NAX GPUs. Affine qmv_mma also needs scales and biases of the input type: the fork's mixed
bf16/f16 metadata path stays on qmv. The instantiations follow this fork's kernel names.
(cherry picked from commit ba8c005)
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Nov 27, 2026
## Summary

Pins `mlx==0.32.5` and brings every zoo route that mirrors or competes
with mlx dispatch in line with it. Workarounds that 0.32.5 fixes
upstream are removed, routes that 0.32.5 makes unreachable or slower are
deleted, and two routing choices made for the pin that cost speed end to
end are corrected.

On an M5 Pro, batched decode is 1.2-2.4x faster at 4-24 rows, short
prefill is 1.1-1.9x faster, and long Gemma 4 prefill is 1.07-1.12x
faster than main on mlx 0.32.4. On an M3 Max, Gemma 4 prefill is
1.03-1.08x faster and batched decode at 8-16 rows 1.06-1.16x.
Single-stream decode and LoRA training step time are unchanged on both.

## Changes

1. **`chore(mlx): pin mlx 0.32.5`**
- Version-pinned mirrors of stock dispatch that is unchanged in 0.32.5
move to `"0.32.5"`, and their bitwise tests are re-gated.
   - Removes workarounds 0.32.5 fixes upstream:
- the row-contiguous copy before cross-entropy (ml-explore/mlx#4702);
     - M1/M2 SDPA thread-limit routing (ml-explore/mlx#4708, #4719);
     - `toks_f + 0` (ml-explore/mlx#4880).
- mlx now reads `MLX_ENABLE_TF32`, `MLX_SDPA_BLOCKS` and
`MLX_SDPA_D512_MIN_KL` through `mx.config`, which caches the first read.
Zoo reads them the same way, and tests use `mx.config.scoped_update`.
- 0.32.5's deeper stock `gelu_approx` (ml-explore/mlx#4906) exposes an
`mx.compile(shapeless=True)` bug: a cache entry first traced inside a
gradient later returns a stale batch shape. Zoo's installed
`gelu_approx` keeps the plain formula for non-fp16 dtypes, and every
trainer installs it.
- The native sliding-window route goes live on 0.32.5. Its fingerprint
of the Gemma 4 compile patch's mask builder is re-pinned.
   - Two Metal tests re-baselined for 0.32.5:
- The KV-shared checkpoint peak bound goes from 1.25x to 1.3x the
unshared peak. On 0.32.5 the unshared stack's peak falls more than the
shared one, so a correctly tied stack reads 1.20-1.28 depending on chip.
With the tie removed it read 1.68 on 0.32.4.
- The VLM stream test with a short arrival during a long prefill keeps
the short row bitwise. The long row keeps its first token exact, and its
logprob must be within 0.125. The arrival splits the long prefill into
different chunk sizes, and stock bf16 matmul is not row-count invariant
on either mlx version. The bitwise result flipped between M1 and M3 with
each mlx release, whichever zoo revision ran.
2. **`perf(mlx): mirror mlx 0.32.5's attention fusion rules`**:
`fused_kernel_exists` follows 0.32.5's `has_fused_kernel` /
`use_fallback`:
   - `sdpa_split` for 33-128 stacked query rows (ml-explore/mlx#4723);
   - NAX head dim 256 from 512 queries (ml-explore/mlx#4893);
   - head dim 512 under array masks;
- array masks whose leading axes the fused kernel would read differently
from the runtime are refused.
3. **`refactor(mlx): drop the NAX staged quantized matmul route`**:
0.32.5 runs staged NAX weight loads in stock `qmm_t`
(ml-explore/mlx#4682), so zoo's copy is unreachable under the pin. The
training qmm chooser over the one remaining dense route becomes
`dense_train_qmm_available()` / `call_dense_train_qmm()`.
4. **`refactor(mlx): drop the NAX small-row quantized matmul kernel`**:
off since the pin closed its gap. Stock 0.32.5's qmv_nax and split-K
qmm_nax (ml-explore/mlx#4712, #4781) are faster than the kernel in most
cells. The NAX scope keeps int8 prefill, sorted gather and dense
prefill.
5. **`perf(mlx): recover small-batch decode and NAX prefill on mlx
0.32.5`**: fixes two losses that came from re-pinning in (1). Each was
isolated by running the zoo revision before the pin and this branch,
both on mlx 0.32.5.
- **SIMD small-row route.** It had been narrowed to rows 17-24 from
per-op timings, which cost about 8% at 3-4 rows end to end on an M3 Max.
Now:
     - rows back to 3-24;
- a 3-4 row entry for 4-bit heads of at least 2^24 weights at any width;
- a `SIMD_QMM_STOCK_ROWS = (5, 16)` band where stock qmv_mma
(ml-explore/mlx#4787) wins and the call stays native.
- **Dense prefill.** Re-pinned to 0.32.5, it went live on NAX GPUs,
where stock's staged `qmm_t_nax` beats dequantize-once (-6-7% long
prefill on an M5 Pro). It now stays off where stock runs its NAX
kernels.

## Performance

End-to-end through the Unsloth Studio in-process backend: main (mlx
0.32.4) vs this branch with the matching Unsloth Studio change (mlx
0.32.5). Numbers are new/base, two interleaved rounds per case, one
`--stable` scheduler slot per case; 4-bit MLX checkpoints unless noted.

| case | M3 Max | M5 Pro |
|---|---|---|
| batched decode Qwen3-4B, 4 / 8 / 16 / 24 rows | 1.02 / 1.06 / 1.07 /
1.02 | 1.20 / 1.39 / 1.55 / 1.82 |
| batched decode Llama 3.2 3B, 4 / 8 / 16 / 24 rows | 1.01 / 1.08 / 1.16
/ 1.07 | 1.21 / 1.42 / 1.51 / 2.44 |
| batched decode Qwen3.6-35B-A3B, 8 / 16 rows | 0.94 (CI to 1.05) / 1.00
| 1.05 / 1.10 |
| short prefill Llama 3.2 3B, 32 / 64 / 512 tokens | 0.99 / 0.98 / 1.02
| 1.92 / 1.89 / 1.09 |
| Gemma 4 E4B prefill, 2k / 8k / 16k | 1.07 / 1.08 / 1.08 | 1.11 / 1.12
/ 1.11 |
| Gemma 4 12B (8-bit) prefill, 2k / 8k | 1.03 / 1.05 | 1.07 / 1.08 |
| Gemma 4 E4B speculative decode, 128 / 2k context | 1.44 / 1.36 | 1.40
/ 1.34 |
| single-stream decode, all models | 0.99-1.01 | 1.00 |
| LoRA training step (Qwen3-4B, Llama 3.2 3B, Qwen3.5 2B, Gemma 4 E2B) |
0.99-1.00 | 0.97-1.01 |

The two zoo-caused losses, before and after (5):

| case | before | after |
|---|---|---|
| M3 Max batched decode at 3-4 rows, Qwen3-4B | 0.93 | 1.035 |
| M3 Max batched decode at 3-4 rows, Llama 3.2 3B | 0.93 | 1.027 |
| M5 Pro prefill, 2k-8k | 0.93-0.94 | 1.00 |

Known losses that are not from zoo; each shows the same with main's zoo
running on mlx 0.32.5:

- Qwen3.6-35B-A3B single-stream decode at 128 tokens on an M5 Pro: 0.95.
- Qwen3.6-35B-A3B speculative decode: noisy, 0.69-1.08 across runs, on
both chips.
- Qwen3.8-27B at 8k tokens on an M3 Max: about 0.95. Isolated over three
interleaved rounds:
  - main's zoo on 0.32.4: 21.7 tok/s decode, 227 tok/s prefill;
  - main's zoo on 0.32.5: 21.3 / 206;
  - this branch on 0.32.5: 21.1 / 220.

So this branch is neutral on decode and +7% on prefill against the same
mlx. The rest comes from mlx and thermal drift within the run.

## Risks

- The removed M1/M2 workaround is upstream-fixed. The gating M1 CI leg
runs the Metal suites without it and passes, but it has not been
benchmarked on M1/M2.
- fp16 `gelu_approx` stays exposed to the shapeless-compile bug: no fp16
body tried satisfies both the stale-shape check and
ml-explore/mlx#4906's finite-gradient contract. This exposure predates
the bump.
- The SIMD row band is measured on an M3 Max and used for every non-NAX
GPU.

## Validation

Targeted Metal suites on an M3 Max and an M5 Pro, mlx 0.32.5:

```bash
python -m pytest -q tests/test_mlx_nax_metal.py tests/test_mlx_generate_metal.py tests/test_mlx_decode_metal.py tests/test_mlx_moe_metal.py tests/test_mlx_attention_metal.py tests/test_mlx_training_e2e_metal.py
```

- M3 Max: 1573 passed. Failures, none from this change:
  - 7 FastVLM tests whose remote processor code needs `timm`;
- 2
`test_verify_moe_qwen4_takes_fast_verify_blocks_unless_lanes_hold_them`
cases, which fail on main as well;
  - 8 training e2e tests whose models were not in the offline cache.
- M5 Pro: 926 passed. The only failures are the 7 `timm` FastVLM tests.
- New and changed tests were mutation-checked: reverting each production
change fails its test.
- The bf16-vs-fp32 gradient error is equal on main and on this branch.
- The gating M1 CI leg (`MLX install + import smoke (Apple Silicon,
pinned)`) passes on this head.

Pairs with the Unsloth Studio change that pins mlx 0.32.5.

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants