Skip to content

Latest commit

 

History

History
828 lines (708 loc) · 43.4 KB

README.md

File metadata and controls

828 lines (708 loc) · 43.4 KB

Benchmarks

Two kinds of benchmark live here:

  • bench_tensor_map.mojo / bench_tensor_map_gpu.mojo (pixi run bench, pixi run bench-gpu) -- numax measured against itself: does its trait-and-TileTensor layer cost anything over a hand-rolled raw-SIMD loop (CPU), and where does its GPU path (map[gpu=True]) actually earn back its own dispatch overhead over the CPU path. See the top-level README.md's Benchmarks section for those two.
  • bench_fusion.mojo (pixi run bench-fusion) -- two chained map calls against one map with a composed step, on CPU and GPU. See the fusion section below.
  • bench_elementwise.mojo (pixi run bench-elementwise) -- numax's serial map against its threaded map_threaded, which is max.algorithm.elementwise underneath. See the threading section below.
  • bench_matmul.mojo (pixi run bench-matmul) -- the Array tier's matmul against MAX's linalg.matmul, to find the size where MAX's blocked, threaded kernel overtakes the generic triple loop. See the matmul section below.
  • bench_linalg.mojo / bench_linalg_gpu.mojo (pixi run bench-linalg, pixi run bench-linalg-gpu) -- the Tensor tier of numax.linalg: BLAS-1, cholesky, lu_factor, solve and qr_factor, each against the linalg.matmul ceiling at the same size, plus a block-size sweep. The cross-language halves are scipy/linalg.py (LAPACK, CPU) and torch/linalg.py / cupy/linalg.py (cuSOLVER, CUDA). See the linalg section below.
  • bench_gpu_roofline.mojo (pixi run bench-roofline) -- not a comparison at all, a diagnosis: how much of the device's memory bandwidth map[gpu=True] actually reaches, whether the ceiling is the memory path or std.math.exp (an identity-copy kernel separates the two), and what per-thread width and block_dim are worth. This is what established that the numbers below are bandwidth-bound rather than compute-bound, and what caught both measurement bugs described under Results.
  • numpy/, mlx/, torch/, thermite/, scipy/, cupy/ (this page) -- numax measured against libraries someone would actually reach for today, on the same machine, for the same kernel.

Every baseline here is a real dependency of its own pixi feature/environment (bench-python for NumPy/MLX/PyTorch, bench-rust for the Rust toolchain thermite needs) — pixi run <task> installs whatever that baseline needs and runs it, the same as any other task in this repo. Nothing here needs a manually-managed virtualenv or a system-wide cargo.

The kernel and methodology

Every benchmark runs the same thing:

gaussian(x) = exp(-x^2)

over float32 arrays of n elements, at six sizes (2^16 through 2^26, 64K to ~67M elements), input x[i] = i * 0.0001 - 50.0. Each measurement is 3 warmup calls followed by 10 timed calls, wall-clock time around the whole operation (dispatch/launch through completion, not an isolated kernel-only time) — what a caller actually experiences, not a best case. Every script also checks its own output against an f64 reference and warns if the max error exceeds 1e-5; none did on the run below.

For the GPU baselines there is one more methodological choice, and it turns out to matter more than anything else on this page: whether the device synchronize happens inside each timed iteration or once after all ten. Every GPU baseline reports both — see Results.

This keeps the comparison to one narrow, well-defined kernel on purpose — it's a statement about elementwise-exp throughput on this machine, not a general verdict on any of these libraries.

The baselines, and why these five

