Skip to content

Execution model: eager modes, deferred ops, torch.compile

30 min read

Prerequisites: Rooflines and arithmetic intensity, The TorchTPU stack and the CUDA translation table

On a GPU, an eager PyTorch op launches a kernel and the only question is when it finishes. On TorchTPU, an op first becomes a record on the host, and three later decisions shape your step time: when that record is turned into a TPU program, how many records go into one program, and how much the compiler is allowed to optimize it. TorchTPU gives you four ways to make those decisions, three eager modes and torch.compile, and one family of mistakes that defeats all of them: reading a device value from Python in the middle of a step. This chapter follows an op through the pipeline, compares the modes, shows where graphs are cut and where recompiles come from, and ends with the measurements that tell you which mode you are really running and whether it helped.

What this chapter covers

  • What TorchTPU does between the moment an ATen op is called and the moment its result exists in HBM, and which of those steps run on the calling thread.
  • Strict, Debug and DeferAndFuse eager modes and torch.compile(backend="tpu") compared by graph size, XLA optimization level, compile cost and runtime overhead, and how to select each one.
  • Materialization points and graph breaks in a training step, including the ones the code does not show, such as if tensor: and data-dependent output shapes.
  • The torch.where rewrite that removes a host sync, and a check that it gives identical results.
  • Choosing an execution mode for a workload, and verifying the choice by counting compiles, comparing step times and checking numerical parity between modes.

What happens when you call an op

Chapter 3 followed one op down the stack. This section slows down the part of that path that lives inside TorchTPU, because the execution modes differ only in how they drive it. The TorchTPU execution model documentation splits it into six stages:

  1. Create a deferred op. No work is sent to the TPU. TorchTPU packages the logical result into a DeferredOp, a host-side object that holds the inputs, the steps to perform (a StableHLO builder) and the shape and dtype of the outputs. The tensor you get back is real as far as PyTorch is concerned, but its storage points at the DeferredOp. Replacing that symbolic result with real data is called materialization.
  2. Enqueue it on a stream. TorchTPU implements the torch.Stream interface, and each DeferredOp is pushed onto the current stream. At this point the calling Python thread is done with the op and moves on. Everything after this happens in the background, except in Debug mode.
  3. Analyze the stream. A background thread picks up the queued work and decides, for all of it together: how many separate executions to split it into, the inputs and outputs of each, the optimization level for each, whether each has been seen before, and whether it should run on a TensorCore or a SparseCore. It marks the outputs as pending.
  4. Compile or fetch. Each execution block is looked up in the compilation cache. On a miss, it is converted to MLIR (StableHLO, or Mosaic for custom kernels) and handed to a compilation thread pool, which compiles many blocks in parallel.
  5. Start execution. With inputs and executable ready, the block is enqueued with PjRt, XLA's runtime. PjRt returns promises for the outputs, which are plugged into the output tensors.
  6. Wait, if you ask to. torch.Event.query tells you whether recorded work is done. torch.Event.synchronize, torch.Stream.synchronize and torch.accelerator.synchronize block Python until the TPU has finished.

A pipeline across three containers, its six stages numbered on the arrows. Top, an amber dashed container labelled Python thread: an ink pill ATen op, an arrow numbered 1 to DeferredOp, an arrow numbered 2 to Stream queue, and, separately on the right, a box Wait, synchronize. From Stream queue an arrow numbered 3, labelled flush, runs down into a gray dashed container labelled Background thread, to Analyze stream. An arrow numbered 4 leads right to Compilation cache. From the cache an arrow labelled hit runs right, out of the container, to PjRt; an arrow labelled miss runs down to StableHLO or Mosaic, which leads down to Compile thread pool, which leads right and up into PjRt. From PjRt an arrow runs down into a blue dashed container labelled TPU, to TensorCore; its number 5 sits inside the container. A dashed arrow numbered 6, labelled wait, runs from the top of PjRt up and left into the right side of the Wait box in the Python thread.

Only the top row runs on your Python thread, and it waits for the TPU only at step 6, when you synchronize or read a value (in Debug mode, after every op). The execution mode decides when the flush at step 3 happens: in Strict mode every new op is flushed on its own; in DeferAndFuse the flush waits for a host read, a synchronize or a detected loop, so more of the queue goes to the background thread at once.

Two consequences follow before any mode is chosen. First, the Python thread can run ahead of the TPU: it only builds DeferredOps, so the host can be several steps of tracing ahead of the device, which is what keeps a TPU busy. Second, anything that makes Python wait for a device value stops that run-ahead. The rest of the chapter is about those two facts.

The TorchTPU announcement adds one detail about the analysis in stage 3. When it decides which deferred ops to materialize, TorchTPU applies a liveness analysis: a tensor that Python no longer references does not need to be written out, and because Python frees objects by reference counting, that decision is the same on every replica of a distributed job. Ops with side effects, such as collectives, are always kept, in their original order.

