All posts

Same Math, Different Programs: JAX and TorchTPU on a TPU

What one training step turns into on a TPU v5e chip: 1 XLA program in jax.jit, 438 in TorchTPU's default mode, and why

PyTorch now runs on TPUs through TorchTPU, a native PyTorch backend: tensors live on a "tpu" device and every operator is lowered to XLA, the same compiler JAX uses. So a PyTorch user looking at TPUs has a choice: rewrite the training loop in JAX, or keep the PyTorch code and pick one of TorchTPU’s execution modes. Both frameworks hand the same compiler the same matrix multiplications, so it is fair to expect the choice not to matter much.

I ran the same models with the same weights and the same batches through JAX and TorchTPU on one TPU v5e chip, and profiled what each one actually launches on the device. The arithmetic matched: at full precision the first-step loss was identical, and gradients agreed to under 1e-5. The speed did not: the slowest mode took 4.3 times as long per step as the fastest, and most of the gap comes from one question: how many compiled programs one training step turns into, and what goes into each of them.

This post builds a small model of what a TPU runs, then walks through each execution mode with an experiment that shows how it splits a step into programs, and ends with the defaults that change the result when you compare the two frameworks.

TL;DR: JAX and TorchTPU 0.2.0 on one TPU v5e chip

  • Trace the whole training step into one program. jax.jit(train_step) and TorchTPU’s torch.tpu.optimizers.SingleTraceTrainer both do; a char-level GPT runs at 10-13 ms per step with them, and at 33-44 ms in TorchTPU’s other modes as written (21 ms for torch.compile with attention written out).
  • TorchTPU’s default (strict eager) runs every operator as its own program: 438 per step here.
  • DeferAndFuse (TORCH_TPU_DEFER_AND_FUSE=1) fuses a forward pass into one program, but cuts a training step apart, by all appearances at every deferred tensor that several results share: 154 programs per step.
  • torch.compile(backend="tpu") captures a training step as several graphs (5 programs per GPT step: Dynamo breaks the graph at optimizer.zero_grad(), inside the optimizer step and at loss.backward()), and spent most of its GPT step copying tensors around F.scaled_dot_product_attention.
  • Compare like with like. jax.nn.dot_product_attention keeps attention scores in fp32 for bf16 inputs and SingleTraceTrainer’s in bf16; XLA keeps excess precision in fusions in JAX and not in TorchTPU; TorchTPU computes GELU with exp and a divide where JAX uses tanh. Matching these one at a time moved the winner back and forth; with scores in bf16 (the trainer’s SDPA against JAX’s attention written out) and ReLU instead of GELU, SingleTraceTrainer was 4% faster (9.9 against 10.3 ms). With identical attention code JAX stayed ahead. At sequence 1024 the attention kernel mattered more: JAX with Pallas splash attention, which doesn’t run inside the trainer, was 25% faster than the trainer’s best.

What a TPU runs

Later sections refer back to a few parts of the chip, so here they are once. A TPU v5e chip has one TensorCore. Inside it:

  • The MXU (matrix unit): four 128x128 systolic arrays that multiply bf16 and accumulate in fp32, 197 TFLOP/s in total. Matrix multiplications go here.
  • The VPU (vector unit): everything elementwise, such as adds and conversions between bf16 and fp32.
  • VMEM: an on-chip scratchpad the compiler manages. Data comes in from HBM, gets computed on, and goes back.
  • HBM: 16 GiB at 819 GB/s. At 197 TFLOP/s, an operation needs about 240 FLOPs per byte it reads or writes before the MXU, not the memory, is what limits it.

The TPU does not launch kernels one at a time from the host the way a GPU stream does. It runs compiled XLA programs: the host hands it a program and its inputs, and the chip runs the whole program. Inside one program XLA can fuse elementwise work into the matrix multiplication that feeds it, keep intermediates in VMEM instead of writing them to HBM, and overlap memory traffic with compute. Between programs it can do little of that: every program boundary writes its outputs to HBM, and the host has to launch the next program.

That gives two costs to watch in every mode below:

  1. Launch cost. Each program costs the host some time to dispatch. When programs are small, the TPU waits.
  2. Lost fusion. Work split across programs makes extra round trips to HBM.

So the question for each framework is: how many programs does one step become, and how much work does each one hold?

