Skip to main content

intro_numba.py walked one function down the tower: Python bytecode → typed IR → LLVM IR → x86-64. JAX is JIT too, but it gets there by a different route — instead of type-specialising Python bytecode, it traces the function by running it once with abstract stand-ins for the arguments, recording every array operation that fires. The recording is the mini language; ordinary Python is just there to generate it.

import jax
import jax.numpy as jnp
import numpy as np

jax.config.update("jax_enable_x64", True)
def mul(C, A, B, α=True, β=False):
    return α * (A @ B) + β * C

Same function, unchanged, works for both backends: NumPy dispatches on the concrete ndarrays passed in; JAX dispatches the same way on jnp.ndarrays. Neither call site knows which library it’s talking to — that’s the duck typing numba’s explicit signature opted out of.

M = 16
N = 12
K = 32
α = 2.0
β = np.pi
A = np.random.randn(M, N)
B = np.random.randn(N, K)
C = np.random.randn(M, K)

A_j, B_j, C_j = jnp.asarray(A), jnp.asarray(B), jnp.asarray(C)
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
%timeit res = mul(C, A, B, α, β)
1.86 μs ± 3.4 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
mul_jax = jax.jit(mul)
mul_jax(C_j, A_j, B_j, α, β).block_until_ready();  # first call: trace + compile, discard timing
%timeit res = mul_jax(C_j, A_j, B_j, α, β).block_until_ready()
6.17 μs ± 238 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

mul_jax is slower than plain mul, and slower still against numba’s fastest, fully-typed version from intro_numba.py — worth bringing in directly, for a fair three-way comparison at the same problem size:

from numba import jit as numba_jit

mul_numba = numba_jit("f8[:, ::1](f8[:, ::1], f8[:, ::1], f8[:, ::1], f8, f8)", nopython=True, nogil=True)(mul)
mul_numba(C, A, B, α, β);  # warm up: compile
%timeit res = mul_numba(C, A, B, α, β)
744 ns ± 0.505 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

Roughly: numpy ~2 μs, numba under 1 μs, jax several μs — slowest of the three, despite XLA fusing the same arithmetic numba fuses. The FLOPs here are tiny (M, N, K = 16, 12, 32): the actual multiply-add work is over before it starts to matter, so what’s being measured is really each dispatcher’s fixed cost per call. Numba’s dispatcher is a thin, typed wrapper straight into machine code. JAX’s is not: every call flattens the arguments into a pytree, looks up the compiled executable in a cache keyed on their shapes/dtypes, and hands the buffers to XLA’s runtime (PjRt) to launch as a device computation — a heavier pipeline built for a different regime: kernels large enough, or repeated often enough (inside jax.lax.scan/vmap/a training loop), that dispatch cost is amortised.

If that story is right, the gap should close as the array gets big enough for compute to dominate dispatch. Test it, at 1024³ instead of 16×12×32:

M_big, N_big, K_big = 1024, 1024, 1024
A_big = np.random.randn(M_big, N_big)
B_big = np.random.randn(N_big, K_big)
C_big = np.random.randn(M_big, K_big)
A_big_j, B_big_j, C_big_j = jnp.asarray(A_big), jnp.asarray(B_big), jnp.asarray(C_big)

mul_numba(C_big, A_big, B_big, α, β)  # same compiled function: numba's signature fixed dtype
mul_jax(C_big_j, A_big_j, B_big_j, α, β).block_until_ready()  # new shape: jax retraces, recompiles
Array([[  44.13832555,   32.46732004,   34.69194233, ...,   91.6443876 ,
          60.10052834,  -35.3131456 ],
       [ -87.67580265,  101.73219404,    5.17908904, ...,   53.80450806,
        -141.39303545,   80.43913773],
       [ 216.93476678,  -14.57996161,   59.98524525, ...,   10.90003678,
          65.6284765 ,  -64.11496431],
       ...,
       [ -98.06125531,   65.43454281,  -18.13363113, ...,  -42.60950986,
          59.2655379 ,  -26.81711222],
       [  18.85388987,   38.80815166,   85.82871406, ...,   34.72536239,
         -22.64519432,  -28.97648271],
       [ -58.89291359,  -12.58191867,  -39.65125629, ...,   12.86065499,
          26.32409715,  -22.38884318]], dtype=float64)
%timeit res = mul(C_big, A_big, B_big, α, β)
4.56 ms ± 59.2 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit res = mul_numba(C_big, A_big, B_big, α, β)
2.49 ms ± 133 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit res = mul_jax(C_big_j, A_big_j, B_big_j, α, β).block_until_ready()
2.79 ms ± 60.5 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

The ranking flips: in this run jax comes out fastest of the three, at milliseconds where before it lost at microseconds. The dispatch overhead that dominated the small case — a few μs, paid once per call regardless of array size — is now negligible next to the cost of an actual 1024³ matmul, so it stops explaining anything. What’s left is which matmul kernel each backend actually calls into (numpy’s BLAS, numba’s BLAS via the same @ operator, XLA’s own dot_general implementation) — a separate, size-dependent question from the fixed dispatch tax this section started with. Small-array JIT overhead and large-array kernel choice are two different stories, and this one function walked through both just by changing M, N, K.