The four execution modes

The TorchTPU documentation describes four ways to drive the pipeline. Three are eager modes, values of the Experimental enum torch.tpu.EagerMode; the fourth is compiled mode.

Mode Also called How to select it What one executable holds XLA level Built for
Strict default eager, "defer never" Nothing to set; EagerMode.DEFER_NEVER One op -O1 Fastest time to first result
Debug launch blocking TORCH_TPU_LAUNCH_BLOCKING=1; EagerMode.DEFER_NEVER_AND_LAUNCH_BLOCKING One op, and the host waits for it -O1 Errors reported at the op that caused them
DeferAndFuse optimized eager TORCH_TPU_DEFER_AND_FUSE=1; EagerMode.DEFER_AND_FUSE Many ops, cut at a materialization point or a detected loop -O2 Faster steady state when torch.compile is not an option
Compiled torch.compile(model, backend="tpu") A whole FX graph -O2 Maximum warmed-up throughput, minimal latency

Selecting a mode

There are three ways to set the eager mode, and they act at different times.

TORCH_TPU_DEFER_AND_FUSE=1 python train.py      # DeferAndFuse for the whole process
TORCH_TPU_LAUNCH_BLOCKING=1 python train.py     # Debug for the whole process

The variables set the default eager mode. Like every TorchTPU variable, they are read once when the backend initializes, usually during import torch, and locked for the life of the process. Setting os.environ["TORCH_TPU_DEFER_AND_FUSE"] after import torch does nothing. If both are set, launch blocking wins (GetDefaultEagerMode() in csrc/eager/eager_mode.cc checks it first).

import torch

print(torch.tpu.eager_mode)          # EagerMode.DEFER_NEVER unless a variable changed the default
with torch.tpu.set_eager_mode(torch.tpu.EagerMode.DEFER_AND_FUSE):
    y = block(x)                     # ops in here are deferred and fused
    print(y.sum().item())            # a materialization point inside the block
print(torch.tpu.eager_mode)          # back to the previous mode

torch.tpu.set_eager_mode(mode) switches the mode for a block and restores the previous one on exit. set_eager_mode is not allowed inside a compiled region, because a compiled graph cannot choose how eager ops are dispatched, so call it around a compiled function, not in it.

torch.tpu.eager_mode = torch.tpu.EagerMode.DEFER_AND_FUSE   # from here on, in this process

torch.tpu.eager_mode is both a getter and a setter for the process-wide mode. All three names (EagerMode, eager_mode, set_eager_mode) are Experimental in TorchTPU's public API list, so expect them to change between releases.

Which mode is the default

Strict is the default. The TorchTPU documentation says so, and the source agrees: GetDefaultEagerMode() in csrc/eager/eager_mode.cc returns kDeferNever unless one of the two variables is set, and the public enum has exactly three members, DEFER_AND_FUSE, DEFER_NEVER and DEFER_NEVER_AND_LAUNCH_BLOCKING. When in doubt, print torch.tpu.eager_mode.

Strict mode, the default

Strict mode is what a PyTorch user expects from eager execution. Every op that is appended to the stream immediately flags the stream for execution, so the background worker processes ops one at a time. A single-op graph gives the compiler little to optimize, so TorchTPU compiles it at the lower -O1 level to keep compiles fast. There are many such compiles, but they are small, they parallelize well across the compilation thread pool, and they are reused often: a model calls the same few ops on the same few shapes over and over. That is why Strict has the shortest time to first result.

Strict is still asynchronous. Python does not wait for an op to finish, so you need a synchronization to observe a result, and a runtime error can surface well after the line that caused it.

Its weakness is small ops. Enqueueing an executable with PjRt costs a small amount of host time, 50 µs or less according to the documentation. An executable that runs for a millisecond or two hides that cost completely: the host enqueues the next one while the TPU is busy. But when executables are shorter than the enqueue cost, the TPU finishes before the host can hand it the next one, and the timeline fills with what the documentation calls microbubbles: short, frequent idle gaps. A bf16 add of two [4096, 4096] tensors is a typical case: it moves about 101 MB (two inputs and one output at 2 bytes per element), which at a v7x device's 3,690 GB/s takes about 27 µs (chapter 2), below the 50 µs enqueue cost. A chain of such elementwise ops in Strict mode spends a large share of its time with the TPU waiting for the host. The cure is to put more work in each executable: larger ops, or a mode that fuses.

Debug mode

Debug mode is Strict with one change: the host blocks and synchronizes after every op. That is slow on purpose, and it means a failure is reported on the line that caused it. It also turns on TorchTPU's runtime debug and bounds checks (TORCH_TPU_ENABLE_DEBUG_CHECKS, which Debug mode enables by default and which can be set to 0 to turn them off). The documentation is explicit that it is for interactive debugging, not production. It is TorchTPU's counterpart of CUDA_LAUNCH_BLOCKING=1.

DeferAndFuse mode

DeferAndFuse is a hybrid that brings part of what torch.compile does into eager mode, with no change to model code. Creating a DeferredOp no longer starts execution. The ops stay in the stream queue across Python calls until one of two things happens:

  • The program forces execution. The most common causes are a device-to-host transfer and an explicit synchronize call.
  • TorchTPU detects a repetition in the dispatched ops, which means the code is in a loop, and compiles one iteration so it can be reused. The announcement's example is a stack of transformer blocks, and calls it the Repeated Ops Heuristic.

Then materialization runs in the background as in Strict mode, except that the graph is larger than one op. Tensors that were already dropped or overwritten when the signal came are skipped: they are fused into the ops that consume them, or eliminated if nothing reads them. Dead code elimination is skipped for distributed collectives, to avoid deadlocks between TPUs.

Because the graphs are larger, they are compiled at -O2. There are fewer of them and they are bigger, so the compilation thread pool helps less, and compile times are longer than in Strict mode. The payoff is in steady state. The execution model documentation reports up to 50% better performance than default eager with no change to model code; the TorchTPU announcement words it as "50% or more faster than Strict Eager" and adds that fusion lowers peak HBM use, because fused ops need fewer temporary buffers. Neither gives the workload, so treat the number as a reason to measure, not a prediction.

An animation in nine frames comparing two eager modes on the same code, s = (gelu(x @ w + b) * 0.5).sum() followed by s.item(). Top panel, Strict (default), EagerMode.DEFER_NEVER: as each of the five ops x @ w, + b, gelu, * 0.5 and sum appears on the Python lane, a small blue executable appears on the TPU lane, with orange idle gaps between them; the label reads 5 executables, -O1. Bottom panel, DeferAndFuse, TORCH_TPU_DEFER_AND_FUSE=1: the same ops appear on the Python lane, but five DeferredOps D1 to D5 pile up in a Queue lane while the TPU lane says nothing launched yet. When .item() is called it is marked as a materialization point and flushes the queue; the TPU lane then shows one green block, 1 fused program, labelled 1 executable, -O2. The last frame notes that the next step with the same shapes takes the fused executable from the cache.

Watch the TPU lanes. In Strict mode work starts at once, in five small pieces with gaps between them; with ops this small, the gaps are the cost. In DeferAndFuse nothing runs until .item(), and then one program does all five ops. The timing is illustrative: with large ops the Strict gaps disappear and the difference shrinks.

One pitfall is specific to this mode. At a materialization point, every tensor that is still alive is materialized. A tensor you keep for logging or debugging becomes a required output, is written to HBM and cannot be fused away. Drop intermediates as soon as you are done with them (del t, or let them go out of scope), or overwrite them in place.

Compiled mode: torch.compile(backend="tpu")

torch.compile gives TorchTPU the most information and the strongest guarantee: the whole FX graph of the compiled function, which will not change between calls. That allows optimizations that would be too risky in eager mode. A later section follows the lowering step by step; the short version is that TorchTPU traces the graph once, compiles a single StableHLO program at -O2, and returns a Python callable. When you call it, no DeferredOps are created, no stream analysis runs and no cache lookup is needed: the executable goes straight to PjRt. That is why the documentation recommends it for the highest warmed-up throughput and the lowest latency.

Materialization points and host syncs

A materialization point is anything that needs a device value to exist now. In DeferAndFuse mode it ends the current fused region; in every mode it can make the host wait for the TPU. The common ones:

What your code does Why it materializes Host waits for the TPU
t.cpu(), t.to("cpu"), t.item() A device-to-host transfer Yes
print(t) Printing reads the values Yes
torch.accelerator.synchronize(), torch.Stream.synchronize(), torch.Event.synchronize() An explicit wait Yes
if t.all():, if y.sum() > 0:, while loss > tol: Python needs a host bool, so PyTorch synchronizes the stream and copies one value back Yes
torch.masked_select(x, mask), torch.nonzero(x) The output shape depends on the data, so the shape metadata has to come to the host before the next op can be built Yes
A loop body repeats (DeferAndFuse only) The repeated-ops detector compiles one iteration for reuse No

The first three rows are visible in the code. The last three are not, and the fourth is the one that costs the most in practice, because it hides in model code that looks harmless.

The silent host sync

def gate_with_host_sync(y):          # anti-pattern
    if y.mean() > 0:
        y = y * 0.5
    return y

y.mean() > 0 is a device tensor. Python's if needs a host bool, so the stream is synchronized and one value is copied back before the next line runs. The execution model documentation spells out the cost by mode. In Strict mode it does not cut any graph, but the whole pipeline drains before the host continues. In DeferAndFuse or compiled mode it is worse: the forced sync also cuts the fused stream or the FX graph at that line, which is an optimization barrier the compiler cannot see across.

An animation in ten frames with two pairs of timelines, host above TPU. Top pair, labelled Before, with the code if y.mean() > 0: y = y * 0.5: the host dispatches the model, then a long orange block, waiting for bool, while the TPU runs the model forward in blue; when the forward ends the host resumes and dispatches * 0.5 and the next step, and meanwhile the TPU shows an orange idle block before it can start * 0.5 and the next step. Bottom pair, labelled After, with the code y = torch.where(y.mean() > 0, y * 0.5, y): the host dispatches model, where and next in three short blocks and is done early, while the TPU runs the forward, the where and the next step back to back with no gap. A vertical cursor sweeps left to right; at the end both pairs show step done, and the After step ends earlier. A footer says orange means host blocked or TPU idle and that the timing is illustrative, not measured.

Count the orange blocks in the top pair: first the host waits for the TPU, then the TPU waits for the host. The bottom pair has none, because the decision never leaves the device. The shape, two stalls per sync, is what a profile shows; the durations are illustrative.

The fix keeps the decision on the device:

def gate_sync_free(y):               # same result, no host sync
    return torch.where(y.mean() > 0, y * 0.5, y)

torch.where evaluates both branches and selects one per element, so it costs one extra elementwise multiply and one select. That is a small price next to a pipeline drain and a graph cut. The same idea covers most data-dependent branches: torch.where, torch.clamp or a mask multiply replace an if on a tensor value. For a data-dependent shape such as masked_select, the usual fix is to keep a fixed shape and carry a mask, which chapter 7 develops.

The companion script checks that the rewrite is exact. On a laptop:

$ python code/ch04_execution/modes.py --cpu-smoke
...
2. host-sync if vs torch.where, branch 'mean > 0, halves': identical
2. host-sync if vs torch.where, branch 'mean <= 0, passes through': identical
   full step, host-sync vs torch.where: identical
3. Dynamo graphs, one call: host-sync step = 3 (graph break at the if), torch.where step = 1
   fullgraph=True on the host-sync step: rejected (Unsupported)
4. Recompiles with dynamic=False: batch sizes [2, 4, 6] -> 3 graphs; same shape three times -> 1 graph (chapter 7)

"Identical" here means torch.equal, bit for bit, on both branches: torch.where computes y * 0.5 exactly as the if branch does. Lines 3 and 4 are the subject of the next two sections.

Graph breaks

A graph break is a point where one compiled graph ends and another begins, with eager execution in between. It happens in two places on TorchTPU.

  • In DeferAndFuse mode, every materialization point is a graph break in the fused stream. The ops before it are compiled and run as one program; the ops after it start a new one. Nothing is wrong, but the compiler cannot fuse across the cut, and the intermediates at the cut go through HBM.
  • Under torch.compile, TorchDynamo stops tracing when it meets something it cannot put in an FX graph, such as an if on a tensor value. It compiles what it has, runs the offending code eagerly, and resumes tracing after it. On TorchTPU each piece becomes its own StableHLO program, and the code between them runs in the current eager mode.

Line 3 of the smoke output shows the second case on the CPU, where Dynamo behaves the same as on a TPU. The companion code counts graphs with a small backend that increments a counter and then hands the graph to the real backend ("eager" on the CPU, "tpu" on a TPU). The torch.where step is one graph. The host-sync step is three: the model up to the call of the gate function, the mean and the comparison, and the multiply on the branch that was taken. With fullgraph=True, Dynamo refuses the host-sync step outright, which makes fullgraph=True a cheap way to prove that a step has no graph breaks.

To see the reason for each break, set PyTorch's logging variable. TORCH_LOGS="+dynamo,graph_breaks" gives a full trace; for a first look, graph_breaks and recompiles are enough. On the companion code with PyTorch 2.15, the break is reported like this (log prefixes and paths trimmed):

$ TORCH_LOGS="graph_breaks,recompiles" python my_step.py
[__graph_breaks] Graph Break Reason: Data-dependent branching
[__graph_breaks]   Explanation: Detected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). ...
[__graph_breaks]   Hint: ... Operations like torch.clamp, torch.nan_to_num, and torch.where are typically
                   no-ops on well-behaved inputs and compile without graph breaks.

The torch.compile lowering pipeline

TorchTPU registers a TorchDynamo backend named "tpu", so the user-facing call is the standard one:

compiled_step = torch.compile(step, backend="tpu")

What happens on the first call, and on every call after it:

Two stacked containers, the six steps numbered on the arrows. Top, a gray dashed container labelled First call, in two rows. Row one: Your function, an arrow numbered 1 to TorchDynamo, an arrow numbered 2 labelled FX graph to AOTAutograd, an arrow numbered 3 to TorchTPU FX passes. From there an arrow numbered 4 turns back to the start of row two: Deferred trace, an arrow numbered 5 labelled StableHLO to Compilation cache; from the cache an arrow labelled miss leads to XLA compiler, marked -O2, which leads to TPU executable, and an arrow labelled hit runs above the row straight to TPU executable. Bottom, a green dashed container labelled Every later call: an ink pill Later call, an arrow numbered 6 to Guard check, an arrow labelled pass to PjRt, an arrow to TensorCore. An arrow from TPU executable runs down into PjRt. An orange arrow labelled recompile runs from Guard check down, along the bottom and up the left margin into Your function.

Steps 1 to 5 run once per graph and per set of guards; on every later call only the guard check runs before the executable goes straight to PjRt. The orange arrow is the expensive way back into the first-call path, and chapter 7 is about avoiding it.

  1. TorchDynamo captures an FX graph. It traces the Python bytecode of your function into a torch.fx.GraphModule and records guards: conditions, such as exact input sizes, under which the graph stays valid. A construct it cannot trace causes a graph break, as above.
  2. AOTAutograd builds the forward and backward graph. TorchTPU's backend goes through PyTorch's AOTAutograd, so a training step's backward pass is part of what gets compiled.
  3. TorchTPU's FX passes rewrite the graph. The source tree has passes such as fold_gqa and detect_causal_mask under src/torch_tpu/_internal/compile/fx_passes/; they are internal and can change, so treat them as an implementation detail.
  4. TorchTPU traces the graph with deferred ops. It runs the FX graph once as if in eager mode, on placeholder tensors (similar to FakeTensor, but carrying TPU-specific metadata), with every op deferred and nothing executed. The result is one fully deferred computation graph that mirrors the FX graph, and from it one StableHLO program.
  5. The program is compiled at -O2. It goes through the same compilation cache as eager graphs, so a Tier-2 or Tier-3 hit skips the XLA compile (chapter 3 covers the tiers). On a miss, XLA compiles it at the higher optimization level.
  6. A Python callable is returned. Later calls check Dynamo's guards; if they pass, the executable is pushed straight to PjRt, with no DeferredOps, no stream analysis and no cache lookup. If a guard fails, Dynamo traces again and the pipeline runs again for the new case.

TorchTPU does not use TorchInductor. Its loader also changes two defaults, which the TorchTPU documentation and source describe:

  • dynamic=False is the default on TPU. When you do not pass dynamic, TorchTPU sets dynamic=False for its backend, so every graph is specialized to exact shapes and a new shape means a new compile. dynamic=None opts in to automatic dynamic shapes with bounded dynamism, and dynamic=True raises NotImplementedError. Chapter 7 is about this choice.
  • No backend means the TPU backend. A torch.compile call without backend selects TorchTPU's backend when TPU tensors are involved, and backend="inductor" with TPU inputs raises a RuntimeError unless options={"tpu_backend": "pallas"} is set (src/torch_tpu/_loader.py).

Two compiled-mode pitfalls:

  • Views as arguments. PjRt needs each input to a compiled executable to be contiguous, zero-offset and of a fixed dtype. If an argument is a non-trivial view or a bitcast, TorchTPU makes a temporary eager copy before the call. When compiled functions feed each other, return contiguous tensors so the next call does not pay that copy. Chapter 5 explains why views cost copies on a TPU.
  • Mode and precision scopes. torch.tpu.set_eager_mode is not allowed inside a compiled region, and torch.tpu.precision causes a graph break there, so wrap the call to the compiled function rather than code inside it (chapter 6).

Compile caching, mode by mode

Every mode compiles, and every compile goes through the three-tier cache from chapter 3. What differs is the shape of the work.

Mode What gets compiled Typical first step Typical steady state
Strict One small -O1 module per distinct op and shape Fast: small compiles in parallel, high reuse Host dispatch per op; microbubbles if ops are small
Debug Same as Strict Like Strict Slow: the host waits on every op
DeferAndFuse One -O2 module per distinct fused region Slower: fewer, larger compiles Fewer launches, fused intermediates
torch.compile One -O2 module per graph and guard set The whole graph, forward and backward, compiles before the first result Lowest overhead: no DeferredOps, no lookup

The orderings come from the documentation's takeaways (Strict for minimum compile time, torch.compile for maximum warmed-up throughput, DeferAndFuse between them for runtime); no measured times are published. Two practical rules follow from the cache key. A step that is compiled once and then reused costs its compile only on the first step, and a Tier-3 cache makes that true across restarts. And a step that keeps producing new graphs, because shapes change or because a host sync moves the cut point, keeps paying compile time on every step. In torch.compile that shows up as a recompile: line 4 of the smoke output compiles three graphs for three batch sizes and one for three calls with the same shape. Recompiles are the main topic of chapter 7.

