Python loops and if statements still work inside jax.jit, but not always the way you expect. The jax.lax operators put a loop or branch into the compiled program as a single instruction.
With jax.jit, the whole function goes down the stack once and runs as one compiled program. Every jax.numpy call is built from jax.lax primitives, and each lax control flow operator stays a single loop or branch op at every level.
What happens to Python if and for under jax.jit
jax.jit first runs your function once on placeholders called tracers. It records each operation and sends that recording to the XLA compiler.
| Python code | Works under jit? |
What happens |
|---|---|---|
for loop with a fixed count |
Yes | Runs while recording, so 1000 steps become 1000 copies of the body (unrolling) |
if on a normal Python value (a flag, a shape) |
Yes | One branch is picked while recording; only that branch is compiled |
if on a traced value, like if x > 0 |
No | ConcretizationTypeError: the placeholder has no True or False yet |
while that stops based on traced data |
No | Same error |
The lax operators handle the two cases that fail, and they keep long loops from being copied out step by step.
The four operators
lax.cond: if / else
Runs one of two functions, chosen by a True/False value. Both must return the same shape and type.
lax.cond(x > 0, lambda x: x * 2, lambda x: x - 1, x)
lax.fori_loop: for i in range
Repeats a body a set number of times and returns the final value. The body gets the step number i and the current value.
lax.fori_loop(0, 10, lambda i, acc: acc + i, 0) # 45
lax.while_loop: while
Repeats a body as long as a condition is True, so the number of steps can depend on the data. Reverse-mode jax.grad does not work through it.
lax.while_loop(lambda x: x < 100, lambda x: x * 2, 1) # 128
lax.scan: loop and keep every step's output
Carries a state from step to step and stacks one output per step. It works with jax.grad, which makes it the usual choice for RNNs and simulations.
def step(total, x):
total = total + x
return total, total # (new state, output for this step)
lax.scan(step, 0, jnp.array([1, 2, 3, 4])) # (10, [1, 3, 6, 10])
| Operator | Python version | Step count known ahead? | Keeps output per step? | Works with jax.grad? |
|---|---|---|---|---|
lax.cond |
if / else |
— | — | Yes |
lax.fori_loop |
for i in range |
Yes | No | Yes, with fixed bounds |
lax.while_loop |
while |
No | No | No (reverse mode) |
lax.scan |
for x in xs + collect |
Yes | Yes | Yes |
Under the hood: Python loop vs lax.fori_loop
Both versions below return the same numbers. The compiled programs are completely different.
@jax.jit
def python_loop(x):
for i in range(1000):
x = x * 2 + 1
return x
@jax.jit
def lax_loop(x):
return lax.fori_loop(0, 1000, lambda i, x: x * 2 + 1, x)
Your code goes through three stages before it runs. Here is what each version becomes at each stage (JAX 0.12.1, CPU, a float32 array of 1,000 numbers):
| Stage | Python for loop |
lax.fori_loop |
|---|---|---|
| jaxpr (what tracing recorded) | 2,000 ops: mul, add written out 1000 times |
1 loop op, with the body recorded once |
| StableHLO (sent to XLA) | A straight list of multiply and add, no loop |
One stablehlo.while: check i < 1000, run the body |
| Machine code (x86 CPU) | 10 KB: 1000 FMA instructions in a row | 287 bytes: a real loop |
The jaxpr for 3 steps shows the difference clearly:
# Python loop: no loop left, just copies
b = mul a 2.0
c = add b 1.0
d = mul c 2.0
e = add d 1.0
f = mul e 2.0
g = add f 1.0
# lax.fori_loop: body once + a repeat count
scan[ length=3, jaxpr={ mul d 2.0 ; add f 1.0 } ]
Writing the expression out by hand, ((x*2+1)*2+1)..., gives exactly the same jaxpr and machine code as the Python loop. JAX only sees the operations that run, not how you wrote them.
In the machine code, the two loops run in opposite order (simplified; FMA = one instruction that does x * 2 + 1 on 8 numbers at once):
# lax.fori_loop # Python loop (unrolled)
for step in 1..1000: for chunk in array (8 numbers):
for chunk in array: load chunk into ymm2
load 4 chunks (ymm2..ymm5) FMA ymm2 # step 1
FMA each one FMA ymm2 # step 2
store them back ... 1000 times, same register
store ymm2
What happens at runtime
Neither version always wins at runtime. The Python loop saves trips to memory; lax.fori_loop saves time spent waiting.
Both versions do the same FMAs. Only the order is different, and the order decides what the CPU spends its time on:
- Waiting. One FMA takes about 4 CPU cycles to finish, but the CPU can start a new one every cycle if it does not need an unfinished answer.
laxkeeps it busy; the unrolled loop makes it wait at every step. - Memory trips. The unrolled loop loads each chunk once and stores it once.
laxloads and stores every chunk on every step, which is cheap only while the array fits in the CPU's fast cache.
Inside the CPU cycle
- A cycle is one tick of the CPU clock, about 3 billion per second. On each tick, every part of the CPU moves its work forward one step.
- An FMA runs in 4 stages, one per cycle: multiply, line up with the number to add, add, round. Each stage is its own piece of hardware.
- Pipelining: once stage 1 passes its work on, it is free for the next FMA. So a new FMA can start every cycle while earlier ones finish, like cars moving through a car wash.
- Two FMA units: this Xeon has two, so up to 4 × 2 = 8 FMAs can be in progress at once.
- The catch: an FMA can only start once its inputs are ready. The CPU looks a few hundred instructions ahead and starts any FMA whose inputs are ready, even out of order.
cycle: 1 2 3 4 5 6 7 8 9
lax unit1 A1 C1 E1 G1 A2 C2 E2 G2 A3
unit2 B1 D1 F1 H1 B2 D2 F2 H2 B3
Python unit1 S1 . . . S2 . . . S3
unit2 . . . . . . . . .
With lax, neighbouring FMAs work on different chunks (A to H), so both units start a new FMA every cycle. In the unrolled loop, each step (S1, S2, S3) waits 4 cycles for the one before it. The next independent chunk is 1000 instructions away, beyond the CPU's look-ahead, so only 1 of the 8 slots is ever used.
Measured on a 2-core Intel Xeon CPU, 1000 steps, time per call:
| Body and data | Python loop | lax.fori_loop |
Faster | Why |
|---|---|---|---|---|
x*0.5+1, 1,000 numbers (4 KB, fits in cache) |
157 µs | 65 µs | lax, 2.4× |
Memory trips are cheap, so waiting dominates |
x*0.5+1, 1,000,000 numbers (4 MB, does not fit) |
96 ms | 179 ms | Python, 1.9× | lax pulls the array from main memory 1000 times |
Very long unrolled loops get worse still. At 5,000 steps the compiler stopped using 8-wide instructions and did one number at a time, and lax became 13× faster.
When to use which
| Situation | Use |
|---|---|
| Branch on a value only known at runtime | lax.cond (Python if fails under jit) |
| Stop point depends on the data | lax.while_loop (only option) |
| Long loop, or the loop count changes between calls | lax.fori_loop or lax.scan |
| Need every step's output, or gradients through a loop | lax.scan |
| Short loop (about 10 steps) | Plain Python loop is fine |
| Cheap math on a big array, many steps | lax.fori_loop(..., unroll=k) with a small k like 4 or 8 |
unroll=k copies the body k times inside each loop turn. XLA can then fuse those k steps, while the code stays small.
To see all three stages for your own function:
print(jax.make_jaxpr(f)(x)) # jaxpr
print(jax.jit(f).lower(x).as_text()) # StableHLO
print(jax.jit(f).lower(x).compile().as_text()) # optimized HLO