These five are the gaussian baselines. The linalg sweep has three of its own -- SciPy (LAPACK + OpenBLAS), and cuSOLVER through both PyTorch and CuPy -- described in the linalg section at the end of this page, because they answer a different question and were measured on different hardware.

  • NumPy (numpy/gaussian.py, pixi run bench-numpy) — the default reference point for anyone doing numerical work in Python. CPU-only; there's nothing to compare against numax's GPU path here, which is what MLX and PyTorch are for.
  • MLX (mlx/gaussian.py, pixi run bench-mlx) — the closest match to what numax's own GPU path is doing: one array library, one API, a stream=mx.cpu/stream=mx.gpu switch, running on the same GPU numax targets via DeviceContext. Metal on macOS; on Linux it needs an explicit CUDA backend wheel, which pixi.toml selects per platform.
  • CuPy (cupy/gaussian.py, pixi run bench-cupy) — NumPy's API on CUDA, and the closest thing to a native NVIDIA counterpart to what numax's GPU path does. CUDA-only, so it appears in the NVIDIA results below and nowhere else, the mirror of MLX's macOS-only position. Three columns, since "CuPy" is not one number: eager, cupy.fuse()d, and a hand-written cupy.ElementwiseKernel.
  • PyTorch (torch/gaussian.py, pixi run bench-torch) — eager and torch.compile'd, on CPU and on whichever GPU torch can see (CUDA, else MPS — the same device as above). torch.compile traces and JIT-compiles the kernel into a fused device program, which is worth a lot over eager PyTorch on this kernel (roughly 3x on MPS, consistent with three elementwise dispatches becoming one) and roughly nothing over numax, which was already one fused kernel — see Results.
  • Rust thermite 0.2 (thermite/, pixi run bench-thermite) — not an arbitrary Rust SIMD crate: it's the library numax's composable-numeric-type pattern was originally ported from (see the top-level README's introduction). Its NEON backend is "Complete. Mandatory on the architecture" for aarch64, so this runs genuinely vectorized code on this machine, not a scalar fallback.
  • numax itself, CPU (map[gpu=False]) and GPU (map[gpu=True]), via bench_tensor_map_gpu.mojo (pixi run bench-gpu), plus its threaded CPU walk (map_threaded) from bench_elementwise.mojo.

How to run each

pixi run bench-gpu       # numax, CPU + GPU sweep (both sync shapes)
pixi run bench-roofline  # numax, bandwidth diagnosis (needs a GPU)
pixi run bench-numpy     # NumPy, CPU
pixi run bench-mlx       # MLX, CPU + GPU (macOS only)
pixi run bench-torch     # PyTorch, eager + compile, CPU + CUDA/MPS
pixi run bench-cupy      # CuPy, eager + fused + raw kernel (Linux/CUDA only)
pixi run bench-thermite  # Rust thermite, CPU (NEON or AVX2)

pixi run bench-linalg    # numax linalg, CPU -- factorizations, spectral, BLAS-1, block sweep
pixi run bench-signal    # numax signal, CPU -- convolve vs. fftconvolve, filters, welch
pixi run bench-fft       # numax fft, CPU -- fft/rfft/irfft/fft2, us per call and launches
pixi run bench-interpolate # numax interpolate, CPU -- interp, CubicSpline
pixi run bench-stats     # numax stats, CPU -- norm.cdf, histogram, quantile, cov
pixi run bench-core-surface # numax core surface, CPU -- exp, add, scale, compare, sum, and map vs. the named call
pixi run bench-linalg-gpu # numax factorizations, CUDA/Metal (needs a GPU)
pixi run bench-blas1-gpu # numax BLAS-1, CUDA/Metal -- separate, see the Metal note
pixi run bench-solvers-gpu # numax solve_sylvester vs. its two schur calls, CUDA/Metal
pixi run bench-core-surface-gpu # numax core surface, CUDA/Metal -- both sync shapes (needs a GPU)
pixi run -e bench-python bench-scipy-linalg # LAPACK, CPU (OpenBLAS or Accelerate)
pixi run -e bench-python bench-scipy-signal # scipy.signal, CPU
pixi run -e bench-python bench-scipy-fft    # scipy.fft (pocketfft), CPU
pixi run -e bench-python bench-scipy-interpolate # numpy.interp and scipy CubicSpline, CPU
pixi run -e bench-python bench-scipy-stats  # scipy.stats.norm, numpy histogram/quantile/cov, CPU
pixi run -e bench-python bench-numpy-core-surface # numpy exp/add/scale/compare/sum, CPU
pixi run -e bench-python bench-torch-linalg # PyTorch: cuSOLVER on CUDA, MPS on Metal
pixi run -e bench-python bench-cupy-linalg  # cuSOLVER via CuPy, CUDA

Each pixi run bench-* task above resolves and installs whatever that baseline needs the first time it's run (a Python interpreter plus NumPy/MLX/PyTorch/CuPy for the Python ones, a Rust toolchain for the last) into its own pixi environment, cached in .pixi/ like every other environment in this repo -- there's no separate setup step. bench-mlx is declared only on the macOS target, so it does not appear at all on Linux: MLX's Linux backend is an opt-in wheel whose name pins a CUDA major version, and a pin that is only correct on one machine is worse than no baseline. bench-cupy is declared only on linux-64 for the same reason in reverse -- CuPy ships one wheel per CUDA major version and no macOS build at all.

Results

Measured on an Apple M3 Pro (12 CPU cores, 36GB unified memory, ~150 GB/s memory bandwidth), macOS 25.5.0, mojo/max per pixi.toml, NumPy 2.5.2, MLX (Metal GPU device), PyTorch 2.13.0, thermite 0.2.1 (NEON backend). All throughput in millions of elements/sec — higher is better.

These are one machine's numbers. The same sweep on Linux/x86_64 with an NVIDIA A10G is in its own section below, which is also where CuPy appears; the figures differ by roughly 4x on the GPU, and the conclusions about where the time goes are the ones that carried across both.

Read the roofline first

This kernel moves 8 bytes per element (one float32 read, one write) no matter how it is written, so at large n every library here is competing for the same memory bandwidth, not for arithmetic. That puts a hard ceiling on the whole table: 150 GB/s ÷ 8 bytes = 18,750 M elem/s. Anything within a few percent of that is at the hardware limit, and a "1.1x win" up there is a different claim from a 1.1x win at 64K.

Confirmed rather than assumed: bench_gpu_roofline.mojo runs an identity copy (no arithmetic at all) through the same walk and gets the same throughput as gaussian does — 118 vs 120 GB/s at 67M. The exp is free; the memory traffic is everything.

Two GPU columns, and why mixing them was wrong

An earlier version of this file claimed "every GPU number includes the same host round-trip (dispatch + synchronize)". That was false, and it flattered PyTorch by roughly 1.6x at the top end: numax's benchmark synchronized inside each timed iteration while torch/gaussian.py synchronized once after all ten, so one was measuring per-call latency and the other pipelined throughput. Those are both legitimate questions, so every GPU baseline now reports both:

  • per-call — synchronize inside each iteration. One full launch-through-completion round trip, i.e. what a caller pays for a single call.
  • amortized — enqueue all iterations, synchronize once. Dispatches pipeline, so this is steady-state throughput for back-to-back work.

A second, separate measurement bug was found at the same time and fixed in bench_tensor_map_gpu.mojo: it accumulated the CPU and GPU timings inside one loop, so a ~28 ms bandwidth-saturating CPU pass ran between every timed GPU launch, on the same unified memory. Splitting them into separate loops (and warming each measurement) moved the reported 67M GPU figure from ~9,400 to ~15,700 M elem/s without changing a line of numax. The old numax GPU column was measuring interference.

CPU-only:

numax gets two columns because it has two CPU walks: serial map (map[gpu=False], one thread, SIMD-vectorized) and map_threaded (max.algorithm.elementwise, multi-threaded). The serial one is what this table used to report, which undersold it by 3-5x at large n.

n numax map numax map_threaded thermite (NEON) NumPy MLX torch eager torch compile
65,536 2,348 3,744 1,706 680 249 1,194 576
262,144 2,340 2,776 1,298 660 811 1,737 2,214
1,048,576 2,355 11,560 1,311 511 1,586 2,165 3,544
4,194,304 2,349 10,099 1,508 626 1,647 2,221 4,136
16,777,216 2,343 8,736 1,627 508 1,893 1,989 4,015
67,108,864 2,347 9,026 1,632 493 1,954 1,935 4,046

map_threaded is the median of three runs and is genuinely noisy — individual runs at 1M ranged 7,955-12,307. Serial map varies by under 2%.

GPU (same Metal device), per-call sync:

n numax MLX torch eager torch compile
65,536 301 328 200 231
262,144 639 864 715 1,007
1,048,576 3,230 3,242 2,810 3,320
4,194,304 7,897 3,684 3,701 9,615
16,777,216 11,722 4,514 4,792 12,332
67,108,864 14,465 4,866 4,807 13,831

GPU (same Metal device), amortized sync:

n numax MLX* torch eager torch compile
65,536 1,280 899 888 799
262,144 4,064 2,772 2,580 4,800
1,048,576 13,206 2,458 4,612 9,119
4,194,304 13,902 3,776 4,423 13,080
16,777,216 15,086 3,896 5,082 15,695
67,108,864 15,755 3,860 4,809 14,380

* MLX's amortized column is not comparable at large n, for a reason specific to MLX rather than to MLX's speed: MLX is lazy, so an unreferenced graph node is never evaluated, and forcing only the last of ten would time one kernel instead of ten. The benchmark therefore has to hold all ten outputs live — ten 268MB buffers at 67M — and that memory pressure makes its amortized number worse than its per-call one. Read MLX's per-call column.

Reading this honestly, not as an numax-wins scoreboard:

  • At matched methodology, numax and torch.compile on MPS are at parity on the GPU, both pinned against the bandwidth roofline. At 67M amortized, numax reaches 15,755 M elem/s (126 GB/s, 84% of peak) and torch.compile 14,380 (115 GB/s, 77%); per-call the two are 14,465 and 13,831. They trade wins by a few percent in both directions across the sweep, which given the run-to-run spread is better described as a tie than as a ranking. The earlier "torch.compile is fastest by a wide margin" conclusion did not survive fixing the two measurement bugs above.
  • The kernel-fusion theory for that old gap was wrong, and is worth retracting explicitly. It was inferred from the shape of the numbers: Inductor fusing exp(-(x*x)) into one Metal kernel instead of three dispatches. But numax's gaussian_step was already one fused kernel, so fusion could never have explained an numax-to-compile gap. It does plausibly explain eager-to-compile (4,809 vs 14,380 amortized at 67M is close to a 3-passes-to-1 ratio), which is where the inference belongs.
  • numax's threaded CPU walk is the fastest CPU number here above ~1M (8,700-11,600 vs torch.compile's 3,500-4,100), and it beats this machine's own GPU path per-call until about 4M elements. For a single elementwise pass on an M3 Pro, threading the CPU is the better first move and the GPU only pays off at scale.
  • Serial numax CPU is flat across every size (~2,350 M elem/s), which says more about Mojo's NEON codegen and std.math.exp than anything numax-specific — pixi run bench already showed numax's layer adds ~0.2% over the same raw loop.
  • numax CPU outperforms thermite (roughly 1.4-1.8x serial, more when threaded), which is worth being skeptical of rather than triumphant about: the two aren't running identical code paths (thermite's run is strictly in-place, dispatch_dyn!'s runtime ISA check happens on every timed call, and std.math.exp vs. thermite's TranscendentalMath::exp may not be the same approximation or accuracy trade). Attributing the gap would need a same-ISA, same-approximation microbenchmark of exp alone.
  • GPU dispatch overhead dominates below ~1M for everyone. Every library here is under 3,400 M elem/s at 1M per-call and under 1,300 at 64K — a fixed cost of a few hundred microseconds that no amount of kernel quality recovers. numax's GPU path only overtakes its own serial CPU path above ~1M, and its threaded CPU path above ~4M.
  • NumPy is the slowest CPU number throughout, consistent with it not doing the same kind of native SIMD-width dispatch the other four do.

Rerun all five on a different machine before trusting these numbers to generalize — this is one data point, on one chip, for one kernel.

Run-to-run spread matters for reading the GPU tables specifically, since the parity claim above rests on differences of a few percent. Repeat runs of numax at 67M moved between 14,081-14,465 per-call and 15,074-15,755 amortized, i.e. ±3%, which is the same order as its margin over torch.compile — hence "tie" rather than "wins". Below 1M the per-call numbers are far worse: 64K moved by up to 2x between runs on the same machine, so treat that row as an order of magnitude, not a measurement.

The same sweep on NVIDIA

Everything above is Metal. This section re-measures it on Linux/x86_64 with a CUDA GPU, which is where CuPy joins the set: it is CUDA-only, so it cannot appear in the Metal tables, exactly as MLX cannot appear here.

NVIDIA A10G (24GB GDDR6, 600 GB/s), 64 CPU cores, driver 580.126, CUDA 12.8, CuPy 14.2.0, NumPy 2.5.2, PyTorch 2.13.0+cu130, thermite 0.2 (AVX2, X86V3 backend). The roofline for this device is 600 GB/s ÷ 8 bytes = 75,000 M elem/s, so read every GPU number against that, not against the Metal tables above.

CuPy gets three columns because "CuPy" is not one number. eager is cupy.exp(-(x * x)) as written, three kernels and two temporaries; fused is the same expression under cupy.fuse(), one kernel; kernel is a hand-written cupy.ElementwiseKernel. That last one is the honest comparison for numax, whose step is a single fused kernel by construction.

GPU (same CUDA device), amortized sync:

n numax CuPy kernel CuPy fused CuPy eager torch compile torch eager
65,536 17,852 6,731 6,020 1,849 1,224 2,277
262,144 70,374 27,579 24,635 8,421 3,963 9,203
1,048,576 68,789 52,428 52,776 18,207 18,213 25,360
4,194,304 58,753 57,718 57,403 19,476 51,489 19,301
16,777,216 60,913 60,127 60,168 20,155 55,153 19,757
67,108,864 61,653 61,051 61,166 20,375 56,245 19,905

GPU (same CUDA device), per-call sync:

n numax CuPy kernel CuPy fused CuPy eager torch compile torch eager
65,536 7,317 4,523 4,193 1,639 950 1,603
262,144 27,417 16,896 15,777 5,088 3,399 3,920
1,048,576 48,203 33,905 31,192 14,930 12,929 19,437
4,194,304 52,077 50,073 49,426 17,725 31,945 17,436
16,777,216 59,016 57,712 57,679 19,824 47,108 19,452
67,108,864 61,013 60,352 60,213 20,239 53,670 19,803

CPU-only (64 cores):

n numax map numax map_threaded thermite (AVX2) NumPy torch eager torch compile
65,536 1,732 2,228 1,349 283 630 770
262,144 1,793 6,929 1,367 283 681 1,796
1,048,576 1,812 10,797 1,366 401 953 8,059
4,194,304 1,730 6,125 1,342 357 973 13,756
16,777,216 1,720 13,167 1,332 307 380 1,619
67,108,864 1,367 8,733 1,329 316 468 1,880

What this says, and what it does not:

  • numax's map is at parity with a hand-written CUDA kernel. At 67M amortized it is 61,653 M elem/s against ElementwiseKernel's 61,051 and cupy.fuse()'s 61,166 — 493 GB/s, 82% of this device's peak. Three implementations within 1% of each other at 82% of peak is the roofline, so the claim is parity rather than a win: a generic FloatLike kernel, carrying autodiff and device independence, costs nothing against CUDA C written by hand for this one expression.
  • The fusion argument is visible directly rather than inferred. CuPy eager sits at 20,375 and its fused form at 61,166 — a ratio of 3.002 against the three passes the expression makes unfused. This is the measurement the Metal section had to infer from PyTorch's numbers and got wrong once. A numax kernel never has an eager column to lose, because composition happens inside step before any tensor walk.
  • torch.compile trails by about 9% at the top end (56,245 amortized, 75% of peak) and needs 4M elements before its compiled kernel beats its own eager path at all. Below that, Inductor's launch overhead costs more than the fusion saves.
  • Below 1M, the amortized GPU numbers are cache, not DRAM. numax reads 70,374 M elem/s at 262K, which is 563 GB/s and would be 94% of a peak the DRAM cannot sustain — a 1MB buffer fits in the A10G's 6MB L2, so those rows measure a different memory system than the 67M row. Compare rows down a column, not across the size sweep.
  • On CPU the threading result holds and torch.compile does not. map_threaded is 5-8x serial map above 256K, and beats every other CPU column at 16M and 67M. torch.compile's CPU path wins the middle of the sweep (13,756 at 4M) and then collapses to 1,619 at 16M. Both are noisy enough that the ordering in any single row is worth less than the shape: the CPU numbers here are one to two orders of magnitude below the GPU ones, which is the difference between 64 cores and an A10G.
  • Run-to-run spread at 67M is ~0.2% on this device, an order of magnitude tighter than the ±3% seen on the M3 Pro: repeats read 61,653 then 61,525 for numax, 61,166 then 61,067 for cupy.fuse(). That is what makes a sub-1% ordering worth reporting at all here, and it still is not worth calling a win.
  • numax serial CPU runs 1.0-1.3x thermite's AVX2 backend, narrowing to a tie at 67M where both are DRAM-bound, against the 1.4-1.8x measured on the M3 Pro's NEON backend. Same caveat as there: different exp approximations, in-place vs. separate output buffer, and a runtime ISA check on every thermite call.