The same three operations as one XLA program, with one launch and intermediates kept in VMEM, and as three programs, with three launches and every intermediate written to HBM and read backThe same three operations as one XLA program, with one launch and intermediates kept in VMEM, and as three programs, with three launches and every intermediate written to HBM and read back

The setup

Everything ran on a Colab TPU v5e-1 runtime (one chip) with JAX 0.11.2 and TorchTPU 0.2.0 on PyTorch 2.14.1 (libtpu 0.0.50). One difference in the environment: JAX sets --xla_tpu_use_enhanced_launch_barrier=true in LIBTPU_INIT_ARGS at import on this image, and TorchTPU doesn’t. Flipping it on either side moved the GPT step by less than 1%. Each framework and mode ran in its own process, because TorchTPU reads its execution mode once at import and only one process can hold the TPU.

Mode What it does Default or opt-in
jax.jit traces the function once and compiles it into one XLA program the usual way to run JAX
JAX eager the same function without jax.jit: about one small program per primitive default when you don’t jit
TorchTPU strict eager one program per PyTorch operator, compiled at a lower optimization level TorchTPU default
TorchTPU DeferAndFuse records operators without running them until a result is needed, then compiles what it collected opt-in, TORCH_TPU_DEFER_AND_FUSE=1
torch.compile(backend="tpu") Dynamo (PyTorch’s bytecode-level graph capture) turns Python into graphs, each compiled as one program opt-in
SingleTraceTrainer traces forward, backward and optimizer into one graph with PyTorch’s make_fx tracer and compiles it opt-in, torch.tpu.optimizers

The workloads: a chain of 128 elementwise operations, a transformer MLP block, a transformer block training step, and a char-level GPT (6 layers, width 384, sequence 256, batch 64) trained for 1,000 steps with AdamW in bf16. The GPT starts from the same NumPy weights on both sides and sees the same batches in the same order. Benchmark times are medians after warmup, with a device synchronize before the clock stops; GPT step times are the mean over 997 steps after 3 warmup steps, in a loop that reads the loss on the host every 50 steps. “Queued” means calls issued back to back with one synchronize at the end (20 calls in the benchmarks; 50 steps in the GPT loop), which is how a training loop runs; “per call” means a synchronize after every call. Program counts come from profiles (jax.profiler and torch.profiler) of a few steps with a synchronize after each, counting the XLA modules on the TPU’s timeline.

The MLP block is written the way each framework is usually written. In JAX, a function of its parameters, with the weights stored (in, out):

def rms(x, g):
    xf = x.astype(jnp.float32)
    return (xf * jax.lax.rsqrt(jnp.mean(xf * xf, -1, keepdims=True) + 1e-6)).astype(x.dtype) * g

def mlp_block(params, x):            # x: (tokens, 1024), bf16
    w1, b1, w2, b2, g = params       # w1: (1024, 4096), w2: (4096, 1024)
    h = jax.nn.gelu(rms(x, g) @ w1 + b1, approximate=True)
    return x + h @ w2 + b2

In PyTorch, a module with nn.Linear layers, which store their weights (out, in):

def rms(x, g):
    xf = x.float()
    return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + 1e-6)).to(x.dtype) * g

class MLP(torch.nn.Module):
    def __init__(self, d=1024, f=4096):
        super().__init__()
        self.g = torch.nn.Parameter(torch.ones(d))
        self.fc1 = torch.nn.Linear(d, f)
        self.fc2 = torch.nn.Linear(f, d)

    def forward(self, x):            # x: (tokens, 1024), bf16
        return x + self.fc2(F.gelu(self.fc1(rms(x, self.g)), approximate="tanh"))

The GPT uses the same pieces in each layer, with (in, out) weights on both sides; its full code is in bench/train_jax.py and bench/train_torch.py.

Before comparing speed, I checked that both sides compute the same thing. In fp32 with matmul precision “highest”, the first-step loss of strict eager, torch.compile and SingleTraceTrainer was identical to JAX’s (4.905652), the worst gradient differed by 7.7e-6 relative to its scale, and optax.adamw, torch.optim.AdamW and torch.tpu.optimizers.AdamW produced the same parameters to within 6e-7 after three steps on the same gradients. At that precision the two frameworks do the same arithmetic, so the speed differences below come from how the work is split and compiled. The bf16 defaults do differ, in attention and in how much precision fusions keep; both have their own part near the end.

One program per operator: the eager modes

Strict eager is TorchTPU’s default. Every PyTorch operator becomes a small XLA program, compiled once per operator and shape and cached. JAX without jit does the same per primitive.

