Skip to content

Quantized matmul: opt-in mode where a batched row matches M=1 #4819

Open

Description

@Augustas11
  • I understand it is strictly prohibited to use AI to write issues.

AI usage disclosure: drafted with AI assistance from measurements we already had. The line numbers below are from current main.

Could quantized matmul grow an opt-in mode where a row inside a batch matches that same row run at M=1?

The Metal dispatch picks the kernel from M.

  • use_qmv_wide (mlx/backend/metal/quantized.cpp, around line 543) runs when M is at least 2. M=1 stays on qmv.
  • QuantizedMatmul::eval_gpu compares M with get_qmv_batch_limit (around line 2183) and sends larger M through qmv_mma, qmm_splitk_nax, or qmm_splitk.
  • qmm_nax_k_partitions (around line 1290) sets the split count from M, because the tile count is ceildiv(M, 64).

A different kernel is a different reduction order, so the result changes with the batch.

What we measured: 16 unequal rows in one forward, against the same rows run alone, flipped 30 to 38 of 256 greedy tokens. That was Qwen3-30B-A3B and a 27B. Grouped short prefill had 12 of 126 rows differ.

oMLX carries a hand patch for the row-exact route: omlx/patches/row_exact_qmv.py. vLLM documents the same property as a feature, docs/features/batch_invariance.md, behind VLLM_BATCH_INVARIANT.

The change we run locally turns qmv_wide and split-K off for every call. That costs throughput, so it has to be a flag. Making it the default would slow the fast path for everyone.

Augustas from Malibu