Fusion: chaining two maps vs composing inside step

pixi run bench-fusion, same machine. Both sides compute 2.5 * exp(-x^2): chained runs map(gaussian) then map(scale) (two passes, two dispatches), fused runs one map whose step is scale(gaussian(x)). Millions of elements/sec.

CPU, via map_threaded:

n chained fused speedup
1,048,576 3,865 11,335 2.93x
4,194,304 4,205 10,968 2.61x
16,777,216 3,979 8,170 2.05x
67,108,864 4,180 7,886 1.89x

GPU, via map[gpu=True]:

n chained fused speedup
1,048,576 1,941 5,533 2.85x
4,194,304 4,035 12,253 3.04x
16,777,216 7,239 13,936 1.92x
67,108,864 7,306 13,973 1.91x

Identical results (max |diff| = 0.0 throughout), 2-3x apart in speed. So "compose inside step, don't chain map calls" is not a style preference, it's the difference between one pass and two — and it costs nothing to follow, because composing FloatLike values is just writing the expression.

Two cautions on reading the GPU column. First, this benchmark enqueues all timed iterations and synchronizes once at the end, so per-call host round-trip is amortized; the cross-language table above pays a synchronize per call, and the two sets of numbers are therefore not comparable. Second, this is the most favorable possible fusion case — two cheap elementwise ops where the second does almost no arithmetic, so the chained version is nearly pure extra memory traffic.

What it does support is the structural claim: numax needs no fusion pass to get this, because a FloatLike kernel composes before any tensor walk begins. What it does not support is a claim of parity with Inductor, which fuses code the user wrote as separate operations — numax requires the caller to write the composition. max.algorithm.dual_elementwise was evaluated as a way to fuse two independent elementwise ops into a single launch, and is unusable here: unlike elementwise, it has only the compile-time-parameter form, so passing a closure fails with "failed to infer parameter __origins__", and a non-capturing function has no way to reach the tensors (its signature passes only a coordinate). It also wouldn't address this case, since it fuses independent ops rather than chained ones.

Threading: map vs map_threaded

pixi run bench-elementwise, same machine and same gaussian kernel. numax.core.functional.map walks the tensor on one thread at native SIMD width; numax.core.functional.map_threaded hands the same step to max.algorithm.elementwise[target="cpu"], which vectorizes and distributes across cores. Millions of elements/sec, higher is better.

n map map_threaded speedup
65,536 2,199 1,424 0.65x
262,144 2,267 3,037 1.34x
1,048,576 2,342 12,206 5.21x
4,194,304 2,323 10,538 4.54x
16,777,216 2,334 8,818 3.78x
67,108,864 2,312 7,804 3.38x

The threaded path costs more than it saves below about 250K elements, then wins by 3-5x. Two things stand out beyond the obvious:

  • Threaded CPU beats this machine's GPU until about 16M elements. Against the GPU table above, map_threaded at 1M elements (12,206) is ~5.6x numax's own Metal path at the same size (2,173), and stays ahead through 4M. Only at 16M+ does the GPU pull in front. For a single elementwise pass on an M3 Pro, threading the CPU is the better first move — the GPU's advantage needs a lot of elements to pay off its dispatch.
  • The threaded path flushes denormals to zero. Results below the smallest normal float32 (~1.2e-38) come back as exactly 0 where the serial walk returns the denormal — the max |diff| column is exactly that threshold at every size where the input sweep reaches it. Verified directly: at x = -9.3639, serial gives 8.32e-39 and threaded gives 0.0. Everything at or above the threshold is bit-identical. This is MAX's worker-thread FP environment, not anything numax chooses, and it's documented on map_threaded rather than papered over.

map_threaded is a separate function rather than a threads: Bool parameter on map, because elementwise needs a DeviceContext and map's signature is shared with the GPU kernel body that enqueue_function launches — an argument that cannot cross that boundary. Same reasoning that keeps reduce_block_gpu separate from reduce.

Matmul: where MAX overtakes the generic loop

pixi run bench-matmul, same machine. MAX's linalg.matmul (blocked, vectorized, threaded, TileTensor of raw float32) against numax.linalg.matmul (naive triple loop over Array[T, n*n], generic in T: FloatLike). Nanoseconds per n x n product, lower is better. The batched column runs Plain[dtype, 4], so one call does four independent products — one per SIMD lane — and the time is divided by four to stay comparable.

n MAX numax scalar numax batched (per matrix)
4 102 57 15
8 143 323 74
16 366 1,870 492
32 380 14,335 3,690
64 900 117,440 30,170

Both implementations agreed to the last bit at every size (the benchmark checks this, and prints max |diff| = 0.0), so this is purely a speed comparison of two correct routines.

The crossover is early and sharp: MAX wins from n = 8 on for a single matrix, from n = 16 on even against the 4-wide batched version, and by n = 64 it is ~130x ahead of the scalar loop. That is the expected shape — blocking and threading are worth exactly nothing at n = 4, where MAX's per-call overhead (~100ns) is most of its time, and worth two orders of magnitude by n = 64.