One more asymmetry worth noting on the way past: mul_numba above ran on the same compiled function, no recompile, because its signature fixes only dtype and memory layout, not shape. mul_jax did recompile — a new shape is a fresh cache entry, exactly as “Tracing, watched directly” below demonstrates next.

Tracing, watched directly

The call above hid a compile inside it. Make it visible by putting a print in the function body: under tracing, that line runs as ordinary Python — once, while JAX walks the function with placeholder arguments — not once per call the way it would in eager NumPy.

def mul_traced(C, A, B, α=True, β=False):
    print(f"tracing for shapes {A.shape}, {B.shape}, {C.shape}")
    return α * (A @ B) + β * C


mul_jax_traced = jax.jit(mul_traced)

print("first call, this shape:")
mul_jax_traced(C_j, A_j, B_j, α, β);
print("second call, same shape:")
mul_jax_traced(C_j, A_j, B_j, α, β);
first call, this shape:
tracing for shapes (16, 12), (12, 32), (16, 32)
second call, same shape:

One print, not two: the second call hit the compiled-code cache and never ran the Python body at all. jax.jit caches on the abstract shape and dtype of the arguments, not their values — so a new shape is a cache miss, and traces (and compiles) again:

A2, B2, C2 = np.random.randn(8, 12), np.random.randn(12, 8), np.random.randn(8, 8)
print("different shape:")
mul_jax_traced(C2, A2, B2, α, β);
different shape:
tracing for shapes (8, 12), (12, 8), (8, 8)

This is the trade the numba version doesn’t have to make in the same way: numba compiled once, ahead of any call, from the explicit f8[:, ::1](...) signature. JAX instead compiles lazily, once per distinct input shape it actually sees — cheap if the shape is stable across a training loop’s thousands of iterations, expensive if it’s called from code whose array shapes vary call to call.

Lowering, traced rather than typed

numba.inspect_types() printed typed IR annotated onto the original bytecode. JAX’s equivalent is a jaxpr — the trace’s own recording, not derived from CPython bytecode at all.

print(jax.make_jaxpr(mul)(C_j, A_j, B_j, α, β))
{ lambda ; a:f64[16,32] b:f64[16,12] c:f64[12,32] d:f64[] e:f64[]. let
    f:f64[16,32] = dot_general[
      dimension_numbers=(([1], [0]), ([], []))
      preferred_element_type=float64
    ] b c
    g:f64[] = convert_element_type[new_dtype=float64 weak_type=False] d
    h:f64[16,32] = mul g f
    i:f64[] = convert_element_type[new_dtype=float64 weak_type=False] e
    j:f64[16,32] = mul i a
    k:f64[16,32] = add h j
  in (k,) }

Notice the types are f64, matching the numpy inputs — only because of the jax.config.update("jax_enable_x64", True) at the top of this file. JAX defaults to silently downcasting everything to 32-bit; without that line the jaxpr below would read f32 regardless of what dtype went in. Another gap the duck typing papers over: same call syntax as NumPy, quietly different numerics unless you opt back in.

Read bottom-up from the let: A @ B is one primitive (dot_general), and — same story as numba’s arrayexpr fusion — the multiply-adds are still separate mul/add primitives here, because fusion is not the tracer’s job. The jaxpr only records which operations happened; whether they get fused into one loop is a decision XLA makes further down, during lowering.

lowered = mul_jax.lower(C_j, A_j, B_j, α, β)
hlo = lowered.compile().as_text()
print(f"{len(hlo.splitlines())} lines of compiled HLO. The fused arithmetic:\n")
for line in hlo.splitlines():
    if "multiply" in line or "add" in line:
        print(line.strip())
58 lines of compiled HLO. The fused arithmetic:

%mul.2 = f64[16,32]{1,0} multiply(%mul.3, %param_2.3), metadata={op_name="jit(mul)/mul" stack_frame_id=5}
%mul.0 = f64[16,32]{1,0} multiply(%mul.1, %param_0.2), metadata={op_name="jit(mul)/mul" stack_frame_id=6}
ROOT %add.0 = f64[16,32]{1,0} add(%mul.2, %mul.0), metadata={op_name="jit(mul)/add" stack_frame_id=5}
ROOT %multiply_add_fusion = f64[16,32]{1,0} fusion(%C.1, %a_.3, %ynn_fusion, %a_.2), kind=kLoop, calls=%fused_computation.1, metadata={op_name="jit(mul)/add" stack_frame_id=5}

One fusion computation, not four separate ops for α * (A @ B) + β * C — XLA’s fusion pass found the same elementwise chain numba’s arrayexpr optimiser found, from a completely different starting representation (a traced op graph, not typed bytecode). Two JIT compilers, built for different domains, converging on the same optimisation because the underlying arithmetic gives them no other choice: read A @ B and C once each, write the result once, and never materialise α · (A @ B) or β · C as arrays of their own.