On the 128-operation chain over a 4096x4096 bf16 array, both launch 128 programs and take the same time: 13.5 ms in JAX eager and 13.7 ms in strict eager, of which 13.1-13.2 ms is the TPU working in both. On a tiny 8x128 array, where the TPU has almost nothing to do, the call costs 8.0 ms in JAX eager and 6.9 ms in strict eager, about 60 and 55 µs per operation. Per-operator dispatch costs about the same in both frameworks.

Where eager modes differ is everything around the operators. Taking gradients in JAX eager means tracing jax.value_and_grad in Python on every call: an MLP training step spent 13.7-15.6 ms of host time per step at every size up to 16,384 tokens. PyTorch’s autograd records the backward pass as the forward runs, so strict eager’s host time was 1.1-1.4 ms per step.

Even with cheap dispatch, eager modes pay the second cost. An MLP forward pass (RMSNorm, two matmuls, GELU, residual, 2048 tokens) is 12 programs in strict eager and one in jax.jit, and the TPU spends 0.47 ms on it against 0.20 ms. Each of the 12 writes its result to HBM for the next to read.

Strict eager also compiles each operator’s program at a lower optimization level (-O1). A lone 8192x8192 bf16 matmul ran at 157 TFLOP/s in strict eager against 179 in JAX, and compiling the GPT’s 438 programs at -O2 brought its step from 43.5 to 38.1 ms. The TPU was busy for 96% of strict eager’s GPT step, so on that model the time goes to the programs themselves more than to launching them.

One program per function: jax.jit

jax.jit traces the Python function once into a graph of primitives (the jaxpr), and XLA compiles the whole graph into one program. The MLP forward pass has 26 primitives; the compiled program has 8 fusions and 2 matrix multiplications, and runs in 0.20 ms on the TPU. A training step written as one function (forward, jax.value_and_grad, optimizer update) becomes one program too:

@jax.jit
def train_step(params, opt_state, batch):
    loss, grads = jax.value_and_grad(loss_fn)(params, batch)
    updates, opt_state = optimizer.update(grads, opt_state, params)
    return optax.apply_updates(params, updates), opt_state, loss

The price is compile time per input shape. The MLP over 24 different sequence lengths compiled 24 programs, about 0.5 s each, and then ran all 24 in 5.5 ms on the second pass.

Tracing also decides what Python values mean. In the chain written with Python constants, 64 repetitions of x = x * 1.0001 + 0.0001, JAX turns the constants into bf16 values while tracing. 1.0001 rounds to 1.0 in bf16, so XLA drops the multiply and folds the 64 adds into one: the whole chain becomes x + 0.006409, 0.10 ms on the TPU. TorchTPU’s eager modes pass Python scalars to the program as runtime arguments (f64[] parameters in the HLO, the program text XLA compiles), so nothing folds and all 128 operations run. torch.compile bakes them in like JAX does. A benchmark of elementwise code can measure the constant folder rather than the framework if the constants are Python numbers.

Deferring work: DeferAndFuse

DeferAndFuse is TorchTPU’s middle ground. Operators don’t run when Python calls them; they are recorded, and when something needs a result (a .item(), a synchronize, a copy to the host), the recorded operators are compiled and run. Below, a result is a tensor the code goes on to use outside the recorded work: one it reads, returns or keeps (a loss, a gradient). On the MLP forward pass this works as intended: one program, 0.31 ms on the TPU, against 12 programs in strict eager.

A training step is a different story. The transformer block’s step became 24 programs, and the GPT’s 154. To find out where DeferAndFuse draws the boundaries, I ran a small MLP through a set of cases and counted programs per call:

Case (deferred tensor h = x @ w1) Programs
forward pass only, with or without gradient tracking 1
h feeds two results: gelu(h).sum() and (h * 2).sum() 3
h feeds two branches that join into one result: (gelu(h) + h * 2).sum() 1
h is itself a result and also feeds gelu(h).sum() 1
two independent results that share nothing 1
forward and backward of the MLP (no optimizer step) 7
the same gradients written out by hand, no autograd 7

DeferAndFuse: when a deferred tensor h feeds two separate results it becomes its own program and each result gets one, three programs; when the branches rejoin into one result, one programDeferAndFuse: when a deferred tensor h feeds two separate results it becomes its own program and each result gets one, three programs; when the branches rejoin into one result, one program