So the Array overload of numax.linalg.matmul was not replaced by a call into MAX, and the reason isn't performance:

  • The two take different arguments and cannot substitute for each other. MAX needs a TileTensor backed by device or host memory; numax's matrix is an Array[T, n*n] living in registers inside a per-element kernel, which is what makes it callable from inside map[gpu=True] at all. Adapting one to the other means materializing a buffer per matrix, which costs more than the multiply at these sizes.
  • MAX's is monomorphic in dtype, so it cannot carry a Dual, a Compensated, or a Complex. Differentiating a matmul is the entire reason numax's exists.

The practical guidance, now in numax/linalg/blas.mojo's docstring as well: if your entries are plain dtype and your matrix is bigger than about 8x8, cross to the Tensor tier. to_tensor, then the same matmul name, which resolves to the overload that is MAX's linalg.matmul — numax allocates the destination, takes .tile()s and calls the kernel, so the dispatch across Apple, NVIDIA and AMD is MAX's and the table above is the number you get.

That overload did not exist when this benchmark was written, and the guidance here used to be "call MAX directly, numax deliberately does not wrap it". It does now, which is why the two spellings sit beside each other in one module instead of one of them being an instruction to leave the library.

Dense linalg: the Tensor tier against LAPACK and cuSOLVER

pixi run bench-linalg (CPU) and pixi run bench-linalg-gpu (device), against bench-scipy-linalg, bench-torch-linalg and bench-cupy-linalg. Measured on an AMD EPYC 7R32 (16 cores / 32 threads, 64 MiB L3) with an NVIDIA A10G, not on the Apple machine the rest of this page uses -- the linalg tables and the gaussian tables are different hardware and must not be read across.

Five methodological choices, all of which change the numbers:

  1. float32 everywhere, CPU and GPU. Not a preference: MAX's linalg.matmul does not compile for GPU at float64 at all (its GEMV path reduces through warp.shuffle, which has no float64 case, and numax's operands are runtime-shaped so every branch of the dispatch gets instantiated). A float64 CPU table beside a float32 GPU one would be comparing two computations, so both halves are float32.
  2. Same matrices in all five harnesses. SPD is 1/(1 + |i - j|) off the diagonal and n on it; general is ((37i + 11j) mod 17)/16 - 0.5 off the diagonal and n on it. Both diagonally dominant, so no row is measuring a conditioning problem, and every harness spells the generators identically.
  3. Standard LAPACK flop counts, so GFLOP/s is comparable across implementations: n^3/3 for Cholesky, 2n^3/3 for LU, 2n^2(m - n/3) for a Householder QR, LU plus two substitutions for solve.
  4. The synchronize is inside the timed loop on every GPU harness. A factorization is a chain of dependent launches and cannot pipeline, so the honest number is launch-through-completion per call.
  5. A ceiling row, not just baselines. The first row of each table is linalg.matmul at the same size. A blocked factorization's cubic term is that call, so the fraction of the ceiling a factorization reaches is how much of its work reached MAX.

Every row also carries a residual -- L L^T against A, A x - b, Q R against A -- so a fast wrong answer cannot hide. One caveat on the GPU residuals: they are computed with a float32 GEMM, so the column is bounded by that GEMM's own precision rather than by the factorization's.

GFLOP/s at n = 1024 (qr at n = 512)

CPU:

op numax SciPy (LAPACK + OpenBLAS)
matmul (ceiling) 776 833
cholesky 22.2 99.5
lu_factor 20.1 43.9
solve 20.4 52.6
qr 4.4 (block=16), 9.6 (block=4) 12.4

A10G:

op numax PyTorch CuPy
matmul (ceiling) 20,459 15,342 14,995
cholesky 62.5 595.0 349.9
lu_factor 30.6 282.9 266.8
solve 28.1 257.6 257.9
qr (n=512) 8.4 80.0 79.1

Re-verified under max-core 26.6 / mojo 1.1 (08a161e), same EPYC 7R32 + A10G box. Every CPU row rose 14-44% from the session above -- matmul's own ceiling went 656 to 776 GFLOP/s, and the four factorizations improved by more than that, so the panel side gained on top of the GEMM. cholesky's A10G number first came back at 44.6 GFLOP/s (-12.5% from 51.0) while its ceiling and its three siblings held. Root cause: its device default tiled the trailing update (tile = 512) for a memory saving this docstring called free in launch cost -- true at the previous pin, a 40% to 3.5x cost at this one as n grows. Fixed by defaulting tile to n (untiled) on a device; the number above is post-fix, 22% ahead of the original 51.0. Full sweep and the fix itself are in numax/linalg/cholesky.mojo's docstring.

MAX's GEMM is not what is slow. It reaches 79% of OpenBLAS on the CPU and beats cuBLAS's FP32 path on the A10G -- 20.5 against 15.3 TFLOP/s. It is also less accurate on the same product: max residual 8.4 against cuBLAS FP32's 3.4, where cuBLAS with TF32 enabled gives 18.2 at 25.2 TFLOP/s (measured directly). So MAX's float32 GEMM sits between the two vendor paths on both speed and error.

