XLA and compilation: jaxprs, StableHLO, fusion and recompiles

What happens between jax.jit(f)(x) and machine code, read in the pinned JAX and XLA sources and measured on the running example's train step (Apple M1 Pro CPU; GPU and TPU read, not run). Child of Topic: jax-and-tpu. Data as of October 2026. Reading: 39 min, plus 13 in closed details.

The idea in one screen

jax.jit hands XLA the whole train step as one program, so the compiler decides everything before the first step runs: which operations share a kernel, where every array sits in memory, and which compiled executable a later call reuses. Almost every JAX performance surprise (a slow first call, a step that keeps recompiling, a copy you did not ask for, memory that does not fit) is one of those decisions, and every one of them can be read in what XLA dumps.

Fig. 1 follows one program down, block 0's attention sub-block (forward only, on the running example's shapes), as one tile per instruction in program order, and in blue the operation this page follows: LayerNorm's x - mu measured here.

  1. Tracing records a jaxpr: 61 equations. Python ran once on tracers and JAX wrote one equation per primitive. LayerNorm's Python computes x - mu twice, so the jaxpr holds it twice (u and z). Section 1.
  2. Lowering: 90 StableHLO operations. One rule per primitive turns each equation into compiler operations in one MLIR module; both subtractions are still there. This is the portable form jax.export ships (section 9).
  3. PJRT hands the module to XLA: 133 HLO instructions. XLA imports it into HLO, its own form. Each subtraction is now four instructions: broadcast the mean, reshape, broadcast again, subtract. PJRT, the plug between JAX and every device, is section 2; installing the right plugin for your jaxlib is its one lever.
  4. Passes rewrite the whole module. Simplification passes fold away reshapes across the module, and common-subexpression elimination (CSE) finds the two identical subtractions and keeps one: the attention block's CSE pass removes exactly one subtract. Dump every pass with --xla_dump_to (section 3); steer them with XLA_FLAGS (section 12).
  5. Fusion: 13 kernels. The surviving subtraction lands in ynn_fusion.7, a library fusion holding all of LayerNorm: 16 jaxpr equations become one kernel of 18 HLO instructions whose intermediates never reach memory. What fuses and why: section 4; layouts: section 5.
  6. Schedule, buffers, executable. XLA orders the kernels, places every byte before the step runs and emits machine code (through LLVM on CPU, PTX on NVIDIA GPUs, inside libtpu on TPU), one executable per cache key: a hit in the in-memory cache skips every stage above it, a hit on disk skips only XLA's compile (section 8). For the whole train step (forward, backward, AdamW) the plates now read 3,411 jaxpr equations, 5,318 StableHLO operations, 4,932 HLO instructions and 817 kernels (783 fusions, 33 matmuls, 1 copy), with a planned peak of 374.4 MB. Levers here: donate_argnums (section 6), jax.checkpoint (7), the caches (8), and the profiler (11).

You need: tracing and what a jaxpr is (JAX core), and the root's Compiler lab (five forms, fusion of one MLP block, donation, remat policies), which this page goes deeper than. Elsewhere: the sharding passes and collectives on Sharding and scale, the TPU's memory hierarchy on TPU programming and performance, hand-written kernels on Pallas kernels.

jaxpr
JAX's own program: one equation per primitive, recorded by tracing.
StableHLO
the versioned, portable compiler format JAX lowers to (an MLIR dialect).
PJRT
the C API between JAX and a device plugin (CPU, CUDA, TPU).
HLO
XLA's internal program, one instruction per line, free to change at any commit; "optimised HLO" is what the passes leave.
Pass
one rewrite of the whole HLO module (simplify, deduplicate, choose layouts, fuse).
Fusion
several operations compiled into one kernel, so their intermediates never reach memory.
Layout
the order an array's dimensions sit in memory; on TPU also the tiles it is cut into.
Buffer assignment
XLA's plan for every byte of the step, fixed before it runs.
Donation
letting an output reuse an input's buffer (donate_argnums).
Recompile
a cache miss: trace, lower and compile again.
How to read the evidence
measured here Apple M1 Pro, CPU only, JAX , on the running example (the tiny 4-layer character model of Topic: jax-and-tpu, 826,368 parameters, batch 32 x 128). Counts, programs and memory plans are deterministic; times are rough (a shared machine, 1-minute load 35 to 60) and labelled. read in source JAX at tag jax-v0.11.2 and XLA at commit 91888df6 (the one that tag pins), file and line found by pattern in a script. Google docs written by the makers. not run here GPU and TPU behaviour, read rather than measured: there is no GPU or TPU on this machine, and XLA's TPU compiler is not open source at all (it ships inside libtpu), so no TPU pass list can be quoted.
Why this page counts 817 kernels and the root's Compiler lab 816 (a reconciliation)

The 817 kernels here are the top-level instructions that do work: 783 fusions, 33 matrix multiplies and one copy. The root's Compiler lab counts the same way and prints 816 for its undonated step (783 fusions and 33 matrix multiplies); the donated step here adds the one copy. An earlier version of the root's lab printed 1,057, because its counter also walked the 241 tiny computations that tell each reduction how to combine two values (an add or a maximum, reached through to_apply=); those are not kernels.

1. Lowering: from jaxpr to StableHLO

Tracing leaves a jaxpr: a flat list of equations, each one primitive (an operation JAX knows how to differentiate, batch and lower, such as dot_general, mul, reduce_sum) applied to typed variables. A compiler cannot read jaxprs. Lowering translates every equation into compiler operations, one rule per primitive, much as a PyTorch backend gives each ATen operator a kernel. One jit call becomes one MLIR module. The card on the right shows one sub-block of the running example in all four forms, the same program Fig. 1 follows.

The target, StableHLO, is an MLIR dialect (MLIR is a framework for building compiler languages; a dialect is one of them) whose operations (stablehlo.dot_general, stablehlo.reduce, stablehlo.broadcast_in_dim, ...) are fixed and versioned: its compatibility document promises "5 years of backward compatibility" and "2 years of forward compatibility" for portable artifacts (openxla/stablehlo compatibility.md, read 2026-10-15) Google docs. That makes it the meeting point between front ends and compilers (PyTorch/XLA emits the same StableHLO) and the format jax.export ships (section 9). Beside it, CHLO ("client HLO") adds convenience operations (chlo.erfc, chlo.square) that are broken into StableHLO before XLA proper sees them.