Choosing a mode

The TorchTPU documentation's own advice is short: Strict for minimum compile time, torch.compile for maximum warmed-up throughput and minimal latency, DeferAndFuse when faster runtime matters and torch.compile is not an option, launch blocking for debugging, and in every mode, avoid forced synchronizations. As two steps: pick a mode, then check it once the step has warmed up.

A decision tree read from top to bottom. Four white rounded question boxes form a spine on the left. Three of the Yes answers lead right to a blue mode card that names the mode, the switch that selects it and its XLA optimization level; the Yes of the second question and the No of the first, third and fourth continue down the spine; the No of the second runs down the left margin into Strict. First question: Is an error reported far from its cause? Yes leads right to the card Debug, TORCH_TPU_LAUNCH_BLOCKING=1, -O1. No leads down to the second question: Does the step run many times? Yes leads down to the third question; No runs down the left margin into the card at the bottom, Strict (default), Nothing to set, -O1. Third question: Does torch.compile capture it with fixed or bucketed shapes? Yes leads right to the card Compiled, torch.compile(step, backend="tpu"), -O2. No leads down to the fourth question: Does the profile show small ops and idle gaps? Yes leads right to the card DeferAndFuse, TORCH_TPU_DEFER_AND_FUSE=1, -O2. No leads down into the same Strict (default) card. A note beside the Strict card reads: -O1, -O2: XLA optimization level.

Every exit to the right selects a mode. Two routes end in Strict, the default: a step that does not repeat, and a repeated step that torch.compile cannot capture and whose ops are already large.

A step that torch.compile does not capture is one with control flow it cannot trace, code it does not support, or a port where the change is not worth making yet.

Two decision rows on one grid, one for each mode that fuses work. Each row starts with a blue card naming the mode, with an arrow down into a white rounded question. Top row: Compiled, then the question Graph breaks in the step? Yes drops to an orange card, Remove host syncs, torch.where, masks. No leads right to the question Recompiles after warm-up? Yes drops to an orange card, Fix shapes, Chapter 7. No leads right to a green card, Keep it, Confirm no new compiles, step time and parity. Bottom row: DeferAndFuse, then the question Retained tensors or host reads? Yes drops to an orange card, Drop intermediates, Move logging out of the step. No leads right along a long arrow to a green card, Keep it, Confirm no new compiles, step time and parity.

Run these checks once the first steps have compiled, and keep host syncs out of the step in every mode, Strict included. An orange card is a change to the step, not a change of mode; a green card still asks for measurements before you keep the mode.

The modes also combine. A training loop can compile the step with torch.compile and leave data loading, metrics and checkpointing in eager mode; the eager parts run in whatever mode is active, which is why the compiled row in the companion code reports DEFER_NEVER as its eager mode. And a model that is not ready for torch.compile can run its forward pass under set_eager_mode(EagerMode.DEFER_AND_FUSE) while the rest of the script stays in Strict.

Failure modes

Symptom Likely cause Fix
TPU idle between short ops in a profile; host time per step close to the step time Microbubbles: Strict mode with ops shorter than the PjRt enqueue cost DeferAndFuse, torch.compile, or larger ops
Gaps in the TPU timeline at the same place every step; DeferAndFuse or torch.compile gives less than expected A host sync in the step: if on a tensor, .item(), print(t), masked_select Keep the decision on the device (torch.where, masks); log every N steps
Compile time on every step, or on every new batch Recompiles from changing shapes, or a host sync that moves the cut point Chapter 7: bucketing, static caches, mark_dynamic
DeferAndFuse uses more HBM than expected and fuses little Intermediates kept alive across the materialization point del them, let them go out of scope, or update in place
A copy before a compiled call A non-contiguous view or bitcast passed to a compiled function Pass and return contiguous tensors
A runtime error reported lines after the op that caused it Asynchronous execution in Strict or DeferAndFuse Rerun with TORCH_TPU_LAUNCH_BLOCKING=1
TORCH_TPU_DEFER_AND_FUSE=1 seems to have no effect Set after import torch, or TORCH_TPU_LAUNCH_BLOCKING is also set Set it before Python starts; print torch.tpu.eager_mode
A production job is much slower than in testing Launch blocking left on Unset TORCH_TPU_LAUNCH_BLOCKING

Verifying the result