Activity

  1. YohannSidot commented on Nov 12, 2026

    @YohannSidot

    I could reproduce this at the op level on a base M5 (MLX 0.32.4, 4-bit affine, group size 64) and looked at what an opt-in invariant path costs. Three things that may help.

    1. Reproduction. On six weight shapes I chose (K × N from 2048 × 2048 to 5120 × 17408), with M from 1 to 128, rows of mx.quantized_matmul start to differ from the same row computed alone at M = 2 in fp16, and at M = 2 to 4 in bf16 depending on the shape. Below a shape-dependent M only a few elements per row change; from M = 16 to 64, depending on the shape, about 40% of the elements differ. In fp16 almost every row is affected; in bf16 only some rows are on the smaller shapes and small batches. Largest difference relative to the largest output value: up to 8e-4 in fp16 and 5e-3 in bf16. This matches the dispatch you describe: what changes the result is the kernel chosen for a given M, not where the row sits in the batch.

    2. A workaround with no new kernel. Cutting the batch into blocks of a fixed size and zero-padding the last block appears to make MLX dispatch the same kernel whatever M is (x is 2-D here; reshape (B, L, K) inputs to (B·L, K) first):

    def qmm_fixed_block(x, w, scales, biases, P=16):
        M, K = x.shape
        Mp = -(-M // P) * P
        xp = mx.concatenate([x, mx.zeros((Mp - M, K), x.dtype)], 0) if Mp > M else x
        out = [mx.quantized_matmul(xp[i:i + P], w, scales, biases, transpose=True, group_size=64, bits=4) for i in range(0, Mp, P)]
        return mx.concatenate(out, 0)[:M]

    In my tests a row then gives the same bits whatever batch it is in: 0 mismatching rows out of 212 per case, in fp16 and bf16, for P = 2, 8, 16 and 32 (four weight shapes, also P = 64). It has a cost: every call computes at least P rows, so a single row is noticeably slower than with plain mx.quantized_matmul. This is an observation on MLX 0.32.4 and one M5, not a documented guarantee, and a single row must also go through this function to match.

    3. A dedicated kernel. A Metal kernel built for this constraint gives 0 bit differences over 4,024 batched rows compared with the same rows alone (8 cases, 18 batch sizes from 1 to 128), and passes 27 accuracy cases (22 against a float64 reference, 5 against mx.quantized_matmul). Over 8 shapes (M from 1 to 32, seven in bf16, one in fp16), 30 interleaved rounds, it runs at 1.21x (0.75 to 1.63) of the fastest invariant MLX composition at each shape, and 1.10x (0.75 to 1.63) of plain mx.quantized_matmul (ratio of medians). It is slower than the best invariant composition at M = 1 (0.75x) and at M = 16 on the 4096 × 14336 shape, and slower than plain mx.quantized_matmul on 4 of the 8 shapes. It uses simdgroup matrices, not Metal 4 tensor operations.

    Limits: invariance is tested, not proven. One machine, a base M5, shapes chosen by me, nothing tried on M1 to M4 or on Max and Ultra chips. 4-bit, group size 64 only. gather_qmm is not covered. No end-to-end run: I did not reproduce the 30 to 38 changed tokens out of 256 on a model. At M = 1 the kernel's result is not bit-identical to mx.quantized_matmul; the invariance holds within the kernel. The invariant compositions it is compared with were written for this test.

    For transparency: the kernel was written by Claude Opus 5.5 in an automated loop I run, and the harness, the checker and the reference compositions around it were also written by Claude, in sessions I directed. The checker compares batched rows with single rows bit for bit, and it rejected mx.quantized_matmul itself and three deliberately non-invariant kernels, two of which passed every numerical check.

    I can share the kernel and the invariance test script (MLX and NumPy only) if that is useful. And if your real case is the MoE path (gather_qmm), which I have not covered, the shapes would be enough for me to look at it.

  2. Augustas11 commented on Nov 13, 2026

    @Augustas11
    ContributorAuthor

    Thanks. Yes, I would like the kernel and the invariance test script.

    Edit: I first asked here whether the kernel could cover gather_qmm. I then checked it, and at decode it is already invariant, so that question is gone.

    The MoE path is my real case (SwitchGLU / SwitchLinear). During decode: one new token per row, B rows, k experts picked per row, bfloat16 input. Typical B is 1 to 16, so 4 to 64 pairs per call on gpt-oss and 8 to 128 on GLM and Qwen. Gate and up: input [B,1,1,1,K], indices [B,1,k]. Down: input [B,1,k,1,N], same indices. From 64 pairs up mlx-lm sorts the pairs by expert before the call.

    4-bit affine, group 64. Weight shape is (experts, output, input).

    Model Experts Picked gate / up down
    GLM-5.3-Flash (Jundot/GLM-5.3-Flash-oQ4e-mtp) 288 8 (288, 2048, 4096) (288, 4096, 2048)
    GLM-4.5-Air (mlx-community/GLM-4.5-Air-4bit) 128 8 (128, 1408, 4096) (128, 4096, 1408)
    gpt-oss-120b (mlx-community/gpt-oss-120b-4bit) 128 4 (128, 2880, 2880) (128, 2880, 2880)
    Qwen3.6-35B-A3B (mlx-community/Qwen3.6-35B-A3B-MTP-4bit) 256 8 (256, 512, 2048) (256, 2048, 512)

    What I measured on gather_qmm: base M5, MLX 0.32.4, bf16, the gpt-oss, GLM-4.5-Air and Qwen shapes above, 2 to 16 rows per call, unsorted and sorted the way mlx-lm does it, against the same row alone. Every case gave 0 differing values. Each (row, expert) pair is its own single-row product, so the batch size does not change the kernel. The variance in these models at decode most likely comes from the plain quantized_matmul layers (attention projections, shared experts, router, lm_head), which your kernel already covers.

    I have not run your function. With a block of 16 it looks too expensive for me at one row: on an M3 Ultra with stock MLX a 16-row decode step takes 4.2 to 4.5 times a 1-row step (Llama-3.1-8B and a 30B MoE, both 4-bit, two runs each). That is the whole step with 16 real rows, so it is an upper bound for padding only the matmuls, and the M3 Ultra is a bad case for these row counts.

    Related work you should know about: Ronald Mannak is working on the same problem in ronaldmannak#6 and ronaldmannak#7. PR 7 adds an exact mode for quantized matmul that matches the stock single-row output, and it names this issue, so it is worth comparing with your kernel. He also found a separate source of batch variance in the attention kernel (ml-explore/mlx-swift-lm#221). That finding is his, so I leave the details to him.

    Two things from my side:

    1. Once you share the kernel I can run it on an M3 Ultra, which has no NAX path.
    2. Is the 0.75x at one row also against plain quantized_matmul, and on which of your eight shapes?

    Augustas from Malibu

  3. YohannSidot commented on Nov 13, 2026

    @YohannSidot

    @Augustas11 I sent both by e-mail this morning to [email protected] (the contact address on your site). The subject starts with "For Augustas: kernels and test scripts for #4819", and there is one zip attached. It also contains a second kernel written for your decode case, 1 to 16 rows. If another address is better, tell me here.

  4. Augustas11 commented on Nov 13, 2026

    @Augustas11
    ContributorAuthor

    Received, thanks, will report numbers!

  5. Augustas11 commented on Nov 17, 2026

    @Augustas11
    ContributorAuthor

    Numbers, as promised. I ran rows_exact, your second kernel, with your own script on a base M5 and an M3 Ultra, MLX 0.32.4, macOS 27.0.1, on its 18 sizes: 15 layer shapes ("layers" below) and three lm_heads, from GLM-4.5-Air, gpt-oss-120b and Qwen3.6-35B-A3B. I did not run invariant_v1. Your README answers my 0.75x question, thanks.

    Check. Each batched row against stock MLX's one-row result, at 2, 4, 8 and 16 rows, bf16 and f16: 10,800 of 10,800 rows bitwise equal on both machines. Plain quantized_matmul gets 3,731 of 5,400 in bf16 and 2,912 of 5,400 in f16, the same on both machines and the same as in your own run.

    Speed. bf16, 30 rounds, 2 to 16 rows, geometric mean with the range. Above 1 means your kernel is faster.

    Your kernel compared with M5 layers M5 lm_head M3 Ultra layers M3 Ultra lm_head
    M one-row calls 1.65x (1.07-4.05) 1.72x (1.34-2.17) 1.05x (0.69-2.54) 1.50x (1.38-1.73)
    plain batched quantized_matmul (not invariant) 0.90x (0.39-1.05) 0.65x (0.25-0.92) 0.83x (0.57-1.07) 0.69x (0.50-0.88)
    fastest invariant composition 1.05x (0.39-1.65) 0.71x (0.25-1.55) 0.86x (0.56-1.12) 0.95x (0.50-1.69)

    Two notes. On the M3 Ultra layer shapes it is slower than one-row calls at 2 and 4 rows (0.97x, 0.92x) and faster at 8 and 16 (1.07x, 1.26x). And treat my M5 columns as indicative only: every arm, MLX's own included, ran about 2x slower than in your M5 run, on a different macOS (27.0.1 against your 26.6.2), and I cannot rule out load on that machine. My 1.72x against your 2.51x on lm_head is probably that, not your kernel.

    So in your check each row matched the one-row result on both machines, including an Ultra and macOS 27. For this issue: a kernel through mx.fast.metal_kernel on stock MLX can match the one-row result bit for bit on two chip generations, and its cost against the plain batched call grows with rows and matrix size, to 0.28x on the M5 and 0.52x on the M3 Ultra for lm_head at 16 rows (mean of the three models).

    For my case the comparison that matters is against the plain batched call, so I will not adopt it. Thank you for sharing it.

  6. zcbenz commented on Nov 28, 2026

    @zcbenz
    Member

    It might make sense adding kernel parameter to quantized_matmul which selects the kernel to use without using heuristics, other than helping this specific use case, it would also make tests and benchmarks much easier.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions