Skip to content

matmul ~36× slower than cuBLAS on Windows when data are allocated in host #3861

Done

Description

@stoyoda0012-cyber

Describe the issue

On an RTX 5070 Laptop (sm_120), mx.matmul sustains 0.32 TFLOP/s
on a 4096³ fp32 GEMM. CuPy calling cuBLAS through the exact same
nvidia-cublas wheel, on the same GPU, in the same WSL2 session

sustains 11.96 TFLOP/s — a ~36× gap. The host CPU (Ryzen 9 8940HX,
NumPy/OpenBLAS) beats the GPU at 0.66 TFLOP/s.

path 4096³ fp32 GEMM (median) effective
CuPy → cuBLAS 11.5 ms 11.96 TFLOP/s
NumPy on host CPU 208.5 ms 0.66 TFLOP/s
mx.matmul (NVIDIA_TF32_OVERRIDE=0) 435.2 ms 0.32 TFLOP/s
mx.matmul (default / TF32) 729.7 ms 0.19 TFLOP/s

Two oddities that may help localize it:

  1. TF32-on is slower than TF32-off in this microbench, consistent
    with a mis-selected tensor-core code path on this arch. Measured
    both off-paths: MLX-native MLX_ENABLE_TF32=0 (requests
    CUBLAS_COMPUTE_32F outright) gives 421 ms and driver-level
    NVIDIA_TF32_OVERRIDE=0 (driver forcing fp32 under the default
    CUBLAS_COMPUTE_32F_FAST_TF32 request) gives 420 ms — identical, so
    the 36× gap is not an artifact of how TF32 is disabled. The default
    TF32 path is 734 ms (0.19 TFLOP/s) either way.
  2. During the slow runs nvidia-smi reports 2805 MHz (near max), P0,
    100 % GPU utilization — at only 40 W. The SMs are busy executing
    very low-efficiency code, not idle and not throttled.

Decomposition: chaining 10 GEMMs into a single mx.eval still costs
~196 ms per GEMM, i.e. the kernel itself is ~17× slow, plus ~220 ms of
per-mx.eval dispatch overhead on top for this graph.

libmlx.so in the mlx-cuda-13 wheel contains CUTLASS kernel
instantiations for SM90 only (e.g. qmm_sm90,
MMA_64x16x8_F32TF32TF32); nothing for sm_120. If matmul on
unrecognized archs falls back to a generic JIT path, that would explain
both the throughput and the wattage signature.

To Reproduce

import time
import numpy as np
import mlx.core as mx

n = 4096
A = mx.array(np.random.default_rng(0).standard_normal((n, n)).astype(np.float32))
B = mx.array(np.random.default_rng(1).standard_normal((n, n)).astype(np.float32))
mx.eval(mx.matmul(A, B))  # warmup / JIT

ts = []
for _ in range(5):
    t0 = time.perf_counter()
    mx.eval(mx.matmul(A, B))
    ts.append(time.perf_counter() - t0)
med = sorted(ts)[2]
print(f"{med*1e3:.1f} ms  {2*n**3/med/1e12:.2f} TFLOP/s")

Control (same wheels, same session): pip install cupy-cuda13x, same
shapes through cupy → 11.5 ms.

Expected behavior

fp32 GEMM within, say, 2× of cuBLAS on supported hardware — or routing
matmul to cuBLASLt on archs without tuned CUTLASS kernels.

Desktop

  • OS: Windows 11 + WSL2 (Ubuntu 24.04), kernel 6.18.33.2-microsoft-standard-WSL2
  • GPU: NVIDIA GeForce RTX 5070 Laptop (Blackwell, sm_120), 8 GB, driver 596.13
  • MLX: 0.32.0 (mlx-cuda-13 0.32.0; nvidia-cublas 13.6.0.2)
  • Python 3.12.3, NumPy 2.3.5, CuPy 14.1.1 (control only)

Additional context

Possibly related: #3056 ("Better support consumer CUDA GPUs") extended
CUDA-graph limits that were tuned for data-center GPUs and could not
saturate consumer Blackwell — same theme of consumer-arch parameters,
though that PR addressed graph limits, not the GEMM kernel selection
itself.