A mode choice has worked when you know which mode ran, the step stopped compiling after warm-up, the steady-state step got faster, and the numbers did not change beyond what fusion can explain. modes.py measures the three default modes on a TPU (Debug on request), for a small stack of identical MLP blocks and for both versions of the gated step.

  1. Confirm the mode. Print torch.tpu.eager_mode at the start of the run. modes.py starts one process per mode and step version, sets the mode's variable in that process's environment before Python starts, and fails the run if the active mode is not the expected one. With --in-process it switches modes with set_eager_mode instead.
  2. Count compiles. For eager modes, count the modules XLA compiled: set XLA_FLAGS="--xla_dump_hlo_as_text --xla_dump_to=DIR" before starting Python, run the step, and count the *after_optimizations.txt files in DIR, one per compiled module. modes.py reports this as "XLA modules". Expect Strict to compile many small modules, DeferAndFuse fewer, and the host-sync step more than the torch.where step under DeferAndFuse, because each sync cuts the fused region into one more piece. For torch.compile, count the graphs with a counting backend ("Dynamo graphs" in modes.py) or read TORCH_LOGS="graph_breaks,recompiles". After the warm-up steps, a further step should add no compiles at all; if it does, find out why before you time anything. Keep the Tier-2 and Tier-3 caches off while you count, since a cache hit skips the compile and the dump; both are off by default on a single device.
  3. Compare step times properly. Time the first call separately: it includes compilation. Then warm up, dispatch a fixed number of steps back to back, and synchronize once at the end, so the measurement includes device time without adding a sync inside the loop. This is the method modes.py uses. The documentation predicts the order: Strict has the fastest first call; in steady state torch.compile is fastest, then DeferAndFuse, then Strict. The torch.where step should not be slower than the host-sync step in steady state. If your numbers disagree, profile before you conclude anything (chapter 10).
  4. Check numerical parity between modes. modes.py compares every mode's output with Strict's torch.where output using allclose(rtol=1e-2, atol=1e-2). All modes use the same MXU precision, so remaining differences come from fusion and the optimization level, which can change rounding order and keep intermediates at higher precision (chapter 6 explains the effect). On the CPU, the two step versions must match bit for bit, and the --cpu-smoke run checks that.
python code/ch04_execution/modes.py --cpu-smoke          # laptop: the logic, no TPU numbers
python code/ch04_execution/modes.py                      # TPU VM: strict, defer_and_fuse, compiled
python code/ch04_execution/modes.py --modes strict,debug # Debug is slow; run it on purpose

Run it on your machine and keep the table: it is the baseline for every optimization in Part III.

Worked problems

Problem 1. A script sets os.environ["TORCH_TPU_DEFER_AND_FUSE"] = "1" on its second line, after import torch. Profiling shows one executable per op. Explain, and give two fixes.

Answer

TorchTPU reads its environment variables once, when the backend initializes during import torch, and locks them. By the second line the default eager mode is already DEFER_NEVER (Strict), so every op gets its own executable. Fix 1: set the variable before Python starts (TORCH_TPU_DEFER_AND_FUSE=1 python train.py), or before import torch at the very top of the file. Fix 2: switch inside the process with with torch.tpu.set_eager_mode(torch.tpu.EagerMode.DEFER_AND_FUSE): around the code that should be fused, or torch.tpu.eager_mode = torch.tpu.EagerMode.DEFER_AND_FUSE. Either way, print torch.tpu.eager_mode to confirm.

Problem 2. In Strict mode, a training step spends a long time in optimizer.step(), which updates hundreds of small bias and norm parameters with a few elementwise ops each. The TPU is idle much of that time. Explain the mechanism, and why DeferAndFuse helps here more than in the matmuls.

Answer

Each elementwise op on a small tensor runs for microseconds, shorter than the cost of enqueueing an executable with PjRt (up to about 50 µs per the documentation). In Strict mode every op is its own executable, so the TPU finishes each one before the host has enqueued the next: microbubbles. The large matmuls run long enough to hide the enqueue cost, so they do not suffer. DeferAndFuse collects many of these small ops into one -O2 program, which removes most launches and lets XLA fuse the elementwise chains so intermediates stay out of HBM. Putting the whole step under torch.compile does the same and more.

Problem 3. Under DeferAndFuse, which of these lines materialize, and which also make the host wait? (a) loss.backward(); (b) if torch.isnan(loss): raise RuntimeError("nan"); (c) losses.append(loss); (d) print(f"{loss.item():.4f}"); (e) idx = torch.nonzero(mask).

Answer

(a) Neither by itself: backward ops are deferred like any other ops. (b) Both: the if needs a host bool, so the stream is synchronized and a value copied back, which also cuts the fused region. (c) Neither now, but it keeps loss alive. At the next materialization point it is a live tensor, so it is materialized as an output; across many steps the list also holds device memory. Store loss.detach() and convert to numbers outside the hot loop, or keep a running sum on the device. (d) Both: .item() is a device-to-host transfer. (e) Both: the output shape depends on the data, so the shape has to come to the host before the next op can be built.

Problem 4. Rewrite this clipping code so it causes no host sync, and say how you would check the rewrite.