The rule these cases point to: a deferred tensor that is not itself a result, but that two or more separate results need, ends a graph. DeferAndFuse moves it into its own program and gives each result a program of its own. Branching inside one result, such as a residual connection, stays in one program. A backward pass needs the forward activations for the loss and for several gradients, which are separate results, so a training step is full of such tensors. The last two rows show that it is the shape of the computation, not autograd: hand-written gradients split the same way. I inferred the rule from these cases; TorchTPU’s documentation doesn’t state it.

A second mechanism cuts loops: DeferAndFuse detects repeated sequences of operators, so the 128-operation chain came out as 64 programs of two (an internal flag turns it off; it didn’t change the transformer block’s 24 programs).

Deferring also moves the launch cost. In the transformer block, the profile shows 3.4 ms of idle TPU between steps in DeferAndFuse, against 0.5 ms in strict eager and JAX. The host trace suggests why: nothing is launched before the step’s synchronize, and after it the host spends about 2.5 ms materializing the recorded graph as its 24 programs while the TPU waits. In a loop that doesn’t read results every step, most of that is hidden: queued, the step took 3.5 ms instead of 5.9.

Capturing graphs: torch.compile

torch.compile(backend="tpu") lets Dynamo capture the Python function into graphs of PyTorch operators (FX graphs) and compiles each graph into one program. On the MLP forward pass it gives one program (0.28 ms on the TPU).

A training step written the usual PyTorch way doesn’t become one graph:

@torch.compile(backend="tpu")
def train_step(batch):
    opt.zero_grad(set_to_none=True)
    loss = model(batch)
    loss.backward()
    opt.step()
    return loss

Dynamo has graph breaks here: points where it stops capturing, runs Python, and starts a new graph. Its graph-break log (TORCH_LOGS=graph_breaks) names three: Optimizer.zero_grad is on Dynamo’s skip list, the optimizer step calls torch._dynamo.graph_break() itself, and loss.backward() can’t run inside the compiled function because it would consume the autograd graph of tensors the function returns. The transformer block’s step ran as 4 programs, the GPT’s as 5. Turning on PyTorch’s compiled autograd (torch._dynamo.config.compiled_autograd = True), its usual fix for the backward break, changed neither count: Dynamo then reports that autograd.grad() inside torch.compile isn’t supported with compiled autograd, and the GPT step took 41.0 ms against 42.3.

The GPT exposed a second problem. Of torch.compile’s 42.3 ms step, the TPU was busy for 41 ms, and 24 ms of that were copy, as_strided_inverse and as_strided operations: layout changes around F.scaled_dot_product_attention. The compiled program names where they come from: the HLO metadata ties 12 copies in the forward and 48 in the backward to the attention op, most of them to its as_strided_inverse (StableHLO, the form TorchTPU hands to XLA, has no strided views, so views become copies), and with attention written out none of the copies tied to the attention op appear (other copies, 5.8 ms of them, remain). The op matters: under torch.compile, F.scaled_dot_product_attention became scaled_dot_product_cudnn_attention and its backward, while SingleTraceTrainer’s trace of the same call became scaled_dot_product_fused_attention_overrideable, whose whole train step had 6 such copies. With attention written as a plain matmul, softmax and matmul, the copies dropped to 5.8 ms and the step from 42.3 to 21.4 ms. That is still twice JAX’s 10.2 ms with the same attention, and not because of launches: its 5 programs kept the TPU busy for 19.8 ms of each step. The extra time is inside the programs (5.8 ms of it the remaining copies); I didn’t break the rest down. (torch.optim.AdamW under torch.compile also needed capturable=True, or the compiled graph got a CPU tensor for the step counter.)

One program per step: SingleTraceTrainer

TorchTPU’s answer to jax.jit(train_step) is torch.tpu.optimizers.SingleTraceTrainer. It traces the forward pass, the backward pass and a functional optimizer step into one graph with make_fx and compiles that:

import torch, torch_tpu

opt = torch.tpu.optimizers.AdamW(lr=1e-3, weight_decay=0.1, beta1=0.9, beta2=0.95,
                                 use_bfloat16_moments=True)   # the bf16 GPT run
trainer = torch.tpu.optimizers.SingleTraceTrainer(
    model, opt, compile_fn=lambda gm: torch.compile(gm, backend="tpu", fullgraph=True))