What is slow is the panel and the launch count. Each block step is a single-block panel kernel -- one SM on the device, effectively serial on the CPU -- followed by a host launch of the trailing GEMM. At block = 32 and n = 1024 that is 32 dependent launches around 32 panels of O(n * block^2) work that no GEMM touches. cuSOLVER's 6-12x is a parallel panel, not a better multiply, and that is the next thing to fix here.

The block-size sweep is the same finding from the other side. At n = 1024: cholesky 22.99 ms at block=32 against 29.66 at 16 and 30.11 at 64; lu_factor 41.43 at 16 against 43.87 at 8 and 58.31 at 32; qr_factor 168 at 4, 203 at 8, 359 at 16, 1502 at 128. A bigger block makes the panel quadratically more expensive faster than it makes the GEMM more efficient -- which is exactly what a panel-bound factorization looks like. cholesky and lu_factor keep their defaults (32 and 16); qr_factor's default of 16 is right at n <= 512 and costs about 2x at n = 1024, so pass block explicitly for a large QR.

BLAS-1, GB/s at n = 67M

Bandwidth over the traffic each operation must move, at 256 MiB -- past this box's L3 on either processor:

op numax CPU SciPy CPU numax A10G PyTorch A10G CuPy A10G
dot 70.6 27.9 298.9 503.9 244.9
nrm2 71.1 13.9 169.2 495.9 163.5
asum 67.4 48.5 169.1 161.2 163.5
axpy 57.9 78.3 444.0 475.8 292.8

The reductions beat OpenBLAS's own level-1 routines on CPU by 1.4-5x, which is the single clearest payoff of routing them through MAX's rowwise scaffolder: sdot and snrm2 are one thread, ReduceSum under rowwise is all sixteen cores. On the GPU they land between CuPy and PyTorch.

axpy is the exception, and its signature is the reason rather than its kernel: it returns a new vector instead of updating y in place, so every call allocates and first-touches its result. Re-verified under max-core 26.6/mojo 1.1: axpy rose from 25.3 to 57.9 GB/s on the CPU and 342.4 to 444.0 on the A10G, dot/nrm2/asum holding within a couple percent on both, closing more than half its old gap to OpenBLAS's in-place saxpy. The ms breakdown below predates this run. Measured at n = 16M: the whole call is 8.5 ms, the elementwise pass alone is 4.3 ms, and the zeroed allocation alone is 4.7 ms. Half the call is allocation, which is why OpenBLAS's in-place saxpy is ahead. Reuse the result on a hot path.

One row in the raw output deserves reading carefully rather than comparing: at n = 16M a float32 vector is exactly 64 MiB, this box's L3, so the CPU reductions there run out of cache and report 264-362 GB/s. That row is in the harness deliberately, next to a memory-resident one.

The same sweep on an Apple M3 Pro

A different machine from the EPYC/A10G tables above -- Apple M3 Pro, 12 cores (6P + 6E), an 18-core GPU, 36 GB unified -- so these are their own tables and no row may be read across. float32, n = 1024, same LAPACK counts, same generators.

Two baseline facts change how these read. SciPy here links Apple Accelerate, not OpenBLAS, so LAPACK runs on the AMX coprocessor and the CPU baseline is 2-5x harder than the EPYC one. And MLX ships no GPU linalg at all -- cholesky, lu_factor, qr and solve each refuse a GPU stream with "not yet supported on the GPU" -- so PyTorch's MPS backend is the only Metal baseline that exists.

CPU:

op numax SciPy (LAPACK + Accelerate)
matmul (ceiling) 1,475* 1,393
cholesky 83.4 280.1
lu_factor 86.9 231.9
solve 80.3 162.8
qr 34.0 52.0

Metal:

op numax PyTorch (MPS)
matmul (ceiling) 1,800 1,143
cholesky 65.2 125.0
lu_factor 18.8 51.5
solve 16.8 20.9

BLAS-1, GB/s at n = 67M:

op numax CPU SciPy CPU numax Metal PyTorch MPS
dot 113.8 102.3 115.3 121.8
nrm2 89.2 29.8 106.2 4.3
asum 116.0 72.1 106.2 39.0
axpy 91.5 109.6 58.0 116.8

The CPU ceiling row is not a kernel comparison. MAX's CPU matmul dispatches to Apple's cblas_sgemm on macOS whenever every operand is float32 (linalg/matmul/cpu/apple_accelerate.mojo), which is exactly this table, so numax and SciPy are calling the same GEMM and the 14% is call overhead. At float64, where the gate does not fire, MAX's own kernel is 264 GFLOP/s against Accelerate's dgemm at 365 -- 0.72x, matching the 0.79x of OpenBLAS on the EPYC. The upshot is cleaner than a win: on this machine the factorization gap is entirely the blocked algorithm, since the multiply underneath is literally LAPACK's own. MAX's Metal GEMM does beat PyTorch's 1,812 to 1,143 -- the Accelerate gate is CPU-only, so that one is like-for-like. The BLAS-1 reductions beat Accelerate by 1.7-3.2x, the same result and the same reason as the EPYC table. solve on Metal reaches 0.80 of PyTorch, the closest any factorization gets to parity on either processor. cholesky moves ~10% between runs at n = 1024 here; read it as a range.

