JAX Control Flow: lax Operators vs Python Loops

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, your whole function becomes one compiled programjax.lax calls become ops in that program; lax loops stay loops all the way down.Your Python functionuses jax.numpy and jax.laxWrapped in jax.jit?noyesRun op by opeach op is sent toXLA on its own;Python drives itTrace to a jaxprruns once on placeholders (tracers)and records every operationLower to StableHLOthe program in XLA's input formatXLA compileroptimizes and fuses ops,plans memory, targets the deviceMachine codeCPU instructions, GPU or TPU kernelsRuns on the devicejax.numpyNumPy-style API, built on laxbuilt onjax.laxprimitives: add, mul, dot, ...control flow: cond, fori_loop,while_loop, scanone jaxpr op per callloops stay one While op in HLO
How a JAX function reaches the device, and where jax.lax fits in.

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.

Same 9 FMAs: lax runs independent ones back to back3 chunks x 3 steps of x*2+1. Numbers = run order. Arrows = needs the previous answer.lax.fori_loopgoes down the columnsstep 1step 2step 3ABC123456789Back-to-back FMAs work on different chunks,so the CPU runs them at the same time.Python for loop (unrolled)goes across the rowsstep 1step 2step 3ABC123456789Each FMA needs the answer of the one before,so the CPU waits about 4 cycles each time.
The same 9 FMAs in two different orders.

Both versions do the same FMAs. Only the order is different, and the order decides what the CPU spends its time on:

Inside the CPU cycle

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