train_step = trainer.make_compiled_train_step(example_inputs=batch)  # model(batch) returns the loss
loss = train_step(batch)

The GPT step became one program, like JAX’s, and ran in 11.2 ms, against 12.7 ms for jax.jit (the attention section below explains why the trainer is ahead there). The host spent 1.9 ms per step handing it over. Two things don’t work inside it yet: TorchTPU’s own fused SGD (aten._fused_sgd_ is not functional, so tracing rejects it) and its splash attention op, a TPU attention kernel written by hand in Pallas, JAX’s language for TPU kernels; its autograd function lacks the setup_context the trace needs.

One setup was slow. With every batch put on the device up front, the trainer’s step took 22.7 ms instead of 11.2 (2 programs instead of 1), though the TPU’s work per step stayed at 11.1 ms; JAX’s step barely changed. I didn’t find the cause; copying each batch from the host, as every other run here does, avoids it.

The MLP training step shows the same groups at every size from 256 to 65,536 tokens: one-program modes first, then torch.compile and DeferAndFuse (which trade places with size), then strict eager. Peak memory at 16,384 tokens: the trainer 197 MiB (XLA’s plan for JAX’s program: 193 MiB), DeferAndFuse 633, torch.compile 742 and strict eager 1,186.

MLP train step at 16,384 tokens: JAX jit and SingleTraceTrainer run one XLA program per step and are fastest; DeferAndFuse, torch.compile and strict eager run 12, 5 and 29 programs and are 1.3 to 2.1 times slowerMLP train step at 16,384 tokens: JAX jit and SingleTraceTrainer run one XLA program per step and are fastest; DeferAndFuse, torch.compile and strict eager run 12, 5 and 29 programs and are 1.3 to 2.1 times slower

At small sizes the host decides. At 256 tokens a queued jax.jit step takes 0.12 ms. jax.jit returns from a call in 0.07 ms and SingleTraceTrainer in 0.23 ms; torch.compile and DeferAndFuse need about 0.8 ms of host time, more than the work itself. At large sizes the compiler decides: at 65,536 tokens, queued, JAX reached 183 TFLOP/s and SingleTraceTrainer 168, against 88 for strict eager. The 9% between the two one-program modes is the GELU, which a later section explains: with ReLU instead, the trainer was within 1% of JAX.

MLP train throughput by tokens per step: JAX jit reaches 183 TFLOP/s and SingleTraceTrainer 168, strict eager stays under 90; at 256 tokens every mode is far below peakMLP train throughput by tokens per step: JAX jit reaches 183 TFLOP/s and SingleTraceTrainer 168, strict eager stays under 90; at 256 tokens every mode is far below peak

Here is what each mode launches for one transformer-block training step, from the profiles:

Device timeline of a transformer-block train step: JAX jit launches one XLA program per step, torch.compile 4, DeferAndFuse 24 and strict eager 65Device timeline of a transformer-block train step: JAX jit launches one XLA program per step, torch.compile 4, DeferAndFuse 24 and strict eager 65

Where they really differ: the defaults

Once both sides run one program per step, what is left are settings that one framework turns on and the other doesn’t. Three of them changed results here, on the GPT and on the smaller benchmarks: attention precision, excess precision and how GELU is computed.

Attention precision. On the GPT, SingleTraceTrainer (11.2 ms) beat jax.jit (12.7 ms), and the reason was not in the compiler. jax.nn.dot_product_attention computes the attention scores in fp32 even for bf16 inputs (its source asks for fp32 output from the score matmul). The attention SingleTraceTrainer uses (TorchTPU’s default lowering of F.scaled_dot_product_attention) keeps them in bf16. Both do the softmax arithmetic in fp32 inside a fusion; the difference is the dtype the 64x6x256x256 score tensor is stored in between kernels, so JAX moved twice the bytes for those tensors through HBM. In the compiled programs, JAX’s step had 18 matrix multiplications with fp32 output (three per layer) where the trainer’s had none; the other 111 were the same. To get bf16 scores in JAX I wrote attention out (einsum, mask, softmax, einsum) and left the scores in bf16; for fp32 scores in TorchTPU I wrote it out with q and k cast to fp32. Then I matched the other defaults one at a time (bold marks the faster framework in each row):

GPT step, what is matched jax.jit SingleTraceTrainer
nothing (each framework’s defaults) 12.7 ms 11.2 ms
attention scores in fp32 12.7 ms 15.3 ms
scores in bf16, the same written-out attention code on both sides 10.2 ms 12.1 ms
scores in bf16 (JAX written out, trainer SDPA) 10.2 ms 11.2 ms
the same, excess precision on in both 10.2 ms 11.1 ms
the same, excess precision off in both 11.5 ms 11.2 ms
the same, ReLU instead of GELU in both 10.3 ms 9.9 ms

(TorchTPU’s fp32 version upcasts the inputs before the matmul, which moves more bytes than JAX’s bf16-in, fp32-out matmul, so that row probably overstates the gap. The ReLU row keeps each side’s excess-precision default, which favors JAX, and trains a slightly different model; its losses are lower in both frameworks. The excess-precision rows are one batch order each; the others are two or three, which varied by 0.02 ms or less.) Which framework is faster depends on what you match: with every default left alone the trainer was 12% faster, and with fp32 scores JAX was 17% faster. With the same attention code on both sides JAX was 15% faster. Only with scores in bf16 and its own SDPA lowering did the trainer stay within 10% of JAX, in either direction. The gap with identical code is not a default, and I didn’t find its cause. The two default configurations compute different things, and a benchmark of defaults measures that choice.

That GPT is small (sequence 256, width 384). I also ran one at sequence 1024, width 768, 12 heads and 6 layers, with batch 16 for the same 16,384 tokens per step (one run per row, 300 steps). There the attention kernel decided the order:

GPT step, sequence 1024 jax.jit SingleTraceTrainer
each side’s default attention 81.5 ms (32% MFU) 62.1 ms (42%)
the same written-out attention code, scores in bf16 65.5 ms (40%) 78.6 ms (33%)
JAX’s Pallas splash attention, trainer’s SDPA 46.7 ms (56%) 62.1 ms (42%)

Splash attention made JAX 25% faster than the trainer’s best, and it doesn’t run inside SingleTraceTrainer. At sequence 256 it had made JAX slower (14.4 against 12.7 ms), so where it starts to pay off lies in between. With identical attention code JAX was again faster, here by 17%. I didn’t run TorchTPU’s splash op in its other modes at this size.

Excess precision. XLA may keep the intermediates of a fusion in fp32 instead of rounding to bf16 after every operation (allow_excess_precision). It is on in JAX and off in TorchTPU. Off, the compiled fusions carry extra rounding instructions (reduce-precision in the HLO) after each operation, which is why keeping more precision is the faster setting. On the GPT it moved JAX by 1.3 ms and the trainer by 0.1 ms; I don’t know why the trainer barely moves. The fused 128-operation chain (the version with its scalars passed as arrays, so nothing folds) took 0.36 ms on the TPU in JAX and 0.71 ms in torch.compile. Turning the flag off in JAX (XLA_FLAGS=--xla_allow_excess_precision=false) made JAX’s chain 0.71 ms; turning it on in TorchTPU (torch.tpu.allow_excess_precision = True) made torch.compile’s 0.36 ms. One caution: with a warm PyTorch compile cache, both this flag and torch.set_float32_matmul_precision seemed to do nothing under torch.compile, apparently because the on-disk cache reused programs compiled under the old setting. The comparisons of settings in this post come from processes with an empty cache.

The GELU. JAX’s jax.nn.gelu(approximate=True) is 0.5x(1 + tanh(u)). TorchTPU lowers F.gelu(approximate="tanh"), the same function, as x / (1 + exp(-2u)), with an exponential and a divide, and XLA fuses it into the second matmul of an MLP. On the MLP forward pass (2048 tokens, nn.Linear weights), TorchTPU’s one program took 40-55% longer on the TPU than JAX’s (torch.compile 0.28 ms, DeferAndFuse 0.31, JAX 0.20), most of it in that fusion. Writing JAX’s GELU in TorchTPU’s form, or replacing both with ReLU, with the weights stored (in, out) on both sides:

MLP forward, TPU time jax.jit torch.compile
GELU as tanh (JAX’s) 0.202 ms  
GELU as exp and divide (TorchTPU’s) 0.237 ms 0.235 ms
ReLU 0.192 ms 0.190 ms

With the same activation, the two frameworks take the same time. nn.Linear’s (out, in) weight layout makes the exp form dearer still (0.28 ms in both frameworks); the compiled programs handle the transposed weight itself the same way on both sides. The GPT uses (in, out) weights on both sides, so there the GELU costs less, but it is still the difference that was left: with attention scores in bf16, JAX led by 1.0 ms with GELU and trailed by 0.4 ms with ReLU (the table in the attention part).

