Skip to content

Batched (padded/masked) attention diverges from single-sequence on M5, not on M3 Max #3897

Closed

Description

@mabaeyens

Summary

On an Apple M5, batched generation produces slightly different logits than running the same prompt single-sequence. The gap is small and does not change the sampled token, but it is large enough to fail mlx-lm's strict batch-vs-single equivalence tests, and it does not appear on M3 Max. It reproduces on both mlx 0.31.2 and 0.32.0, so it is silicon-specific rather than a version regression.

Environment

  • Apple M5, 32 GB, macOS 26.5.2 (build 25F84), applegpu_g17g. (Corrected 2026-07-25: this line originally read "macOS 15", which was a typo. It matters, because is_nax_available() requires macOS >= 26.2, so the original value made the kernel-gate explanation in the comments look inapplicable to this machine.)
  • mlx 0.31.2 and mlx 0.32.0 (both reproduce, identically).
  • Contrast: Apple M3 Max, mlx 0.32.0, where the same tests pass (reported by another contributor on Implement KV-cache quantization for the continuous-batching path (RotatingKVCache/BatchRotatingKVCache) mlx-lm#1584).

Downstream symptom (model level)

Running mlx-lm/tests/test_generate.py on the M5 fails 8 of 28 tests, all of them batch or stream equivalence assertions (test_batch_matches_single, test_batch_sliding_window, test_batch_continued_generation*, test_stream_generate_input_embeddings*). Same 8 pass on M3 Max. The failing assertion is mx.allclose(batch_logprobs, single_logprobs) at the default rtol=1e-5.

Measured gap on the M5 (Qwen1.5-0.5B-Chat-4bit, one decode step, batch of 4):

prompt                        max|Δlogprob|   argmax match
Write a story about Einstein     0.031250          True
Hi                               0.031250          True
What time is it?                 0.039062          True
How tall is Mt Everest?          0.031250          True

So the divergence is about 1/32 of a logprob and never changes the selected token. Functionally harmless, but it trips bit-equivalence tests.

Localization (minimal, model-free)

Plain batched attention and quantized matmul are bit-identical batch-vs-single on the M5:

import mlx.core as mx
def maxdiff(a, b): return float(mx.max(mx.abs(a.astype(mx.float32) - b.astype(mx.float32))))
B, H, L, D = 4, 8, 48, 64
q = mx.random.normal((B, H, L, D)).astype(mx.float16)
k = mx.random.normal((B, H, L, D)).astype(mx.float16)
v = mx.random.normal((B, H, L, D)).astype(mx.float16)
s = 1.0 / D**0.5
full = mx.fast.scaled_dot_product_attention(q, k, v, scale=s, mask="causal")
rows = mx.concatenate([mx.fast.scaled_dot_product_attention(q[i:i+1], k[i:i+1], v[i:i+1], scale=s, mask="causal") for i in range(B)], axis=0)
mx.eval(full, rows); print(maxdiff(full, rows))   # -> 0.0 on M5

The gap only shows up on the padded/masked path that batched generation actually uses (left-padding shorter sequences and masking the pad positions):

import mlx.core as mx
def maxdiff(a, b): return float(mx.max(mx.abs(a.astype(mx.float32) - b.astype(mx.float32))))
dt = mx.float16; H, D = 16, 64; Lreal, pad = 40, 8; Lpad = Lreal + pad; s = 1.0 / D**0.5
q1 = mx.random.normal((1, H, Lreal, D)).astype(dt)
k1 = mx.random.normal((1, H, Lreal, D)).astype(dt)
v1 = mx.random.normal((1, H, Lreal, D)).astype(dt)
single = mx.fast.scaled_dot_product_attention(q1, k1, v1, scale=s, mask="causal")
lp = lambda a: mx.concatenate([mx.zeros((1, H, pad, D), dtype=a.dtype), a], axis=2)
ri = mx.arange(Lpad); m = (ri[None] <= ri[:, None]) & (ri >= pad)[None]
addmask = mx.where(m, mx.array(0.0, dt), mx.array(-mx.inf, dt))[None, None]
batched = mx.fast.scaled_dot_product_attention(lp(q1), lp(k1), lp(v1), scale=s, mask=addmask)
mx.eval(single, batched)
print(maxdiff(single, batched[:, :, pad:, :]))   # M5: ~4.9e-4 (fp16), ~3.9e-3 (bf16)

On the M5 the masked-path gap is 2^-11 (fp16) and 2^-8 (bf16). Both are clean powers of two and bf16 is 8x fp16, which reads like a reduced-precision accumulation over the masked reduction rather than random noise. Accumulated across the model's layers this lands at the ~1/32 seen above.

Cross-silicon confirmation (M3 Max)

The masked-path snippet run on an M3 Max (mlx 0.32.0, swept over 8 seeds):

dtype M5 M3 Max ratio
fp16 4.88e-4 (2^-11) 2.44e-4 (2^-12) 2x
bf16 3.91e-3 (2^-8) 7.63e-6 (2^-17) ~512x

bf16 is the tell. The masked batch-vs-single gap is nine bits smaller on M3 Max (2^-17, essentially rounding) than on M5 (2^-8). On M5 the gap scales 8x going from fp16 to bf16; on M3 Max that scaling is gone. So this is not a general masked-softmax floating-point effect (that would be silicon-independent). It points specifically at the M5 fused-attention kernel accumulating the masked reduction at a lower width than earlier silicon.

Questions

  1. Is the M5 fused-attention kernel intended to accumulate the masked reduction at reduced width (the bf16 2^-8 vs 2^-17 gap above), or is that an oversight in the M5 path? Earlier silicon keeps it near bit-identical.
  2. If it is intended, documenting it would help, since it silently fails the strict allclose(rtol=1e-5) batch-equivalence tests in mlx-lm on M5 only (Implement KV-cache quantization for the continuous-batching path (RotatingKVCache/BatchRotatingKVCache) mlx-lm#1584 has the context) while being functionally harmless (argmax unchanged).

Possible mitigations

Two directions, whichever fits better. Narrow the M5 fused-attention kernel's masked-reduction accumulation to match earlier silicon, or relax the batch-vs-single equivalence tests in mlx-lm to tolerate the M5 gap (an atol alongside the rtol, or a per-arch tolerance). The kernel side is yours; I am happy to send the mlx-lm test PR if that is the direction you want.

Happy to run further probes on the M5 if a specific shape or kernel would help isolate it.

Activity

  1. katlun-lgtm commented on Jul 23, 2026

    @katlun-lgtm
    Contributor

    Before this gets a maintainer's eyes I swept the masked snippet over 32 seeds and a few head dims on the M3 Max, and it changed my read a bit — worth folding in.

    mlx 0.32.0, your masked snippet, 32 seeds, median and max of the maxdiff:

    D dtype M3 Max median M3 Max max
    64 fp16 2⁻¹⁴·⁴ 4.88e-4 (2⁻¹¹)
    64 bf16 0 4.88e-4 (2⁻¹¹)
    128 fp16 2⁻¹² 9.77e-4 (2⁻¹⁰)
    128 bf16 2⁻¹¹·⁴ 1.95e-3 (2⁻⁹)

    Two things I got wrong / that need matching up:

    The 2⁻¹⁷ bf16 number I gave you was an 8-seed fluke. This gap is heavy-tailed — at D=64 bf16 the median is actually 0 (most seeds are bit-identical) and the max just walks up as you add seeds. The fp16 max lands at 4.88e-4, which is the same value in your M5 column. So on a matched seed sweep the D=64 split between our two machines is a lot smaller than 512× — more like single-digit, with the M3 median sitting at 0.

    And it scales with head dim. At D=128 (what the real models use) the M3 Max bf16 gap is median 2⁻¹¹·⁴ / max 2⁻⁹, within a bit of your M5 D=64 number. The plain unpadded path stays exactly 0 at every D and fp32 stays at the ~2e-7 floor, so your mechanism holds — it's masked-path, reduced-precision reduction-order rounding — it just doesn't look as M5-specific once you sweep seeds and head dim.

    Could you run the same 32-seed sweep at D=64/96/128 on the M5? If M5 at D=128 is still well clear of the M3 Max there, the silicon story survives with clean numbers. If they converge, it's mostly head_dim + precision, and relaxing the mlx-lm batch-equivalence tolerance (an atol, or per-arch) is the right call either way — a strict rtol=1e-5 won't survive real reduction-order rounding on any silicon once the head dim is big enough. Happy to paste the seed/D loop I used.

  2. mabaeyens commented on Jul 24, 2026

    @mabaeyens
    Author

    Ran your 32-seed sweep on the M5, same snippet, D=64/96/128, fp16 and bf16, and I threw in an fp32 control since that turned out to be the cleanest cut. I ran it on both mlx 0.31.2 and a clean 0.32.0 to match your stack, and the two are identical cell for cell (every median and max the same value), so this lines up against your 0.32.0 M3 Max column with no version confound.

    D dtype M5 median M5 max
    64 fp16 2⁻¹¹ 2⁻¹⁰
    64 bf16 2⁻⁸ 2⁻⁸
    96 fp16 2⁻¹² 2⁻¹¹
    96 bf16 0 2⁻⁹
    128 fp16 2⁻¹¹ 2⁻¹⁰
    128 bf16 2⁻⁸ 2⁻⁷
    64 fp32 2⁻¹¹·⁷ 2⁻¹¹·³
    96 fp32 2⁻²¹·⁴ 2⁻¹³
    128 fp32 2⁻¹¹·⁷ 2⁻¹¹·³

    The matched-cell medians answer your question directly. At D=64 bf16 you're bit-identical (median 0) and the M5 sits at 2⁻⁸. At D=128 bf16 you're at 2⁻¹¹·⁴ and the M5 is at 2⁻⁸, so it doesn't converge onto you, it stays about 2.6 bits above (~11x). fp16 is the same direction but tighter, roughly one bit at D=128 and three at D=64. So on a matched seed sweep the M5 is worse than the M3 Max in every cell, widest on bf16. The silicon split holds.

    The fp32 control is the part I'd lean on, though. On the M5 the masked path diverges from single at a median of 2⁻¹¹·⁷ (about 3e-4) for D=64 and D=128, where you had the M3 Max fp32 sitting at the ~2e-7 floor. That's around ten bits, and it's fp32, so it isn't a storage-precision thing. The M5 fused kernel is taking a different reduction on the masked path even with nothing quantized. That's the cleanest cross-silicon evidence in the set, and it's dtype-independent, which is what the head_dim + precision reading couldn't produce.

    One oddity I can't fully explain, worth flagging: D=96 is the clean one on the M5. Across every dtype it's better than both D=64 and D=128 (bf16 median 0, fp32 median 2⁻²¹·⁴, basically floor). The mask is identical at every D, so this is head dim selecting a kernel, not head dim scaling an error. Reads like the fused vectorized path only engages on 64-multiple head dims and 96 falls back to something cleaner. So the divergence tracks which kernel gets picked, not D monotonically, which fits a kernel story better than a general masked-softmax one.

    Net from here: the silicon story survives with matched numbers, and the fp32 control pins it to the M5 kernel rather than precision. That said, I still agree the tolerance point is orthogonal and worth doing regardless. Even your M3 Max max walks to 2⁻⁹ at D=128 bf16, so a strict rtol=1e-5 batch-equivalence assertion in mlx-lm won't survive real head dims on any silicon. An atol floor or a per-arch tolerance is the right call either way the kernel question lands.

    Happy to run more shapes if it helps draw the kernel-path boundary (other head dims around the 96 cliff, or varying Lreal/pad).

  3. katlun-lgtm commented on Jul 24, 2026

    @katlun-lgtm
    Contributor

    Ran the matched fp32 control and your D=96 question on the M3 Max — 32-seed sweep, same masked snippet — and the D=96 result turns out to be the decisive one.

    fp32, matched. The M3 Max masked path stays at the fp32 floor at every head dim: median 2⁻²²·¹ (D=64), 2⁻²¹·⁴ (D=96), 2⁻²²·⁰ (D=128), against your M5 2⁻¹¹·⁷ / 2⁻²¹·⁴ / 2⁻¹¹·⁷. So at D=64 and D=128 the M5 sits ~10 bits above the M3 Max in fp32. Being fp32, that's the kernel, not storage precision — confirms your read.

    D=96 is the tell, and it's the same value on both machines. In fp32, D=96 gives an identical 2⁻²¹·⁴ on the M5 and the M3 Max — both at floor — while D=64/128 split (M3 Max 2⁻²², M5 2⁻¹¹·⁷). So D=96 isn't "cleaner on the M5"; it's a kernel both silicons run identically, and the divergence is specifically the M5 fused kernel on the 64-multiple head dims. That pins your kernel-selection reading: the fused vectorized path engages on 64-aligned D and only the M5 build accumulates the masked reduction at reduced width; D=96 falls back to the shared clean path on both.

    Full M3 Max table (mlx 0.31.2 — cell-for-cell identical to my earlier 0.32.0 numbers, so it's version-independent on the M3 Max too, matching your M5):

    D dtype median max
    64 fp16 2⁻¹⁴·⁴ 2⁻¹¹
    64 bf16 0 2⁻¹¹
    64 fp32 2⁻²²·¹ 2⁻²¹·⁷
    96 fp16 2⁻¹³ 2⁻¹⁰
    96 bf16 0 2⁻⁹
    96 fp32 2⁻²¹·⁴ 2⁻²⁰·⁴
    128 fp16 2⁻¹² 2⁻¹⁰
    128 bf16 2⁻¹¹·⁴ 2⁻⁹
    128 fp32 2⁻²²·⁰ 2⁻²¹·⁴

    Unpadded control = 0 at every cell. And agreed the mlx-lm tolerance fix is worth doing regardless of where the kernel question lands — the M3 Max bf16 max already hits 2⁻⁹ at D=128, so a strict rtol=1e-5 batch-equivalence assertion won't survive real head dims on any silicon.

  4. PhilipJohnBasile commented on Jul 25, 2026

    @PhilipJohnBasile
    Contributor

    Third M5 datapoint, plus a same-silicon control that I think settles the kernel question without needing a second machine.

    Rig: Apple M5 Max (128 GB, macOS 27.0, mlx 0.32.0, applegpu_g17s) — a different M5 variant from @mabaeyens', so this also tests whether the effect is chip-wide or one machine.

    1. The M5 table reproduces exactly

    Your 32-seed sweep, same snippet, H=16 / Lreal=40 / pad=8. All nine cells identical to @mabaeyens' — same medians, same maxes, including the D=96 anomaly and the fp32 split:

    D dtype median max
    64 fp16 2⁻¹¹ 2⁻¹⁰
    64 bf16 2⁻⁸ 2⁻⁸
    64 fp32 2⁻¹¹·⁷ 2⁻¹¹·³
    96 fp16 2⁻¹² 2⁻¹¹
    96 bf16 0 2⁻⁹
    96 fp32 2⁻²¹·⁴ 2⁻¹³
    128 fp16 2⁻¹¹ 2⁻¹⁰
    128 bf16 2⁻⁸ 2⁻⁷
    128 fp32 2⁻¹¹·⁷ 2⁻¹¹·³

    Unpadded control: exactly 0 in every cell. So it's M5-generation-wide, not a single unit.

    2. Same-silicon control: it is kernel selection, and both kernels are on one machine

    MLX_METAL_GPU_ARCH overrides the architecture string that mlx's dispatch predicates read (Device's ctor takes env::metal_gpu_arch() before the real device name, so get_architecture_gen() follows it). Forcing gen-16 on this same M5 Max, nothing else changed:

    D dtype native g17s forced g16s @katlun-lgtm's M3 Max
    64 fp32 2⁻¹¹·⁷ 2⁻²²·¹ 2⁻²²·¹
    128 fp32 2⁻¹¹·⁷ 2⁻²²·⁰ 2⁻²²·⁰
    96 fp32 2⁻²¹·⁴ 2⁻²¹·⁴ 2⁻²¹·⁴
    64 bf16 2⁻⁸ 0 0
    128 bf16 2⁻⁸ 2⁻¹¹ 2⁻¹¹·⁴
    64 fp16 2⁻¹¹ 2⁻¹⁴ 2⁻¹⁴·⁴
    128 fp16 2⁻¹¹ 2⁻¹² 2⁻¹²

    Forcing gen-16 reproduces the M3 Max column cell-for-cell, on M5 silicon. applegpu_g14s gives byte-identical results to g16s, so the responsible gate sits between gen-16 and gen-17 — not between M3 and M5. The "silicon split" is a kernel split that happens to correlate with silicon because the gate is a generation check.

    3. The gate, from the v0.32.0 source

    scaled_dot_product_attention.cpp line 177, in sdpa_full_self_attention_metal:

    if (metal::is_nax_available() && q.shape(3) != 80 &&
        (env::enable_tf32() || q.dtype() != float32)) {
      return sdpa_full_self_attention_nax(...);

    is_nax_available() (device.cpp:943) is macOS ≥ 26.2 and arch_gen >= 17. So on gen-17 the masked/full attention path routes to the NAX steel-attention kernel, which accumulates the masked reduction at reduced width. Forcing gen-16 fails the predicate and lands on sdpa_full_self_attention_metal's ordinary steel path — the one the M3 Max has always used.

    This also explains D=96 from source rather than inference. A few lines down:

    const bool sdpa_full_supported_head_dim = query_head_dim == value_head_dim &&
        (query_head_dim == 64 || query_head_dim == 80 || query_head_dim == 128);

    96 isn't in the set, so D=96 never enters the fused path at all — it falls back to the generic composition on every machine. That's exactly why @katlun-lgtm measured an identical 2⁻²¹·⁴ on both rigs: not "cleaner on the M5," but the same non-fused code on both. Your kernel-selection reading was right, and the head-dim list is the reason.

    4. A control that doesn't need an arch override

    The gate's third clause is (enable_tf32() || dtype != float32). That predicts MLX_ENABLE_TF32=0 should opt fp32 out of the NAX kernel while leaving fp16/bf16 on it, since dtype != float32 short-circuits true for them. Measured on native g17s:

    D dtype native native + MLX_ENABLE_TF32=0
    64 fp32 2⁻¹¹·⁷ 2⁻²²·¹
    128 fp32 2⁻¹¹·⁷ 2⁻²²·⁰
    64 fp16 2⁻¹¹ 2⁻¹¹ (unchanged)
    64 bf16 2⁻⁸ 2⁻⁸ (unchanged)

    Confirmed in both directions. So the fp32 divergence @mabaeyens isolated as "isn't a storage-precision thing" is TF32 accumulation inside the NAX attention kernel — ~10–11 mantissa bits, which is precisely the 2⁻¹¹·⁷ observed — and it is opt-out-able today with an env var. The fp16/bf16 divergence is not; those take the NAX path regardless.

    5. On the tolerance question

    Both of you concluded rtol=1e-5 can't survive real head dims, and the fp32 numbers make that sharper: on gen-17 the fp32 masked path diverges at ~3e-4 by default, so a strict batch-equivalence assertion fails even with nothing quantized and nothing in reduced storage precision. An atol floor or per-arch tolerance is right regardless of how the kernel question is resolved — and for mlx-lm's suite specifically, MLX_ENABLE_TF32=0 would make the fp32 assertions pass on gen-17 without loosening anything, which may be the cheaper CI fix.

    6. One inconsistency worth a one-line check

    @mabaeyens, your environment says macOS 15, but is_nax_available() requires macOS ≥ 26.2 — on macOS 15 the NAX path should be unreachable and you should be seeing the gen-16 numbers. Since you're seeing the gen-17 numbers, I suspect that line is a typo for a 26.x/27.x build. Worth pasting sw_vers to confirm: if your machine genuinely reports macOS 15 and still diverges, then the gate above doesn't explain your rig and my mechanism is incomplete.

    Script and the four arm JSONs (32 seeds each, native / g16s / g14s / native+tf32off) available if useful — happy to sweep the head dims around the 96 cliff or vary Lreal/pad to draw the boundary more precisely.

  5. mabaeyens commented on Jul 25, 2026

    @mabaeyens
    Author

    Thanks, this is a much better answer than I had. Confirming your mechanism on a second M5, correcting my environment line, and flagging one place where I think the D=96 explanation needs adjusting.

    1. The macOS line was a typo, and you were right to catch it

    sw_vers on my machine:

    ProductName:    macOS
    ProductVersion: 26.5.2
    BuildVersion:   25F84
    

    So macOS 26.5.2, not 15. I will edit the issue body. That satisfies the is_nax_available() gate, so your mechanism does cover my rig and the inconsistency goes away.

    For the record my chip is a base Apple M5, 32 GB, applegpu_g17g, so between us that is gen-17 confirmed on two different variants (your g17s).

    2. Both of your controls reproduce here

    mlx 0.32.0, your snippet, 32 seeds, H=16 / Lreal=40 / pad=8. Medians:

    D dtype native g17g MLX_ENABLE_TF32=0 forced g16s
    64 fp16 2^-11.0 2^-11.0 2^-14.4
    64 bf16 2^-8.0 2^-8.0 0
    64 fp32 2^-11.7 2^-22.1 2^-22.1
    96 fp16 2^-12.0 2^-12.0 2^-13.0
    96 bf16 0 0 0
    96 fp32 2^-21.4 2^-21.4 2^-21.4
    128 fp16 2^-11.0 2^-11.0 2^-12.0
    128 bf16 2^-8.0 2^-8.0 2^-11.4
    128 fp32 2^-11.7 2^-22.0 2^-22.0

    Forcing gen-16 reproduces katlun-lgtm's M3 Max column cell for cell on M5 silicon, same as you got. TF32 off moves fp32 only and leaves fp16/bf16 untouched, exactly as the third clause predicts. Both directions confirmed independently.

    3. D=96 is not off the fused path, and the median hides it

    This is the one place I would adjust your reading. The D=96 median is identical across all three arms, which looks like "TF32 does nothing here". Per seed it is not:

    arm median max seeds differing from native
    native 2^-21.4 2^-13.0 (reference)
    tf32off 2^-21.4 2^-20.4 27 of 32
    g16s 2^-21.4 2^-20.4 27 of 32

    tf32off and g16s are bit-identical on all 32 seeds. Native disagrees with both on 27, and ten of those spike well above the floor (2^-13.0, 2^-13.4, 2^-13.6, 2^-13.7, 2^-13.9, 2^-14.8, 2^-14.8, 2^-14.9, 2^-15.5, 2^-15.6) while the rest sit near 2^-21. Deterministic across repeat passes. So my original "D=96 is the clean one on the M5" was a median artifact, and the agreement katlun-lgtm and I saw at D=96 was also only a median agreement.

    The reason is not the head-dim list, though. Checking v0.32.0, the NAX branch at line 177 lives inside sdpa_full_self_attention_metal, which is only reached when supports_sdpa_full holds (line 632). At D=96 with Lreal=40, sdpa_full_supported_head_dim is false because 96 is not in {64, 80, 128}, and supports_sdpa_vector is false because the query length exceeds 8. So D=96 composes attention from ordinary matmuls and never reaches NAX, which is your conclusion. But it still responds to MLX_ENABLE_TF32, because that flag is not attention-specific.

    Plain fp32 matmul, 512x512x512, GPU against CPU as reference, nothing to do with attention:

    arm rel error
    native g17g 2^-10.4
    MLX_ENABLE_TF32=0 2^-19.8
    forced g16s 2^-19.8

    TF32 is on by default for fp32 GEMM on gen-17. That is what the D=96 fp32 tail is, and it is a second mechanism sitting alongside the NAX one.

    So I would split the summary in two rather than put all of it on the NAX kernel. The fp16/bf16 divergence is the NAX attention kernel: only the arch override moves it, and TF32 does nothing. The fp32 divergence is TF32 in fp32 GEMM on gen-17, which is wider than attention, and both flags move it (including at head dims that never enter a fused attention path at all).

    Your 2^-11.7 to TF32 mapping holds and the width matches. I would just not scope it to inside the NAX kernel, since D=96 shows it firing where NAX never runs.

    4. Your CI suggestion is better than you pitched it

    You suggested MLX_ENABLE_TF32=0 would make the fp32 assertions pass. On the actual mlx-lm suite it does more than that. mlx-lm at 24b2b4e, mlx 0.32.0, this M5:

    native:              8 failed, 20 passed
    MLX_ENABLE_TF32=0:  28 passed
    

    All eight go green, stable over three repeat runs each. The eight are test_batch_matches_single, test_batch_sliding_window, test_many_batches, test_batch_continued_generation{,_gated_delta,_ssm}, and test_stream_generate_input_embeddings{,_prefill}.

    That surprised me, because those run a 4-bit model whose compute is fp16/bf16, and the attention sweep above says TF32 does nothing to fp16/bf16. The implication is that the model-level failures are dominated by fp32 accumulation in the quantized matmul path rather than by the NAX attention kernel. Which also means the conclusion I drew in the original issue, pointing at the M5 fused-attention kernel, is at best only part of the story. For the failing tests the larger part is TF32 in GEMM.

    Practical upshot for the tolerance question: if the goal is just getting the suite green on gen-17, MLX_ENABLE_TF32=0 does it today with no test changes. Whether that is the right default for CI is a separate call, since it disables TF32 for all GEMM and that has a throughput cost. An atol floor still seems worth having regardless, because it covers the fp16/bf16 attention gap that TF32 cannot reach.

    Happy to sweep head dims around the 96 boundary or vary Lreal/pad if that helps pin the NAX head-dim gate more precisely. Scripts and the per-seed JSONs are available if useful.

  6. PhilipJohnBasile commented on Jul 25, 2026

    @PhilipJohnBasile
    Contributor

    Your correction is right, and I've reproduced the load-bearing part of it here before agreeing.

    The GEMM claim reproduces on a third rig

    Plain fp32 matmul, 512×512×512, GPU against a float64 CPU reference — no attention anywhere:

    arm rel error (M5 Max, g17s) yours (g17g)
    native 2^-10.4 2^-10.4
    MLX_ENABLE_TF32=0 2^-20.9 2^-19.8
    forced g16s 2^-20.9 2^-19.8

    Native matches your figure exactly, and as you found, tf32off and g16s land on the same value — they are not two independent effects for fp32, they are one.

    So TF32 is on by default for fp32 GEMM on gen-17, and it is not attention-specific. Confirmed on two M5 variants.

    What that means for my summary — it was wrong in one specific way

    I wrote that the fp32 divergence is "TF32 accumulation inside the NAX attention kernel." The TF32 half was right; attaching it to the attention kernel was not. It is a GEMM-wide property of gen-17, which is why it shows up at D=96 where, as we both now agree, nothing ever enters a fused attention path.

    Your two-mechanism split is the correct summary and I'd adopt it verbatim:

    • fp16/bf16 divergence — the NAX attention kernel. Only the arch override moves it; MLX_ENABLE_TF32 does nothing, because dtype != float32 satisfies the third clause regardless.
    • fp32 divergence — TF32 in fp32 GEMM on gen-17. Wider than attention, and both flags move it identically, including at head dims that never reach a fused kernel.

    One consequence for my own claim that is worth stating plainly, since I made it confidently: the same-silicon arch override is a clean proof of kernel selection only for the fp16/bf16 rows. For the fp32 rows it was confounded — g16s also disables TF32, so those rows were never evidence about kernel dispatch. The mechanism I was most pleased with was doing two jobs and I only checked one of them.

    On D=96

    My head-dim reasoning still holds — sdpa_full_supported_head_dim is {64, 80, 128}, supports_sdpa_vector fails at qsl > 8, so D=96 composes from ordinary matmuls. What I got wrong was the inference from it: I treated "never reaches NAX" as "unaffected", and read the identical medians as confirmation. Your per-seed table shows the medians were hiding a 27-of-32 disagreement with a ten-seed tail up to 2^-13, which is exactly the fallback matmuls picking up TF32. The median was the wrong statistic and I should not have leaned on it for a claim about a mechanism.

    That also retires the "D=96 is the shared clean path on both machines" reading that has been in the thread since the first cross-silicon comparison — it was a median agreement, not an agreement.

    Where this leaves the issue

    Two independent gen-17 behaviours, one of which is far wider than the title suggests:

    1. NAX attention kernel changes the masked reduction for fp16/bf16 at 64-aligned head dims.
    2. TF32-by-default changes every fp32 GEMM, which is a much broader statement about numerical expectations on M5 than "batched attention diverges".

    The tolerance conclusion is unchanged and arguably strengthened — a strict rtol=1e-5 batch-equivalence assertion cannot hold on gen-17 even in fp32, and now for a reason that has nothing to do with the cache or the attention path. Worth someone deciding whether TF32-on-by-default for fp32 GEMM is intended and documented, because that is a separate question from this issue and probably deserves its own.

    Happy to run anything further on the g17s variant.

  7. katlun-lgtm commented on Jul 25, 2026

    @katlun-lgtm
    Contributor

    The TF32 half already has an issue open, which I don't think anyone here has seen: #3860, filed 07-17 and retitled to "fp32 matmul silently defaults to TF32-class precision (MLX_ENABLE_TF32=1), undocumented on both backends" after @pierre427 posted M5 numbers on it. There's a plan agreed in that thread too — pierre taking a one-time log line that fires when an fp32 GEMM actually engages the reduced-precision route, the reporter taking the doc line. So the "someone should decide whether this is intended and documented" question has a home, and pointing at it beats opening a second one.

    One measurement to add from the pre-gen-17 side, since both GEMM controls in this thread are gen-17. M3 Max, applegpu_g15s, stock mlx 0.32.0, same 512³ fp32 GEMM against a float64 CPU reference:

    arm rel err
    native 2⁻²¹·⁷
    MLX_ENABLE_TF32=0 2⁻²¹·⁷

    Bit-identical, max|Δ| = 0 — and the same at 1024³ (2⁻²⁰·⁷ both arms). Which is what the source predicts: on Metal every TF32 gate is is_nax_available() && (env::enable_tf32() || dtype != float32) — the steel and gather GEMM paths in matmul.cpp, quantized.cpp, and the SDPA gate you quoted — and is_nax_available() requires macOS ≥ 26.2 and arch_gen >= 17 (18 on 'p' parts). So the flag is inert before gen-17 on Metal. On CUDA it isn't gated at all: dtype_to_compute_type picks CUBLAS_COMPUTE_32F_FAST_TF32 for fp32 (and complex64) on every device.

    That difference in scope seems worth putting in #3860's doc line. On CUDA the fp32 default is TF32 everywhere; on Metal it changes with GPU generation under the same MLX version and the same flag. Someone checking MLX_ENABLE_TF32 on an M3 Max will measure exactly nothing and reasonably conclude it doesn't apply to Metal at all.

    On the CI angle: mlx-lm#1595 (open, @pierre427) already pins MLX_ENABLE_TF32=0, but only in tests/test_models.py — tests/test_generate.py, where @mabaeyens' eight live, isn't covered by it. I'll flag that over there.

  8. zcbenz commented on Aug 9, 2026

    @zcbenz
    Member

    I'm closing this as won't fix since it is an MLX_ENABLE_TF32 behavior and for precision tests we should always turn it off.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions