Skip to content

[BUG] fp32 matmul silently defaults to TF32-class precision (MLX_ENABLE_TF32=1), undocumented on both backends #3860

Closed

Description

@stoyoda0012-cyber

Describe the bug

On the CUDA backend, fp32 mx.matmul runs in TF32 (10-bit mantissa)
by default: enable_tf32() in mlx/utils.h defaults MLX_ENABLE_TF32
to 1, and dtype_to_compute_type() in
mlx/backend/cuda/gemms/cublas_gemm.cpp then selects
CUBLAS_COMPUTE_32F_FAST_TF32 for float32 (and complex64) inputs.

The switch exists, but nothing tells the user about it: there is no
warning, and MLX_ENABLE_TF32 appears nowhere in the documentation —
the only occurrences in the repo are mlx/utils.h and
python/tests/mlx_tests.py. We spent a full-pipeline bisection tracing
a ~9 dB accuracy regression before finding it, and initially worked
around it with NVIDIA's driver-level NVIDIA_TF32_OVERRIDE=0 because
we could not find any MLX-side control.

Relative Frobenius error of a 512×512 fp32 GEMM against a float64
reference:

backend rel. error
NumPy fp32 2.9e-07
MLX CPU stream 4.1e-07
MLX Metal (M-series) fp32-class
MLX CUDA (default, MLX_ENABLE_TF32=1) 2.9e-04
MLX CUDA + MLX_ENABLE_TF32=0 2.1e-07
MLX CUDA + NVIDIA_TF32_OVERRIDE=0 (driver-level) 2.1e-07

~1000× the error of fp32 — the expected TF32 mantissa signature.
MLX_ENABLE_TF32=0 is measured equivalent to the driver-level
override (2.08e-07 vs 2.077e-07 on the same seed). Because the flag is
read lazily on first use, os.environ["MLX_ENABLE_TF32"] = "0" before
the first kernel call also works in-process (measured: 2.08e-07) —
useful, but only if the user knows the flag exists.

The practical problem is the silent divergence from Metal: the same
MLX program produces fp32-accurate results on Apple silicon and
TF32-accurate results on CUDA. In our fitting engine this flipped
near-tie argmax decisions over correlation scores (1.4–2.5 % of
spectra picked a neighbouring dictionary entry) and cost ~9 dB of
end-to-end PSNR — while every op-level parity test still passed, since
the corruption enters through the accumulated matmul, not any single
op. It took a full-pipeline bisection to trace it back to TF32.

To Reproduce

import numpy as np
import mlx.core as mx

rng = np.random.default_rng(0)
A = rng.standard_normal((512, 512)).astype(np.float32)
B = rng.standard_normal((512, 512)).astype(np.float32)
ref = A.astype(np.float64) @ B.astype(np.float64)

g = np.array(mx.matmul(mx.array(A), mx.array(B)))
err = np.linalg.norm(g.astype(np.float64) - ref) / np.linalg.norm(ref)
print(f"rel Frobenius err: {err:.1e}")   # ~3e-04 default; ~2e-07 with MLX_ENABLE_TF32=0

Expected behavior

Any of these would resolve it (in order of preference):

  1. Default MLX_ENABLE_TF32 to 0 — true fp32 for fp32 inputs,
    matching Metal and NumPy semantics — and make TF32 opt-in.
  2. Expose a runtime switch (analogous to
    torch.backends.cuda.matmul.allow_tf32) instead of a
    read-once-at-first-use environment variable.
  3. At minimum, document MLX_ENABLE_TF32 and the TF32-by-default
    behavior prominently for the CUDA backend.

(Related: #3235 asked what MLX_ENABLE_TF32 actually does on the
Metal/NAX path — the flag is doing double duty across backends, which
is another reason to document it.)