One default the two share: fp32 matmuls run as a single bf16 pass unless you ask for more (JAX’s default precision, TorchTPU’s medium), with 2.35e-3 relative error on a 4096x4096 product. PyTorch on GPUs defaults to full fp32 (6e-7 relative error here at “highest”), so code ported from GPUs gets about 4,000 times the matmul error on TPU unless it sets torch.set_float32_matmul_precision("highest").

Where it ended up

The GPT, 1,000 steps on one TPU v5e chip, same weights and batches. MFU is model FLOPs utilization: the share of the chip’s 197 TFLOP/s peak that the step’s model FLOPs (matmuls and attention, counted without a causal discount) reach. jax.jit steps also run a tiny second program that stages the inputs; the table counts the step itself.

Framework / mode ms per step MFU Programs per step
jax.jit, attention written out (scores in bf16) 10.2 57.8% 1
SingleTraceTrainer (SDPA, scores in bf16) 11.2 52.6% 1
jax.jit with jax.nn.dot_product_attention (fp32 scores, the default) 12.7 46.6% 1
torch.compile, attention written out 21.4 27.6% 5
DeferAndFuse 32.8 18.0% 154
torch.compile 42.3 14.0% 5
strict eager 43.5 13.6% 438

Against JAX’s default attention, strict eager takes 3.4 times as long per step; the 4.3x in the introduction is against the fastest row.

The losses agree: over the last 100 steps, three batch orders gave 1.35-1.50 in JAX and 1.39-1.56 in SingleTraceTrainer, and every other mode landed inside that range.

bf16 GPT training loss over 1,000 steps: JAX jit and SingleTraceTrainer curves overlap within the spread of three batch ordersbf16 GPT training loss over 1,000 steps: JAX jit and SingleTraceTrainer curves overlap within the spread of three batch orders

Three things I would check on any model on a TPU, though everything here is one v5e chip and one small GPT:

Count the programs per step before tuning anything. A profile’s device timeline shows it in a second. Here it separated the one-program modes from the rest. It did not order the modes in between: on the GPT DeferAndFuse, at 154 programs, ran in 32.8 ms and torch.compile, at 5, in 42.3; on the MLP sweep, queued, torch.compile led up to 4,096 tokens and DeferAndFuse from 16,384.

Trace the whole step, optimizer included. In JAX that is jax.jit around the training step. In TorchTPU it is SingleTraceTrainer, which came within 10% of JAX on the small GPT with scores in bf16 and its own SDPA lowering (JAX was 15% faster with identical attention code). At sequence 1024, JAX with splash attention was 25% faster than the trainer’s best.

Check the defaults you are comparing. On the GPT step, attention score precision moved JAX from 12.7 to 10.2 ms, excess precision moved it from 10.2 to 11.5, and the GELU moved the trainer from 11.2 to 9.9; on a fused elementwise chain excess precision alone was 2x. None of them is in the API you call.

If you keep PyTorch code: start with SingleTraceTrainer for training; for a forward pass, torch.compile and DeferAndFuse both make one program (0.62 and 0.82 ms per call on the MLP, against 1.14 in strict eager); write attention as plain operations if you use torch.compile; and store weights you multiply as (in, out) parameters used as x @ w rather than nn.Linear’s (out, in), which made TorchTPU’s fused GELU cheaper on the MLP forward pass (0.22 against 0.31 ms in DeferAndFuse; I didn’t measure a full model with nn.Linear). If you write JAX: jax.jit the whole step, choose the attention precision on purpose, and try splash attention once sequences get long.

What’s left. Why the (out, in) layout makes the fused exp GELU so much dearer is not visible in the compiled program; it would take the TPU’s per-operation schedule. Why SingleTraceTrainer idles with batches already on the device is open too. Everything here is one v5e chip; I didn’t measure v6e or multi-chip training. Four of the TorchTPU findings are now upstream issues: the GELU lowering (#7277), splash attention inside SingleTraceTrainer (#7278, with a fix in #7281), the copies around SDPA under torch.compile (#7279), and the compile cache ignoring the excess-precision setting (#7280, fix in #7282).

The benchmarks, the raw results behind every number in this post, and the scripts that produce them are in bzantium/jax-vs-torchtpu.

Further reading