Profiling with XProf¶
Prerequisites: Rooflines and arithmetic intensity, Dynamic shapes and recompilation
A port that is correct and compiles once can still be slow, and a stopwatch around the training step will not tell you why. On a TPU the step is split between two machines that run asynchronously: the host dispatches work and the TPU executes it, so time can go missing on either side, or in the gap between them. XProf shows both sides on one timeline. This chapter covers what the TPU profiler records, how to capture a trace from PyTorch with torch.profiler and TpuProfilerConfig, how to read the result in a fixed order (step time, device idle time, top ops, bound type), the signatures that the common problems leave in a trace, and the mistakes that make a trace lie: profiling overhead, captured warm-up, and traces from the wrong run. It ends with the checks that tell you a profile can be trusted and that a fix worked.
What this chapter covers¶
- Capturing a few steady-state training steps with
torch.profiler.profile, the TPU activity andTpuProfilerConfig, with warm-up kept out, and opening the result in XProf. - Checks that make a capture trustworthy: the files exist, the step count matches, and the traced step time matches an unprofiled run.
- The Trace Viewer's host and device rows, and splitting a step into device busy time and idle gaps with their host-side cause.
- Ranking the top ops and comparing each with its roofline estimate to tell compute-bound, memory-bound and slower-than-bound ops apart.
- The trace signatures of host-bound gaps, recompiles, waiting collectives, copies and padding, and the chapters that fix each.
- vLLM-TorchTPU's capture modes (offline, server, phased, disaggregated) and the failure modes behind empty or misleading traces.
What XProf captures on a TPU¶
XProf is the viewer for XLA profiles, the same tool the scaling book uses for JAX programs. TorchTPU does not have a profiling context manager of its own: it plugs into PyTorch's standard torch.profiler.profile context manager and adds two things, a ProfilerActivity.TPU activity that turns on tracing of the TPU hardware, and a configuration object, torch.tpu.profiler.TpuProfilerConfig, that sets the TPU tracers' options. That object is the only public API in torch.tpu.profiler; the API reference lists nothing else there, and TorchTPU's source exports only that one name in the public module. It is marked experimental.
Inside the context manager, two tracers run:
- The host tracer records what the CPU does: PyTorch operator dispatch, your
torch.profiler.record_functionranges, and TorchTPU's and XLA's own runtime events. - The device tracer records what each TPU executes: the XLA programs and the HLO operations inside them, with start times and durations measured on the device.
When the profiler stops, the TPU trace is written as an XPlane protobuf file, <hostname>.xplane.pb, in the directory you pass as run_dir. An XPlane file holds several timelines, called planes. The vLLM-TorchTPU guide lists the five in a single rank's capture on a v6e: the chip (/device:TPU:0), /host:metadata (which carries the HLO protos, so XProf can show the program behind each op), /device:CUSTOM:Megascale Trace, Task Environment, and /host:CPU. Separately, torch.profiler.tensorboard_trace_handler(dir) writes PyTorch's usual Chrome-format trace, <host>_<pid>.<timestamp>.pt.trace.json, which any Chrome trace viewer or Perfetto opens. XProf reads the XPlane files.
Two tracers, two files. Only the .xplane.pb path leads to XProf; the Chrome trace is the host-side view you also get on a CPU.
TpuProfilerConfig takes these keyword arguments (from the TorchTPU guide, with the level meanings from the class's docstring):
| Argument | Default | Meaning |
|---|---|---|
host_tracer_level |
2 |
0 off; 1 user-instrumented TraceMe events; 2 adds XLA TraceMe events; 3 adds low-level XLA events |
device_tracer_level |
1 |
0 off; 1 TPU hardware activity |
python_tracer_level |
0 |
1 records Python function calls; off by default to keep overhead down |
run_dir |
None |
Directory for the .xplane.pb files. Unset, it falls back to the Kineto trace directory; the API reference names TORCH_TPU_PROFILER_OUTPUT_DIR as the fallback |
worker_rank |
None |
A string appended to the file name, <hostname>_<rank>.xplane.pb, so ranks on one host do not overwrite each other |
experimental_options |
None |
Extra keys passed to the profiler backend, such as the v7x counter options below |
The class's docstring says the defaults are the standard XLA profiling defaults used by JAX and TensorFlow: host and TPU tracing on, Python tracing off. Two version notes: the native torch.profiler TPU integration needs PyTorch 2.12 or newer, and worker_rank is documented in the current repository guide but not in the 0.2.0 documentation, so check your installed version before relying on it.
Labelling regions. TpuProfilerConfig is the only public name in torch.tpu.profiler, and it takes no mode argument. TorchTPU has a named_scope helper that tags the TPU ops themselves, but in 0.2.0 it lives in the internal module torch_tpu._internal.profiler.named_scope. This chapter labels regions with torch.profiler.record_function, which is standard PyTorch and shows up as a host range on every device. vLLM-TorchTPU has its own TraceAnnotation for serving; see the section on serving engines.
Capturing a trace from PyTorch¶
Install the viewer first. TensorBoard depends on pkg_resources, which setuptools 81 removed, so pin it:
pip install "setuptools<81"
pip install xprof tensorboard
The capture itself is the TorchTPU guide's pattern with three additions that make the trace easier to trust: warm-up steps run before the profiler starts, each step is labelled, and the device is synchronized before prof.step() so the host range covers the device work.
import pathlib
import torch
from torch.tpu.profiler import TpuProfilerConfig
log_dir = pathlib.Path("/tmp/profiler_output")
config = TpuProfilerConfig(
host_tracer_level=2,
device_tracer_level=1,
python_tracer_level=0,
run_dir=log_dir,
)
for _ in range(warmup_steps): # compiles happen here, outside the trace
train_step(batch)
torch.accelerator.synchronize()
with torch.profiler.profile(
activities=[
torch.profiler.ProfilerActivity.CPU,
torch.profiler.ProfilerActivity.TPU,
],
experimental_config=config,
on_trace_ready=torch.profiler.tensorboard_trace_handler(str(log_dir)),
) as prof:
for i in range(5):
with torch.profiler.record_function(f"train_step#{i}"):
train_step(batch)
torch.accelerator.synchronize()
prof.step()
print(prof.key_averages().table(sort_by="self_device_time_total", row_limit=8))
import torch
for _ in range(warmup_steps):
train_step(batch)
with torch.profiler.profile(
activities=[torch.profiler.ProfilerActivity.CPU],
record_shapes=True, # lets you compute a matmul's intensity later
on_trace_ready=torch.profiler.tensorboard_trace_handler("/tmp/cpu_profile"),
) as prof:
for i in range(5):
with torch.profiler.record_function(f"train_step#{i}"):
train_step(batch)
prof.step()
print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=8))
Each line has a reason:
- Activities.
CPUtraces host work (dispatch, data loading);TPUtraces the hardware (compute, memory, interconnect). With onlyCPU, expect no device timeline at all. - Warm-up outside. The first calls of a compiled step, and the first steps of an eager one, pay compilation. Inside a trace they are a step that is many times longer than the rest, and every average you read afterwards includes it. The companion script's
capture()warms up before entering the profiler for this reason, and the vLLM offline script separates--num-iters-warmup(not traced) from--num-iters(traced) because "the first iterations pay XLA compilation". - Labels. Without a
schedule,torch.profilerdoes not mark step boundaries on its own (PyTorch profiler behaviour, see its documentation in the references);record_functionputs a named range on the host timeline that you can find, measure and count. - Synchronize, then step. TorchTPU dispatches asynchronously (chapter 4). Without the synchronize, the host range for step \(i\) ends as soon as Python has queued the work, long before the TPU finishes it. The TorchTPU guide's loop calls
torch.accelerator.synchronize()beforeprof.step(); keep it there while profiling, and remove it from production loops. - How many steps. The guide says to profile "a representative subset of steps" and gives 100 to 1,000 as its example, because the profiler adds overhead and the files grow with every step. The vLLM phased profiler defaults to 15 engine steps per phase and its examples use 5. These are not in conflict: a Trace Viewer reading needs only a few identical steps, while summary statistics over many steps smooth out noise. Start with a handful, and capture more only when you need averages.
- The table.
key_averages()gives a quick text summary before you open the viewer: on a TPU, sort byself_device_time_totalto see the ops that took the most device time.
PyTorch's torch.profiler.schedule(wait=..., warmup=..., active=...) is the standard way to skip early steps inside one profile block and also makes the profiler mark ProfilerStep#N ranges for you. The TorchTPU guide does not use it, so this chapter warms up outside the block, which works the same with or without a schedule.
Multi-host runs. Every process captures its own chips. Give each a distinct worker_rank (a string), or a per-rank run_dir, so files do not collide. TORCH_TPU_XPROF_SESSION_ID sets a shared profiling session ID across multi-host workers.
Ironwood counters. On TPU7x (v7x) and later, TpuProfilerConfig can also sample fine-grained hardware performance counters, the tool for seeing inside a Pallas kernel (chapter 12):
config = TpuProfilerConfig(
experimental_options={
"tpu_enable_periodic_counter_sampling": True,
"tpu_tc_perf_counter_sampling_options": (
"interval_us:1 scaling:0 counter_size_bits:1 indices:10"
" indices:11 indices:56 indices:57 indices:58"
),
}
)
The counter indices and the other sampling parameters are documented in the OpenXLA kernel profiling guide.
Check the files, then open them¶
Before reading anything, confirm the capture wrote files. The TorchTPU guide's check is to list the trace directory and stop if it is empty; the companion script also looks for at least one .xplane.pb file. Then start a viewer on the directory, not on a file:
xprof --logdir=/tmp/profiler_output --port=6006
# or: pip install tensorboard-plugin-profile, then
tensorboard --logdir=/tmp/profiler_output --port=6006 # and open the Profile tab
Open http://localhost:6006. On a TPU VM, VS Code's Remote-SSH forwards the port for you; otherwise forward it when you connect, ssh -L 6006:localhost:6006 <tpu-vm-host>. To keep traces after the VM is gone, copy them down with their directory structure intact: XProf reads the plugins/profile/<timestamp>/ layout, not loose files. On GKE, write the trace directory to a Cloud Storage bucket mounted with the Cloud Storage FUSE CSI driver so the traces outlive the pod, and point the viewer at it with xprof --logdir=gs://<bucket>/profiler_output.
Anatomy of a trace¶
The TorchTPU guide lists four XProf views:
| View | What it shows |
|---|---|
| Overview | High-level summary: step time, device utilization, top ops |
| Trace Viewer | A timeline of every op on the CPU and the TPU; look for gaps, which are idle hardware |
| Op Profile | Time per operation; find the most expensive ops |
| Memory Profile | HBM usage over time; find memory spikes |
The scaling book's profiling chapter calls the Trace Viewer "probably the most useful part of the profiler", and it is where this chapter spends most of its time. The figure is a schematic: the row names are XProf's, the timings are illustrative.
The host rows say what Python asked for; the TPU rows say what ran. Read across them at the same moment: callout 2 is a stretch where the host is busy loading a batch and no XLA op runs on the chip.
Host rows and device rows. The timeline is grouped by process and thread. The host section holds CPU threads, including the Python thread with your record_function ranges. The device section has one group per TPU core you captured; the scaling book reads only TPU:0, because typically all cores execute the same instructions. When a run's per-rank files sit in one session directory, the viewer's host picker switches between ranks (the vLLM guide relies on this).
Steps, XLA Modules, XLA Ops. Within a TPU group, the Trace Viewer has rows for steps, for XLA modules (each compiled program as it runs), and for XLA ops. The scaling book is specific about the last one: the XLA Ops row shows the operations the TPU actually executed, under their HLO names (fusion.3, copy.4, all-reduce.1), and every other row is an approximation built from annotations and stack traces. Trust the XLA Ops row for what ran and for how long.
Clicking an op. Selecting an op shows its details, including where in your code it came from, and links to the Graph Viewer, which draws the HLO graph around it. The scaling book's tip for moving around: W and S zoom, A and D pan.
Reading an op's name. The details give an HLO line, which looks dense but has a fixed structure. The scaling book's example is
%fusion.3 = bf16[32,32,4096]{2,1,0:T(8,128)(2,1)S(1)} fusion(bf16[32,32,8192]{...} %fusion.32), kind=kCustom, calls=%all-reduce-scatter.3
Read it left to right: the op's name (fusion.3); its output dtype and shape (bf16[32,32,4096], two bytes per element); its layout in braces, where 2,1,0 is the order of dimensions in memory from most minor to most major and T(8,128)(2,1) is the tiling, an outer \(8 \times 128\) tile with a \(2 \times 1\) inner tile that bf16 uses so loads stay multiples of 4 bytes; the memory space, where S(1) means VMEM and no S or S(0) means HBM; and its inputs with their shapes. A fusion holds at most one matrix multiplication plus the elementwise operations around it, and its calls= part says what it computes; here a reduce-scatter collective sits inside a fusion. The tiling is the same \((8, 128)\) tile chapter 5 described, and it explains padding: an array whose last two dimensions are not multiples of the tile is stored padded up to them. The scaling book works through f32[3,5] tiled T(2,2), which is stored as \([4, 6]\), about 1.6 times the memory.
The other views. The Op Profile ranks ops by time, so it answers "what are the top ops" in one screen, and the vLLM guide notes that it and the Memory Profile cover MXU utilization and HBM usage. The Memory Profile shows memory over time; the scaling book uses it to read how much HBM the parameters take and how much is free, the first thing to check before an out-of-memory error. The Overview page summarizes step time, device utilization and top ops. TorchTPU's documentation does not describe a roofline tool, so this chapter does the roofline step by hand, from the op's shape, as chapter 2 taught.
A reading workflow¶
A trace shows thousands of events. Reading them in a fixed order keeps you from chasing the first interesting one. The order goes from the whole step down to one op, and every stage either sends you to a fix or to the next stage.
Read the stages in order and leave at the first one that shows a problem: an op ranking taken from a trace with large idle gaps points at the wrong thing. Whatever you fix, capture again with the same settings and compare. The host rows are chapter 4, recompiles chapter 7, and the op-level fixes chapter 11.
1. Step time. Count the step ranges: the number must equal what you asked for. Read their durations. They should be close to each other; one step far longer than the median is a compile or warm-up that got into the capture. Then compare the median with the same loop timed without the profiler. The TorchTPU guide puts the profiler's overhead at about 5 to 10% per step; a gap much larger than that means you are reading a different program from the one you run.
2. Device idle. Look at the XLA Ops row across one step. Long continuous blocks are what the TorchTPU guide calls the ideal profile ("the compiler fused many ops into one execution"). Gaps between ops are idle hardware, and the guide's reading is that large gaps mean a host-side bottleneck: data loading or Python overhead. Do not stop at "the host is slow": move up to the host rows at the moment the gap starts and see what the host was doing. A .item() shows up on a CPU trace as aten::item and aten::_local_scalar_dense; a blocking data loader shows as time in your input code; a stretch with no host op at all is Python work between ops.
3. Top ops. Rank ops by total time across the captured steps, in the Op Profile or by sorting key_averages() on device time. Usually a few ops take most of the step. Click the top one and read its name, shape and source line.
4. Bound type. For each top op, estimate its time from its shape with chapter 2's roofline, \(\max(T_\text{math}, T_\text{mem})\), and compare. The scaling book does exactly this on a TPU v2 trace: it predicts 95.6 ms for a sharded feed-forward matmul and measures 96 ms, and predicts about 1.1 ms for a reduce-scatter and measures 1.13 ms. Close to the estimate means the op runs at its bound; the arithmetic intensity says which bound (above the ridge, the MXU; below it, HBM bandwidth), and the only ways to make it faster are fewer FLOPs or fewer bytes. Far above the estimate means something the roofline does not model is taking time: a copy, padding, a poor layout, waiting on a collective. Those are the playbook's targets in chapter 11.
Follow the stage tracker at the top. The gap is found at stage 2 and fixed before stage 3 starts: ranking ops in a trace that is a third idle would have pointed at the wrong thing. Timings are illustrative.
A worked example on a laptop¶
The companion script code/ch10_profiling/capture.py runs the whole workflow on a CPU, where the Chrome trace is the complete profile and can be read by a program. The workload is a three-layer MLP trained with SGD, batch 512, hidden size 512. It captures three traces: one where each step starts with a 5 ms host-side wait that no op covers (standing in for synchronous input preparation), one with the input ready (prefetched), and one that makes the warm-up mistake on purpose with a compiled model. For each it prints the four reading steps. Real output from a laptop, abridged, with the host name in the file names shortened:
$ python code/ch10_profiling/capture.py --cpu-smoke
== before: input prepared synchronously in the step
trace: <host>_<pid>.<ts>.pt.trace.json
1. step time 5 steps; median 9.59 ms; per step: 11.02, 9.39, 9.59, 9.48, 9.89
unprofiled wall clock median 9.44 ms (trace / wall = 1.02)
2. idle time 66.9% of each steady-state step has no op running
3. top ops aten::mm 6.1 ms (37%); aten::addmm 4.6 ms (28%); aten::gelu_backward 1.2 ms (7%); ...
4. bound type largest matmul aten::addmm [512x512] @ [512x512]: 85 FLOPs/byte as recorded, 171 in bf16:
memory-bound on v6e (ridge 560), memory-bound on v7x (ridge 313)
== after: input prefetched
1. step time 5 steps; median 3.13 ms; per step: 3.20, 3.15, 3.12, 3.11, 3.13
unprofiled wall clock median 3.00 ms (trace / wall = 1.04)
2. idle time 4.9% of each steady-state step has no op running
3. top ops aten::mm 6.0 ms (40%); aten::addmm 4.0 ms (27%); aten::gelu_backward 1.3 ms (9%); ...
== mistake: compiled model, warm-up step captured
1. step time 6 steps; median 3.21 ms; per step: 61.68, 3.50, 3.20, 3.19, 3.21, 3.17
outliers (> 2x median): train_step#0: compile or warm-up inside the capture
3. top ops bytecode_tracing (dynamo_timed) 31.9 ms (42%); aten::mm 7.8 ms (10%); ...
== checks
[ok] each steady-state trace holds the 5 steps requested
[ok] no step in the steady-state traces is above 2x the median
[ok] before: trace median 9.59 ms within 30% of wall clock 9.44 ms
[ok] after: trace median 3.13 ms within 30% of wall clock 3.00 ms
[ok] idle share falls after the fix (67% -> 5%)
[ok] step time falls after the fix (9.6 -> 3.1 ms)
[ok] with warm-up captured, the first step is flagged as an outlier
cpu-smoke: OK
Three things in this output generalize to a TPU.
The top-ops list did not change when the step got 3 times faster. Before and after, aten::mm and aten::addmm take about two thirds of the busy time. An Op Profile alone would have sent you to optimize the matmuls, which were never the problem; the step time was 67% idle. That is why idle time comes before top ops in the workflow.
The captured warm-up step is not the only distorted one. With the compiled model's first call in the trace, step 0 takes 62 ms against about 3.2 ms for the rest, and the outlier test catches it. Step 1 is still about 10% slower than the settled steps (3.50 ms); it stays under the 2x threshold, so it is not flagged. The median of 3.21 ms hides both: one slow step in six does not move a median. Warm up until the step time settles, and look at the per-step list, not only the median.
The bound type is a property of the shape. A \([512, 512] \times [512, 512]\) matmul has an intensity of about 171 FLOPs per byte in bf16 wherever it runs, below both TPU ridges. On a TPU it would be memory-bound; making it faster means moving fewer bytes, for example by fusing it with its neighbours, not by finding more FLOP/s.
On a TPU, python code/ch10_profiling/capture.py --log-dir /tmp/profiler_output --compiled runs the same capture with the TPU activity and TpuProfilerConfig, prints the device-time table, checks that an .xplane.pb file was written, and tells you to open it in XProf; the device rows live in that file, so idle time and the Op Profile are read there. --host-stall-ms 5 adds the same host stall so you can see what it looks like on the device rows.
Common signatures¶
Each problem from Part I leaves a recognizable shape in a trace. The table gives the shape, how to confirm it, and where the fix is.
| Signature in the trace | Likely cause | Confirm with | Fix, and where |
|---|---|---|---|
| Large gaps between TPU ops, lined up with host work | Host-bound: a sync (.item(), .cpu(), print(tensor), if on a tensor), synchronous data loading, Python overhead |
The host rows at the start of each gap; aten::item and aten::_local_scalar_dense on the host |
Keep decisions on the device, read values every N steps, prefetch data (chapter 4) |
| Many short TPU bursts with small gaps, in eager mode | Microbubbles: executables shorter than the roughly 50 µs it takes to enqueue one, so the TPU outruns dispatch | Op durations near or below the enqueue cost | More work per op, DeferAndFuse, or torch.compile (chapter 4) |
Frequent short bursts, or every step slow by the same large amount, under torch.compile |
Graph breaks, or a recompile every step (for example a growing cache under dynamic=False: 38 to 50 ms per decode step against 0.4 ms) |
TORCH_LOGS="recompiles", a counting backend, TORCH_TRACE for graph breaks; absolute step time against a known good run |
Static shapes, a static cache, buckets (chapter 7); remove the syncs that break the graph |
| One step far longer than the others | Compile or first-call warm-up inside the capture | The per-step list; the step's host rows show compiler work | Warm up before the profiler starts |
copy ops you did not write |
A view forced a layout change, often in backward (the FLUX case study's einops.rearrange QKV split; its reference RoPE shows "large copy blocks") |
The op's source line; whether the copy sits in backward | Zero-copy views (.view(), torch.unbind), compact layouts (chapter 9, chapter 11) |
| A matmul much slower than its roofline estimate, low MXU utilization | Dimensions not aligned to the 128 tile, so the hardware works on padding | Shapes in the op's details; the layout's tile against the logical shape | Pad dimensions to multiples of 128 (chapter 5, chapter 11) |
A collective (all-reduce, all-gather, reduce-scatter, possibly inside a fusion's calls=) with compute idle around it, or longer than its estimate |
Communication not overlapped with compute, or a slow link for the collective's size | Estimate its time from bytes and ICI bandwidth, as the scaling book does for its reduce-scatter, and compare | Overlap and placement in chapter 13 |
| HBM usage climbing to the limit, or a spike in the Memory Profile | Activations, caches or temporary buffers larger than planned | The Memory Profile around the spike | Smaller caches or batches, checkpointing, sharding (chapters 11 and 14) |
The TorchTPU guide adds a target for the healthy end state: long continuous TPU compute blocks, minimal gaps between host and TPU, and MXU utilization above 60%.
Profiling serving engines¶
A serving engine is harder to profile than a training loop: requests arrive at their own pace, prefill and decode share batches, and each worker process owns only its own chips. vLLM-TorchTPU drives one profiler session per worker process, since each worker can trace only the chips it owns, writes .xplane.pb files like the ones above, and merges the per-rank captures into one run directory. It offers four ways to capture:
| Approach | Best for |
|---|---|
Offline script examples/tpu_profiling.py |
One shape in isolation: one prefill or one decode batch, with warm-up iterations not traced |
Server-side capture (/start_profile, /stop_profile) |
A real serving window under vllm bench serve --profile or your own client |
Phased profiling (USE_PHASED_PROFILER=true) |
One bounded trace per inference phase (prefill_only, prefill_heavy, balanced, decode_heavy, decode_only) from one mixed run |
| Disaggregated serving (Raiden3) | Correlating prefill and decode traces across pods through the shared transfer uuid in KV_Cache_* trace annotations |
Four rules from the vLLM guide carry over from this chapter:
- Configured is not armed. A server started with
--profiler-config.profiler torchand a trace directory is configured; nothing is recorded until something calls/start_profile. A run that finishes with an empty directory was configured but never armed. - Never compare profiled numbers with unprofiled ones. In benchmark runs, profiling costs roughly 11% time to first token and 4% throughput. The vLLM benchmark harness profiles an extra run after the measured one for this reason, and the FLUX case study disables the profiler during its timed steps.
- Profile the backend you serve with. The phased example passes
--attention-backend CUSTOM; without it vLLM falls back to a different attention backend, and you would profile code you do not run. - Keep runs apart. Clear the trace directory between phased runs, and keep a merged XPlane file (
python -m vllm_torchtpu.tools.merge_xplane <dir>) out ofplugins/profile/<timestamp>/: XProf builds its host list from the file names there, and a merged file beside the per-rank ones makes a 4-rank capture report 8 TPU cores and twice its events, with nothing to show that anything is wrong.
The recipes for each mode, the output layout and the troubleshooting list belong to chapter 18 and the Guides.
Failure modes¶
| Symptom | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'pkg_resources' starting TensorBoard |
setuptools 81 or newer removed it |
pip install "setuptools<81" |
| No TPU rows in the trace; only CPU threads | ProfilerActivity.TPU missing, or PyTorch older than 2.12 (expect no TPU rows there) |
Add the activity; check torch.__version__ |
| The trace directory is empty | The profiler never stopped cleanly, or (serving) was configured but never armed | Let the with block exit; call /stop_profile |
| The viewer finds no profile | --logdir pointed at a file, or traces were copied without their plugins/profile/<timestamp>/ directories |
Point it at the directory above plugins/; copy with the hierarchy |
| One step many times longer than the rest | Warm-up or compilation captured | Run warm-up steps before entering the profiler |
| Step times in the trace far from the wall clock | Missing synchronize (host ranges end at dispatch), heavy tracer levels, or a different program | Synchronize before prof.step(); default tracer levels; profile the code you run |
| Step time with the profiler on reported as the result | Profiler overhead, about 5 to 10% per step (11% TTFT, 4% throughput in vLLM benchmarks) | Measure speed with the profiler off; use traces to explain, not to time |
| Ranks overwrite each other's files | Same host name, same directory | worker_rank per process, or a per-rank run_dir |
| Traces from an earlier run mixed in | Old files left in the directory | Clear the directory, or a new directory per run |
| A trace too large to load or navigate | Too many steps or too verbose a tracer level | Fewer steps; host_tracer_level=2, python_tracer_level=0 |
| Per-expert MoE timings look skewed on one device | With expert parallelism, one device sees only the experts routed to it | VLLM_MOE_ROUTING_SIMULATION_STRATEGY=uniform_random, for profiling only |
Verifying the result¶
A profile is evidence only if the capture was right, and a fix is real only if the next profile changes. The companion script runs all of these checks on a CPU:
python code/ch10_profiling/capture.py --cpu-smoke # ends "cpu-smoke: OK"
pytest tests/ch10 -q
- The capture wrote what XProf needs. The trace directory holds an
.xplane.pbfile (a.pt.trace.jsonfile on a CPU-only run), andxprof --logdiron the directory shows the run. - The trace holds the steps you asked for. Count the
train_step#ranges (or the Steps row): the number equals the steps you captured, and no step is far longer than the others. A long first step means warm-up got in. - Steady-state step time matches the wall clock. The median step in the trace is within the profiler's overhead of the same loop timed without the profiler (about 5 to 10% on a TPU per the TorchTPU guide). If it is not, fix the capture before reading anything else.
- The findings change after a fix. After the change the profile pointed to, capture again with the same settings: the specific finding (the gap, the copy, the recompile) is gone or smaller, the ranking of what remains has moved, and the unprofiled step time has dropped by about what the removed time predicts. If the profile looks the same, the change did not touch the bottleneck.
Keep the trace directories of the before and after runs with the step times, the TorchTPU and PyTorch versions and the machine type. Chapter 24 returns to how to report such numbers.
Worked problems¶
Problem 1. Your training loop is for batch in loader: loss = step(batch); print(loss.item()), with step compiled with backend="tpu". Write the profiling code for 5 steady-state steps on a two-host slice, so that each host's files are distinct and the trace can be trusted. Say what you changed in the loop and why.
Answer
import pathlib, os, torch
from torch.tpu.profiler import TpuProfilerConfig
rank = os.environ.get("RANK", "0")
log_dir = pathlib.Path("/tmp/profiler_output")
it = iter(loader)
for _ in range(3): # warm-up: compiles stay out of the trace
step(next(it))
torch.accelerator.synchronize()
config = TpuProfilerConfig(run_dir=log_dir, worker_rank=rank) # default tracer levels
with torch.profiler.profile(
activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.TPU],
experimental_config=config,
on_trace_ready=torch.profiler.tensorboard_trace_handler(str(log_dir)),
) as prof:
for i in range(5):
with torch.profiler.record_function(f"train_step#{i}"):
loss = step(next(it))
torch.accelerator.synchronize()
prof.step()
print(loss.item()) is a host sync every step; it would put a gap in every step of the trace. Either profile the loop as it is first (to see the gap) and then without it, or move the read to every N steps. Warm-up steps run before the profiler; each step is labelled; the synchronize makes each host range cover the device work; worker_rank (a string) keeps the two hosts' file names apart in a shared directory. The run needs PyTorch 2.12 or newer and a TorchTPU version that has worker_rank. Open the directory with xprof --logdir=/tmp/profiler_output.
Problem 2. You meant to capture 5 steady-state steps after 2 warm-up steps, but the trace shows 7 steps, and the first three are each many times longer than the rest. The model is compiled with dynamic=None. Explain both observations and how you would capture again.
Answer
Seven steps means the two warm-up steps ran inside the profile block instead of before it. Three long steps means two warm-up steps were not enough anyway: under bounded dynamism the dynamic shapes guide's decode loop compiles on each of its first three steps (the static shape, then a bucket, then once more for the output layout), so the first step you meant to keep also compiled. Run at least as many warm-up steps as it takes for step time to settle (three or more here; check with an unprofiled run), outside the profile block, then capture the 5 steps. The trace should then show 5 steps of similar length whose median matches the wall clock.
Problem 3. In a trace of a training step on v6e, the XLA Ops row is busy for 62% of each step. Every idle stretch starts right after a host range named aten::item, and the next XLA op starts a few milliseconds after the idle stretch ends. The top op is a fusion that takes 30% of the step. What do you fix first, and what do you expect the next trace to show?
Answer
Fix the idle time first: 38% of the step is the TPU waiting, which is more than the top op's entire share. The aten::item before each gap is a .item() (or a Python if on a tensor) that makes the host wait for the TPU to drain, read one value, and only then dispatch the next work, during which the TPU idles; that is the host-sync pattern from chapter 4. Move the read out of the step (every N steps) or keep the decision on the device with torch.where. Expect the next trace to show the gaps gone or much shorter, the step time down by up to the idle share (about a third here), and the same top ops taking a larger share of a shorter step. Only then is ranking ops worth doing.
Problem 4. The top op in a v6e trace is a bf16 matmul of shape \([8192, 8192] \times [8192, 8192]\), measured at 1.40 ms. Another top op is a decode matmul of shape \([8, 8192] \times [8192, 8192]\), measured at 0.30 ms. Using chapter 2's v6e numbers (918 TFLOP/s bf16, 1,638 GB/s), classify each and say whether it runs near its bound.
Answer
First op: \(2 \cdot 8192^3 \approx 1.10 \times 10^{12}\) FLOPs, \(T_\text{math} \approx 1.10 \times 10^{12} / 918 \times 10^{12} \approx 1.20\) ms. Bytes: \(2 \cdot 3 \cdot 8192^2 \approx 403\) MB, \(T_\text{mem} \approx 0.25\) ms. Intensity about 2,731 FLOPs per byte, far above the 560 ridge: compute-bound, estimate 1.20 ms. Measured 1.40 ms is about 86% of the roofline: near its bound, so only fewer FLOPs would help much.
Second op: \(2 \cdot 8 \cdot 8192^2 \approx 1.07 \times 10^9\) FLOPs, \(T_\text{math} \approx 1.2\) µs. Bytes: \(2(8 \cdot 8192 + 8192^2 + 8 \cdot 8192) \approx 134.5\) MB, almost all of it the weight, \(T_\text{mem} \approx 82\) µs. Intensity about 8: memory-bound, estimate about 0.08 ms. Measured 0.30 ms is almost four times the estimate, so something the roofline does not model takes time. Click the op and look at what its fusion contains, its layout and padding, and whether a copy or a cast sits next to it, before concluding anything. Even at its bound, the fix would be fewer bytes (batching more tokens per weight read), not more FLOP/s.
Problem 5. After removing a host stall, the companion script's step time fell from 9.59 ms to 3.13 ms, but its top-ops list barely changed (aten::mm about 40% of busy time both times). A colleague concludes the profile was useless because "it pointed at the matmuls." Who is right, and what in the output proves it?
Answer
The profile was right; the colleague read the wrong part of it. The top-ops list ranks ops by busy time and is blind to idle time. The idle line said 67% of each step had no op running before the fix and 5% after, and the step time fell by about the idle time removed (from 9.59 to 3.13 ms, while busy time stayed around 3 ms). The unchanged op ranking is expected: the matmuls were never the bottleneck. This is why the workflow checks device idle before top ops, and why "the findings change after a fix" is about the specific finding (the idle share), not the whole report.
Problem 6. You profile a vLLM-TorchTPU server at TP=4 with the benchmark harness. The run finishes, the trace directory is empty, and in a second attempt XProf reports 8 TPU cores for your 4-chip slice. Diagnose both.
Answer
The empty directory means the server was configured (a profiler kind and a trace directory) but never armed: nothing called /start_profile. Through the harness, CAPTURE_PROFILE must resolve to 1 (it is inferred when EXTRA_SERVE_ARGS contains --profiler-config.torch_profiler_dir), so that vllm bench serve --profile calls the endpoints. The 8 cores mean a merged XPlane file sits inside plugins/profile/<timestamp>/ next to the per-rank files; XProf builds its host list from the file names there and counts every rank twice. Move the merged file up to the phase or run directory, or delete it; xprof --logdir reads the per-rank files as one session without merging.
Quick questions¶
- What do the host tracer and the device tracer each record, and which file does XProf read?
- What are the three
TpuProfilerConfigtracer levels and their defaults, and which one would you raise to see Python calls? - Why does the capture loop call
torch.accelerator.synchronize()beforeprof.step()? - Why should warm-up steps run outside the
profileblock, and what does a captured warm-up step look like in the trace? - In the Trace Viewer, which row do you trust for what ran on the TPU and for how long, and why?
- What does
S(1)mean in an HLO layout, and what doesT(8,128)tell you about padding? - Why does the reading workflow check device idle time before ranking the top ops?
- Given an op's shape and a measured time, how do you decide whether it runs near its bound?
- Name the signature in a trace of: a host sync, a recompile every step, a hidden layout copy, an unoverlapped collective.
- Why must speed be measured with the profiler off, and how large is the profiler's overhead according to the TorchTPU and vLLM guides?
Key takeaways¶
- TorchTPU profiles through standard
torch.profiler.profile: addProfilerActivity.TPUand passTpuProfilerConfig(the one publictorch.tpu.profilerAPI, experimental) asexperimental_config. The TPU trace is an.xplane.pbfile inrun_dir; open the directory withxprof --logdiror TensorBoard's Profile tab. It needs PyTorch 2.12 or newer andsetuptools<81for TensorBoard. - A trustworthy capture warms up outside the profiler, labels each step with
record_function, synchronizes beforeprof.step(), and captures a few steady-state steps. Check it before reading it: the files exist, the step count matches, and the median matches an unprofiled wall-clock run. - Read in a fixed order: step time, device idle, top ops, bound type. Idle time comes first because the op ranking cannot see it; the companion example's op list was the same before and after a 3.5x speedup.
- Trust the XLA Ops row for what ran on the TPU. Line its gaps up with the host rows to find the cause; click an op for its HLO name, shape, layout and source line.
- Compare each top op with its roofline estimate from chapter 2. Near the estimate, intensity says whether compute or memory bounds it; far above it, look for a copy, padding, a layout change or a collective wait.
- The common signatures map to Part I: gaps to host syncs and dispatch (chapter 4), uniformly slow steps to recompiles (chapter 7),
copyops to views and layouts (chapters 5 and 9), low MXU utilization to dimensions not aligned to 128. - Profiling costs about 5 to 10% per step (11% time to first token and 4% throughput in vLLM benchmarks): explain with traces, measure with the profiler off. For serving, pick the vLLM capture mode by question, and remember that a configured server records nothing until it is armed.
References¶
- Performance profiling with XProf: install,
TpuProfilerConfigoptions, the capture loop, XProf views, red flags, Ironwood counters, overhead; the current repository version addsworker_rank - TorchTPU API Reference:
torch.tpu.profiler.TpuProfilerConfig,TORCH_TPU_PROFILER_OUTPUT_DIR,TORCH_TPU_XPROF_SESSION_ID,TORCH_TRACE - TorchTPU repository:
TpuProfilerConfigand the publictorch.tpu.profilermodule in the source - How to Profile TPU Programs: the Trace Viewer, HLO names, layouts and tiling, predicted against measured op times
- vLLM-TorchTPU: Profiling: offline, server, phased and disaggregated capture, output layout, viewing, troubleshooting
- TorchTPU Performance: Execution Modes, XProf and Pallas Kernels:
TpuProfilerConfigfields,named_scope, v7x counters, a red-flag table - Sample code: TorchTPU execution modes, XProf and Pallas (sample_01)
- TorchTPU execution model: microbubbles and the enqueue cost
- Dynamic shapes: decode step times with
dynamic=Falseanddynamic=None - FLUX optimization: backward
copyops in XProf, the profiler off during timed steps - XProf kernel profiling
- XProf
- PyTorch profiler
- Companion code for this chapter

![Annotated schematic of XProf's Trace Viewer for two training steps. A Host CPU section has one row, Python thread, holding train_step#3, a darker load batch block, then train_step#4. A TPU:0 section has three rows: Steps, with blocks step 3 and step 4; XLA Modules, with one XLA module block per step; and XLA Ops, with each step made of fusion, fusion.12, copy (orange), fusion, all-reduce (purple) and a short fusion. Between the steps an orange hatched region spans the TPU rows. Numbered callouts: 1 a bracket over step 3, the step time; 2 the orange idle gap; 3 fusion.12 outlined in green, with a Selected op details panel reading fusion.12, bf16[8,1024,4096], duration 12.0 ms, source model.py:42; 4 the copy, a layout change you did not write; 5 the all-reduce, a collective to compare with the ICI roofline; 6 the host range from record_function. The axis notes W/S zoom, A/D pan.](../../../assets/ch10/trace-anatomy.png)

![An animation in ten frames on a schematic trace with a Host CPU section (Python thread) and a TPU:0 section (Steps, XLA Modules, XLA Ops), under a tracker of four stages: 1 Step time, 2 Device idle, 3 Top ops, 4 Bound type. Frame 1 rings three equal steps of the before profile: 3 asked for, 3 captured. Frame 2 shades in orange the end of every step where no XLA op runs, about a third of each step. Frame 3 rings a loss.item() block at the end of each host step and draws a line down to the start of each gap: the host waits for a value, then the TPU waits. Frame 4 shows the fix as a code diff: print(loss.item()) every 50 steps instead of every step, and step_fn = torch.compile(step, backend="tpu"). Frame 5 shows the after profile: the same 3 steps, each 40% shorter, no orange gaps, and a note that 5 steps fit where 3 did before. Frame 6 rings fusion.7 in each step and shows a share-of-step bar list: fusion.7 56%, fusion.3 22%, copy 11%, fusion.9 11%. Frame 7 opens a details panel: fusion.7, dot + gelu, bf16[1024,4096], model.py:31. Frame 8 computes the bound type: fusion.7 is [1024x1024] @ [1024x4096] in bf16, intensity 455 FLOPs per byte, marked on a scale between the v7x ridge at 313 and the v6e ridge at 560: memory-bound on v6e, compute-bound on v7x. Frame 9 compares the roofline estimate with the measured time: near the estimate needs a different algorithm or fewer bytes; far above it points to padding, a copy, a bad layout or a kernel. Frame 10 lists the four stages with what each checks.](../../../assets/ch10/reading-trace.gif)