import re
import timeit
import jax
jax.config.update("jax_enable_x64", True) # match numba's f8, same as `intro_jax.py`
import jax.numpy as jnpThe loop numba needed, jax doesn’t
numba_loop.py’s whole argument turned on one fact: Numba’s array-expression fuser stops at a named value. r2 is used twice, so between the two arrayexpr loops it has to become a real 127 MB array — and the fix was either to stop naming it, or to abandon array notation altogether and write the loop by hand, where r2 lives as a scalar in a register.
Same kernel, same reason to name r2, run through jax.jit instead.
def f_jax(x, y, σ):
"""Ricker wavelet — identical maths to `f_numpy`/`f_numba`, `r2` named on purpose."""
r2 = (x.reshape(-1, 1) ** 2 + y.reshape(1, -1) ** 2) / (σ * σ)
return (1.0 - r2) * jnp.exp(-0.5 * r2)M, N, σ = 3600, 4400, 1.5
x = jnp.linspace(-4.0, 4.0, M)
y = jnp.linspace(-4.0, 4.0, N)
f_jax_jit = jax.jit(f_jax)
f_jax_jit(x, y, σ).block_until_ready() # trace + compile once, discard timingAn NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
Array([[-0.01078917, -0.01081881, -0.01084851, ..., -0.01084851,
-0.01081881, -0.01078917],
[-0.01082541, -0.01085514, -0.01088494, ..., -0.01088494,
-0.01085514, -0.01082541],
[-0.01086174, -0.01089157, -0.01092147, ..., -0.01092147,
-0.01089157, -0.01086174],
...,
[-0.01086174, -0.01089157, -0.01092147, ..., -0.01092147,
-0.01089157, -0.01086174],
[-0.01082541, -0.01085514, -0.01088494, ..., -0.01088494,
-0.01085514, -0.01082541],
[-0.01078917, -0.01081881, -0.01084851, ..., -0.01084851,
-0.01081881, -0.01078917]], dtype=float64)
Did tracing erase the name?
The obvious explanation is that jax.jit traces f_jax symbolically, so by the time a compiler sees anything there is no r2 left to materialise: the name went in and a graph came out, and the graph is free to be rearranged because it records what was computed rather than how it was spelled. Half of that is true, and it is the half that does no work. The name is gone. The sharing the name introduced is not.
print(jax.make_jaxpr(f_jax)(x, y, σ)){ lambda ; a:f64[3600] b:f64[4400] c:f64[]. let
d:f64[3600,1] = reshape[dimensions=None new_sizes=(3600, 1) sharding=None] a
e:f64[3600,1] = integer_pow[y=2] d
f:f64[1,4400] = reshape[dimensions=None new_sizes=(1, 4400) sharding=None] b
g:f64[1,4400] = integer_pow[y=2] f
h:f64[3600,4400] = add e g
i:f64[] = mul c c
j:f64[] = convert_element_type[new_dtype=float64 weak_type=False] i
k:f64[3600,4400] = div h j
l:f64[3600,4400] = sub 1.0:f64[] k
m:f64[3600,4400] = mul -0.5:f64[] k
n:f64[3600,4400] = exp m
o:f64[3600,4400] = mul l n
in (o,) }
r2 is k: bound once by the div, and read twice — by l (the \(1 - r^2\)) and by m (the \(-r^2/2\)). Tracing recorded the data flow exactly as written, shared subexpression and all. This is the same structure Numba’s typed IR had, and Numba materialised it into 127 MB.
Nor does the sharing get lost on the way into XLA. .lower() stops one step before XLA’s optimiser runs, and prints the program as XLA first receives it:
print(f_jax_jit.lower(x, y, σ).as_text())module @jit_f_jax attributes {mhlo.num_partitions = 1 : i32, mhlo.num_replicas = 1 : i32} {
func.func public @main(%arg0: tensor<3600xf64>, %arg1: tensor<4400xf64>, %arg2: tensor<f64>) -> (tensor<3600x4400xf64> {jax.result_info = "result"}) {
%0 = stablehlo.reshape %arg0 : (tensor<3600xf64>) -> tensor<3600x1xf64>
%1 = stablehlo.multiply %0, %0 : tensor<3600x1xf64>
%2 = stablehlo.reshape %arg1 : (tensor<4400xf64>) -> tensor<1x4400xf64>
%3 = stablehlo.multiply %2, %2 : tensor<1x4400xf64>
%4 = stablehlo.broadcast_in_dim %1, dims = [0, 1] : (tensor<3600x1xf64>) -> tensor<3600x4400xf64>
%5 = stablehlo.broadcast_in_dim %3, dims = [0, 1] : (tensor<1x4400xf64>) -> tensor<3600x4400xf64>
%6 = stablehlo.add %4, %5 : tensor<3600x4400xf64>
%7 = stablehlo.multiply %arg2, %arg2 : tensor<f64>
%8 = stablehlo.convert %7 : tensor<f64>
%9 = stablehlo.broadcast_in_dim %8, dims = [] : (tensor<f64>) -> tensor<3600x4400xf64>
%10 = stablehlo.divide %6, %9 : tensor<3600x4400xf64>
%cst = stablehlo.constant dense<1.000000e+00> : tensor<f64>
%11 = stablehlo.broadcast_in_dim %cst, dims = [] : (tensor<f64>) -> tensor<3600x4400xf64>
%12 = stablehlo.subtract %11, %10 : tensor<3600x4400xf64>
%cst_0 = stablehlo.constant dense<-5.000000e-01> : tensor<f64>
%13 = stablehlo.broadcast_in_dim %cst_0, dims = [] : (tensor<f64>) -> tensor<3600x4400xf64>
%14 = stablehlo.multiply %13, %10 : tensor<3600x4400xf64>
%15 = stablehlo.exponential %14 : tensor<3600x4400xf64>
%16 = stablehlo.multiply %12, %15 : tensor<3600x4400xf64>
return %16 : tensor<3600x4400xf64>
}
}
Still one value, still grid-shaped, still read twice: %10 is r2, a full tensor<3600x4400xf64>, consumed by %12 and %14. At this point JAX has handed XLA precisely the problem Numba’s array-expression pass was handed, in precisely the same shape. Whatever saves the memory here, it has not happened yet.
Fusion, checked at the lowering, not assumed
numba.inspect_types() could count arrayexpr nodes directly because Numba’s typed IR is the fusion decision — the pass has already run by the time you read it. Neither listing above has that property: the jaxpr is a record of the trace, and the StableHLO is XLA’s input. The fusion decision is made later, inside XLA, so read the module on the far side of the optimiser instead.
def hlo_lines(jitted):
"""Optimised HLO for these argument shapes: one line per instruction, metadata stripped."""
text = jitted.lower(x, y, σ).compile().as_text()
return [line.split(", metadata")[0] for line in text.splitlines()]
hlo = hlo_lines(f_jax_jit)
for line in hlo:
if " fusion(" in line:
print(line.strip())%multiply_divide_fusion = f64[] fusion(%a_.1), kind=kLoop, calls=%fused_computation.1
ROOT %exponential_multiply_fusion = f64[3600,4400]{1,0} fusion(%multiply_divide_fusion, %y.1, %x.1), kind=kLoop, calls=%fused_computation
Two calls, not the four-or-more you would get from naively counting operators (+, /, -, *, exp, *). One is %multiply_divide_fusion — a scalar, computing \(1/\sigma^2\) once, outside the grid entirely. The other is %exponential_multiply_fusion, and it is the whole grid-shaped computation: both squares, both broadcasts, the add, the scaling by \(1/\sigma^2\), 1 - r2, -0.5 * r2, exp, the final multiply — every one of them, in a single f64[3600,4400] loop. There is no separate grid-shaped array here for r2 to be. Pull the body out to see it in full:
def computation(lines, name):
"""The lines of one HLO computation, brace to matching brace."""
start = next(i for i, l in enumerate(lines) if l.startswith(f"{name} ("))
depth = 0
for stop, line in enumerate(lines[start:], start):
depth += line.count("{") - line.count("}")
if depth == 0:
break
return [l.strip() for l in lines[start : stop + 1]]
body = computation(hlo, "%fused_computation")
print("\n".join(body))%fused_computation (param_0.3: f64[], param_1.6: f64[4400], param_2.6: f64[3600]) -> f64[3600,4400] {
%constant.4 = f64[] constant(1)
%sub.1 = f64[3600,4400]{1,0} broadcast(%constant.4), dimensions={}
%param_2.6 = f64[3600]{0} parameter(2)
%integer_pow.5 = f64[3600]{0} multiply(%param_2.6, %param_2.6)
%add.2 = f64[3600,4400]{1,0} broadcast(%integer_pow.5), dimensions={0}
%param_1.6 = f64[4400]{0} parameter(1)
%integer_pow.4 = f64[4400]{0} multiply(%param_1.6, %param_1.6)
%add.1 = f64[3600,4400]{1,0} broadcast(%integer_pow.4), dimensions={1}
%add.0 = f64[3600,4400]{1,0} add(%add.2, %add.1)
%param_0.3 = f64[] parameter(0)
%broadcast.3 = f64[3600,4400]{1,0} broadcast(%param_0.3), dimensions={}
%multiply.1 = f64[3600,4400]{1,0} multiply(%add.0, %broadcast.3)
%sub.0 = f64[3600,4400]{1,0} subtract(%sub.1, %multiply.1)
%constant.1 = f64[] constant(-0.5)
%mul.2 = f64[3600,4400]{1,0} broadcast(%constant.1), dimensions={}
%mul.1 = f64[3600,4400]{1,0} multiply(%multiply.1, %mul.2)
%exp.0 = f64[3600,4400]{1,0} exponential(%mul.1)
ROOT %mul.0 = f64[3600,4400]{1,0} multiply(%sub.0, %exp.0)
}
One fusion, one pass over the \(3600 \times 4400\) grid. But r2 has not been optimised away, and saying so would be the wrong lesson. It is still in there, and it is still shared — read the operands back out and look for a value computed inside the fusion that more than one instruction reads. (The parameter instructions are excluded: those are the fusion’s inputs, and they have buffers by definition.)
def shared_values(body):
"""Values computed inside a fusion body that more than one instruction reads."""
computed, reads = set(), {}
for line in body[1:-1]:
target, rhs = line.removeprefix("ROOT ").split(" = ", 1)
args = rhs[rhs.index("(") + 1 : rhs.rindex(")")]
if " parameter(" not in rhs:
computed.add(target)
for operand in sorted(set(re.findall(r"%[\w.]+", args))):
reads.setdefault(operand, []).append(target)
return {v: c for v, c in reads.items() if v in computed and len(c) > 1}
for value, consumers in shared_values(body).items():
print(f"{value} is read by {' and '.join(consumers)}")%multiply.1 is read by %sub.0 and %mul.1
Exactly one, and it is r2. %multiply.1 is the same value the jaxpr called k and the StableHLO called %10, read by %sub.0 (the \(1 - r^2\)) and by %mul.1 (the \(-r^2/2\)). It was not eliminated, not duplicated, not recomputed. XLA evaluates it once and reads it twice, just as the source says.
So the answer is not that r2 stopped existing. It is that a value with two consumers does not have to be an array. The two compilers differ in what a fusion is:
- Numba’s
arrayexpris a node in the IR, and a node produces one value: one array. The pass grows it by absorbing an operand’s defining expression into its parent, and it does that only when the operand is a compiler-generated temporary — never when it is a variable you named. (operand.is_temp, literally, innumba/np/ufunc/array_exprs.py. It is not a use count: a name read once splits the fusion too.)r2is a name you wrote, so it becomes the root of its ownarrayexprnode, and the root of anarrayexprnode is an allocated array. - XLA’s
fused_computationis not a node but a subcomputation: an arbitrary DAG with one root, emitted as a single loop nest over the output shape. Its interior values are per-index scalars in that loop — registers — and reading one twice is reading a register twice. What gets a buffer is settled after fusion, by buffer assignment, which gives buffers to the fusion’s parameters and its root.%multiply.1is neither; it is interior, so it never gets an address.
That is the whole of it. Not “the name was erased before the fuser ran” — the fuser could see the sharing perfectly well, in a listing you can print. It is that XLA’s fusion unit is big enough to put the sharing inside it, and Numba’s, by construction, is not.
The part of the hunch that was right
The compiler is free to rewrite the how once it knows the what, and it did — just not here. Look again at what %multiply.1 is: a multiply, where f_jax wrote a divide. The missing division is the other fusion:
print("\n".join(computation(hlo, "%fused_computation.1")))%fused_computation.1 (param_0.5: f64[]) -> f64[] {
%constant.5 = f64[] constant(1)
%param_0.5 = f64[] parameter(0)
%mul.3 = f64[] multiply(%param_0.5, %param_0.5)
ROOT %divide.1 = f64[] divide(%constant.5, %mul.3)
}
\(1/\sigma^2\), evaluated once, on a scalar, outside the grid — and then multiplied in per point. A loop-invariant divide became a reciprocal hoisted out and a multiply left behind, which is a genuine “knowing the what, choosing the how” rewrite, and it is the same line we had to think of and write by hand in f_numba_loops:
inv = 1.0 / (σ * σ) # once
r2 = xi + y[j] * y[j] * inv # per pointBut notice the scale of it. That is a strength reduction and a loop-invariant hoist: both textbook, both local, both worth a few percent. It is not what saved the 127 MB. The two facts are easy to conflate because they show up in the same listing, and only one of them is the reason f_jax is four readable lines instead of nine hand-written ones.
So: writing r2 as a named intermediate cost Numba a full round trip to DRAM and costs XLA nothing — not because the name was traced away, but because XLA never had a rule that a name, or a second reader, means an array.
Testing it: remove the name
All of that is a claim about a mechanism, and it makes a prediction sharp enough to be wrong.
In numba_loop.py, un-naming r2 was a performance edit. f_numpy_inlined wrote the subexpression out twice, and that really did trade memory for arithmetic: three extra flops per grid point in exchange for not storing 127 MB, and it won. The natural expectation is that JAX faces the same trade in the other direction — that f_jax, having kept the name, is the one paying for a temporary, and that removing the name would buy the same thing it bought Numba.
If the reading above is right, that expectation is wrong twice over: f_jax was never paying for a temporary, and un-naming cannot buy back something that was never spent. Make exactly the same source edit — character for character, f_numpy_inlined with np swapped for jnp — and see.
def f_jax_inlined(x, y, σ):
"""`f_jax` with the name removed: the same edit `f_numpy_inlined` made for Numba."""
X2 = x.reshape(-1, 1) ** 2
Y2 = y.reshape(1, -1) ** 2
return (1.0 - (X2 + Y2) / (σ * σ)) * jnp.exp(-0.5 * (X2 + Y2) / (σ * σ))
f_jax_inlined_jit = jax.jit(f_jax_inlined)
print("matches f_jax:", jnp.allclose(f_jax_inlined_jit(x, y, σ), f_jax_jit(x, y, σ)))matches f_jax: True
Start where the difference is real, at the trace. Tracing is a recorder, not an optimiser, so it writes down what the source said — including saying it twice:
print(jax.make_jaxpr(f_jax_inlined)(x, y, σ)){ lambda ; a:f64[3600] b:f64[4400] c:f64[]. let
d:f64[3600,1] = reshape[dimensions=None new_sizes=(3600, 1) sharding=None] a
e:f64[3600,1] = integer_pow[y=2] d
f:f64[1,4400] = reshape[dimensions=None new_sizes=(1, 4400) sharding=None] b
g:f64[1,4400] = integer_pow[y=2] f
h:f64[3600,4400] = add e g
i:f64[] = mul c c
j:f64[] = convert_element_type[new_dtype=float64 weak_type=False] i
k:f64[3600,4400] = div h j
l:f64[3600,4400] = sub 1.0:f64[] k
m:f64[3600,4400] = add e g
n:f64[3600,4400] = mul -0.5:f64[] m
o:f64[] = mul c c
p:f64[] = convert_element_type[new_dtype=float64 weak_type=False] o
q:f64[3600,4400] = div n p
r:f64[3600,4400] = exp q
s:f64[3600,4400] = mul l r
in (s,) }
Seventeen equations against thirteen. h and m are the same add e g, and i and o are the same mul c c; k and q are two separate grid-sized divides where f_jax had one. The sharing that f_jax had is genuinely gone, and JAX has handed XLA strictly more work than before. This also settles the earlier question from the other side: tracing does not deduplicate, so it was never tracing that made f_jax cheap.
Now the optimised HLO:
inlined = hlo_lines(f_jax_inlined_jit)
for line in inlined:
if " fusion(" in line:
print(line.strip())
inlined_body = computation(inlined, "%fused_computation")
for value, consumers in shared_values(inlined_body).items():
print(f"{value} is read by {' and '.join(consumers)}")%multiply_divide_fusion = f64[] fusion(%a_.1), kind=kLoop, calls=%fused_computation.1
ROOT %exponential_multiply_fusion = f64[3600,4400]{1,0} fusion(%multiply_divide_fusion, %y.1, %x.1), kind=kLoop, calls=%fused_computation
%add.0 is read by %multiply.6 and %multiply.4
Two fusions again — and a shared value again, with the sharing rebuilt out of source that no longer contains it. XLA’s common-subexpression elimination recognised the two x² + y² as one computation and merged them back into %add.0, which is now the value read twice. The name moved from %multiply.1 to %add.0; nothing else did.
How much arithmetic did the recomputation actually cost? Count the instructions that run at every grid point — the ones whose result is f64[3600,4400] — in each version’s fusion:
GRID = f"f64[{M},{N}]"
def grid_ops(body):
"""The instructions in a fusion body that are evaluated once per grid point."""
return [
rhs.split("(")[0].split()[-1]
for rhs in (line.split(" = ", 1)[1] for line in body[1:-1])
if rhs.startswith(GRID)
]
named, unnamed = grid_ops(body), grid_ops(inlined_body)
print(f"f_jax : {len(named)} grid-shaped instructions")
print(f"f_jax_inlined: {len(unnamed)} grid-shaped instructions")
print("same sequence:", named == unnamed)
print(" ", " ".join(named))f_jax : 11 grid-shaped instructions
f_jax_inlined: 11 grid-shaped instructions
same sequence: True
broadcast broadcast broadcast add broadcast multiply subtract broadcast multiply exponential multiply
The same eleven instructions, of the same kinds, in the same order: one add, two multiplies, a subtract, an exponential, a final multiply, and four broadcasts, which are index arithmetic inside the loop rather than work. The recomputation cost nothing, and there is nothing left to fuse away.
That zero deserves a second look, because CSE alone does not explain it. CSE recovered the shared x² + y², but f_jax_inlined also wrote / (σ * σ) twice, and those two divides did not merge into one: %add.0 feeds two separate grid-shaped multiplies, %multiply.6 and %multiply.4. What paid for them was constant folding. In f_jax, r2 is scaled by \(1/\sigma^2\) and the result is then scaled again by \(-0.5\) — two grid multiplies, one after the other. In f_jax_inlined, XLA folded the \(-0.5\) into the scalar to get \(-0.5/\sigma^2\) and applied that to %add.0 directly — also two grid multiplies, but side by side.
So the two are not quite the same program: same instructions, slightly different dependency shape, one chained where the other is parallel. What they are is the same amount of grid-shaped work, with the same single fusion and the same buffers.
So the arithmetic is a wash. What about the memory the trade was supposed to be against? XLA reports it directly, which is the JAX counterpart of numba_loop.py’s tracemalloc peak:
def memory(jitted):
"""Bytes XLA reserves for one call: scratch beyond the arguments, and the output."""
m = jitted.lower(x, y, σ).compile().memory_analysis()
return m.temp_size_in_bytes, m.output_size_in_bytes
for name, fn in [("f_jax", f_jax_jit), ("f_jax_inlined", f_jax_inlined_jit)]:
temp, out = memory(fn)
print(f"{name:15s}temp {temp:>3,d} B output {out:>13,d} B")f_jax temp 8 B output 126,720,000 B
f_jax_inlined temp 8 B output 126,720,000 B
Eight bytes of scratch, both times. Not 127 MB, not one grid-sized array — eight bytes, which is the one f64 scalar %multiply_divide_fusion produces. The output is the only large allocation either version makes, and that is the floor: you cannot return \(M \times N\) words in fewer.
There was no memory to trade.
A control: what the boundary would have cost
The timings are going to be a null result, and a null result only means something next to the thing it is null against. So build the version where the boundary is where Numba was forced to put it. Two jits instead of one does it: a compilation boundary is a real boundary, and a value crossing it has to be a device array.
@jax.jit
def r2_of(x, y, σ):
return (x.reshape(-1, 1) ** 2 + y.reshape(1, -1) ** 2) / (σ * σ)
@jax.jit
def wavelet(r2):
return (1.0 - r2) * jnp.exp(-0.5 * r2)
def f_jax_split(x, y, σ):
"""Same maths, but `r2` now crosses a compilation boundary — so it must be an array."""
return wavelet(r2_of(x, y, σ))
print("matches f_jax:", jnp.allclose(f_jax_split(x, y, σ), f_jax_jit(x, y, σ)))
argument_bytes = wavelet.lower(r2_of(x, y, σ)).compile().memory_analysis().argument_size_in_bytes
print(f"wavelet reads {argument_bytes:,d} B of arguments")matches f_jax: True
wavelet reads 126,720,000 B of arguments
Timing all three
The other notebooks use %timeit, one cell per version. That is the wrong instrument here, and it is worth saying why rather than quietly switching. %timeit runs one candidate to completion before the next one starts, which is fine when the gap is large — it resolves f_jax_split without difficulty. But on a 127 MB working set the drift between one phase of the process and the next is worth several percent all by itself, and measured that way whichever version happens to run second comes out slower, whichever one it is. That is the page-recycling effect numba_loop.py warned about, here large enough to swamp the comparison it is being asked to make.
Interleaving helps: run the candidates round-robin, so each is spread over every phase of the run. It does not abolish the noise, so run the whole thing three times and print all three. The spread between trials is the measurement’s resolution, and here the resolution is the result.
def bench(candidates, rounds=8, number=20):
"""Best time per candidate, measured round-robin so no candidate owns one phase of the run."""
best = dict.fromkeys(candidates, float("inf"))
for _ in range(rounds):
for name, call in candidates.items():
best[name] = min(best[name], timeit.timeit(call, number=number) / number)
return best
calls = {
"f_jax": lambda: f_jax_jit(x, y, σ).block_until_ready(),
"f_jax_inlined": lambda: f_jax_inlined_jit(x, y, σ).block_until_ready(),
"f_jax_split": lambda: f_jax_split(x, y, σ).block_until_ready(),
}
for candidate in calls.values():
candidate() # compile and settle before anything counts
for _ in range(3):
times = bench(calls)
print(" ".join(f"{n} {t * 1e3:5.1f} ms ({t / times['f_jax']:.2f}×)" for n, t in times.items()))f_jax 5.4 ms (1.00×) f_jax_inlined 5.7 ms (1.06×) f_jax_split 13.6 ms (2.52×)
f_jax 5.7 ms (1.00×) f_jax_inlined 5.7 ms (1.00×) f_jax_split 13.4 ms (2.34×)
f_jax 5.6 ms (1.00×) f_jax_inlined 5.9 ms (1.05×) f_jax_split 13.3 ms (2.38×)
Read the three lines together rather than any one of them.
f_jax_split — the same maths with one fusion boundary added — is well over half again as slow in every trial, and stays there across repeated runs of the notebook. That is the same range as the gap numba_loop.py measured between f_numba and f_numba_loops, for the same reason, on the same grid. wavelet taking a 127 MB argument is that gap, itemised.
f_jax against f_jax_inlined is a different kind of answer: they differ by up to about ten percent, in whichever direction this particular run happens to land. Re-run the notebook and the ordering changes. That is not a result about the two functions, it is the resolution of the instrument: every call allocates a fresh 127 MB output, and whether those pages come back from the allocator warm or have to be faulted in one at a time moves the number by more than any difference between the two versions. The honest statement is that the difference is smaller than this measurement can see, which is the right outcome for two programs issuing the same grid-shaped work — and it is worth being clear that “we could not measure it” is all a wall-clock number can ever establish here. The HLO above is what establishes why: same fusion, same buffers, same eleven instructions.
Note also how far outside that band f_jax_split sits. The instrument is blunt. It is not blunt enough to hide a fusion boundary.
So the boundary is expensive, and XLA declines to put one at r2. Which answers the question directly. Yes, un-naming r2 trades a memory allocation for computing the same thing twice — in the source. The trade never reaches the hardware, because two passes undo it before code generation: CSE takes the recomputation back out, and fusion had already taken the allocation out.
For Numba, editing the source between these two spellings was the tool for moving the fusion boundary — the only tool, since the boundary is defined by which variables you named. For JAX the boundary does not move, so the same edit is not a performance tool at all. It is a readability choice, and you should write whichever version reads better. That is f_jax.
So what does the deciding?
Which leaves the obvious question. If the source spelling does not decide the fusion boundary, something else must, and trading arithmetic against memory is not a call you would want made carelessly. It is worth separating two answers that get run together — what enables this, and what decides it — because they belong to different pieces of software.
Tracing enables it, and optimises nothing
It is tempting to credit the tracer, and by now there are two pieces of evidence against that. f_jax_inlined’s jaxpr kept the duplicated add e g rather than noticing it; and the jaxpr is a faithful transcript in the other direction too. Nest jit inside jit and it does not even flatten the calls:
@jax.jit
def f_jax_nested(x, y, σ):
"""The `f_jax_split` decomposition, with both halves inside one outer `jit`."""
return wavelet(r2_of(x, y, σ))
print(jax.make_jaxpr(f_jax_nested)(x, y, σ)){ lambda ; a:f64[3600] b:f64[4400] c:f64[]. let
d:f64[3600,4400] = jit[
name=f_jax_nested
jaxpr={ lambda ; a:f64[3600] b:f64[4400] c:f64[]. let
e:f64[3600,4400] = jit[
name=r2_of
jaxpr={ lambda ; a:f64[3600] b:f64[4400] c:f64[]. let
f:f64[3600,1] = reshape[
dimensions=None
new_sizes=(3600, 1)
sharding=None
] a
g:f64[3600,1] = integer_pow[y=2] f
h:f64[1,4400] = reshape[
dimensions=None
new_sizes=(1, 4400)
sharding=None
] b
i:f64[1,4400] = integer_pow[y=2] h
j:f64[3600,4400] = add g i
k:f64[] = mul c c
l:f64[] = convert_element_type[
new_dtype=float64
weak_type=False
] k
e:f64[3600,4400] = div j l
in (e,) }
] a b c
d:f64[3600,4400] = jit[
name=wavelet
jaxpr={ lambda ; e:f64[3600,4400]. let
m:f64[3600,4400] = sub 1.0:f64[] e
n:f64[3600,4400] = mul -0.5:f64[] e
o:f64[3600,4400] = exp n
d:f64[3600,4400] = mul m o
in (d,) }
] e
in (d,) }
] a b c
in (d,) }
Two jit primitives, each carrying its own sub-jaxpr, structure intact. The tracer preserved the decomposition exactly as written. Now compile it:
temp, out = memory(f_jax_nested)
fusions = sum(1 for line in hlo_lines(f_jax_nested) if " fusion(" in line)
print(f"{fusions} fusions temp {temp} B output {out:,d} B")2 fusions temp 8 B output 126,720,000 B
Two fusions and eight bytes: byte for byte what plain f_jax compiled to. XLA inlined both calls and fused straight through them, so the r2 that f_jax_split had to write to DRAM never gets an address here — same source decomposition, same maths, and the only difference is that this time both halves are inside one compilation.
That is the sense in which “boundaries” get crossed, and it is worth being exact about it: nothing is simplified at trace time. What tracing delivers is the precondition for the simplification — the whole computation, in one graph, with the Python gone. No data-dependent control flow, no aliasing, no mutation, no calls into code the compiler cannot see. This is precisely the discipline that jax.jit imposes on the functions you give it, and it is what the tracing restrictions are for. Numba’s fuser, working over Python source that could do anything, could never assume as much. Compilation-unit boundaries are the only ones that survive — which is why f_jax_split, where the two halves are separately compiled and separately dispatched, is the version that pays.
What decides it is blunter than a cost model
So XLA is the one deciding, and this is where the “how does it know which is cheaper” question turns out to have an anticlimactic answer: for r2, there was nothing to decide.
A fusion region grows from its root by absorbing producers. When %multiply.1 was absorbed, both of its consumers were already inside the region, so it joined as an interior value: computed once per grid point, in a register, read twice. That is fewer buffers and identical arithmetic — better on both axes at once, with no trade to weigh. No cost model is needed to prefer it, and f_jax never needed anything more than this.
The genuine trade only appears when a producer’s consumers land in different regions, because then fusing it into both means computing it twice. That is a real exchange of arithmetic for memory, and it can go either way. Force the situation — one producer, two outputs, so the consumers cannot share a root — and watch which way XLA goes:
def duplication_rule(op):
"""Fusion count for `op`'s result feeding two outputs: 2 means recomputed, 3 means buffered."""
def f(x, y):
t = op(x.reshape(-1, 1) + y.reshape(1, -1))
return 1.0 - t, 2.0 - t # two roots, so `t` cannot be interior to both
text = jax.jit(f).lower(x, y).compile().as_text()
return sum(1 for line in text.splitlines() if " fusion(" in line)
for label, op in [
("t", lambda t: t),
("t + 3", lambda t: t + 3.0),
("t * 3", lambda t: t * 3.0),
("abs(t)", jnp.abs),
("3 / t", lambda t: 3.0 / t),
("sqrt(t)", jnp.sqrt),
("exp(t)", jnp.exp),
("log(t)", jnp.log),
("tanh(t)", jnp.tanh),
]:
n = duplication_rule(op)
print(f"{label:10s}{n} fusions {'recomputed per consumer' if n == 2 else 'computed once, buffered'}")t 2 fusions recomputed per consumer
t + 3 2 fusions recomputed per consumer
t * 3 2 fusions recomputed per consumer
abs(t) 2 fusions recomputed per consumer
3 / t 3 fusions computed once, buffered
sqrt(t) 3 fusions computed once, buffered
exp(t) 3 fusions computed once, buffered
log(t) 3 fusions computed once, buffered
tanh(t) 3 fusions computed once, buffered
A clean split, and not one drawn by measurement. Addition, multiplication, abs and plain copies get recomputed — XLA duplicates them into both consumers rather than store a grid-sized array. Division and the transcendentals get materialised — computed once, written out, read twice.
That is the whole decision procedure, and it is a taxonomy rather than a model: a static classification of opcodes into cheap and expensive. Nothing in it looks at the shape, the working set, the cache size, or a bandwidth figure. It encodes, as a fixed rule, exactly the exchange rate numba_loop.py measured at this grid size — an extra multiply costs a few cycles, a DRAM round trip costs a few hundred, so recompute cheap things freely — and then declines to recompute the handful of operations expensive enough to make that reasoning unsafe.
Being blunt has consequences worth knowing about. The rule is not size-aware, so on a grid small enough to sit in cache, where storing the intermediate is nearly free, it will still duplicate the multiply and still refuse to duplicate the exp — the same call, on a machine where the numbers no longer support it. It is a good default rather than an oracle, and it is a heuristic in the CPU backend measured here; other backends make this decision with their own machinery.
So the honest answer to “how does it know” is that it mostly does not have to. XLA knows two things: that fusing without duplicating is free, and that a few opcodes are too expensive to repeat. f_jax only ever needed the first — which is why writing r2 down, the most natural thing in the world to do, costs exactly nothing.
What this buys, and what it costs
numba_loop.py earned the fused, register-resident version by dropping array notation and writing a loop nest by hand — nine lines, hard-coded to this one kernel’s rank and shape. f_jax is four lines that read like the formula, and it gets the same fusion for free, because XLA’s fusion unit is a whole subgraph rather than a single array-valued node, and because nothing in its pipeline consults how you spelled the source.
The cost moved, it didn’t vanish. jax.jit retraces per distinct input shape (intro_jax.py showed the print that only fires once per shape), and everything inside the compiled region has to be expressible as this kind of pure, shape-typed array graph — no data-dependent Python control flow, no in-place mutation. Numba’s hand-written loop paid for its register-locality in code you have to write and re-derive per kernel; JAX pays for it in the tracing discipline you have to write your function around. Different bill, same item bought.