A lowering rule is a Python function that receives the operands as MLIR values and emits operations. Most elementwise primitives share one rule, _nary_lower_hlo, which first broadcasts every operand to the output shape and then emits the single operation (exp's whole registration is one line). Some rules are JAX code traced again (mlir.lower_fun, which is how integer_pow becomes a few multiplies), and a rule can be registered per platform: dot_general registers one for each, which section 9 meets when one export serves CPU, CUDA and TPU.

Counting by the name JAX writes into every operation's location (jit(train_step)/jvp(...)/mul): the train step's jaxpr has mul equations. How many StableHLO operations do they lower to?

One attention sub-block, four forms: 61 equations grow to 90 operations and 133 instructions, then XLA's passes leave 13 kernels

Block 0's x + attention(layer_norm(x)), forward only, on the running example's shapes measured here. Switch forms; the text is the real output with paths removed (optimised HLO also without its metadata).


import jax
tr = jax.jit(attn_block).trace(p0, x)   # p0: block 0's parameters, x: float32[32, 128, 128]
print(tr.jaxpr)                          # jaxpr
lo = tr.lower()
print(lo.as_text())                      # StableHLO (an MLIR module)
print(lo.as_text(dialect="hlo"))         # XLA HLO before any pass
print(lo.compile().as_text())            # optimised HLO, after XLA's passes

From src/lab/lowering.py. In the jaxpr, t = div s 128.0 is followed by the same subtraction sub q t recorded twice (as u and as z), because LayerNorm's Python computes x - mu twice. Tracing records exactly what Python did; removing the duplicate is the compiler's job (common-subexpression elimination, section 3).

The lowering walk in the source, and what every primitive becomes (reference)

The walk from one jit call to one MLIR module, at jax-v0.11.2 read in source:

Each primitive's equations against the operations its rule produced, counted over the whole train step measured here:

How to read it: reduce_sum doubles in StableHLO because every reduction carries its initial value as a constant, and again in HLO because the reduction's combiner (add) is a small computation of its own. integer_pow and the other primitives under nested jits (optax's helpers, jnp.where) appear fewer times than in the flattened jaxpr: a nested jit is lowered once into a private function and called from each place. square stays a CHLO operation until XLA's import expands it. Rows with zero HLO instructions under their own name had their HLO renamed by those calls.

2. PJRT: the plug between JAX and a device

