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.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.
x - mu twice, so the jaxpr holds it twice (u and z). Section 1.jax.export ships (section 9).subtract. Dump every pass with --xla_dump_to (section 3); steer them with XLA_FLAGS (section 12).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.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.
donate_argnums).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.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.
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.
jit(train_step)/jvp(...)/mul): the train step's jaxpr has mul equations. How many StableHLO operations do they lower to?broadcast_in_dim measured here. A jaxpr may multiply an array by a scalar (mul bc 0.5); StableHLO requires both operands to have the same shape, so the rule broadcasts the scalar first. The broadcasts cost nothing at run time: fusion folds them into the kernel that reads them.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 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.
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.
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.
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.
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.
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 .
cse, from to instructions. The step computes the global gradient norm twice (once inside clip_by_global_norm, once for logging), one square, sum and add per parameter array each time, and broadcasts the same scalars into each of the 69 optimiser updates. Tracing records all of it; CSE keeps one copy. Its header: "Identical constants and identical instructions with the same operands are commoned" (hlo_cse.h:32).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.
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.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).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.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).dot-library-rewriter wraps matmuls and many reductions into 173 YNNPACK library fusions (kCustom).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.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).
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.
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:
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.--xla_disable_hlo_passes=fusion XLA emits 7 kernels, and the three broadcasts each write a full 512 KiB array holding one constant.cost_analysis().kLoop kernel, broadcast_multiply_fusion, and every intermediate stays in registers.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.
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.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.
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.
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.
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.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:
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.
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 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().
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.
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.
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).
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.
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
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.
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.
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.
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.
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:
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.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 decides | you, 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 acts | always: what is not saved is recomputed in the backward pass | only when the planned peak exceeds the device's memory limit |
| Where | every backend | the 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 see | a known slowdown you chose | a 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).
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.
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:
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.
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. 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).
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:
f(x, 3.0) after f(x, 2.0) compiles once for both calls: values are not in the key.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.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.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.[2. 2.] twice). Pass it as an argument.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.
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).
jax_log_compiles printed for the storm's first callsThe 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.
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.
"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.
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.
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 XLA | torch.compile (Dynamo, AOTAutograd, Inductor) | |
|---|---|---|
| Failure mode | one program or an error, never a silent fallback | splits the graph at what Dynamo cannot trace and runs that part in Python (the root's lab shows both on the same branch) |
| Dynamic shapes | every shape static under jit; symbolic shapes only through jax.export; padding to buckets is your job | marks a dimension dynamic after it changes and compiles one program for a range of sizes |
| Where decisions live | C++ 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 |
| Memory | every byte planned before running and reported (memory_analysis) | allocated at run time, reported afterwards |
| Scope | the whole train step, optimiser included, as one program | often 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.
| Stage | JAX and XLA | Nearest PyTorch counterpart | Here |
|---|---|---|---|
| Capture the program | Tracing: run the Python once with abstract values, record a jaxpr | TorchDynamo reads Python bytecode and records an FX graph, falling back to Python at graph breaks | 1 |
| Portable program format | StableHLO, versioned, with compatibility guarantees | Core ATen IR in torch.export (PyTorch/XLA also produces StableHLO) | 1 |
| Talk to a device | PJRT: 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 PJRT | 2 |
| Optimise the graph | XLA's HLO pass pipeline, different per backend | AOTAutograd plus Inductor's graph passes and scheduler | 3 |
| Fuse operations | XLA fusion passes with fixed rules (CPU) or a cost model (GPU) | Inductor's fusion into generated C++ or Triton kernels | 4 |
| Plan memory | Buffer assignment before anything runs; donation lets outputs reuse inputs | The caching allocator at run time; no plan ahead | 6 |
| Reuse compiled code | In-memory caches per function, plus a persistent on-disk cache | Dynamo's code cache guarded by checks, FX graph and AOTAutograd caches | 8 |
| Ship a compiled model | jax.export (StableHLO with a calling convention), serialized executables | torch.export plus AOTInductor | 9 |
| Find why it recompiled | jax_explain_cache_misses, jax_log_compiles, jax.monitoring | TORCH_LOGS=recompiles, guard failure reasons | 10 |
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).
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.
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.XLA's CPU pipeline replayed on two real programs of the running example, one pass at a time: what each pass changed in the program text, opcode by opcode, and where the pass is added in the CPU and GPU compilers at the pinned XLA commit. Dumped with XLA_FLAGS="--xla_dump_to=DIR --xla_dump_hlo_pass_re=.*" on an Apple M1 Pro, CPU only (src/lab/passes_diff.py). The Reading tab's section 3 explains passes; this tab is for looking.
How to read a diff: - lines left the program, + lines entered it; metadata (source locations) is stripped before comparing, and lines are cut at 170 characters. The attention block's diffs are shown up to 50 lines, the train step's up to 14 (its full dumps are 64 MB). Instruction counts are top-level: a fusion counts as one. Passes that ran without changing the text are not dumped.
Every fusion in the running example's optimised train step, the fusion pass's own reasons for what it refused, and thirteen small programs that keep or break fusion, each compiled three ways. Everything here was compiled on an Apple M1 Pro, CPU only, JAX 0.11.2 (src/lab/fusion_lab.py); kernel counts, kinds and bytes are deterministic. The mechanics are explained in Reading, section 4.
Colour is the model function the fusion's first instruction came from, read through the stack frames XLA keeps in metadata; a dashed outline marks a YNNPACK library fusion (kCustom). Phase comes from the JAX operation name: jvp forward, transpose(jvp) backward, neither the optimiser; "unlabelled" fusions have no operation name (constants and copies). Sixteen fusions, the two largest of each kind and phase, carry their full HLO body.
Counted from TF_CPP_VMODULE=cpu_instruction_fusion=2,instruction_fusion=3 over the train step's compilation. Click a reason for the first producer and consumer it was logged for (metadata removed, names as in the log).
Inputs: a 256 x 512 float32 array; 256 x 128 by 128 x 512 for the matmul; a 65 x 128 table and 32 x 128 indices for the lookup. Bytes moved is XLA's cost_analysis()["bytes accessed"] for the whole program. "Library off" is --xla_cpu_experimental_ynn_fusion_type=-individual_dot,-individual_convolution,-reduce; "fusion off" is --xla_disable_hlo_passes=fusion.
Eleven small cases. For each, read the code and predict whether the last call traces and compiles again; then see what JAX counted (through jax.monitoring: traces, lowerings and backend compilations) and what jax_explain_cache_misses printed. Run on JAX 0.11.2, CPU (src/lab/recompile_lab.py); inputs are NumPy arrays so that creating them compiles nothing. Counts and messages are deterministic. Why the cache works this way: Reading, sections 8 and 10, where Fig. 3 steps through the common causes and the recompilation storm is drawn call by call.
One train step of the running example as the profiler recorded it: a jax.profiler.trace of five steps on an Apple M1 Pro, CPU only, converted with xprof 2.23.2 and scrubbed of the host name (src/lab/profile_lab.py). Every kernel is joined to the fusion it ran (its phase and model function, from the Fusion explorer). Timings are measured on a shared machine at low priority (1-minute load given below) and vary from run to run; the structure does not. Which xprof view answers which question: Reading, section 11.
Rows are threads: Python (the main thread, waiting in block_until_ready), the PJRT client that dispatches, and the XLA:CPU worker pool (10 threads: the thread-count flags have no measurable effect here, as the setup notes record). Only events of at least us are drawn ( of ). On a GPU or TPU the device has its own rows, one per stream or core, and the host rows show only dispatch.
Thread time summed over all worker threads for the step drawn (so it exceeds the step's wall time). "Optimiser" includes the gradient norm and clipping. Matmuls run inside YNNPACK library fusions (kCustom), which is why "linear" dominates. Files the trace wrote: .
This page's tabs, the parent topic and its labs, the sibling pages, the knowledge base pages on the PyTorch and GPU side, and the best outside sources, each with an approximate time. Outside sources are marked Google (written by the makers of JAX, XLA or StableHLO: authoritative on how things work) or third-party. Links checked on 2026-10-15.
The whole pipeline from jaxpr to machine code, then fusion, layouts, buffers, remat, caches, export, recompiles, profiling, flags, and how XLA compares with torch.compile; mistakes and two interview questions in closed blocks. 39 min, plus 14 in closed details
XLA's CPU pipeline replayed pass by pass on the attention block and the train step, with diffs and source lines. 10 to 20 min
All fusions of the step, the fusion pass's refusals with examples, 13 programs that keep or break fusion. 15 min
Eleven predict-then-reveal cases with JAX's own explanations and fixes. 10 min
A small trace viewer of one step, kernels joined to phases and model functions. 10 min
The overview this page goes deeper than. Its Compiler lab tab: the five forms, fusion of one MLP block, donation, remat policies, scan against unroll, caches, debugging tools; its Transforms lab: tracing line by line; Sharding lab: GSPMD and collectives on 8 simulated devices; TPU and Pallas lab: rooflines and a first Pallas kernel. Reading: 32 min, plus 13 in closed details; each lab 18 to 25 min
Tracing in depth, jaxpr anatomy, autodiff, vmap, pytrees: everything before lowering.
Flax NNX, optax, orbax, grain; donation with nnx.jit.
Porting the running example; numerical differences.
The SPMD partitioner passes (GSPMD, Shardy) and the collective passes named in section 3.
Tiles, padding, rooflines and TPU profiles.
When XLA's fusion is not enough: write the kernel.
MaxText's remat policies, scan and XLA flags in production.
The PyTorch and CUDA side of this page: Dynamo, AOTAutograd, Inductor's fusion, down to SASS.
Guards, graph breaks, recompiles, caches, torch.export and AOTInductor.
Block-level kernels; what XLA:GPU's Triton fusions generate.
Nsight and honest timing on GPUs.
The PyTorch counterpart of sections 6, 7 and 11: memory, profiling, attention kernels.
PyTorch's caching allocator, against XLA's ahead-of-time plan.
The hardware the closed TPU compiler targets.
FLOPs, bytes and rooflines, for reading bytes-moved numbers.
Google. The stages API. 15 min
Google. jax.export, calling conventions, compatibility windows. 40 min
Google. Settings, multi-node use, the trust warning. 15 min
Google. Cache-miss explanations and compile logs. 10 min
Google. Taking traces; XProf and Perfetto. 15 min
Google. The compiler's stages on one page. 10 min
Google. Every HLO operation defined. reference
Google. TPU tiles and padding, with the index formulas. 15 min
Google. Which flags to use for TPU and GPU performance. 20 min
Google. The operation set JAX lowers to. reference
Google. The device interface and its plugins. 15 min
Google. Each profiler view explained. 30 min
Google DeepMind authors. Reading HLO and XProf for a real TPU workload (published TPU traces). 40 min
Third-party (2023). How XLA's fusion passes worked on GPU then, with measured effects; older than the pinned code. 60 min
Third-party (2020). XLA, TVM, Glow and others side by side. 90 min