norm = grad.norm()
if norm > max_norm:
    grad = grad * (max_norm / norm)
Answer

norm = grad.norm()
scale = torch.clamp(max_norm / (norm + 1e-6), max=1.0)
grad = grad * scale
or, keeping the exact original arithmetic, grad = torch.where(norm > max_norm, grad * (max_norm / norm), grad). The torch.where form gives identical results to the if (check with torch.equal on CPU for one input above and one below max_norm, as the companion script does for the gate). The clamp form adds 1e-6 to avoid dividing by zero, so it is close but not bit-identical; check it with torch.allclose.

Problem 5. You compile a step with torch.compile(step, backend="tpu") and TORCH_LOGS="graph_breaks,recompiles". The log shows one graph break, "Data-dependent branching" at if attn_mask.any():, and a recompile every few steps with "size mismatch at index 1". Name the two problems, the fix for each, and how you will confirm both are gone.

Answer

The graph break: an if on a tensor value forces a host sync and splits the step into separate graphs with eager code between them. Fix: compute both cases and select with torch.where, or apply the mask unconditionally if it is a no-op when nothing is masked. The recompiles: dimension 1 (probably the sequence length) changes between steps, and with TorchTPU's default dynamic=False every new size is a new graph. Fix: pad to a small set of bucket sizes, or opt in to bounded dynamism (chapter 7). Confirm with torch.compile(..., fullgraph=True), which must now accept the step, a counting backend whose count stops growing after warm-up, and a log with no graph_breaks or recompiles lines after the first steps.

Problem 6. modes.py on your TPU prints, for the torch.where step, an XLA module count under DeferAndFuse that is a small fraction of Strict's, and a first call that is slower. The steady-state time is lower. Then you run the host-sync step under DeferAndFuse and its module count is higher than the torch.where step's. Explain all three observations.

Answer

Strict compiles one small -O1 module per distinct op and shape, so the count is roughly the number of distinct ops in the model. DeferAndFuse compiles one -O2 module per distinct fused region. The blocks are identical, so the same region recurs (the repeated-ops heuristic cuts at iteration boundaries for exactly this case) and is compiled once, which keeps the count small. Its first call is slower because larger graphs at -O2 take longer to compile and parallelize less across the thread pool; the steady state is faster because there are fewer launches and fused intermediates. The host-sync step has a materialization point in the middle (if y.mean() > 0), which cuts the fused stream into more regions, and each new region is another module to compile. A real profile is still needed to say how much of the steady-state gain came from fewer launches and how much from fusion.

Quick questions

  1. List the six stages between calling an op and having its result, and say which run on the calling Python thread.
  2. Give the enum value, the environment variable (if any) and the XLA optimization level for each of the three eager modes.
  3. Name two events that start materialization in DeferAndFuse mode, and one kind of tensor that is skipped when it does.
  4. Why can Strict mode leave the TPU idle on a model made of small ops, and what two changes fix it?
  5. What does if t.any(): cost in Strict mode, and what extra cost does it add under DeferAndFuse or torch.compile?
  6. What happens on the first call of a function compiled with torch.compile(backend="tpu"), and what happens on later calls when the guards pass and when they fail?
  7. What dynamic setting does TorchTPU use when you do not pass one, and what does that mean for a sequence length that changes every step?

Key takeaways

  • Every TorchTPU op starts as a host-side DeferredOp on a stream queue. A background thread analyzes the queue, fetches or compiles executables through the compilation cache, and enqueues them with PjRt; the Python thread never waits unless it asks for a value.
  • Strict (DEFER_NEVER) is the default: one op per -O1 executable, fastest first result, asynchronous, with microbubbles when ops are shorter than the enqueue cost. Debug (TORCH_TPU_LAUNCH_BLOCKING=1) waits on every op and is for debugging only.
  • DeferAndFuse (TORCH_TPU_DEFER_AND_FUSE=1) keeps ops queued until a device-to-host transfer, a synchronize or a detected loop, then compiles the region at -O2, skipping tensors that were already dropped. The documentation reports up to 50% over default eager with no code change.
  • torch.compile(backend="tpu") traces the FX graph once with deferred placeholder tensors, compiles one StableHLO program at -O2, and sends later calls straight to PjRt. TorchTPU defaults to dynamic=False, so new shapes recompile.
  • Environment variables are read at import torch; use torch.tpu.set_eager_mode to switch inside a process, and print torch.tpu.eager_mode to know which mode ran.
  • Host syncs (.item(), print(t), if on a tensor, data-dependent shapes) stall the host and then the TPU, and under DeferAndFuse or torch.compile they also cut the graph. torch.where and masks keep the decision on the device with identical results.
  • Verify a mode choice by counting compiles (XLA dump files, a counting Dynamo backend, TORCH_LOGS), timing first call and steady state separately, and checking parity between modes.

References