Notably, TF32 wasn't even buying speed in our measurements on sm_120
(TF32-on was slower than TF32-off in a 4096³ GEMM microbench —
reported separately in #3861), so on this arch the default trades ~3 decimal
digits of precision for nothing.

Desktop

  • OS: Windows 11 + WSL2 (Ubuntu 24.04)
  • GPU: NVIDIA GeForce RTX 5070 Laptop (Blackwell, sm_120), driver 596.13
  • MLX: 0.32.0 (mlx-cuda-13 0.32.0)
  • Python 3.12.3, NumPy 2.3.5

Activity

  1. pierre427 commented on Jul 21, 2026

    @pierre427
    Contributor

    Data point from M5 hardware: the "diverges from Metal" part of the title only holds for pre-M5 Apple silicon. On M5, the Metal backend does the same thing — fp32 GEMM dispatches to the neural accelerator at TF32-class precision under the same default (env::enable_tf32() gate in backend/metal/matmul.cpp), confirmed as expected behavior in #3534. So the undocumented default currently affects both backends on current-generation hardware, which strengthens the documentation ask.

    Measurements on M5 Max (macOS 26.5, mlx 0.32.0 wheel), fp32 vs a float64 reference:

    shape default MLX_ENABLE_TF32=0
    (64,1)@(1,128) outer product, max rel err 1.9e-3 6.0e-8
    (48,64,128)@(48,128,32), max abs err 4.3e-2 2.8e-5

    Two properties that made this expensive to bisect downstream:

    • Shape-dependent: matvec shapes (M=1 or N=1) don't take the NAX route and stay exact fp32, so the same dtype + op gives different precision depending on operand shapes. In mlx-lm's test_ssm, the output comparison passes (gemv-shaped contractions) while the state comparison fails (outer product) — which initially reads as a kernel bug rather than a precision-regime change.
    • Latching: the env var is read once on first use, so it must be set before the first matmul in the process; setting it later silently does nothing.

    Concrete downstream trip: mlx-lm's tests/test_models.py::test_ssm (kernel-vs-reference at atol=rtol=1e-4) fails out of the box on any M5 + mlx >= 0.32 with default settings — fix in ml-explore/mlx-lm#1595. A documented default plus a runtime-visible toggle (or a one-time log line when TF32 kicks in for fp32 inputs) would have saved both bisections.

  2. stoyoda0012-cyber commented on Jul 21, 2026

    @stoyoda0012-cyber
    ContributorAuthor

    Thanks, this is a great data point — and you're right to correct the title. "diverges from Metal" held for the pre-M5 silicon I tested against (my Metal box is an M3 Max, where fp32 GEMM stays exact), but if M5's Metal backend routes fp32 GEMM through the NAX under the same env::enable_tf32() gate (confirmed expected in #3534), then this is a cross-backend undocumented default on current hardware, not a CUDA-vs-Metal divergence. That strengthens the documentation ask. Happy to retitle to something like "fp32 matmul silently defaults to TF32-class precision (MLX_ENABLE_TF32=1), undocumented on both backends".

    The downstream cost is the part I'd put front and center: on CUDA (sm_120), the silent TF32 default flipped near-tie argmax decisions on 1.4–2.5% of spectra in a fitting workload, while every op-level parity test still passed. That op-level-green / downstream-wrong split is exactly the test_ssm trap you hit — which is the whole case for documenting the default.

    Two mechanics from the CUDA side that match your M5 findings:

    • Shape-dependent: matvec (M=1 / N=1) stays exact fp32; it's the accumulated GEMM that carries the TF32 signature — same as your M5 observation.
    • First-use-latched: os.environ["MLX_ENABLE_TF32"]="0" set before the first matmul works (measured 2.08e-07, matching the driver-level NVIDIA_TF32_OVERRIDE=0); set any later it silently does nothing.

    So both backends, shape-dependent and first-use-latched. A documented default plus a one-time log line when TF32 engages for fp32 inputs would have saved bisections on both sides. If you want to take the one-time-log PR (it touches both backends' init paths), please do — I can send the doc-line PR and add the CUDA-side numbers (likely within a couple of weeks), and I'm happy to review. Thanks for the M5 measurements and the mlx-lm#1595 link.

  3. pierre427 commented on Jul 21, 2026

    @pierre427
    Contributor

    That split works for us — we'll take the one-time-log PR, and the retitle you propose matches what we measured.

    Plan for the log PR: emit a single line, once per process, at the point where an fp32 GEMM first actually engages the reduced-precision route (Metal: the NAX dispatch gate in backend/metal/matmul.cpp; CUDA: where the cuBLAS math mode is applied), naming MLX_ENABLE_TF32=0 and pointing at the docs line you're adding. Firing on actual engagement rather than at init keeps it silent for processes that never hit a TF32-class GEMM (pure matvec/decode workloads, non-fp32 dtypes, pre-M5 Metal).

    One dependency to be upfront about: we have no NVIDIA hardware, so the CUDA side will be compile/CI-verified only from our end — your sm_120 review offer is exactly what that half needs. We'll test the Metal side on M5 (both that it fires once for a GEMM-shaped fp32 matmul and that it stays silent under MLX_ENABLE_TF32=0 and for gemv shapes).

    Your argmax-flip numbers are a strong argument for putting the downstream cost first in the doc line — op-level parity tests passing while decisions flip is the exact failure mode a reader needs to recognize. Will link the PR here when it's up.

  4. changed the title [-][BUG] [CUDA] fp32 matmul silently defaults to TF32 (`MLX_ENABLE_TF32=1`); undocumented, diverges from Metal[/-] [+][BUG] fp32 matmul silently defaults to TF32-class precision (`MLX_ENABLE_TF32=1`), undocumented on both backends[/+] on Jul 21, 2026
  5. mabaeyens commented on Jul 26, 2026

    @mabaeyens

    Adding the Metal side of the backend-scope point @katlun-lgtm raised on #3897, since this seems to be where the doc line is being written.

    Two gen-17 measurements

    Apple M5 (base, applegpu_g17g), 32 GB, macOS 26.5.2 (25F84), mlx 0.32.0. Plain fp32 matmul, 512x512x512, GPU against a CPU reference, no attention involved:

    arm rel error
    native 2^-10.4
    MLX_ENABLE_TF32=0 2^-19.8
    forced MLX_METAL_GPU_ARCH=applegpu_g16s 2^-19.8

    @PhilipJohnBasile measured the same thing on an M5 Max (g17s): native 2^-10.4, matching exactly, with both opt-outs landing together at 2^-20.9. @katlun-lgtm measured an M3 Max (g15s) as bit-identical with and without the flag, max delta 0, at both 512³ and 1024³.

    So on Metal the default changes with GPU generation under one MLX version and one flag, which is the part likely to confuse people. Someone checking MLX_ENABLE_TF32 on an M3 Max measures exactly nothing and can reasonably conclude the flag does not apply to Metal. It does. Their hardware just sits behind the is_nax_available() gate (macOS >= 26.2 and arch_gen >= 17). On CUDA there is no such gate, so fp32 takes the TF32-class route on every device.

    If it helps the doc line, the shape is: CUDA, always; Metal, gen-17 and up on macOS 26.2+. Worth stating the negative explicitly too, that pre-gen-17 Metal is unaffected, because that is what makes the flag look broken when it is not.

    One consequence that may be worth a sentence

    The effect is not limited to code that looks like a matmul. On gen-17 it also moves attention paths that compose from ordinary GEMMs rather than a fused kernel. We hit this at head_dim 96, which fails sdpa_full_supported_head_dim ({64, 80, 128}) and so never enters the fused path, yet still responds to MLX_ENABLE_TF32 because the fallback is built from matmuls. Diagnosing that took a while precisely because "TF32 affects matmul" reads as narrower than it is.

    Downstream, in mlx-lm, this is enough to fail 8 of 28 tests in tests/test_generate.py on gen-17, all batch-vs-single equivalence assertions, all of which pass with the flag off. Those tests pin their model to fp32 (set_dtype(mx.float32)), so they sit squarely in this issue's lane rather than the separate fp16/bf16 attention one. mlx-lm#1595 is pinning the flag off in its test suite.

    Happy to run other shapes or dtypes on the g17g part if a specific number would help the docs.

  6. stoyoda0012-cyber commented on Jul 26, 2026

    @stoyoda0012-cyber
    ContributorAuthor

    Thanks @mabaeyens — this is exactly the scope information the docs page needed. I've updated #3894 accordingly:

    • the Metal condition now reads "the M5 generation and newer, on macOS 26.2 or later", with the negative stated explicitly: on pre-gen-17 machines the flag has no observable effect because the reduced-precision path is never taken, not because the setting is ignored;
    • a new bullet notes that the default applies to anything that lowers to these operations, not only code that calls mx.matmul directly, with attention fallbacks composed from ordinary GEMMs as the example — your head_dim 96 case is exactly the surprise the page should prevent.

    The three-generation table (g15s bit-identical, g17g and g17s both at 2^-10.4) is a neat confirmation that the observable is the dispatch gate rather than the flag itself. The numbers already on the page (~1e-4 to 1e-3 default vs ~2e-7 full fp32 for a 512x512 product) line up with your measurements, so I believe the page is covered — thank you for the offer to run more shapes.

  7. mabaeyens commented on Jul 26, 2026

    @mabaeyens

    Glad it was useful, and the page sounds well covered. One refinement to a line already in your outline, rather than new scope.

    "float16 and bfloat16 inputs are unaffected" is correct about this flag, but on gen-17 it can be read as "fp16 and bf16 have no reduced-precision behaviour", which is not the case. The masked-attention divergence in #3897 is fp16 and bf16 only, it is the NAX attention kernel rather than TF32, and no environment variable opts out of it. Forcing MLX_METAL_GPU_ARCH=applegpu_g16s is the only thing that moves it, which is a debugging tool and not something to suggest in docs.

    The failure mode that costs someone an afternoon: they see batch-vs-single divergence in bf16, find this page, set MLX_ENABLE_TF32=0, observe no change at all, and conclude either that the flag is broken or that their own code is. Half a sentence such as "this flag affects float32 only; reduced-precision behaviour in float16 and bfloat16, where it exists, has other causes" would close that off.

    Your call whether that belongs on a TF32 page. I raise it only because the existing line already makes a claim about those two dtypes.

  8. stoyoda0012-cyber commented on Jul 26, 2026

    @stoyoda0012-cyber
    ContributorAuthor

    Agreed it belongs here — the bullet already makes a claim about those two dtypes, so it should carry the boundary too. Updated in #3894: the line now reads that the setting applies to float32 only, and that reduced-precision behaviour involving float16 or bfloat16 inputs, where it exists, has other causes and is not controlled by MLX_ENABLE_TF32.

    I kept it deliberately cause-agnostic — no reference to the NAX attention kernel or the arch override — so the page stays a TF32 page while still closing the afternoon-costing path you describe: someone who lands here from a bf16 divergence now learns immediately that this flag is not their lever.

  9. stoyoda0012-cyber commented on Aug 3, 2026

    @stoyoda0012-cyber
    ContributorAuthor

    Recording the hardware-specific measurements here, since #3894 has been
    reduced to what holds independently of backend and hardware generation
    and no longer carries them.

    CUDA, measured 2026-07-22/23 -- RTX 5070 Laptop (sm_120), WSL2
    Ubuntu 24.04, CUDA 13.3, a source build at 0.32.0.dev whose only delta
    from the release was logging.

    case default MLX_ENABLE_TF32=0
    fp32 GEMM, Frobenius relative error vs a float64 reference 2.9e-04 2.1e-07
    fp32 matvec (M == 1 or N == 1), relative error vs a float64 reference 9.7e-08 --

    The matvec row is the shape exception: rank-1 shapes stay fp32-exact
    under the default. The CUDA compute-type selection in
    dtype_to_compute_type() is dtype-only and shape-blind, so reduced
    precision is requested for those shapes too; cuBLASLt then selects the
    kernel by runtime heuristic, so what is requested and what actually
    executes cannot be matched up statically.

    The environment variable is read once, at the first operation that could
    take the reduced-precision path, and the value is fixed for the rest of
    the process; setting it afterwards has no effect. Set before that point,
    it reproduces the driver-level NVIDIA_TF32_OVERRIDE=0 result.

    Parity: the 774-test suite produces a failure set identical to the
    0.32.0 wheel, both with the variable unset and with MLX_ENABLE_TF32=0.

    Metal measurements are in the comments above, from the people who own
    that hardware, with their own dates and OS versions: M5 base and M5 Max
    at gen-17, and an M3 Max as the negative control.

    Status: #3883 is closed. #3894 now states only that float32
    matmul-family operations may run at reduced precision by default on
    hardware with dedicated matrix-multiplication units, and that
    MLX_ENABLE_TF32=0 opts out.

  10. zcbenz commented on Aug 4, 2026

    @zcbenz
    Member

    I'm closing this issue since this behavior is being documented in #3894, having a programmable switch would be nice but at the moment I think there is no necessarility to add that.

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