Found while porting an MLX-based (Metal-first) XPS spectral-fitting
engine to CUDA. Correctness parity with the NumPy reference passes
fully (with TF32 disabled — see #3860 for the TF32-by-default report); throughput is the remaining blocker — the
GPU currently loses to the host CPU on GEMM-heavy paths despite the
hardware being demonstrably capable of ~12 TFLOP/s through cuBLAS.

Activity

  1. stoyoda0012-cyber commented on Jul 22, 2026

    @stoyoda0012-cyber
    ContributorAuthor

    Datapoint: rebuilt from source with CMAKE_CUDA_ARCHITECTURES=120
    (CUDA 13.3, RTX 5070 Laptop) — 4096³ fp32 GEMM is unchanged
    (425 ms native vs 435 ms wheel, TF32 off both). So the gap is not
    PTX JIT for a missing arch; CuPy hits 11.5 ms through the same
    cublas wheel, which points at the MLX-side cublasLt invocation
    (heuristic/workspace/dispatch) rather than kernel codegen.

  2. zcbenz commented on Aug 7, 2026

    @zcbenz
    Member

    I can reproduce with 5090 on native Windows build, but not with DGX on Linux. I think this is pure Windows issue that something has super high overhead when launching the kernel, we need some profiling to be sure though.

  3. changed the title [-][PERF] [CUDA] fp32 matmul ~36× slower than cuBLAS on sm_120 (RTX 50 / consumer Blackwell)[/-] [+]matmul ~36× slower than cuBLAS on Windows[/+] on Aug 7, 2026
  4. stoyoda0012-cyber commented on Aug 9, 2026

    @stoyoda0012-cyber
    ContributorAuthor

    Root cause on this box, and it is not the launch path: MLX arrays built from
    host data stay in cudaMallocHost memory for their lifetime, so every kernel
    reading them streams its operands over PCIe. Same shape, same dtype, same
    call, each case in a fresh process:

    mlx 0.32.0, 4096x4096 float32 matmul, TF32 at MLX's default
    
                        device :     7.88 ms    17.44 TFLOP/s
                          host :   775.12 ms     0.18 TFLOP/s
       device_after_freed_host :   803.54 ms     0.17 TFLOP/s
    

    In the third case not even the construction differs, only that a host-built
    array was allocated and freed beforehand.

    RTX 5070 Laptop (sm_120), WSL2 / Ubuntu 24.04, CUDA runtime 13.2, stock
    0.32.0 wheel. Repro is 35 lines, MLX and NumPy only.

    Could you print cudaDeviceGetAttribute(cudaDevAttrConcurrentManagedAccess)
    on the 5090?
    supports_managed_memory() returns false when any device
    reports 0 for it, and the comment there already names Windows and WSL. It is
    0 here, measured. If it is 0 on the 5090 and 1 on the DGX, that is a mechanism
    for your split rather than a coincidence. If your benchmark builds its arrays
    with mx.random.normal or similar, this is not it and I would want to know.

    Mechanism

    supports_managed_memory() (backend/cuda/allocator.cpp:31-53) returning false
    sends unified_malloc() to cudaMallocHost (:60) rather than
    cudaMallocManaged (:58). Host data takes that path: cpu_nd_array_to_mlx →
    out.set_data(mx::allocator::malloc(...)) (python/src/convert.cpp:158)
    reaches malloc_async(size, -1, nullptr) (:252), and move_to_unified_memory
    (:283) returns immediately for device == -1, so nothing moves afterwards.
    mx.load reaches the same allocator.

    The cache then spreads it beyond those arrays. The key is buf->size and
    nothing else (:143-146), reuse_from_cache(size) (:185) runs before the
    device == -1 decision (:201-202), and the residency correction below it only
    fires for buf->device >= 0 (:246). So a cached host buffer satisfies a later
    device request untouched.

    Operands device-generated in all three arms, TF32 off, differing only in how a
    prior host-built buffer was released:

    kept alive freed + clear_cache() freed only
    10.36 ms 10.21 ms 410.26 ms

    Three repetitions in separate processes agree to within 0.2%. 40x, invisible
    from user code. Any program that loads data from NumPy or HDF5 and then
    allocates working arrays hits this.

    repro.py
    """Minimal reproduction for ml-explore/mlx#3861.
    
    On a device with concurrentManagedAccess == 0 (Windows, WSL2, Tegra),
    MLX arrays built from host data are allocated with cudaMallocHost and
    stay in pinned host memory for life, so every kernel reading them
    crosses PCIe. The buffer cache is keyed on size alone, so once such a
    buffer is freed it is also handed out to later device-side allocations.
    
    Expected on an affected machine: three timings that should be identical
    differ by ~40x. Expected on Linux with concurrentManagedAccess == 1:
    all three the same.
    
        python repro_3861.py            # runs all three cases as subprocesses
        python repro_3861.py device     # one case only
    """
    import subprocess
    import sys
    import time
    
    N = 4096
    FLOPS = 2.0 * N**3
    
    
    def run_case(case):
        import numpy as np
        import mlx.core as mx
    
        if case == "device":
            # operands generated on the device
            a = mx.random.normal((N, N))
            b = mx.random.normal((N, N))
        elif case == "host":
            # operands built from host data -- what any data-loading code does
            a = mx.array(np.zeros((N, N), dtype=np.float32))
            b = mx.array(np.zeros((N, N), dtype=np.float32))
        elif case == "device_after_freed_host":
            # device-generated operands, but the cache holds freed host buffers
            h1 = mx.array(np.zeros((N, N), dtype=np.float32))
            h2 = mx.array(np.zeros((N, N), dtype=np.float32))
            mx.eval(h1, h2)
            del h1, h2                     # returned to MLX's buffer cache
            a = mx.random.normal((N, N))
            b = mx.random.normal((N, N))
        else:
            raise SystemExit(f"unknown case {case}")
    
        mx.eval(a, b)
        mx.eval(mx.matmul(a, b))           # warm up
        ts = []
        for _ in range(5):
            t0 = time.perf_counter()
            mx.eval(mx.matmul(a, b))
            ts.append(time.perf_counter() - t0)
        t = sorted(ts)[2]
        print(f"{case:>26} : {t*1e3:8.2f} ms   {FLOPS/t/1e12:6.2f} TFLOP/s")
    
    
    if len(sys.argv) > 1:
        run_case(sys.argv[1])
    else:
        # each case needs a fresh process: the cache is per-process state
        import mlx.core as mx
        print(f"mlx {mx.__version__}, {N}x{N} float32 matmul\n", flush=True)
        for case in ("device", "host", "device_after_freed_host"):
            subprocess.run([sys.executable, __file__, case])
        print("\nIf these differ, arrays built from host data are not on the "
              "device.\nCheck with: cudaDeviceGetAttribute("
              "cudaDevAttrConcurrentManagedAccess)", flush=True)

    Operands that are not row-contiguous get copied to a device buffer by
    check_transpose (matmul.cpp:21-33), which masks the effect. The cases above
    are contiguous.

    Corroborating measurements

    Three concordant signals on a 1 GiB array:

    built by cudaMemGetInfo nvidia-smi streaming read verdict
    mx.random.normal −1.00 GiB +1024 MiB 346.5 GB/s device
    mx.array(numpy) −0.00 GiB −1 MiB 12.6 GB/s host, over PCIe

    The budget closes. At N=4096 with 128×128 tiling each operand is re-read ~32
    times, so operand traffic is 2 × 67.1 MB × 32 ≈ 4.3 GB; at the measured
    12.6 GB/s that predicts 341 ms against 410–425 ms measured with TF32 off.
    Within 20%, from two independently measured quantities.

    Driving cublasLtMatmul from ctypes with everything else held fixed (same
    algorithm, same descriptors, same workspace size) and changing only the
    allocator reproduces it, TF32 on:

    operands median TF/s
    cudaMalloc 8.48 ms 16.2
    cudaMallocHost 410.66 ms 0.33

    The poisoned arm in the cache table lands on the same 410 ms, so two
    independent routes reach one number.

    On TF32, since three regimes are in play: the repro runs at MLX's default and
    gives 775 ms, while my 07-22 comment reported 425 ms with TF32 explicitly off.
    Both are this bug. Once the operands are the bottleneck, the TF32 kernel does
    the arithmetic faster and starves harder on the same PCIe feed. I have not
    measured that decomposition, so take it as the likely reading rather than an
    established one.

    Why nothing else moved: MLX_USE_CUDA_GRAPHS=0 gives 194.82 vs 196.12 ms; a
    source build with CMAKE_CUDA_ARCHITECTURES=120 gave 425 vs 435 ms; the
    cuBLASLt heuristic query costs 0.059 ms against an 18 ms matmul; sweeping the
    workspace ceiling 0→256 MiB through raw cuBLASLt moves 18.5→11.4 ms. None of
    them change where the operands live.

    Chaining matmuls inside one mx.eval gives 0.70 TF/s against 0.33 for
    one-per-eval. Chain intermediates are device-allocated, so after the first
    step each GEMM has one hot operand and one cold, which would give roughly
    this. Not measured directly.

    Two retractions of my own earlier comments

    My 07-22 comment blamed the MLX-side cublasLt invocation (heuristic,
    workspace, dispatch). The heuristic and workspace numbers above rule out two
    thirds of that.

    More usefully as a warning: I tested this residency hypothesis earlier and
    reported it refuted. That test was contaminated twice. I compared mx.array
    against mx.random.normal in one process, where the first arm's freed host
    buffers were already in the cache for the second to reuse, so both arms were
    on host memory and agreed to 0.3%. And I checked bandwidth on an array that
    happened to be device-resident and generalised from it. A
    cudaPointerGetAttributes reading of type=1 was in front of me and I
    explained it away. Fresh processes per case is why the repro spawns
    subprocesses.

    Two handles if you want them, both small: keying the cache on residency as
    well as size (buf->device is already a CudaBuffer member), or promoting
    host buffers on device use, which needs the symmetric demotion since
    device == -1 also backs .item(), numpy export and CPU-stream ops. Happy to
    test patches on this box, or to run the repro with other shapes and dtypes.

  5. changed the title [-]matmul ~36× slower than cuBLAS on Windows[/-] [+]matmul ~36× slower than cuBLAS on Windows when data are allocated in host[/+] on Aug 11, 2026
  6. zcbenz commented on Aug 11, 2026

    @zcbenz
    Member

    Thanks for debugging this, I agree it is the root cause. A possible fix is to force using device memory and doing a synchronous copy for the imported data.

  7. stoyoda0012-cyber commented on Aug 11, 2026

    @stoyoda0012-cyber
    ContributorAuthor

    That covers the case people actually hit. Happy to test a patch on this box
    whenever you have one.

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