The optimization playbook¶
Prerequisites: Memory model, storage and views, Profiling with XProf
Chapter 10 ends with a trace you can trust and a list of what bounds the step. This chapter turns that list into changes. A TPU step loses time in a small number of ways, and each one leaves its own signature in a trace: gaps where the host is busy, compiles that repeat, chains of small memory-bound ops, matmuls doing arithmetic on padding, copy ops nobody wrote, collectives the chip waits for, and matmuls running far below their roofline. For each signature the chapter names the cause, the fix and the mechanism by which the fix works, then argues for an order to try them in, shows how to measure one change at a time without fooling yourself, and reads a published optimization log (FLUX.1 on TorchTitan, 11.49 s to 2.78 s per step) stage by stage. The companion code applies the same ladder to a small model on your laptop, checking parity before it believes any number.
What this chapter covers¶
- Seven trace signatures that bound a step (host-bound, recompiles, memory-bound ops, padding waste, hidden copies, exposed collectives, poor MXU utilization), read from chapter 10's workflow.
- The four mechanisms behind the fixes (fewer programs, fewer bytes, fewer wasted FLOPs, hidden communication), and which signature each fix can and cannot remove.
- An order for trying fixes that keeps every later measurement valid, and why each step sits where it does.
- Reading a published optimization log stage by stage: seconds removed against percentages quoted on a shrinking base.
- The evidence a change needs: parity with the baseline, before and after step times taken the same way, and a trace in which the targeted signature is gone.
Four levers behind every fix¶
The TorchTitan TPU optimization guide reduces its whole strategy to two ideas: raise the work done per launched program, and reduce the number of host dispatches. Those two cover the most common case, a step that is idle between programs. Add the other two places time goes on a chip that is busy, and every fix in this chapter pulls one of four levers:
| Lever | What it removes | Fixes that pull it |
|---|---|---|
| Fewer, larger programs | Host dispatch and the gaps between programs | torch.compile per block, DeferAndFuse, GraphTrainer, larger batch and model dim, removing host syncs |
| Fewer bytes | HBM round trips, layout copies, materialized intermediates | Fusion under compile, zero-copy views, compact math, fused kernels that never write an intermediate (fused cross-entropy, Splash attention) |
| Fewer wasted FLOPs | Arithmetic on padding, extra MXU passes | Dimensions aligned to the MXU tile, sequence packing, bf16 or one-pass matmul precision |
| Hidden communication | Collectives the compute waits for | SimpleFSDP with compile so XLA schedules collectives against matmuls, scheduler flags (Part IV) |
The roofline from chapter 2 says which of the last three can help a given op: below the ridge, only fewer bytes; above it, only fewer FLOPs or a better MXU fill. The first lever is outside the roofline entirely. A step whose TPU is idle a third of the time gains nothing from making its matmuls faster.
Read each row left to right: the shape in the trace, the cause it usually has, the first fix. The sketches have no time scale; what identifies a row is the shape (where the orange is), not the length.
From trace to fix: the decision tree¶
The tree starts where chapter 10's reading workflow ends. Each branch is a question you answer from the trace, and each leaf is a section of this chapter. Branches are ordered: you do not reach the top-ops questions until the idle and recompile questions are answered, for the same reason chapter 10 reads idle time before ranking ops.
A trusted trace is one that passed chapter 10's checks. The cards are the chapter's sections in order, from host-bound (two cards: a host read and dispatch look different in the host rows) to poor MXU use, then chapter 12; idle time is answered first, and every fix ends in a new capture.
The loop back to the top is the point. A fix that removes a signature also changes the trace around it, so the next decision is made from a new capture, never from the old one. Memory pressure, the last section, has no leaf: running out of HBM is not a step-time signature, but it limits how far the levers above can go.
The fixes, signature by signature¶
1. Host-bound: the TPU waits between programs¶
Two different causes produce gaps on the device rows, and chapter 10 separates them by looking at the host rows at the moment a gap starts.
A host read. Anything that needs a device value on the host forces the stream to drain: .item(), .cpu(), print(tensor), if tensor > x, and ops whose output shape depends on the data, such as torch.masked_select. The TorchTPU execution model documentation adds that in DeferAndFuse or compiled mode the same read also cuts the fused region or breaks the graph, so the cost is twofold. The fixes are the ones in chapter 4: read every N steps and keep metrics on the device (the TorchTitan guide's advice for loss logging), and replace data-dependent Python branches with torch.where. The guide also tells you to switch off per-op Python checks (shape or type validators) in benchmark runs, since they add host time in eager mode.
Dispatch. In the default Strict eager mode every op is its own program. Enqueueing a program costs up to about 50 µs of host time, and when programs are shorter than that the TPU runs out of work between them (the microbubbles of chapter 4). The TorchTitan guide's mental model is blunt: run uncompiled, and a small or naively configured model is idle "a large fraction of every step", while the matmuls, when they do run, are fine. Its prescription is to treat torch.compile as step zero of performance, not an optional lever.
The three ways to put more work in each program, from least to most invasive:
export TORCH_TPU_DEFER_AND_FUSE=1 # read once at backend start-up
with torch.tpu.set_eager_mode(torch.tpu.EagerMode.DEFER_AND_FUSE):
train()
Ops are deferred and cut into programs at host reads and detected loops, then compiled at -O2. No model change. The execution model documentation reports up to 50% over default eager. The TorchTitan guide uses the internal path torch_tpu._internal.execution_mode for the same context manager; the public name is torch.tpu.set_eager_mode (TorchTPU API reference). It composes with compile: compiled regions run as compiled programs and DeferAndFuse fuses the eager glue between them. On a model already compiled per block the guide expects it to add little, and if a fusion crashes at the libtpu level (it names some unaligned dynamic-update-slice fusions), turn it off for that model.
for i, block in enumerate(model.layers): # blocks held in an nn.ModuleList
model.layers[i] = torch.compile(block, backend="tpu", dynamic=False)
Each block becomes one XLA program: its ops are fused, launched once, and scheduled together with the block's collectives. The snippet sketches what TorchTitan's apply_compile does; the real function is switched on by --compile.enable in its trainer, and the guide calls it "the single highest-impact change". Per block rather than whole model keeps activation checkpointing between blocks, so memory stays bounded. The block has to trace, which rules out data-dependent Python inside it.
config.compile = TpuGraphTrainerCompileConfig(
enable=True, components=["model"], memory_policy="default",
optimizer_compile="in_graph", # optional: fold AdamW into the step graph
)
TorchTitan's TpuGraphTrainer traces forward, loss, backward and optionally the optimizer step with make_fx into one graph, and runs it as one XLA program, with a graph-level policy that decides per tensor whether to save, recompute or offload activations. The whole step must trace: no graph breaks to fall back on. The guide's limits apply: optimizer_compile="in_graph" costs HBM because step inputs are not donated today, and on libtpu 0.0.48 and later the recipes set xla_enable_hlo_sharding_v3=False, because Shardy HLO sharding v3 segfaults on GraphTrainer.
Why not compile the whole model? The guide lists the failure modes of torch.compile(model, fullgraph=True) on TorchTPU: without checkpointing inside the graph all layers' activations are live at once, so deep models run out of memory at compile time or at run time; the token-embedding backward can bind incorrectly when compiled, so leave the embedding eager; lazily created buffers such as RoPE tables must exist before tracing; and even when it works it covers only forward and backward, so the loss and the optimizer step remain separate programs. No TorchTitan TPU recipe uses it.
The dispatch ceiling. Per-block compile leaves the optimizer step, the loss, the embedding and layout ops as separate programs, and the gaps between them set a ceiling that compiling the transformer harder cannot raise: the guide's point is that the idle is "in everything around it". Shrink that surface with the glue's own switches (compile.optimizer_compile="separate_graph", compile.compile_grad_norm=True, loss in compile.components), keep batch and model dim large so compiled regions dominate the step, or remove the surface with GraphTrainer. The guide expects a well-sized dense model with per-block compile and the fused cross-entropy to land in the low to mid tens of percent MFU, and says that further gains come from shrinking the eager surface, not from more tuning. The TorchTitan integration post reports 51 to 52% MFU for Qwen3-8B with the functional AdamW update traced into the GraphTrainer step.
More work per program. The guide's largest lever at small scale is batch: a larger per-device batch raises the compute in every launched program while the dispatch cost stays the same. Push it until HBM is the limit. A larger hidden dim does the same, since matmul FLOPs grow with \(\text{dim}^2\); moving from 1024 to 2048 can roughly double MFU by itself. Both change the training configuration, so they are decisions to make with whoever owns the model, not free optimizations.
2. Recompiles: every step pays a compile¶
The signature is a host that spends each step compiling while the device idles, or (under a cache) every step slower by the same large amount; chapter 7 has the decode loop that pays 38 to 50 ms per step for it. The cause is a shape or guard that changes every step: a growing cache, ragged batches, a Python scalar that Dynamo specializes on.
The fix is static shapes. TorchTPU's backend sets dynamic=False when you do not pass dynamic, and the TorchTitan guide says to pass dynamic=False explicitly for training anyway, because a region left at PyTorch's default None can switch to dynamic shapes after a recompile, which on XLA forces padding and defeats fusion. Shapes that genuinely vary go into buckets (chapter 7's bucket_for and padding_waste), a static KV cache with a 0-D length tensor, or, where bounded dynamism fits, mark_dynamic with explicit bounds.
A related cost is not a recompile but looks like one in a trace: a view passed into a compiled function. PjRt requires executable inputs to be contiguous, zero-offset and of the expected dtype, so TorchTPU makes a temporary eager copy of a non-trivial view before the call. When compiled functions are chained, make each one return contiguous tensors.
Confirm the fix with the tools of chapter 7: a counting backend or torch._dynamo counters, TORCH_LOGS="recompiles" for the reason, and torch.compiler.set_stance("fail_on_recompile") to keep it fixed. The companion ladder counts compiles for every compiled rung and checks that each compiles once.
3. Memory-bound ops: elementwise chains that each touch HBM¶
In eager mode every op reads its inputs from HBM and writes its output back. A normalization, an activation, a rotary embedding and a residual add are each a few FLOPs per byte, far below the ridge, so a chain of them costs one HBM round trip per op. In a trace this is a run of short ops between the matmuls, each memory-bound.
Fuse them by compiling. Under torch.compile, XLA fuses elementwise ops, normalizations and residual additions into the surrounding fusion, so the intermediates never reach HBM. The FLUX case study measures what that is worth and how much it depends on the workload: compiling the DoubleStreamBlock takes the step from 178.61 to 159.33 ms (1.12x) at sequence length 32,768, where attention dominates, and about 3x at sequence length 640, where the elementwise work does.
Make the math compact. The case study's reference RoPE builds a \(2 \times 2\) rotation matrix per frequency pair and contracts against 6-D reshaped queries and keys; the trace shows "large copy blocks". The rewrite stores [cos, sin] pairs and rotates with elementwise multiply-adds. The same multiplications and additions happen in the same order, so the result is bit-identical, the table is half the size, and under compile the rotation fuses with its neighbours: 159.08 to 153.60 ms (3.4%) in the compiled block.
Never write the intermediate at all. Some intermediates are too large to fuse away. TorchTitan's fused linear cross-entropy computes the LM-head matmul, softmax and loss one vocabulary tile at a time, so the [batch, seq, vocab] logits are never materialized; the guide says its main value is memory, which then pays for a larger batch, and that its throughput effect grows with batch and is neutral when the logits are small. Splash attention does the same for the attention score matrix and matters most at long sequence; at short sequence the guide calls it often a wash against TorchTPU's built-in flash SDPA. Both are Pallas kernels exposed to PyTorch through torch.tpu.pallas.jax_op, and both have block sizes to tune (below, and in chapter 12).
4. Padding waste: arithmetic on zeros¶
A TPU array is stored in tiles, and the MXU is a \(128 \times 128\) or \(256 \times 256\) systolic array depending on generation. A dimension that is not a multiple of the tile is padded up to it in memory, and a matmul over it spends MXU cycles on the padding. In a trace the op takes longer than its roofline estimate from the logical shape, and the op's layout in the details panel shows the tile (chapter 10 reads T(8,128) there).
- Align model dimensions. The TorchTitan guide's rule is a hidden dim that is a multiple of the MXU tile, with 256 a safe multiple across generations. Vocabulary, head and intermediate dims follow the same rule. The vLLM-TorchTPU optimization best practices, which number their rules P-n (performance) and PR-n (pull request discipline), add where to pay for alignment in a serving stack: once at weight-loading time, not per call (rule P-14).
- Do not pad the batch you train on. In the TorchTitan FLUX.1 log, the Splash attention stage used sequence packing with segment ids "so that no MXU cycles go to padding". Bucketed inputs pay padding up to the bucket bound; chapter 7 measures that waste and trades it against the number of compiled shapes.
- Respect kernel tiles. The fused cross-entropy requires the flattened token count (
batch × seq) to be a multiple ofloss_b_block_size(default 1024); otherwise it silently falls back to XLA. Keep the token count divisible by 1024, and check that the memory you expected to save was saved.
5. Hidden copies: data moved that the math did not need¶
On TorchTPU, views are not free and copies often are, the inversion of CUDA habits that chapter 5 works through. A permute followed by a reshape that the tiled layout cannot express becomes a relayout, a real HBM-to-HBM copy, and it often appears only in backward, where autograd has to put a gradient back into a layout the forward pass only viewed. In a trace these are copy ops whose source line points at a reshape, a rearrange or a permute, frequently inside the backward pass.
The FLUX case study's Milestone 1 is the cleanest example, and the animation follows it on a buffer small enough to label every element. The reference splits a fused QKV projection with einops.rearrange(qkv, "B L (K H D) -> K B L H D"), which moves the Q/K/V axis to the front. In forward that is a strided view. In backward, the gradients of Q, K and V are stacked along that front axis, so they land Q/K/V-major, and turning them back into the projection's token-major layout needs a full copy (the FLUX example's traces name it tt_jit_copy__as_strided_inverse). The fix keeps the size-3 axis next to (H, D):
def split_qkv(self, qkv):
b, l, _ = qkv.shape
- return qkv.view(b, l, 3, self.heads, self.head_dim).permute(2, 0, 1, 3, 4).unbind(0)
+ return torch.unbind(qkv.view(b, l, 3, self.heads, self.head_dim), dim=2)
Watch the arrows. Both versions write the stacked gradient once; only the naive one has arrows that cross, and crossing arrows are a second, full-size write.
The step-time effect in the FLUX block is small (178.61 to 178.30 ms eager) because attention dominates a 32K-token step, but the change is free and grows with the number of blocks. The same family of rewrites ended the TorchTitan FLUX.1 log: splitting a fused projection into two separate linear layers so its output no longer had to be sliced apart, simplifying the rotary embedding to elementwise math, and unpacking Q, K and V with a view instead of a transpose. "None of them changes what the model computes; each removes copies and lets XLA fuse more of the graph."
Other sources of hidden copies, all from the TorchTPU memory and execution model documentation:
- Partial writes into large buffers. An in-place write is functionalized into a new buffer, and TorchTPU donates the old one when it can prove it dead. When it cannot, the update copies the whole base storage, not just the slice written. Prefer many small tensors to slices of one large one, and overwrite contiguous tensors whole.
- Views passed into compiled functions (section 2): a temporary eager copy per call.
- Retained intermediates under DeferAndFuse. At each materialization point every live tensor is materialized, so a tensor kept for logging becomes a forced output. Delete intermediates early.
- Framework copies. In the TorchTitan FLUX.1 log the largest single stage was a copy problem at framework level: FSDP2 copied parameter shards into a flat staging buffer before each all-gather and back out afterwards, and SimpleFSDP, which all-gathers each parameter directly, removed both copies.
What not to remove: .clone() and .contiguous() are often free on TorchTPU because of copy-on-write. Remove the copies the trace shows, not the ones the code seems to make.
6. Exposed collectives: compute waits for communication¶
A collective (all-gather, reduce-scatter, all-reduce, possibly inside a fusion's calls=) with compute idle around it, or one that takes longer than its estimate from bytes and ICI bandwidth, is communication that is not hidden. The fixes belong to chapter 13 and chapter 14; the playbook's part is to know which lever they pull and what they risk.
- Put the collectives where the compiler can see them. FSDP2 issues its collectives from module hooks, outside any traced region. SimpleFSDP expresses sharding as a DTensor parametrization, so the all-gather is a
redistributein forward and the reduce-scatter is its backward, both ordinary nodes in the compiled graph, which XLA can schedule against the matmuls. The guide says FSDP with per-block compile is "meaningfully faster" than FSDP alone. - Keep the reduction precision. Use
MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32). The guide is explicit that droppingreduce_dtypeto bf16 to save bandwidth is a model-quality regression, not a performance lever. - Scheduling flags. The TorchTitan recipes carry libtpu flag bundles, such as the latency-hiding scheduler, SparseCore collective offload and hierarchical reduce-scatter. The integration post's warning applies to every flag: a pure scheduling flag leaves the loss bit-identical, but a flag that changes fusion or reduction order, hierarchical reduce-scatter among them, shifts rounding, so check the step-1 loss and gradient norm after every flag sweep.
7. Poor MXU utilization: busy, but slow¶
The device is busy and the top matmul is well below its roofline estimate. Work through the causes in order of cost:
- Precision passes. A float32 matmul under
"high"or"highest"precision takes 3 or 6 bf16 MXU passes (chapter 6). Run compute in bf16 (an FSDP mixed-precision policy, ortorch.autocastwithout FSDP), keep norms in float32, and scope higher precision to the layers that need it. The guide's code-level warning: if you cast to bf16 by hand, a bf16 input against a float32 norm weight can raise a dtype mismatch, so compute the norm in float32 and cast back. - Too little work per matmul. A small batch or narrow dim keeps intensity low (chapter 2). Batch and dim (section 1) are the levers; the fused cross-entropy frees the memory to raise the batch.
- Kernel tiles. Splash attention and the fused cross-entropy are Pallas kernels whose performance depends on block sizes, and the guide says the defaults are "a starting point, not an optimum". The FLUX case study is concrete: with the default 512-token blocks, Splash was about 10% slower than standard SDPA under compilation, and float32 inputs slower still; with 2048-token blocks in bf16 it took the compiled block from 153.60 to 122.51 ms. Tiles are bounded by the scoped VMEM limit, which on v6e the guide sets with
LIBTPU_INIT_ARGS="--xla_tpu_scoped_vmem_limit_kib=65536"(64 MiB, the value TorchTitan's Trillium recipes converged on). The value is generation-specific; check that it is accepted at start-up, and expect tiles tuned on one generation not to carry over to another.
When a top op is already near its bound and still dominates, no setting will help. Fewer FLOPs or fewer bytes by design is the remaining move, which means a fused or custom kernel: chapter 12.
Memory pressure¶
HBM exhaustion is not a step-time signature, but it limits every lever above, since a bigger batch or a larger tile needs memory. The guide's memory levers are the fused cross-entropy (the logits are never materialized), SimpleFSDP fully_shard across chips, activation checkpointing or GraphTrainer's memory policy, and, for very large models, scan over layers or the graph splitter with CPU offload. It calls offload "a memory lever, not a speed lever": after enabling it, look in the profile for exposed host-to-device and device-to-host waits, because transfers that are not hidden behind compute cost step time for the memory they free.
The order to try fixes in¶
The TorchTitan integration post states the principle: "The order matters, because each step changes what the next one measures." A fix earlier in the order changes the trace that every later decision is read from. From that, and from what each fix risks, the order this book recommends is:
- Make the measurement valid. Warm-up outside the timed steps, the profiler off while timing, a TorchTPU build with optimizations on (the guide warns that a fastbuild wheel can have dramatically slower eager dispatch and "will silently ruin every measurement"). Nothing below is worth doing on a measurement you cannot trust.
- Remove host syncs and recompiles. They put idle time into every step, and idle time hides everything else: an op ranking taken from a trace that is a third idle points at the wrong thing (chapter 10). Both fixes are usually parity-neutral.
- Compile, per block, with
dynamic=False. The guide's step zero. It changes the trace more than any other change: elementwise chains fuse, many copies fold into fusions, and the top-ops list you would have optimized against no longer exists. Optimizing an eager trace and then compiling wastes the first round of work. - Remove copies and fix layouts. Zero-copy views, compact math, aligned dims. Cheap, local, and parity-neutral by construction, so each is easy to verify.
- Size the work: batch and dim. The largest lever at small scale, but it changes the training configuration; agree it with the model's owner and check convergence, not just parity.
- Kernels and precision for the top op. Fused cross-entropy, Splash attention, tile sizes within the VMEM budget, matmul precision. Each needs a tolerance-based parity check and a sweep.
- Collectives, sharding and flags. Part IV. Flags that change reduction order need a loss-curve comparison, not only a step-1 check.
- A custom kernel last. Only for an op that is near its bound and still dominates, and only after the compiler's version has been shown to be the limit (chapter 12).
Two principles sit behind the order. Earlier fixes are the ones that change what later ones measure, so they go first. And within that constraint, cheaper-to-validate fixes go first: a change that cannot alter the math (a view, a read every N steps) needs a parity check that passes bit for bit; a change that alters rounding (a kernel, a flag, a precision) needs a tolerance and sometimes a loss curve.
Each dot is the check the fix normally needs. The order is set first by what each fix changes in the trace and only then by the cost of its check, so the dots do not run in a diagonal: compile is third because it changes the trace most, and a custom kernel is last because only an op still near its bound and on top deserves one.
Real logs do not always follow this order, and the FLUX.1 log below applied compile fourth. That does not make it wrong, but it changes the attribution: a stage applied late is measured against a step that earlier stages already shortened.
Measuring one change at a time¶
A speedup is a claim with three parts, and each part has a check.
The change did not change the answer. Run the baseline and the change from the same weights on the same batches and compare. The integration post's rule for flags generalizes to every change: bit-identical means the change is free; a small difference means a rounding-order change, which is safe only after a loss-curve comparison against the baseline says so. For a rewrite that is meant to be exact (a view instead of a permute, the compact rotary embedding) anything but bit-identical in float32 on the same device is a bug. For a change that compiles, fuses or switches kernels, use the dtype's tolerances (chapter 6) and compare gradients as well as outputs. The vLLM-TorchTPU rules add the operational habit: revert fast on a numeric issue and find the root cause offline (rule PR-2).
The step got faster, measured the same way. Use one timing method for every rung. The FLUX case study's is a good default: 3 warm-up steps, then 10 timed steps dispatched back to back with one torch.accelerator.synchronize() after the last, mean step time as total time over steps, profiler disabled. Change one thing per measurement; if two changes go in together, you cannot say which one helped, or whether one of them hurt.
The trace changed the way the mechanism predicts. The vLLM-TorchTPU rules call XProf traces the unit of evidence: an end-to-end number alone proves nothing, and a claim needs the trace plus a mechanism explanation of where the gain came from (rule P-1). Concretely: the targeted signature is gone or smaller (no gap after the host read, no copy op at that source line, the collective now overlapped), and the time removed is about what that signature took. A speedup that the mechanism does not predict needs explaining before it is believed; the same rules note that in parallelism comparisons such a win is usually a batch-size artifact (rule P-4).
Keep a log with one row per change. The columns that make it useful later are: the change, the signature it targeted, parity (bit-identical, within tolerance, or loss-curve checked), step time before and after with the method, whether the signature is gone in the new trace, and the versions and machine. Chapter 24 turns logs like this into numbers you can defend.
A worked optimization log: FLUX.1 on TorchTitan¶
The TorchTitan integration post reports one model taken through the playbook stage by stage: FLUX.1, a 12-billion-parameter diffusion transformer, trained at \(1024 \times 1024\) on a TPU v6e-8 with FSDP in bf16 and a batch of three samples. Chapter 9 analyzed the smaller FLUX case study (one DoubleStreamBlock on one chip) as a port; this log is the full model under the full playbook, and its stages map onto this chapter's signatures.
| Stage | Step time | Quoted gain | Seconds removed | Signature it removed |
|---|---|---|---|---|
| Eager, FSDP2, full activation checkpointing | 11.49 s | (baseline) | ||
| + DeferAndFuse eager mode | 9.95 s | 15.5% | 1.54 | Host-bound: 28% fewer HLO module invocations |
| + SimpleFSDP instead of FSDP2 | 6.52 s | 52.6% | 3.43 | Hidden copies: FSDP2's staging-buffer copies around each all-gather |
| + Splash attention, sequence packing, segment ids | 5.55 s | 17.5% | 0.97 | Memory-bound attention and padding |
+ per-block torch.compile |
3.02 s | 83.8% | 2.53 | Host-bound and memory-bound: large sub-graphs, control flow out of Python |
| + three local rewrites | 2.78 s | 8.6% | 0.24 | Hidden copies: split projection, elementwise RoPE, view instead of transpose |
Compare the two numbers in each bar on the right. Compile has the largest quoted percentage and removed less time than SimpleFSDP; the percentage is taken against a step that three earlier stages had already shortened.
Three readings of this log generalize.
Percentages against a shrinking base mislead. The post's percentages are throughput gains over the previous stage (old over new, minus one: \(11.49 / 9.95 - 1 = 15.5\%\)). Measured against the 11.49 s baseline instead, the same 2.53 s would have been a 28% gain (\(11.49 / 8.96 - 1\)). To compare stages, use seconds removed: SimpleFSDP is 39% of all the time removed, compile 29%, DeferAndFuse 18%, Splash 11%, the rewrites 3%.
The order sets the attribution. Compile came fourth here, after DeferAndFuse. The guide expects DeferAndFuse to add little on a model that is already compiled per block, because the compiled path already fuses the compute; applied before compile, it was worth 1.54 s. Had compile gone first, some of DeferAndFuse's 1.54 s would probably have shown up as compile's. The post does not report other orders, so the log cannot say what each lever is worth on its own; chapter 9 found the FLUX block's levers close to additive, which is the only evidence here that the order does not change the end point much.
The last stage is small and still worth taking. The three rewrites removed 0.24 s, 8.6% of a 3.02 s step, with no change to what the model computes. They came last because only a compiled, fused trace shows which copies are left: before compile, the step's copies would have been mixed with the eager ops around them. The final 2.78 s is 4.1 times faster than the start and, per the post, about 99% of the throughput of the JAX-based MaxDiffusion on the same hardware.
A worked example on a laptop¶
code/ch11_optimize/ holds a small model in two versions. naive.py is a correct pre-norm transformer block (RMSNorm, fused QKV projection, rotary embedding, SDPA, GELU MLP) with three habits from the FLUX reference code: the permute-based QKV split, the \(2 \times 2\)-matrix rotary embedding, and a training loop that reads the loss with .item() every step. optimized.py subclasses it, so both share parameters and load the same state_dict, and puts each fix behind its own switch. compare.py walks the ladder in this chapter's order, one change per rung. For each rung it first checks parity (same weights, same batches, loss curve and final weights against the baseline's), then times the step, then counts with torch.profiler on the CPU: aten ops dispatched, layout copies (aten::clone called by a reshape or .contiguous()) and the bytes they write, host reads of the loss, and compiles (a counting backend). Real output from a laptop, two blocks, hidden 256, two heads of 128, abridged (two explanatory notes and the precision line are cut):
$ python code/ch11_optimize/compare.py --cpu-smoke
== chapter 11 ladder on the CPU: depth 2, hidden 256, heads 2 x 128, batch 2, seq 128, 10 steps
rung change parity step ms vs base aten ops copies copy KiB reads compiles RoPE KiB
baseline naive, eager, .item() every step ok 5.88 1.00x 989 2.0 1536 1.0 - 128
sync every 10 read the loss every 10 steps ok 5.91 1.00x 989 2.0 1536 0.1 - 128
compile torch.compile(dynamic=False) ok 5.91 0.99x 989 2.0 1536 0.1 1 128
zero-copy QKV view + unbind(dim=2) ok 5.94 0.99x 973 0.0 0 0.1 1 128
compact RoPE [cos, sin] elementwise rotation ok 5.46 1.08x 1022 0.0 0 0.1 1 64
== checks
[ok] every rung matches the baseline's loss curve and final weights (float32 assert_close)
largest difference from the baseline: 0.00e+00
[ok] host reads per step fall from 1.0 to 0.1 after 'sync every 10'
[ok] each compiled rung compiled exactly once over all its steps (no recompiles)
[ok] zero-copy QKV removes copies: 2.0 -> 0.0 per step (1536 -> 0 KiB)
[ok] compact RoPE halves the rotary table: 128 -> 64 KiB
[ok] compact RoPE adds no copies
[note] eager aten ops per step: 973 -> 1022; the elementwise rotation pays off when it is compiled and fused, not in eager op counts
[ok] every Linear dimension is a multiple of 128
cpu-smoke: OK
Read it the way the chapter reads any log.
Parity first. Every rung reproduces the baseline's ten losses and final weights exactly, a difference of 0.0. That is what these changes should do: none of them alters the arithmetic. On a TPU the compiled rungs are compared at bf16 tolerances, because a compiled program may round in a different order from eager.
The step times are not the result. On a CPU the first four rungs take the same 6 ms within noise, and only the compact rotary embedding moves the time, by about 8%. There is no dispatch gap for compile to close, no tiled layout for the permute to fight, and the counting backend runs the captured graph as is. The counts carry over: one host read per step becomes one per ten, the compiled rungs compile once, and the layout copy, one per block per step at 768 KiB each (the full \(2 \times 128 \times 768\) float32 projection gradient), disappears. On a TPU each of those is a signature you would confirm gone in XProf: the gap after each step, the compile on the host rows, the copy op in backward.
A count is not a speedup. The compact rotary embedding dispatches 49 more eager ops per step than the matrix version, because it multiplies cos and sin into each half of the input separately and stacks the results. On a TPU the count stops mattering once the block is compiled, because the elementwise rotation fuses with the surrounding ops; the FLUX case study measured its 3.4% only in the compiled block. Its 8% on the CPU transfers no better than its op count. The table halving is a real, device-independent saving; the rest needs a TPU measurement. This is why the playbook measures on the target, in the mode you deploy.
On a TPU, python code/ch11_optimize/compare.py runs the same ladder in bf16 at hidden 1024, eight heads, sequence 1024, timing each rung the FLUX way, and --profile-dir /tmp/ch11_traces adds one short XProf trace per rung so you can open the before and after side by side.
Failure modes¶
| Symptom | Cause | Fix |
|---|---|---|
| A big speedup on the top op, almost no change in step time | The step was idle-bound; the top-ops list cannot see idle time | Read idle time first (chapter 10); fix host syncs and dispatch before ops |
| Work spent tuning ops that disappear after compiling | Optimizing an eager trace | Compile first, then read the compiled trace |
| A speedup that vanishes on re-measurement | Different timing methods, profiler on during timing, warm-up inside the timed steps | One method for every rung: warm-up, back-to-back steps, one synchronize, profiler off |
| Every measurement slower than expected, eager especially | A fastbuild TorchTPU wheel | Build with optimizations on (-c opt for Bazel), as the guide warns |
| A "free" change moves the loss in the last digits | It changes rounding order (a flag, a fusion, a kernel) | Treat it as a numeric change: tolerance check, then a loss-curve comparison |
| An exact rewrite changes the loss at all in float32 | A bug in the rewrite | Revert, compare layer by layer; exact rewrites must be bit-identical |
reduce_dtype dropped to bf16 for speed |
Bandwidth traded for accuracy | A quality regression, not a lever; keep float32 reductions |
| The fused cross-entropy saves no memory | Token count not a multiple of loss_b_block_size: silent fallback to XLA |
Keep batch × seq divisible by 1024 |
| Splash attention slower than SDPA | Default 512-token blocks, short sequence, or float32 inputs | Sweep block sizes in bf16 at your sequence length; at short sequence, keep SDPA |
| Kernels cannot use larger tiles, or start-up rejects the VMEM limit | Scoped VMEM limit too low, or too high for the generation | Set --xla_tpu_scoped_vmem_limit_kib per generation (65536 on v6e per the guide) and check it is accepted |
| A fusion crash under DeferAndFuse | Some op patterns do not lower under fusion (unaligned dynamic-update-slice) | Disable DeferAndFuse for that model; compile or run plain eager |
| CPU offload makes the step slower | Transfers not hidden behind compute | Look for exposed host-device waits in the trace; prefetch, or do not offload |
| A parallelism change wins by more than its mechanism predicts | Different global batch between the runs | Compare at matched global token budget (vLLM-TorchTPU rule P-4) |
| The device fails to initialize after a crash | Stale libtpu lock | rm -f /tmp/libtpu_lockfile, per the guide's operational notes |
Verifying the result¶
An optimization worked when three things hold at once, and the companion code checks all three on a CPU:
python code/ch11_optimize/compare.py --cpu-smoke # ends "cpu-smoke: OK"
pytest tests/ch11 -q
- Parity holds. From the same weights and batches, the changed run's loss curve and final weights match the baseline's: bit-identical for changes that cannot alter the math (views, read frequency, compact rewrites), within the dtype's tolerance for changes that recompile, fuse or switch kernels, and confirmed by a loss-curve comparison for changes that alter reduction order. A faster step with a different answer is a regression.
- The step time fell, measured the same way. Before and after are timed with one method (warm-up, back-to-back timed steps, one synchronize, profiler off) on the same machine, versions and batch. Report both numbers and the seconds removed, not only a percentage.
- The targeted signature is gone from the trace. Capture the after trace with the same settings as the before trace (chapter 10). The thing you targeted (the gap after the host read, the per-step compile, the
copyop at that source line, the exposed collective) is gone or smaller, the time removed is about what it took, and the next top item has moved. If the trace looks the same, the change did not touch the bottleneck, whatever the stopwatch says.
Worked problems¶
Problem 1. For each trace, name the signature and the first fix to try. (a) Each step ends with a host range aten::_local_scalar_dense and a device gap of the same length. (b) Eager mode, hundreds of XLA ops per step each lasting a few microseconds, with small gaps between all of them. (c) A compiled step; in backward, a copy op whose source line is an einops.rearrange. (d) A compiled step where a [4096, 1000] @ [1000, 4096] matmul takes noticeably longer than its roofline estimate.
Answer
(a) Host-bound by a host read: aten::_local_scalar_dense is what .item() (or a Python if on a tensor) dispatches. Read the value every N steps or keep the decision on the device with torch.where. (b) Dispatch-bound: ops shorter than the roughly 50 µs enqueue cost, so microbubbles. Compile per block with backend="tpu", dynamic=False; DeferAndFuse if the code cannot be compiled. (c) A hidden copy from moving an axis before a split: replace it with a view that keeps the split axis next to the inner dims (torch.unbind(qkv.view(b, l, 3, h, d), dim=2)), then check the copy is gone in the next trace. (d) Padding: 1000 is not a multiple of 128, so the contraction dimension is padded in its tiles (chapter 5) and the MXU works on that padding. Align the dimension (to 1024, or a multiple of 256); if it is a model dimension, that is a configuration change to agree with the model's owner.
Problem 2. Using the FLUX.1 TorchTitan log, a colleague concludes that per-block compile (83.8%) was worth more than twice as much as SimpleFSDP (52.6%). Evaluate the claim with the step times, and say what the log cannot tell you.
Answer
The percentages are throughput gains against the previous stage, and compile's base was already shorter. In seconds: SimpleFSDP removed \(9.95 - 6.52 = 3.43\) s, compile removed \(5.55 - 3.02 = 2.53\) s. SimpleFSDP removed more time, 39% of the 8.71 s removed overall against compile's 29%. Measured against the original 11.49 s, compile's 2.53 s would be a 28% gain (\(11.49 / 8.96 - 1\)). What the log cannot say is what either is worth alone or in a different order: compile came after DeferAndFuse, which overlaps with it (the guide expects DeferAndFuse to add little on a compiled model), so some of DeferAndFuse's 1.54 s might have been compile's had the order been reversed.
Problem 3. A team's trace of a long-context training step shows 30% device idle, with an .item() on the host before each gap; attention is the top op at 35% of busy time. They plan to write a Pallas attention kernel first. Propose an order for the work, and say what you expect each trace to show.
Answer
First remove the host read (read the loss every N steps): expect the gaps to vanish and the step to shrink by up to the 30% idle, with attention then a larger share of a shorter step. Then make sure the step is compiled per block with dynamic=False and compiles once: expect fused elementwise chains and a different top-ops list. Then remove any copy ops the compiled trace shows. Only then look at attention: estimate it against its roofline, and try the existing Splash kernel with block sizes swept for this sequence length in bf16 before writing anything (the FLUX case study found default 512-token blocks 10% slower than SDPA under compile, 2048-token blocks 1.25x faster). A custom kernel comes last, for an op near its bound that still dominates. Starting with the kernel would have optimized 35% of the 70% busy time while the 30% idle stayed.
Problem 4. Three changes, three parity results against the baseline, all in float32 on the same device: (a) the zero-copy QKV split gives a loss differing by \(3 \times 10^{-4}\) at step 1; (b) enabling a hierarchical reduce-scatter flag gives a step-1 loss differing in the seventh significant digit; (c) reading the loss every 10 steps gives exactly the same losses. Which changes do you keep, and what do you do next for each?
Answer
(c) Keep: bit-identical is what a change to read frequency must give. (a) Do not keep: the split is an exact rewrite (the same values in the same order), so any difference means a bug, for example a wrong heads/head_dim order in the view or unbinding the wrong axis. Revert and compare Q, K and V tensors directly, as the tests in tests/ch11 do. (b) A small difference is expected from a flag that changes reduction order; per the integration post it is safe only once a loss-curve comparison against the baseline recipe says so. Run that comparison before keeping it, and confirm in the trace that the reduce-scatter's exposed time actually fell.
Problem 5. In the companion output, the compact rotary embedding raises the eager aten op count from 973 to 1022 per step, yet its CPU step is about 8% faster. One colleague says the op count proves the change is bad for a TPU; another says the CPU timing proves it is good. Evaluate both arguments, and say what evidence on a TPU would settle it.
Answer
Neither number settles it. The op count is an artifact of eager dispatch: the elementwise rotation multiplies each input half separately and stacks the results, which is more dispatches in eager mode, and under compile it fuses with the surrounding ops. What does not depend on the device holds: the result is bit-identical, the table is half the size, and no copies were added. The case study measured the change only in the compiled block, 159.08 to 153.60 ms (3.4%), because that is where it pays. Settle it on a TPU with the compiled rung before and after: bit-identical (or tolerance-level) parity, the mean step time with the FLUX timing method, and the trace showing the rotary ops fused, with the reference's stack and reshape ops (the "large copy blocks") gone. The CPU timing is no better evidence: a CPU has neither the TPU's dispatch cost nor its tiled layouts, so its 8% says nothing about the compiled TPU block.
Problem 6. A run enables TorchTitan's fused linear cross-entropy with batch 6 and sequence length 1000, and HBM usage does not fall. The Memory Profile still shows a large tensor of shape about [6000, vocab]. Diagnose, and propose a configuration that would work.
Answer
The kernel requires the flattened token count to be a multiple of loss_b_block_size (default 1024), or it silently falls back to XLA, which materializes the logits. \(6 \times 1000 = 6000\) is not a multiple of 1024, so the logits are still written to HBM. Choose a batch and sequence with a token count divisible by 1024, for example sequence 1024 with batch 6 (\(6144 = 6 \times 1024\)) and keep the default block size. Check the result the same way: the [tokens, vocab] tensor is gone from the Memory Profile, and the freed memory can then go to a larger batch.
Quick questions¶
- What are the four levers behind the fixes in this chapter, and which one can a roofline say nothing about?
- Why is
torch.compileper transformer block, rather than on the whole model, the TorchTitan guide's recommendation? Name two failure modes of whole-model compile on TorchTPU. - What is the dispatch ceiling, and what three things shrink or remove it?
- Why does the TorchTitan guide tell you to pass
dynamic=Falseexplicitly, and what happens when a non-contiguous view is passed into a compiled function? - Why does the FLUX reference QKV split cost a copy in backward but not in forward, and why does
torch.unbind(qkv.view(B, L, 3, H, D), dim=2)avoid it? - Name three sources of hidden copies other than a permute before a split.
- Why should compile come before removing copies in the order of fixes?
- What does "bit-identical", "a small difference" and "a large difference" each mean for a change you are evaluating?
- Why can a quoted percentage gain mislead when stages are applied in sequence, and what number should you compare instead?
- What three pieces of evidence does this chapter require before a change counts as an optimization?
Key takeaways¶
- Every fix pulls one of four levers: fewer, larger programs; fewer bytes; fewer wasted FLOPs; hidden communication. The first is invisible to a roofline and is the most common case on a small or uncompiled model.
- Read the fix from the trace: gaps after host reads or many tiny programs mean host-bound; uniformly slow steps mean recompiles; short elementwise ops mean memory-bound; slow matmuls on unaligned shapes mean padding; unexpected
copyops mean hidden copies; collectives with idle compute mean exposed communication; busy but slow matmuls mean poor MXU use. - Compile per transformer block with
backend="tpu", dynamic=Falseas step zero; use DeferAndFuse for code that cannot compile or for the eager glue, and GraphTrainer to remove the eager surface entirely. Whole-model compile has known failure modes on TorchTPU. - On TorchTPU views can cost and copies can be free. Keep split axes next to the inner dims (
.view()plustorch.unbind), write compact elementwise math, pass contiguous tensors into compiled functions, and remove only the copies the trace shows. - Order matters because each fix changes what the next one measures: valid measurement, host syncs and recompiles, compile, copies and layouts, batch and dims, kernels and precision, collectives and flags, custom kernels last.
- Measure one change at a time: parity first (bit-identical for exact rewrites, tolerances or a loss curve otherwise), one timing method throughout, and a new trace showing the targeted signature gone.
- Compare stages by seconds removed, not by percentages against a shrinking base. In the FLUX.1 TorchTitan log (11.49 s to 2.78 s, 4.1x) SimpleFSDP removed the most time, 3.43 s, though compile has the largest quoted percentage.
References¶
- Guide to optimizing LLMs on TorchTPU: the TorchTitan TPU optimization guide, from per-block compile and DeferAndFuse to fused kernels, SimpleFSDP, GraphTrainer and the dispatch ceiling
- Integrating TorchTPU into TorchTitan and Optimizing Models for TPU: the TorchTitan playbook and the FLUX.1 optimization log on TPU v6e-8
- TorchTitan TPU recipes:
tpu_job_config.pyand the Llama 3config_registry.py - FLUX optimization: the four milestones, their step times and the timing method
- FLUX Performance Optimization Tutorial on Google Cloud TPUs: the einops copy in the trace and the rewritten code
- vllm-torchtpu Optimization Work Best Practices: the P- and PR- rules for evidence, tradeoffs and matched token budgets
- TorchTPU execution model: host reads, microbubbles, views passed into compiled functions, DeferAndFuse
- TorchTPU and the TPU memory model: views, relayout copies, functionalization and donation
- TorchTPU API Reference:
torch.tpu.set_eager_modeandEagerMode.DEFER_AND_FUSE - TorchTPU repository:
_loader.py, which setsdynamic=Falsewhen a TPU backend is called without it - TorchTPU Performance: Execution Modes, XProf and Pallas Kernels: views and donation, copy pitfalls, the FLUX milestones and the QKV split
- Companion code for this chapter