Two harness defects had to be fixed before any of this could be measured, and both are worth knowing about:

  • bench-linalg-gpu did not build on Metal at all. It failed with "Metal Compiler failed to compile metallib" before running anything -- not a defect in any kernel, but a limit on one module: bisection put every factorization and every size through on its own, and both proper subsets build, so only the full set fails. BLAS-1 now lives in bench_blas1_gpu.mojo behind pixi run bench-blas1-gpu.
  • torch/linalg.py was CUDA-only in four places, including .double(), which MPS rejects outright. Its float64 references now run on the host on both backends.

The 0.2 surfaces: spectral, signal, interpolation, statistics

Apple M3 Pro, float32, numax against SciPy 1.18.1 on Accelerate, from bench-linalg's spectral table, bench-signal, bench-interpolate and bench-stats with their bench-scipy-* baselines. Ratios are numax / SciPy on time, so above one is numax ahead.

area ahead behind
spectral, n = 1024 -- eigvalsh 0.11, eigvals 0.06, svdvals 0.02, schur 0.02, eigh 0.015, svd 0.002: the band iterations run on the host, and with vectors that is O(n^3) scalar Givens
convolution direct convolve within 1.2-2x of SciPy to 128 taps fftconvolve about 3x behind pocketfft at 2^18 points, down from 14x once the engine fused its first six stages and went radix-4; the crossover is near k = 100 at m = 4096 and k = 300 at 65536, from ~250 and ~550
filters medfilt 2.0x, savgol_filter 1.9x, welch 12.4x lfilter 0.08, filtfilt 0.44 -- Float64 host recurrences over a List
interpolation interp 9.4x, CubicSpline evaluation 3.9x CubicSpline construction 0.3x (host tridiagonal solve, a quarter of a millisecond)
statistics norm.cdf 5.4x, histogram at par quantile 0.05 (host sort), cov/corrcoef 0.11 (host loop)

The full tables, and what each gap is made of, are in docs/performance.md under "The 0.2 surfaces, measured". The one-line summary: everything that is one elementwise or one batched transform is ahead of SciPy; everything that is a host loop over a List is behind it, and by the ratio of a scalar loop to C. The spectral vector accumulations are the largest of those loops and the first thing to move.

The ceiling row overstates the gap

Every table here opens with linalg.matmul at n x n x n. A blocked factorization never issues that GEMM -- its trailing update is rank-block. On the M3 Pro through Accelerate, at n = 1024: the square product runs at 1,355 GFLOP/s, rank-128 at 668, rank-64 at 470, rank-32 (cholesky's block) at 248 and rank-16 (lu_factor's and qr_factor's) at 149. So block = 32 gives up 5.4x and block = 16 9x before the panel costs anything, and on Metal rank-16 is 168 against the square 2,394.

That does not overturn the panel diagnosis -- the block sweep still finds its optimum at a small block even though each doubling buys ~1.7x on the GEMM, which means the panel term is steeper than the square ceiling alone suggests -- but "reaches 12% of the ceiling" is not a claim the square row supports. The honest denominator for cholesky at block = 32 is 248.

Linux x86_64 re-run for 0.3

A second full pass on AMD EPYC 7R32 (64 vCPU, AVX2) with an NVIDIA A10G, CUDA 12.8 toolkit, Mojo 1.1 and max-core 26.6, every task in docs/performance.md's task list, float32, CPU and GPU kept apart. The tables are in docs/performance.md; the short version:

  • The Gaussian sweep at 2^26 elements: numax on the A10G 60,939 M elem/s per call and 61,519 amortized, against CuPy's hand-written kernel at 60,275 and 61,037, torch.compile at 53,734 and 56,199, and torch eager at 19,801. The identity copy is 489.3 GB/s against the Gaussian's 488.7, so the exp is free. On the host, map is 1,418, map_threaded 8,298, NumPy 314, thermite 1,334 and torch.compile 1,813.
  • Dense linalg on the A10G at n = 1024: numax's matmul ceiling is 21,848 GFLOP/s against PyTorch's 14,924 and its cholesky/lu_factor/solve/ qr_factor are 50.6/44.6/39.3/17.3 against 598/282/257/269 (cuSOLVER). On the host, cholesky/lu_factor/solve/qr_factor are 17.3/17.0/15.7/4.0 against SciPy's 52.3/46.1/46.1/15.5, with lu_factor ahead of SciPy at n = 4096 (79.3 against 49.5).
  • Where the host loses: fft at 2^20 is a third of pocketfft, rfft an eighth, fftconvolve 8x slower than SciPy at 4096 x 8, quantile a third of NumPy's. Where it wins: interp 15.7x, norm.cdf 48x, cov 4.4x, welch 7.4x, medfilt 9.2x.
  • bench-cupy-linalg does not run on this host (CUBLAS_STATUS_INVALID_VALUE from cupy-cuda12x on a CUDA 13 driver); its column is from the earlier session.

ROCm

Unmeasured, and the tables say nothing about it. numax reaches every accelerator the same way -- pass target="gpu" and let linalg.matmul dispatch Apple simdgroup, CDNA, RDNA or cuBLAS underneath, with no per-architecture code anywhere in numax -- so the coverage is inherited from MAX's dispatch. That is a claim about what compiles and runs plus what MAX supports, not a performance claim about anyone else's hardware.

Metal was in this position too until the M3 Pro tables above; it is measured now. The distance between "coverage is inherited" and "measured" turned out to be two harness defects rather than anything in the library, which is the argument for measuring ROCm rather than assuming it.