JAX should not need to know how to compile for, allocate on or launch work on each kind of hardware, and a vendor should not need to change JAX to support a new chip. PJRT is the C API in between, which each device plugin implements: create a client, list devices, compile a StableHLO module into an executable, allocate and copy buffers, execute. A jax.Array holds one buffer per device, allocated through PJRT (wrapped by IFRT, a layer above it; jaxlib's start-up log line reads PjRt-IFRT device count: total=1, addressable=1). The PyTorch analogue is the dispatcher plus a device backend; PyTorch/XLA goes through PJRT as well.

When it matters. Installing GPU or TPU support means installing the plugin that matches your jaxlib (the jax-cuda12-plugin or jax-cuda13-plugin wheels, or libtpu). Anything that can load a PJRT plugin (a C++ server, another framework) can compile and run the StableHLO that JAX produces, which is the basis of jax.export. And JAX's asynchronous dispatch (a call returns before the work is done; block_until_ready waits) is PJRT's execute returning futures.

One API, one plugin per kind of device; only the CPU client exists on this machine

Structure from xla/pjrt/c/pjrt_c_api.h and xla_bridge.py at the pinned versions read in source; the highlighted client is the only one that started here measured here.

Versioning, plugin discovery, and what this machine reports

The API is versioned in xla/pjrt/c/pjrt_c_api.h: PJRT_API_MAJOR 0, incremented "when an ABI-incompatible change is made", and PJRT_API_MINOR at the pinned commit, incremented for compatible additions read in source. JAX finds plugins at start-up: any installed module under the jax_plugins namespace, or any package advertising a jax_plugins entry point (discover_pjrt_plugins, xla_bridge.py:434), each registered with register_plugin (:584). The CPU client is built into jaxlib.

measured here A tpu backend factory is registered by default but cannot start without libtpu; no plugin is installed, so only the built-in CPU client runs. In jax.devices() that client's single device is cpu:0.

3. XLA's HLO and its pass pipeline

HLO (High Level Operations) is XLA's own program form. A module holds computations: the ENTRY computation is the program, and the others are called from it (fusion bodies, loop bodies, the two-argument functions that tell a reduction how to combine values). Each line is one instruction. One line of the optimised attention block, taken apart:

%dot.4 = f32[4096,128]{1,0} dot(%param_0, %param_1), lhs_contracting_dims={1}, rhs_contracting_dims={0}
 name     shape (dtype[dims])  opcode   operands          attributes: which dimensions are summed over
                       {1,0} = layout: dimension 1 is fastest-varying in memory (row-major)

The shape [4096,128] is the batch of 32 x 128 characters flattened by a pass called dot_decomposer, which puts every matmul into one canonical form. On a TPU the same line would carry a tiled layout such as {1,0:T(8,128)(2,1)} and possibly a memory space S(1), which XLA's docs gloss as "this array lives in VMEM (on a TPU)" (docs/shapes.md) Google docs; section 5 explains tiles.

The same program, pass by pass: CSE removes the duplicates, the library rewrite and fusion collapse the rest

Bars: top-level instructions after each pass that changed the text (a fusion counts as one), the current stretch highlighted; the line: how many of them are fusions measured here. Each pass's diff, opcode by opcode, is in the Pass diff viewer.

Passes. XLA optimises by running passes: each reads the whole module and rewrites it (simplify algebra, remove duplicates, choose layouts, fuse, insert copies). Passes are grouped into pipelines; a pipeline wrapped in HloPassFix repeats until nothing changes, which is why the dumps show algsimp, dce and reshape-mover six times in a row. Each backend assembles its own pipeline: cpu_compiler.cc has AddPass calls naming pass classes, gpu_compiler.cc with its fusion pipeline naming , and classes appear in both read in source. The TPU pipeline lives in the closed libtpu.

How to watch them. XLA_FLAGS="--xla_dump_to=DIR --xla_dump_hlo_pass_re=.*" writes the module after every pass that changed it: for the train step per-pass files ( MB with everything else XLA dumps), of which differ in program text once metadata is set aside; for the attention sub-block forward and backward, of .

Predict before you step through the passes: which single pass removes the most instructions from the train step before fusion?

The chart on the right replays the pipeline on two real programs, grouped into the seven stretches below; the numbers in the steps are the train step's, and the counters follow the program you pick.

  1. Canonicalise and inline. dot_decomposer puts every matmul into one canonical form, adding reshapes and transposes around each (4,993 to 5,368 instructions), and call-inliner pastes the nested jits JAX lowered as private functions into their callers.
  2. Simplify to a fixed point. algsimp, dce and reshape-mover (with constant folding) repeat to a fixed point. tree_reduction_rewriter adds 134 reduce-windows along the way (section 4 says why).
  3. Fold transposes, then CSE. transpose-folding lets dots read their inputs transposed; common-subexpression elimination then removes the duplicates tracing recorded, from 4,681 to 3,758 instructions, the largest drop before fusion.
  4. Choose layouts. layout-assignment gives every array one memory order and adds 88 copies where a producer and a consumer disagree; reshape-decomposer turns 142 reshapes into free bitcasts (section 5).
  5. Hand work to the library (CPU only). dot-library-rewriter wraps matmuls and many reductions into 173 YNNPACK library fusions (kCustom).
  6. Fuse. fusion takes the module from 3,677 to 2,006 instructions, and fusion-wrapper wraps every leftover operation in a one-operation fusion: 799 fusions.
  7. Clean up, copy, schedule. CSE, algsimp and dce run once more, copy-insertion adds the copies aliasing needs, and the scheduled module is left with 1,784 instructions, 783 of them fusions.

Only on GPU read in source not run here: . They are the passes that need a cost model of the device (PriorityFusion ranks fusions by estimated run time), call vendor libraries (GemmRewriter for cuBLAS), generate Triton kernels (GemmFusion, SoftmaxRewriterTriton), fit memory (HloRematerialization, section 7), or overlap communication (the collective passes taught on Sharding and scale).

Every pass that changed these programs, with its class, header line and where each backend adds it (reference)

Pass names are the ones in the dump file names; each is matched to its class by finding the name() string in the class's header at the pinned commit (header and line in the table). "GPU" lists the lines of gpu_compiler.cc (or fusion_pipeline.cc) that add the same class or its GPU variant (GpuAlgebraicSimplifier, GpuLayoutAssignment, PriorityFusion in the fusion row). Copy insertion on GPU happens in a separate pipeline file not fetched here. PyTorch's nearest counterpart to this pipeline is AOTAutograd plus Inductor: decompositions, functionalisation, pattern passes, then the scheduler that fuses.

4. Fusion: how XLA decides, and why it stops

Run a chain of elementwise operations one kernel at a time and every intermediate result is written to memory and read straight back; for this kind of work memory traffic, not arithmetic, is the cost. Fusion compiles a group of operations into one kernel so intermediates stay in registers or on-chip memory. The root's Compiler lab shows the result on one MLP block; this section shows the decisions.

Fig. 2 runs the smallest case, four elementwise operations, with the fusion pass off and on (the Fusion explorer's "elementwise chain", compiled on this CPU) measured here:

  1. The program: seven HLO operations. tanh(x * 2.0 + 1.0) * 3.0 on a 256 x 512 float32 array, 512 KiB: three broadcasts that turn the constants into arrays, then multiply, add, tanh and multiply. The arrows are the data dependences.
  2. Fusion off: every operation is its own kernel. With --xla_disable_hlo_passes=fusion XLA emits 7 kernels, and the three broadcasts each write a full 512 KiB array holding one constant.
  3. Each kernel reads its inputs from memory and writes its result back. The first multiply reads x and a broadcast array and writes x * 2; add, tanh and the last multiply do the same with the previous result. Fourteen trips of 512 KiB: 7,340,044 bytes in XLA's cost_analysis().
  4. Fusion pulls each producer into its consumer. Walking back from the output, the fusion pass asks of every operand whether to pull it in (the rule below); all seven operations are cheap, so they merge into one kLoop kernel, broadcast_multiply_fusion, and every intermediate stays in registers.
  5. Fused: read x once, write y once. 1,048,576 bytes, 7.0 times fewer. Where elementwise work is limited by memory bandwidth (every accelerator), bytes moved predict the time; the whole train step's count is in the table below.

The rule: pull producers into consumers, duplicate only what is cheap

XLA's basic fusion pass (InstructionFusion, which the CPU subclasses as CpuInstructionFusion) walks the program from its outputs back to its inputs. For each instruction (the consumer) and each of its operands (the producer) it asks one question, ShouldFuse(consumer, operand_index); a yes pulls the producer's computation inside the consumer's kernel. If the producer has other users it now runs twice, once inside the fusion and once for the others, and XLA accepts that only for cheap operations, decided by a fixed list in InstructionFusion::IsExpensive (instruction_fusion.cc:80): add, multiply, select, broadcast, transpose are cheap; exp, dot, convolution, collectives and custom calls are expensive read in source.

Two programs on a 256 x 512 array: e = jnp.exp(x), then (e + 1).sum(-1) and (e * 2).max(-1); and the same with e = x * 2. Which compiles to fewer kernels? Predict, then switch the card below.

One producer, two consumers: a cheap producer is copied into both, an expensive one is stored

Kernels and their operations are the optimised HLO, default setting; bytes are XLA's cost_analysis() for the whole program measured here. With x * 2: 2 kernels, each recomputing the multiply. With exp: 3 kernels, the first writing a 512 KiB result that both reductions read back. The reductions are library fusions (kCustom), explained below.

Fusion kinds

Every fusion carries a kind, a hint for code generation that each backend uses differently: kLoop (one loop over the output's elements: elementwise chains, broadcasts, on CPU even reductions), kInput (built around a reduction, transpose, concatenate or scatter), kOutput (work fused after an operation such as a matmul) and kCustom (backend-specific: here the YNNPACK library; on GPU, Triton and cuDNN). The train step's fusions are kLoop and kCustom measured here.

The four kinds in the header's own words, and who assigns kInput on GPU

Every fusion instruction carries a kind, defined in hlo_instruction.h:301 read in source:

  • kLoop: "we emit code that generates one element of the root at a time": one loop over the output. Elementwise chains, broadcasts, and on CPU even reductions.
  • kInput: "the primary node is the root of the fused instruction": a kernel built around a reduction (or transpose, concatenate, scatter) with its inputs fused in. XLA:GPU's PriorityFusion assigns it to exactly those four emitter kinds, with Triton, cuDNN and sort fusions getting kCustom (priority_fusion.cc:1351-1367); this CPU program has none.
  • kOutput: "the primary node is not the root", and one operand buffer must be able to alias the output: work fused after an operation such as a matmul (an epilogue). The CPU chooses it only when CanBeOutputFused holds; none appear here.
  • kCustom: "backend-specific fusions that don't fit into the above patterns": here the YNNPACK library fusions; on GPU, Triton and cuDNN fusions.

The header's own comment adds "TODO(b/79869434): This categorization scheme is not great": the kinds are hints for code generation, used differently by each backend.

A library inside the CPU compiler
XLA:CPU at this commit hands matmuls and many reductions to the YNNPACK library: its debug-option defaults add three library fusion types, INDIVIDUAL_DOT, INDIVIDUAL_CONVOLUTION and REDUCE (debug_options_flags.cc:272), while the help text of the flag that controls them still says "The default list is currently empty" (:1660). The code wins: the kCustom fusions named ynn_fusion in every dump here are those. On GPU the counterpart is cuBLAS or Triton for matmuls; on TPU, XLA's own code for the MXU.

What XLA refuses, and why

XLA logs every decision at verbose level (TF_CPP_MIN_LOG_LEVEL=0 TF_CPP_VMODULE=cpu_instruction_fusion=2,instruction_fusion=3). Counted over the whole train step measured here:

The fusion pass's own reasons, counted over the train step

XLA's own strings (FusionDecision::Forbid("...")), instruction names replaced by X; counts are decisions, not pairs. "operand can not be duplicated" and "expensive producer would be duplicated" are the duplication rule above; "Too many reductions inside single fusion" is a CPU limit of five, "to avoid excessive compilation times" (cpu_instruction_fusion.cc:482); "Fusion is not profitable" refuses an expensive producer whose consumer reads each element more than once (a broadcast does); "Producer is not loop-fusible" covers library fusions, sorts, custom calls and loops. First logged examples: Fusion explorer.

The same softmax, three ways

Two things show. With the library off, XLA's own tree_reduction_rewriter splits each reduction into a reduce-window over chunks and then a smaller reduction, a pass whose header explains it as increasing "precision for the reduction operation by applying the reduce-window first" (pairwise-style summation, smaller rounding error). And with the fusion pass off, the CPU still wraps each remaining operation in a one-operation kLoop fusion (FusionWrapper, "so that the fusion emitter can kick in"), which is why "no fusion" still prints fusions.

One softmax: 4 kernels by default, 6 with the library off or the fusion pass off

One jax.nn.softmax(x, axis=-1) on a 256 x 512 array, compiled three ways on this CPU measured here: XLA's default; with the YNNPACK library fusions switched off (--xla_cpu_experimental_ynn_fusion_type=-individual_dot,-individual_convolution,-reduce); with the fusion pass switched off (--xla_disable_hlo_passes=fusion). Each box is one kernel with the operations inside it, in the order they run; every kernel writes its result to memory for the next to read back. Bytes moved is XLA's cost_analysis().

The whole train step, with and without fusion

Kernels, bytes moved and the temporary-memory plan are deterministic; step and compile times are CPU seconds measured here on a shared machine (each in a fresh process; medians of 7 steps after 2 warm-up steps). Losses after 5 steps from the same start are identical to every printed digit with fusion on or off; with the library off the last digit moves (a different summation order).

Without fusion the step moves times the bytes (10.57 GB against 2.52 GB) and plans MB of temporaries against MB. On this CPU the time cost is moderate ( s against s of CPU per step) because the matmuls dominate and stay in the library; on an accelerator, where elementwise work is limited by memory bandwidth, the byte count is the better predictor. not run here: the GPU and TPU ratios.

On GPU and TPU

XLA:GPU replaces the fixed rules with PriorityFusion (fusion_pipeline.cc:79), which estimates each candidate's run time with a cost model of the device and fuses the most profitable first, followed by MultiOutputFusion (:89), which lets one kernel produce several outputs (two reductions that read the same input, done in one pass over it). Matmuls go to cuBLAS through GemmRewriter or become Triton kernels through GemmFusion (gpu_compiler.cc:2132), and SoftmaxRewriterTriton (:2172) turns softmax-like patterns into Triton kernels read in source. On the CPU multi-output fusion exists (CpuMultiOutputFusion) but is added only when a backend option asks for it (cpu_compiler.cc:1098). The TPU's fusion rules are inside libtpu. What transfers from this CPU: the rules' logic (cheap producers duplicate, expensive ones materialise, loops and custom calls are walls) and the byte accounting. What does not: the exact kernels, and the library split. When no compiler will fuse what you need (attention's online softmax), you write the kernel: Pallas kernels in JAX, Triton in PyTorch.

Every one of the step's fusions, with its kind, phase and model function, and thirteen small programs that keep or break fusion, are in the Fusion explorer.

5. Layouts and tiling

An array's layout is the order in which its dimensions sit in memory, written minor-to-major: f32[4096,128]{1,0} means dimension 1 changes fastest (row-major, PyTorch's contiguous); {0,1} would be column-major. In PyTorch a transpose is a free view with new strides and the kernel that reads it copes. XLA instead gives every array one layout, chosen by the layout-assignment pass so that matmuls and reductions read memory in the order they want; each transpose then either disappears into the instruction that reads it or becomes a real copy.

In the train step, layout assignment added copies, and reshape-decomposer ("Postcondition: All reshapes are turned into bitcasts") turned reshapes into bitcasts or a bitcast plus copy (see the Pass diff viewer).

Three transposes and reshapes, compiled: a copy, nothing, and a free bitcast measured here

Entry computations of the optimised HLO, metadata removed (src/lab/buffer_lab.py). A transpose alone is a physical copy (transpose_copy_fusion). Fed into a matmul it vanishes: transpose-folding rewrites the dot to contract over dimension 0 instead, because, in its header's words, the dot "is implemented by a GEMM kernel that can transpose its inputs". A reshape that does not change memory order becomes a bitcast, a free reinterpretation, inside the fusion.

Tiling, on TPU. A TPU layout also cuts the array into fixed tiles because, in XLA's words, "XLA TPU uses a variety of tile-based formats due to the two-dimensional nature of its vector registers". The docs write F32[3,5]{1,0:T(2,2)} for a 3 x 5 array in 2 x 2 tiles, padded to whole tiles, and state that bf16 on TPU uses (8,128)(2,1): tiles of 8 x 128 elements, with pairs of rows interleaved inside (docs/tiled_layout.md at the pinned commit) Google docs. The cost is padding.

Padding to whole 8 x 128 tiles: a minor dimension just past a multiple of 128 nearly doubles the bytes

Predict first: with 128 rows in bf16, which wastes more, a minor dimension of 127 or of 129? Then drag.

derived padded bytes over real bytes = (8 · ⌈r/8⌉ · 128 · ⌈c/128⌉) / (r · c), from the docs' bf16 tile (the (2,1) interleave inside a tile adds no padding when rows are a multiple of 8). The default is the running example's output head in bf16, [128, 65] with 65 as the minor dimension: padded to [128, 128], 1.97 times its bytes. The embedding table [65, 128] pads only its 65 rows to 72 (1.11 times). That is the arithmetic behind "choose dimensions that are multiples of 128", taught with the MXU on TPU programming and performance. not run here

Bytes live at each point of the train step's schedule: the peak sits where forward turns into backward

Reconstructed from XLA's own dump measured here: the schedule ( positions) and every value's live range from *-live-range.txt, sizes from *-buffer-assignment.txt. The reconstructed peak is MB against the 374.4 MB XLA reports at position 407 (a 0.3% difference from values that share an allocation). Phase bands come from the operation names: jvp is the forward pass, transpose(jvp) the backward pass, the rest the optimiser and gradient norms. The dashed frame is the current stretch; the red dot, the peak.

6. Buffer assignment: every byte planned before the step runs

PyTorch allocates as it goes, from a caching allocator, and you learn the peak afterwards (torch.cuda.max_memory_allocated()). XLA plans memory ahead: after the passes it fixes an order of execution (the schedule), gives every value a live range (from the instruction that defines it to the last one that reads it), and packs values whose ranges do not overlap into the same bytes. The result is the buffer assignment; compiled.memory_analysis() summarises it, and the dump writes it out in full.

  1. Before the forward pass. The step's inputs (parameters, both Adam moments, the batch) are live from the first position to the last: the floor under the whole curve.
  2. Forward: live bytes climb. Each layer adds the activations the backward pass will need, and none of them can be freed yet.
  3. The peak, at the turn. 374.4 MB at schedule position 407, where the forward pass ends and the backward pass begins; the bars below say which operations produced those bytes.
  4. Backward: freed as consumed. The backward pass uses the saved activations layer by layer, last layer first, and frees each when it is done; a few optimiser instructions are scheduled in between.
  5. Optimiser. Gradient norm, clipping and the AdamW update: small, elementwise, one chain per parameter array, on top of the inputs' floor.

XLA attributes the bytes live at the peak to the JAX operation that produced them (right). The divisions (28%) are LayerNorm's normalised values and softmax outputs saved for the backward pass; erfc (17.9%) is the exact GELU's intermediate, kept at the MLP's 512 width, four layers deep; reduce_max is softmax's row maxima broadcast back to full size. This is the list to read before reaching for rematerialisation.

What is live at the peak, by the operation that produced it

From the dump's "Stack trace breakdown for peak usage" measured here.

What is in the plan. allocations: are parameters that may also hold an output (the donated parameters and optimiser state, reused for the new ones), are thread-local scalars inside loops and reduction bodies, and one preallocated temporary buffer of MB holds every intermediate at its planned offset. On CPU, memory_analysis().peak_memory_in_bytes leaves the temporaries out: add temp_size_in_bytes or read total_allocation_bytes.

Aliasing and in-place updates

Donation (jax.jit(step, donate_argnums=(0, 1)), shown in the root's Compiler lab) lets an output reuse an input's buffer. Without it XLA must keep the input intact, and a pass makes sure it does. Checked on a MiB array with x.at[i].set(v) measured here:

Correction
An old note on this knowledge base said that under jit "XLA turns these [x.at[i].set(v)] into true in-place updates, so no copy cost in practice". The update is in place only when the array is donated or is an intermediate inside the jitted function. Updating a non-donated argument copies the whole array first, because copy-insertion must keep "Entry parameter[s] ... live out of the entry computation" in their own allocation (copy_insertion.h:41) read in source. In a loop that updates a large state each step, that is a full copy per step: donate.

7. Rematerialisation: yours and the compiler's

Two different mechanisms share the name, and they differ in who decides and what failure looks like:

jax.checkpoint (alias jax.remat)XLA's HloRematerialization pass
Who decidesyou, at trace time, with a policy such as dots_saveable (measured on this model in the root's Compiler lab)the compiler, after scheduling
When it actsalways: what is not saved is recomputed in the backward passonly when the planned peak exceeds the device's memory limit
Whereevery backendthe GPU pipeline (gpu_compiler.cc:3378); absent from the CPU pipeline, so no dump here shows it; the TPU equivalent is inside libtpu read in source
What you seea known slowdown you chosea model that barely does not fit may not fail: the step just gets slower, with no error

How to check. compiled.memory_analysis() against the device's memory, and a dump filtered to the pass (--xla_dump_hlo_pass_re=rematerialization). The fix you control is the explicit one: choose what jax.checkpoint saves, so the compiler has nothing left to guess. The two meet at one point: jax.checkpoint lowers its recomputation behind an optimization_barrier so that XLA's CSE (section 3) cannot merge the recomputed values back into the forward pass and undo the saving (ad_checkpoint.py:867 at jax-v0.11.2, quoted in the root's lab).

The pass's algorithms and strategies

Its header names two algorithms, kAlwaysRemat ("Rematerializes anything it can at any point the HLO is above the memory limit. Default rematerialization algorithm.") and kPeakPriority ("Prioritize rematerializing the highest peak ... Much slower than the default algorithm"), and three strategies a mode can enable: recompute, compress (keep a value in a more compact shape that the backend supplies through a CompactShapeFunction) and host offload (move it to host memory and back) (hlo_rematerialization.h:78-96) read in source.

8. The caches: paying for compilation once

In memory. A jitted function keeps a cache keyed on everything that can change the program: the function object itself, the abstract signature of its arguments (shapes, dtypes, weak types, the pytree structure), the values of static arguments, and the tracing context (configuration that affects tracing, such as jax_default_matmul_precision). A hit skips tracing, lowering and compiling; a miss does all three, and in every scenario of the Recompile detective, counted through jax.monitoring, the three counts move together measured here. This cache dies with the process; f._cache_size() reports how many entries a jitted function holds.

On disk. The persistent compilation cache stores executables between processes:

jax.config.update("jax_compilation_cache_dir", "/path/to/cache")
jax.config.update("jax_persistent_cache_min_compile_time_secs", 0.0)  # default 1.0: faster compiles are not written

Its key is a SHA-256 over eight ingredients, hashed in order in cache_key.py (the entries list at line ): . The XLA flags are hashed after removing flags that cannot change the program, among them --xla_dump_to and --xla_force_host_platform_device_count. So upgrading jaxlib or the device plugin, adding a flag, or any code change that alters the module (donation included) misses. JAX logs each ingredient's hash at debug level, which tells which one changed between two runs:

Two caches in front of the compiler: a call misses only if its key is new to both

The in-memory key as the recompile scenarios exercise it (section 10); the persistent key's eight ingredients from cache_key.py at jax-v0.11.2 read in source. The 1 s threshold is jax_persistent_cache_min_compile_time_secs's default.

Each row is a fresh process compiling the running example's train step against the same cache folder (the "threshold" row uses its own empty folder) measured here. Hits, misses, files and changed ingredients are deterministic; CPU seconds are rough. One entry is KB; a hit costs s of CPU against s for a compile.

When it matters. On a TPU pod every host compiles the same program at start-up, for minutes on large models; the JAX docs recommend a cache "in a shared file system (eg: NFS) or remote storage" for multi-node jobs, and describe a Cloud Storage bucket for it. The same docs warn: "The compilation cache is considered trusted. ... Sharing a compilation cache is equivalent to allowing anyone who can write to the cache directory to run code on your machine" (docs/persistent_compilation_cache.md) Google docs. Keep it per user, or read-only for everyone but a trusted job.

9. Ahead of time: stages, serialized executables and jax.export

Stages. jax.jit(f) hides stages you can call one at a time: .trace(*args) gives a Traced (the jaxpr), .lower() a Lowered (StableHLO), .compile() a Compiled (an executable you call directly). Arguments can be real arrays or jax.ShapeDtypeStruct placeholders, so a program can be compiled before any data exists. A Compiled object never retraces; called with a different shape it refuses (compile one per shape bucket, or call the jit function instead) measured here:


Serialized executables. jax.experimental.serialize_executable.serialize(compiled) turns the compiled CPU executable of the forward pass into KB; in a fresh process deserialize_and_load brings it back in s of CPU and it returns the same logits (difference 0.0) measured here. The bytes are machine code for this backend and this jaxlib: a cache you manage yourself, not a format to ship.

jax.export: the format to ship. jax.export.export(jax.jit(f), platforms=...)(*args) returns an Exported: the StableHLO module plus everything needed to call it later (input and output types, shardings, the platforms, and a calling convention version that fixes how arguments are passed; here, the current one). .serialize() gives bytes; jax.export.deserialize(...).call(...) compiles and runs them, in another process or years later. On the running example's forward pass measured here:

Three things to notice. Lowering needs no device, so this CPU-only machine produced the CUDA and TPU exports. A three-platform export is one module: it takes an extra argument, _platform_index, and wraps every operation whose lowering rule is platform-specific in a stablehlo.case that picks a branch at run time; here only dot_general registers such rules (lax.py:6385), so the module grows by operations although the three branches print identically for float32. And a TPU-only export refuses to run here with an error naming both platforms (in the table): export for every platform you will run on (platforms=("cpu", "cuda", "tpu")).

Compatibility. The JAX docs promise that a serialized export runs on JAX "up to 6 months newer" and "up to 3 weeks older" than the JAX that exported it (docs/export/export.md) Google docs, much shorter windows than StableHLO's own 5 and 2 years, because an export also depends on JAX's calling convention and on the custom calls it emits, which the same document versions separately.

Shape polymorphism, gradients of an export, and a stale line in the docs

Shape polymorphism. With b, = jax.export.symbolic_shape("b") and an input of jax.ShapeDtypeStruct((b, 128), jnp.int32), one export serves every batch size:

Gradients of an export. .serialize(vjp_order=1) includes the backward function:

A stale line. docs/export/export.md still says "As of June 2024, all function exported with version 9 (the latest ...)" one line above an example printing 10: version 10 (propagating the Shardy partitioner setting) became the default in JAX 0.7.0. Calling an export from TensorFlow goes through jax2tf and from C++ through a PJRT plugin; neither was run here (TensorFlow is not installed).

10. Recompiles: causes, evidence and the fix

Anything in the in-memory cache key (section 8) that changes between calls costs a full trace, lower and compile: for the train step, seconds; for a large model on TPU, minutes. Usually nothing fails; the step just gets slow. JAX can explain every miss: with jax.config.update("jax_explain_cache_misses", True) each one logs a warning that names the argument and what changed. Fig. 3 runs the common causes, each a case of the Recompile detective (eleven scenarios) with JAX's own words; how one hit and one miss work inside is drawn once, on JAX core's Fig. 2:

  1. The first call misses. Nothing is cached: trace, lower and compile, then store the executable under the call's key. Every case starts this way.
  2. New values, same signature: a hit. f(x, 3.0) after f(x, 2.0) compiles once for both calls: values are not in the key.
  3. Shapes that vary miss. The last, smaller batch of an epoch, or a new sequence length: "different input types: * at x, now f32[31,128] and before f32[32,128]". Two compilations; the same array in bfloat16 misses the same way.
  4. Weak types miss. A Python 2.0 is weakly typed, a np.float32(2.0) is not: "now f32[]{weak_type=False} and before f32[]{weak_type=True}". Two compilations.
  5. Anything else in the key misses. Static arguments: every new value of a static_argnums argument is a new program (JAX's explanation here is only "cache miss explanation unavailable"), and the value must be hashable (a list raises; pass a tuple). A dict that gains a key is a new pytree structure. Configuration: changing jax_default_matmul_precision between calls gives "Tracing context doesn't match". Two compilations each.
  6. A new function object never hits. jax.jit(lambda ...) created inside a loop: "never seen function ... maybe the function is being re-defined repeatedly": 3 calls, 3 compilations, one cache per lambda. Wrapping the same named function again is fine: one compilation.
  7. And its opposite: a stale hit. A Python global read inside the function is baked in at trace time as a constant; changing it later neither recompiles nor takes effect (the detective prints [2. 2.] twice). Pass it as an argument.
  8. A storm: one executable per length. A decoding-style loop on a prefix that grows from 1 to 64 positions compiles 64 times with exact shapes, and 4 times when each length is padded up to a multiple of 16 and masked.

The storm of step 8, call by call: a decoding-style loop calls a jitted attention-like function on a prefix that grows from 1 to 64 positions. Exact shapes compile once per length; padding each length up to a multiple of 16 (and masking) needs four programs. Same inputs, same outputs; compile counts are deterministic, seconds are measured here (the second of three repeats is drawn; compile time in the counters is the median of the three). Switch between the two on the right.

A recompilation storm: 64 compilations for 64 prefix lengths, 4 with buckets

At scale, count compilations instead of reading logs. jax.monitoring.register_event_duration_secs_listener receives an event for every trace (/jax/core/compile/jaxpr_trace_duration), lowering and backend compile (/jax/core/compile/backend_compile_duration), the same hooks the detective uses; export them to your metrics system and alert when the count grows after warm-up. jax_log_compiles prints one line per stage (sample below).

What jax_log_compiles printed for the storm's first calls

The fixes, in the order to try them: make the shapes static (pad and mask to a few buckets, drop or pad the last batch); keep Python scalars out of the signature or make their types consistent; hoist jax.jit out of loops and keep one jitted function per role; pass configuration as static arguments deliberately, not by accident; and warm up every bucket before timing. When shapes must vary at run time and padding wastes too much, export with symbolic shapes (section 9) or let the serving framework bucket for you.

11. Profiling: which view answers which question

Taking a profile. Wrap a few steps after warm-up:

with jax.profiler.trace("/tmp/prof"):
    for i in range(5):
        with jax.profiler.StepTraceAnnotation("train", step_num=i):
            state = step(*state)
            jax.block_until_ready(state)   # without it the trace shows dispatch, not work

and open the folder in XProf (pip install xprof; the tool behind TensorBoard's Profile tab), which the JAX docs describe as "a great way to acquire and visualize performance traces and profiles of your program, including activity on GPU and TPU" (docs/profiling.md) Google docs, or in Perfetto. The files carry the machine's host name: scrub before sharing.

For a performance question, the trace viewer (one row per thread or device stream, every kernel named after its HLO instruction), HLO op stats (time, FLOP rate, bandwidth and whether each instruction is compute- or memory-bound) and the memory profile answer most of it; on this CPU, HLO op stats, the op profile and the memory profile came back empty.

Which XProf view answers which question, and what each returned on this CPU

"On this CPU" is what xprof 2.23.2's own converter returned for the running example's trace measured here. The device-side tables are empty on a CPU: their columns (the header of hlo_stats includes "HBM BW (GiB/s)", "Bound by" and "TPU core type") are filled from device events that a CPU run does not record. not run here: their TPU and GPU content.

What the trace says about the running example. One step is about ms of wall time on this loaded machine; of the kernels' thread time, the backward pass takes about %, the forward % and the optimiser and gradient norms % measured here. Matmuls and the projections around them (the linear function) dominate. On a TPU the same table would be read against the roofline (is each fusion limited by FLOPs or by HBM bandwidth?), which TPU programming and performance teaches. Every kernel of one step, joined to its phase and model function, is in the Profile reader.

How to read a trace you did not expect. Gaps on the device row with a busy Python row mean the host cannot feed the device (dispatch, data loading, a host sync such as float(loss) every step). One kernel far longer than its neighbours: find it by name in the optimised HLO (fusion names are stable within one compile) and look at what was fused into it. Many tiny kernels: fusion broke (section 4). Time inside jit calls that should be cached: a recompile (section 10). The PyTorch profiler and Nsight equivalents are on Profiling, benchmarking and correctness.

12. XLA flags that matter, and their risks

XLA reads XLA_FLAGS once, when the backend starts: "Set XLA_FLAGS before importing Jax or other relevant libraries. Changing XLA_FLAGS after backend initialization will have no effect" (docs/xla_flags.md) Google docs; set inside a running script, they fail silently, so set them in the shell or in os.environ before import jax. Every flag is a field of DebugOptions, defined with its default and help text in xla/debug_options_flags.cc read in source (the flags this page uses, with their help text, are in the closed block below). Five CPU settings on the train step measured here, each in a fresh process; losses are the first five steps from the same initial state:

CPU seconds on a shared machine (1-minute load printed per row): read ratios, not values. --xla_backend_optimization_level=0 roughly halves compile time and more than doubles step time; numbers stay identical, and the optimised HLO is the same ( kernels, fusions, checked with the flag on): the level steers the backend's code generation, not the HLO passes. Fast math changed nothing measurable on this program.

On TPU, flags go in LIBTPU_INIT_ARGS and are read by the closed compiler. MaxText keeps a library of them: a scoped VMEM limit of 98304 KiB for dense models, flags that fuse and overlap collectives with compute, and data-parallel overlap (benchmarks/xla_flags_library.py at the pinned commit) read in source not run here.

Risks
Flags are debug options, not an API: names change between releases and help text goes stale (the YNNPACK flag's help contradicts its default, section 4). Some change numbers (fast math, disabling passes). Disabling a pass can make compilation fail or the program slow in ways that only show at scale. Every flag that is not on JAX's exclusion list is part of the persistent cache key (section 8), so a new flag recompiles everything. Keep production flags in one place, record them with each run, and re-measure after every JAX upgrade.
The flags on this page, with their defaults and help text at the pinned commit (reference)

13. How XLA compares with torch.compile

Where XLA sits among the GPU compilers (what each one decides about fusion, code generation and assembly, side by side with Inductor, nvcc and TVM) is drawn once, on The compiler stack, section 1 (What each compiler decides on the way down). Against torch.compile specifically, the stages line up and the behaviour differs in five places:

jax.jit and XLAtorch.compile (Dynamo, AOTAutograd, Inductor)
Failure modeone program or an error, never a silent fallbacksplits the graph at what Dynamo cannot trace and runs that part in Python (the root's lab shows both on the same branch)
Dynamic shapesevery shape static under jit; symbolic shapes only through jax.export; padding to buckets is your jobmarks a dimension dynamic after it changes and compiles one program for a range of sizes
Where decisions liveC++ passes, readable for CPU and GPU, closed for TPU; XLA:GPU itself emits Triton for some fusions (GemmFusion, SoftmaxRewriterTriton)Python, emitting Triton or C++ you can read
Memoryevery byte planned before running and reported (memory_analysis)allocated at run time, reported afterwards
Scopethe whole train step, optimiser included, as one programoften the model only, with the optimiser outside or compiled separately

The first row is the root of the rest: because JAX gets the whole step or nothing, XLA can fuse across the forward and backward pass, plan every byte, and cache the result by a key it can compute. On the PyTorch twin of the running example the root measured eager operators in one step against Inductor-generated kernels. A hand-written Triton kernel's JAX counterpart is a Pallas kernel. How Dynamo, AOTAutograd and Inductor work inside: The compiler stack, section 8 (its section 1 sets what each compiler on the way down decides); from the user's side (guards, TORCH_LOGS=recompiles, the FX graph and AOTAutograd caches, torch.export plus AOTInductor): torch.compile from the user's side.

Every stage of this page beside its nearest PyTorch counterpart (reference)
StageJAX and XLANearest PyTorch counterpartHere
Capture the programTracing: run the Python once with abstract values, record a jaxprTorchDynamo reads Python bytecode and records an FX graph, falling back to Python at graph breaks1
Portable program formatStableHLO, versioned, with compatibility guaranteesCore ATen IR in torch.export (PyTorch/XLA also produces StableHLO)1
Talk to a devicePJRT: one C API, a plugin per device (CPU built in, CUDA, ROCm, TPU)The dispatcher plus a backend per device (CUDA, PrivateUse1); PyTorch/XLA uses PJRT2
Optimise the graphXLA's HLO pass pipeline, different per backendAOTAutograd plus Inductor's graph passes and scheduler3
Fuse operationsXLA fusion passes with fixed rules (CPU) or a cost model (GPU)Inductor's fusion into generated C++ or Triton kernels4
Plan memoryBuffer assignment before anything runs; donation lets outputs reuse inputsThe caching allocator at run time; no plan ahead6
Reuse compiled codeIn-memory caches per function, plus a persistent on-disk cacheDynamo's code cache guarded by checks, FX graph and AOTAutograd caches8
Ship a compiled modeljax.export (StableHLO with a calling convention), serialized executablestorch.export plus AOTInductor9
Find why it recompiledjax_explain_cache_misses, jax_log_compiles, jax.monitoringTORCH_LOGS=recompiles, guard failure reasons10

Depth: mistakes and interview rehearsal

Mistakes the sections above do not already show, with the real errors (4)

Every error message is real output from src/lab/ on JAX , paths removed.

A list (or dict) as a static argument. Static arguments are cache-key entries, so they must be hashable: . Pass a tuple.

Serializing an export without flatbuffers. ImportError: Please install 'flatbuffers' in order to use Exported serialization. It is not a dependency of jax 0.11.2; install it next to JAX.

Leaving jax.debug.print in the training step. It compiles to a host callback, a custom call that splits fusion: the three-operation chain that is 1 kernel without it is 3 kernels with it, plus a round trip to Python each step (Fusion explorer, "jax.debug.print in the middle").

Diagnosing a slow step by reading the Python. The Python ran once, at trace time. Read what the compiler made of it, in this order: the explanation of cache misses (section 10), the dumped HLO before and after the change (count fusions, copies and transposes; a layout change can add copies), memory_analysis() and whether donation still aliases (alias_size_in_bytes; a bigger plan can trigger XLA's rematerialisation on GPU), and a profile (which kernels grew, and whether the device now waits on the host).

Interview rehearsal: two questions that add a design angle (optional)

Why does XLA not fuse everything into one kernel? Fusing a producer with several users duplicates its work, which XLA accepts only for cheap operations; matmuls and (on this CPU) many reductions go to libraries; loops, sorts, custom calls and host callbacks are walls; and backends cap fusion size (five reductions per fusion on CPU, concatenations of more than eight operands) to keep compile time and code quality reasonable. On GPU a cost model decides which fusions pay.

Design: serve a JAX model on TPU for requests of any length up to 8,192 tokens, with predictable latency. Fix a small set of shape buckets (for example powers of two in length, and a few batch sizes), pad and mask into them, and AOT-compile every bucket at start-up with jax.ShapeDtypeStruct placeholders so no request ever compiles; count compilations through jax.monitoring and alert on any after warm-up. Share a read-only persistent cache among replicas built by a trusted job, keyed by the exact jaxlib and libtpu versions. The trade-off is padding waste against the number of programs: with power-of-two buckets the expected waste is up to half of each request's length in the worst case, so add intermediate buckets where traffic concentrates. If the model must also run elsewhere, ship it as a multi-platform jax.export. Measure with a profile per bucket: decode steps are memory-bound, so small batches waste the MXU and the batch buckets matter as much as the length buckets.

Scripts, outputs and the check scripts are in this page's src/lab/ (see src/README.md). Pinned sources: JAX jax-v0.11.2 (32544801e261, 2026-09-17), XLA 91888df6 (the commit that JAX tag pins), MaxText 1a95d1e5; XLA files fetched one by one, listed in src/inputs/. Everything ran on 2026-10-15.