Dynamic shapes and recompilation¶
Prerequisites: Memory model, storage and views, Numerical precision and the MXU
A decode loop that takes 40 ms per token when the arithmetic should take well under one is rarely slow because of the arithmetic. It is slow because it compiles a new XLA program for every token. XLA plans a TPU program around fixed tensor sizes, and torch.compile on TorchTPU specializes each graph to the exact sizes it saw, so any dimension that changes between calls (a KV cache that grows, a prompt length, a batch size) turns into a fresh compilation unless you arrange otherwise. This chapter explains why shapes matter so much to the compiler, then gives you the three ways out: TorchTPU's bounded dynamism, which compiles a range of sizes at once; a static KV cache, which stops the shape from changing at all; and padding to buckets, which turns an unbounded set of sizes into a small fixed one. It ends with the measurements that prove a loop has stopped recompiling: a compile count that stays flat after warm-up and a per-step latency that drops to its steady value and stays there.
What this chapter covers¶
- Why a change in any tensor dimension triggers a new compilation under
torch.compileon TorchTPU, in terms of XLA's static shapes and Dynamo's guards. - What
dynamic=False,dynamic=None,dynamic=Trueandtorch._dynamo.mark_dynamicdo on TorchTPU, and how bounded dynamism compiles one executable per bucket and pads at run time. - Reading a per-step latency trace of a decode loop and attributing each slow step to a compile.
- A static KV cache, and padding to buckets with
bucket_for, to keep a decode or serving loop at a fixed number of compiled shapes. - The padding waste of a bucket set for a length distribution, and the trade between fewer compiles and less padding.
- Per-step timing, a counting backend,
torch._dynamocounters,TORCH_LOGS="recompiles"andfail_on_recompileas evidence that a loop no longer recompiles after warm-up.
Why a new shape means a new program¶
The TorchTPU dynamic shapes documentation gives the reason in one sentence: XLA "is traditionally designed around statically known tensor shapes", so that HBM buffers can be laid out ahead of time, operator pipelines can be fused, and matrix multiplications can be tiled for the MXUs. Each of those decisions uses the sizes. The buffer plan assigns every intermediate an offset and a length in HBM. The tiling of a matmul fixes loop bounds over (8, 128) tiles (chapter 5). The fusion decisions depend on how big each intermediate is. A program compiled for a sequence length of 16 has 16 baked into all of them, and it cannot run a sequence of 17.
Two mechanisms turn that compiler fact into recompiles you can observe.
The compilation cache keys on dimensions. Chapter 3 described TorchTPU's cache key: a shapeless key for the graph's structure, a dimensions key for its sizes, and a compile options key. A new size is a new dimensions key, so even in eager mode a new shape is a cache miss and a compile.
Dynamo guards on sizes. Under torch.compile, TorchDynamo records guards when it captures a graph (chapter 4): conditions under which the graph stays valid. With dynamic=False, those guards include the exact size of every input dimension. On the next call, a different size fails the guard, Dynamo traces again, and the whole lowering pipeline runs again: FX graph, StableHLO, XLA compile.
The documentation's motivating case is autoregressive decoding with a KV cache that grows by torch.cat:
- Prefill: the prompt has shape
[B, S]and produces a KV cache of shape[B, H_kv, S, D]. - Decode step 1: the new token has shape
[B, 1]; concatenating it gives a cache of[B, H_kv, S + 1, D]. - Decode step \(t\): the cache length is \(S + t\).
Every step has a new length, so every step fails the guard. The documentation measures it with a minimal loop: a bf16 cache of shape [1, 8, 16, 128] on a TPU, one position appended per step along dimension 2.
def decode_step(kv_cache: torch.Tensor, new_token: torch.Tensor) -> torch.Tensor:
return torch.cat([kv_cache, new_token], dim=2)
step_static = torch.compile(decode_step, backend="tpu", dynamic=False)
With dynamic=False, all ten steps take between 37.75 and 49.54 ms. The concatenation itself moves tens of kilobytes; the documentation's own comparison below shows the same step running at about 0.4 ms once it is not being compiled. Nearly all of the 38 ms is compile.
The orange line never leaves the compiler. The green line pays three compiles and then runs the same executable for every later step; the gap between the two lines from step 4 on is the cost of a compile per token. The x-axis shows the decode step, with the sequence length after that step in brackets (the step that appends the token that makes the cache 17 long is step 1). Numbers from the TorchTPU dynamic shapes documentation. The table in Reading the warm-up says what compiles at steps 1 to 3.
The rest of the chapter is about making the green line, or something better, happen in your code.
The dynamic argument on TorchTPU¶
torch.compile has a dynamic argument with three values. TorchTPU gives each a specific meaning, and it changes the default.
| Setting | What Dynamo does | On TorchTPU |
|---|---|---|
dynamic=False |
Specializes every dimension to the size it saw; a new size fails the guard and recompiles | The default when you do not pass dynamic and the backend is TorchTPU's. One executable per exact shape |
dynamic=None |
Compiles static first; when a dimension changes, marks it dynamic (a SymInt) and recompiles once for a range. This is PyTorch's automatic dynamic shapes |
Opt in to bounded dynamism: the dynamic dimension gets an upper bound and buckets, below |
dynamic=True |
Treats every size as dynamic from the first compile | Not supported: raises NotImplementedError asking you to use dynamic=None |
torch._dynamo.mark_dynamic(t, dim, min=..., max=...) |
Marks one dimension of one input dynamic before the first call, with explicit bounds | Bounded dynamism from the first call, with [min, max] as the range |
The default is dynamic=False, even though PyTorch's is None
The dynamic shapes page describes torch.compile(model, dynamic=None) as "default dynamism", which is PyTorch's default. TorchTPU changes it: when the backend is TorchTPU's and dynamic is not passed, _loader.py sets dynamic=False, and the Muse Glimmer 30B inference case study says the same in prose ("TorchTPU changes the torch.compile default from dynamic=None to dynamic=False ... unless you opt in"). Both the page's own examples and the case study pass dynamic=None explicitly. Do the same: torch.compile(model) alone gives you one compile per shape.
The case study states the policy behind this: dynamic shape support on TorchTPU is "currently experimental, so it's opt-in", and TorchTPU focuses on automatic dynamic shapes because PyTorch recommends against dynamic=True. Keeping dynamism limited to the dimensions that actually change, such as a KV cache length, lets XLA optimize everything else as static.
Bounded dynamism: compiling a range¶
XLA needs a fixed buffer size. Bounded dynamism gives it one, the upper bound of the range, and passes the real size as a runtime value.
With S = 300, up to eight buckets and upper_bound = 700, the buckets end at 384, 512, 640 and 768: the cap at 700 is rounded up to the 128 grid, Dynamo guards the whole span once, and XLA compiles one executable per U. Every call then pays for U, not for S. The bucket bounds come from the companion code's model of the documentation's rules; the first bucket starts at lower_bound and is not drawn to scale.
Compile time. When Dynamo hands TorchTPU an FX graph in which a dimension is a SymInt, TorchTPU:
- determines a range
[lower_bound, upper_bound]for that dimension, frommark_dynamic(..., min=..., max=...)or inferred by Dynamo from the initial runtime size \(S\); - splits the range into contiguous buckets aligned to multiples of
bucket_size(default 128, the TPU's 128-lane tile dimension), up tonum_dynamic_buckets(default 1, maximum 8). The first bucket runs fromlower_boundto \(U_1\), the next multiple of 128 at or after \(S\); the second runs from \(U_1 + 1\) to the next multiple, and so on:[lower_bound, 128],[129, 256], ...; - caps the buckets at a finite
upper_bound: if the first bucket already reaches it, or there is only one bucket, that bucket is capped atupper_bound; if a later bucket reaches it, the cap is rounded up to the bucket grid (the documentation's "128k - c" grid, where \(c\) is the constant offset of output shapes such as \(S + 1\)) so output layouts stay consistent when execution moves between buckets; - registers one range guard across all buckets with Dynamo, so Dynamo recompiles only when the size leaves the overall range;
- for each bucket, replaces the symbolic dimension with the bucket's static upper bound \(U\), passes the real size as an input, lowers to StableHLO with bounded tensor types, and has XLA compile one executable per \(U\).
Step 3 is described in the current documentation; the 0.2.0 page does not have it.
Every call. TorchTPU picks the executable whose bucket contains the actual size. XLA pads the dynamic input up to \(U\) and resets the padded region to algebraic identity values, so the padding cannot change the result (a zero adds nothing to a sum, for example). Dynamic outputs keep their padding at the end of the buffer, which lets TorchTPU hand the buffer back to PyTorch with a shape metadata update instead of slicing it.
The companion code models the bucket rules (with \(c = 0\), and without the fallback described under the limitations below):
from bucketing import bounded_dynamism_buckets
bounded_dynamism_buckets(17) # [128]: the docs' [17, 128] bucket
bounded_dynamism_buckets(17, num_buckets=4) # [128, 256, 384, 512]
bounded_dynamism_buckets(16, upper_bound=128) # [128]: mark_dynamic(min=16, max=128)
bounded_dynamism_buckets(300, num_buckets=8, upper_bound=700) # [384, 512, 640, 768]
Configuring the buckets. The documentation names bucket_size and num_dynamic_buckets and their defaults, but shows no call that sets them. The backend's docstring (_backend.py) lists both as keys of the options dictionary, and validates them: num_dynamic_buckets must be an integer from 1 to 8 and bucket_size a positive integer, or the backend raises ValueError.
step = torch.compile(decode_step, backend="tpu", dynamic=None,
options={"num_dynamic_buckets": 4, "bucket_size": 128})
Treat that spelling as specific to TorchTPU 0.2.0, since it comes from the source rather than the user guide.
Reading the warm-up: three compiles, then none¶
The green line in the chart above is worth reading step by step, because the same pattern appears in every real model that uses dynamic=None.
| Step | seq_len | Time | What the documentation says happens |
|---|---|---|---|
| 1 | 16 → 17 | 49.59 ms | Dynamo sees the inputs for the first time and compiles a static executable for 16 |
| 2 | 17 → 18 | 206.68 ms | Dimension 2 changed, so Dynamo marks it dynamic and TorchTPU compiles a bounded executable for the bucket [17, 128], for the standard input layout |
| 3 | 18 → 19 | 64.29 ms | Step 2's output buffer has XLA's padded layout, so TorchTPU compiles the [17, 128] bucket once more for that layout |
| 4 to 10 | 19 → 26 | 0.37 to 0.51 ms | Size inside the bucket and layout matched: the cached executable runs with no compile |
The documentation puts the steady state at about 100 times faster than the dynamic=False steps. If you know in advance which dimension will vary, mark it before the first call:
torch._dynamo.mark_dynamic(kv_cache, 2, min=16, max=128)
Dynamo then traces dimension 2 as dynamic on step 1, which skips the static compile of step 1 and sets explicit bounds. The documentation does not say whether the layout compile still follows on the next step, so measure it (worked problem 2).
On the CPU, where there is no TorchTPU bucketing, the same loop compiles twice under dynamic=None (static, then dynamic) and once with mark_dynamic, which is what the companion code reports. The third compile is TPU-specific.
What bounded dynamism costs, and what it does not cover¶
The documentation describes bounded dynamism as "actively evolving" and tuned for the autoregressive KV cache. Its limitations decide when you should reach for a static cache or bucketing instead.
- You pay for \(U\), not for \(S\). Execution runs on buffers padded to the bucket's upper bound, so HBM footprint and FLOPs scale with \(U\). A
maxof 4096 for sequences that are usually 200 long costs the compute and memory of 4096. - At most 8 buckets, and no unbounded dynamism. Growing past the highest compiled bucket's upper bound triggers a recompile.
- Shape constraints can collapse the buckets. Bucket upper bounds must satisfy Dynamo's shape constraints, such as divisibility from a
reshapeorview. Otherwise TorchTPU falls back to a single bucket with upper bound \(2S\). - Layout changes recompile. A change in the XLA physical layout of an input recompiles the bucket even if the size fits, which is the step 3 compile above.
- No persistent cache for bounded executables. They are not serialized to
AOTAutogradCache, so every new process compiles them again. Static executables are cached; the backend source marks a graph with dynamicSymInts as not serializable. - Not everything is supported: some operators, tensor views passed directly as inputs, data-dependent output shapes such as
torch.nonzero, and custom kernels such as Pallas kernels registered withtorch.tpu.pallas.jax_op.
Static KV cache: never change the shape¶
Bounded dynamism makes a changing shape cheap. A static cache removes the change. The documentation's Muse Glimmer 30B inference case study gives the rules for a StaticCache that compiles under dynamic=False with no decode recompiles:
- Fixed-size buffers. Keys and values are preallocated as
[B, H_kv, max_cache_len, D]. - On-device length. The fill level is a 0-D tensor on the TPU, updated in place, not a Python
intthat Dynamo would guard on. - In-place writes, fixed-shape masks. New entries are written with
index_copy_; positions not yet written are masked out of attention. - Two compilations: one for prefill and one for decode, reused by every later step.
The companion code's StaticKVCache is the smallest version of those rules, for one attention layer:
class StaticKVCache(torch.nn.Module):
def __init__(self, batch, heads, max_len, head_dim, dtype=torch.float32):
super().__init__()
shape = (batch, heads, max_len, head_dim)
self.register_buffer("k", torch.zeros(shape, dtype=dtype), persistent=False)
self.register_buffer("v", torch.zeros(shape, dtype=dtype), persistent=False)
self.register_buffer("length", torch.zeros((), dtype=torch.long), persistent=False) # 0-D
self.register_buffer("slots", torch.arange(max_len), persistent=False)
def forward(self, q, k, v): # [B, H, T, D], T = prompt length or 1
t = k.shape[2]
positions = self.length + torch.arange(t, device=k.device)
self.k.index_copy_(2, positions, k) # in-place partial write
self.v.index_copy_(2, positions, v)
self.length.add_(t) # stays on the device
mask = self.slots[None, :] <= positions[:, None] # causal, hides unfilled slots
return F.scaled_dot_product_attention(q, self.k, self.v, attn_mask=mask)
Each line serves one of the rules. The 0-D length is the subtle one. A Python integer that changes every step would be a constant in the traced graph and a guard on every call, so it would recompile exactly like the growing cache. A tensor's value is not guarded, and reading it never leaves the device, so no host sync happens either (chapter 4). The mask compares positions instead of slicing the cache to its live length, because a slice would change the shape. And the index_copy_ write is the partial write from chapter 5: a dynamic_update_slice into a contiguous buffer, where donation can avoid copying the cache. The StaticCacheAutoregressiveDecoder in the TorchTPU performance sample code applies the same rules to a whole decoder, and Hugging Face's StaticCache follows the same pattern.
Watch the two counters: the green one stops at 2 after the first decode step, the orange one never stops. Counts are Dynamo compilations measured by the companion code on the CPU; Dynamo's guards behave the same on a TPU.
The companion code checks both properties that matter: the static cache compiles twice however many steps you run, and it returns the same attention output as a growing torch.cat cache (largest difference about \(2 \times 10^{-7}\) in float32).
Static cache or bounded dynamism: the measured comparison¶
The case study runs both caches on the full 52-layer Muse Glimmer 30B model on one TPU v7x chip, 20 decode steps, with an empty compilation cache: StaticCache under dynamic=False and the growing DynamicCache under dynamic=None.
Both lines end at the same height. The difference is the purple band: two extra compiles of about 22 s and 5 s, which bounded executables repeat in every new process because they are not persistently cached. Numbers from the case study's benchmark table.
StaticCache, dynamic=False |
DynamicCache, dynamic=None |
|
|---|---|---|
| Model changes | Preallocated buffers, 0-D length, index_copy_, masks |
None: the default Hugging Face-style cache |
| Compiles | Prefill and decode step 1, then none | Prefill, steps 1, 2 and 3, then none |
| Steady decode | 23.58 ms per token (steps 2 to 20) | 24.17 ms per token (steps 4 to 20), about 2.5% slower |
| Memory | max_cache_len slots from the start |
Grows with the sequence, padded to the bucket bound \(U\) |
| Next process | Static executables can come from AOTAutogradCache |
Bounded executables compile again |
| Custom kernels | Work: shapes are static | Not supported with bounded dynamic shapes |
For a model you control, the static cache is the stronger choice: fewer compiles, cacheable executables, and compatible with Pallas kernels. Bounded dynamism earns its place when you cannot change the model, or for dimensions other than a cache length. Chapter 22 works through this case study in full.
Padding to buckets: serving and variable-length training¶
The decode cache grows in a predictable way. Request lengths do not: a server sees prompts of every length, and a training set has sequences of every length. Compiling each length separately is the compile storm again, spread over requests instead of over tokens. The standard answer is bucketing: choose a small set of sizes in advance, pad each input up to the smallest one that fits, and compile once per bucket with dynamic=False.
from bucketing import bucket_for, pad_to_bucket, padding_waste
buckets = [128, 256, 512, 1024]
bucket_for(17, buckets) # 128
bucket_for(129, buckets) # 256
bucket_for(1025, buckets) # ValueError: exceeds the largest bucket
x, real_len = pad_to_bucket(tokens, dim=1, buckets=buckets) # pad, keep the real length
bucket_for raises rather than rounding down or growing the set when a request does not fit: a length past the largest bucket is a decision for the caller (reject it, split it, or add a bucket and accept one more compile), not something to hide. It also rejects an empty or unsorted bucket list. Whatever pads the input must also keep the real length, because padded positions must not reach the result: mask them out of attention, and give padded labels the loss's ignore index in training.
Four compiles instead of ten. The price is the light orange area: a quarter of the padded slots hold no data, and the TPU computes over them anyway. Computed by the companion code, which also runs the requests through a compiled layer to confirm the compile counts.
Padding waste is the share of padded slots that hold padding:
Because compute and HBM scale with the padded size, it is also the share of that work spent on nothing. padding_waste(lengths, buckets) computes it. More buckets mean less padding and more compiles, and the shape of that trade-off depends on your length histogram:
For lengths spread over orders of magnitude, powers of two waste less per compiled shape at first, because short requests get small buckets; evenly spaced buckets win only when you can afford many of them. The lengths are synthetic; run padding_waste on your own histogram.
Choosing buckets follows a short procedure:
- Collect the length histogram of real traffic or of the training set. The trade-off curve depends on it entirely.
- Set the largest bucket at the longest length you will serve or train on. Anything above it needs an explicit policy.
- Keep buckets on the 128 grid where the padded dimension is a matmul or lane dimension, for the tile reasons in chapter 5. The documentation's default
bucket_sizeof 128 encodes the same rule. - Add buckets where the histogram is dense until the next bucket saves less padding than its compile is worth. A compile costs once per process (or once per fleet with the Tier-3 cache, chapter 3); padding costs on every step.
- Compile every bucket at startup, before you take traffic or start timing, so no request pays a compile.
A fixed shape is a bucket of one. The Hugging Face Diffusers integration compiles the transformer with dynamic=False; the first call compiles, and every later call with the same image size reuses the graph. A second image size is a second compile, so a service that offers three sizes has three buckets whether it plans them or not.
Serving engines do this for you. vLLM-TorchTPU and SGLang-TorchTPU pad token counts and batch sizes to precompiled buckets and warm them up at startup; chapter 18 and chapter 19 configure them. The point to carry there is the trade-off above: a bucket grid is a choice between compile count and padding waste, and the engine's defaults assume a histogram that may not be yours.
Variable-length training uses the same tool on the host: pad each batch in the DataLoader's collate function to a bucket, so the step sees a handful of shapes, and mask padded positions out of the loss. Sorting or grouping examples by length before batching reduces the waste further, because each batch's members then share a bucket. For jagged NestedTensor inputs, TorchTPU provides torch.tpu.ops.align_jagged_to_multiple(nt, ...), which pads a torch.jagged buffer to a multiple for TPU alignment, and torch.tpu.ops.strip_jagged_padding(nt, ...), which removes that padding.
Detecting recompiles¶
A recompile is invisible in the output of a model and very visible in its timing. Use several signals, because they see different layers.
Per-step latency is the ground truth on a TPU. Synchronize and time each step, as the documentation's loop does:
for step in range(num_steps):
start = time.perf_counter()
kv_cache = compiled_step(kv_cache, new_token)
torch.accelerator.synchronize()
print(f"step {step + 1}: {(time.perf_counter() - start) * 1000:.2f} ms")
A compile shows up as a step tens to thousands of times slower than its neighbours. After warm-up, the per-step times must be flat. A periodic spike means a shape that keeps changing; a slow drift upward is something else (a growing buffer, for example), and a steady value that is too high is a roofline question (chapter 2), not a compile.
Count Dynamo's compiles. A counting backend increments a counter for each graph Dynamo hands it, then delegates to the real backend. The companion code's CompileCounter wraps "eager" on the CPU and "tpu" on a TPU, and PyTorch keeps its own tally in torch._dynamo.utils.counters["stats"]["unique_graphs"]; the code reads it when the build has it and checks that the two agree.
Ask Dynamo why. TORCH_LOGS="recompiles" prints every recompile with the guard that failed. On the companion loop with PyTorch 2.15 (log prefixes and paths trimmed):
$ TORCH_LOGS="recompiles" python decode.py
[__recompiles] Recompiling function decode_step in decode.py:2
[__recompiles] triggered by the following guard failure(s):
[__recompiles] - 0/0: tensor 'kv' size mismatch at index 2. expected 16, actual 17
[__recompiles] Recompiling function decode_step in decode.py:2
[__recompiles] triggered by the following guard failure(s):
[__recompiles] - 0/1: tensor 'kv' size mismatch at index 2. expected 17, actual 18
[__recompiles] - 0/0: tensor 'kv' size mismatch at index 2. expected 16, actual 18
The tensor name and the index tell you which dimension to fix. Under dynamic=None the same loop prints one recompile and then nothing, because the dimension became dynamic. For a full record of a run, the TorchTPU API reference lists TORCH_TRACE, an output directory for structured compiler and dispatcher trace logs that tlparse reads.
Know the recompile limit. Dynamo stops compiling a function after torch._dynamo.config.recompile_limit entries. On PyTorch 2.15 the default is 8: the ninth new shape prints a warning (torch._dynamo hit config.recompile_limit (8)) and the function runs uncompiled from then on, which on TorchTPU means the current eager mode. That is why the documentation raises the limit to 64 before its dynamic=False demonstration. In your own code, treat hitting the limit as a bug report, not a setting to raise.
Make recompiles fail. After warm-up, torch.compiler.set_stance("fail_on_recompile") turns any further recompile into a RuntimeError ("Detected recompile when torch.compile stance is 'fail_on_recompile'"). It is the right guard for a test or a serving process that should never compile after startup.
Dynamo's count is not the whole count on a TPU
Dynamo counters and logs see graph captures. TorchTPU also compiles inside a captured graph: one executable per bucket, and again when an input arrives with a new on-device layout. The backend logs the second case with the warning Compiling <name> again for new on-device layouts of its inputs. The documentation's step 3 is such a layout compile. On a TPU, compare the Dynamo count with the number of slow steps; if they differ, the extra compiles are inside the backend, and per-step latency is the number to trust.
Choosing a strategy¶
If the dimension never changes, keep dynamic=False; if it depends on tensor values, keep a fixed shape and a mask (chapter 4). Otherwise:
For a dimension that varies per request, Pallas kernels, a new process per job, and no known maximum or a range too wide to pay for each rule out bounded dynamism, and each of those routes ends in padding on the host to buckets that you warm at startup. For a cache that grows step by step, changing the model to a static cache is the stronger choice; without that change, bounded dynamism is the only route.
The rules behind the branches: data-dependent shapes are out of scope for bounded dynamism and need a fixed shape with a mask; custom kernels do not support bounded dynamic shapes; bounded executables are not persistently cached, so short-lived processes pay their compiles every time; and bounded dynamism computes over the full bucket, so a range much wider than the typical size wastes compute just as a coarse bucket does. A cache that grows inside the model and cannot be changed has one route, bounded dynamism; with Pallas kernels in the graph or no known maximum, the model code has to change, since padding on the host cannot reach a buffer the model grows itself.
Failure modes¶
| Symptom | Likely cause | What to do |
|---|---|---|
| Every step costs tens of milliseconds or more, about the same each time | Compile storm: a dimension changes every step under dynamic=False (often a cache grown by torch.cat) |
Find it with TORCH_LOGS="recompiles"; use a static cache or dynamic=None |
Fast for 8 steps, then slower for good, with a recompile_limit warning |
Dynamo gave up compiling and runs the function eagerly | Fix the shape; do not just raise the limit |
torch.compile(model) recompiles even though you expected bounded dynamism |
dynamic not passed, so TorchTPU used dynamic=False |
Pass dynamic=None explicitly, or mark_dynamic |
NotImplementedError from torch.compile |
dynamic=True |
Use dynamic=None |
| Three slow decode steps after prefill, then fast | Normal dynamic=None warm-up: static, bucket, padded layout |
Expected. mark_dynamic before step 1 removes the static compile |
| A recompile when a sequence crosses a bucket bound, or when a long prompt arrives | The size crossed the highest compiled bucket bound | Set max (or the bucket set) at the real maximum; consider more buckets |
| Slow steps at every process start, even with a persistent cache | Bounded executables are not serialized to AOTAutogradCache |
Accept it, warm up before timing, or use a static cache |
| Many buckets compiled at startup, minutes of warm-up | Bucket explosion: too many buckets, or buckets on several dimensions multiplying (batch × length) | Measure the histogram; drop buckets with little traffic; bucket one dimension at a time |
| High HBM use and compute for short inputs | Padding waste: buckets, max or bucket_size far above typical sizes |
Compute padding_waste for the real histogram; add smaller buckets |
| Wrong outputs after padding | Padded positions reached the result (attention, loss, a reduction) | Carry the real length or a mask; use the loss's ignore index |
ValueError from the backend when compiling |
num_dynamic_buckets outside 1 to 8, or a non-positive bucket_size |
Use values in range |
| Recompile although size and dtype match | A new on-device layout for an input; the backend logs it | Keep inputs contiguous and produced the same way every step |
Verifying the result¶
A loop has stopped recompiling when two measurements agree: the compile count stops growing after warm-up, and the per-step latency drops to a steady value and stays flat. The companion script checks both:
python code/ch07_dynamic_shapes/bucketing.py --cpu-smoke # laptop: Dynamo counts, buckets, static cache
python code/ch07_dynamic_shapes/bucketing.py # TPU VM: the docs' decode loop, timed
- On the CPU, the compile counts match the predictions. The smoke run reports 10 compiles for ten
dynamic=Falsesteps of the growing cache, 2 fordynamic=None, 1 withmark_dynamic(min=16, max=128), 2 for the static cache over a prefill and 20 decode steps, and one compile per distinct bucket for padded requests. It confirms that the static cache's attention output matches the growing cache and thatfail_on_recompileraises on a new shape. If any count differs, your PyTorch version guards differently; find out why before relying on it. - On the TPU, steps 4 onward are flat. Without
--cpu-smokethe script runs the documentation's loop underdynamic=False,dynamic=Noneandmark_dynamic, prints every step's time and Dynamo's count, and checks that thedynamic=Nonesteps from 4 on are all far below step 1. Compare the shape of your output with the chart at the top of this chapter: underdynamic=Falseevery step should be slow; underdynamic=Nonethree steps should be slow and the rest fast. Keep your output as the record for your TorchTPU version and TPU generation. - In your own loop, plot per-step latency. Time 50 or more steps with
torch.accelerator.synchronize()around each. After the warm-up steps the line must be flat, like the right-hand side of the Muse Glimmer chart. Count the slow steps and compare them with your prediction from this chapter (2 for a static cache, 4 for a cache grown underdynamic=Nonewith a separate prefill, one per bucket for bucketing). - Prove it stays that way. Run warm-up, then wrap the steady loop in
torch.compiler.set_stance("fail_on_recompile")in a test, or count with a backend that wraps"tpu"and assert the count does not change across another 100 steps. Run withTORCH_LOGS="recompiles"once and confirm there are no lines after warm-up. - Check the cost you accepted. For bucketing, compute
padding_wasteon the real length histogram and confirm the number of compiled buckets. For bounded dynamism, check thatmaxor the bucket bound is close to the sizes you actually run, since you pay for \(U\).
Worked problems¶
Problem 1. A team compiles a decoder step with torch.compile(step, backend="tpu") and passes a KV cache that grows with torch.cat. Generation is about 40 ms per token on a model whose arithmetic should take under 1 ms. Explain the cause, and give two fixes with the compile count each produces for a prefill plus 100 decode steps.
Answer
No dynamic argument was passed, so TorchTPU set dynamic=False. Dynamo guards on the exact cache length, and the length grows by one every step, so every step fails the guard and pays a full XLA compile; the documentation's loop shows exactly this at 38 to 50 ms per step. (After 8 entries, PyTorch's default recompile_limit, Dynamo would also stop compiling the function and run it eagerly.) Fix 1: a static cache with a 0-D length, index_copy_ writes and a mask, compiled with dynamic=False: 2 compiles (prefill and decode) for any number of steps. Fix 2: keep the growing cache and pass dynamic=None: by the case study's pattern, prefill and decode step 1 compile static, step 2 compiles the bounded bucket and step 3 compiles again for the padded layout, so 4 compiles, provided 100 decode steps stay inside the bucket (for a prompt of \(S\) tokens the first bucket ends at the next multiple of 128 at or after \(S + 1\), so a long generation may cross into a new bucket or past the range and compile again).
Problem 2. In the documentation's loop under dynamic=None, steps 1, 2 and 3 compile. You add torch._dynamo.mark_dynamic(kv_cache, 2, min=16, max=128) before step 1. Which compile disappears, which may remain, and how do you find out?
Answer
The static compile of step 1 disappears: Dynamo traces dimension 2 as dynamic from the first call, so step 1 compiles the bounded executable for the range [16, 128] directly. The documentation does not say what happens to the layout compile. Step 1's input is a freshly created tensor in the standard layout, and its output has XLA's padded layout, which is the situation that caused step 3's compile before; so expect a second compile on step 2 unless something else changes. Find out by timing each step with torch.accelerator.synchronize() (the TPU path of the companion script does this) and by checking the backend's log for "Compiling ... again for new on-device layouts". The Dynamo count alone may say 1 either way, since the layout compile happens inside the backend.
Problem 3. A server pads prompts to the buckets [128, 256, 512, 1024]. Four requests arrive with lengths 90, 130, 17 and 600. Compute the padding waste, the number of compiled shapes, and the number of compiles without bucketing.
Answer
bucket_for maps them to 128, 256, 128 and 1024. Padded slots: \(128 + 256 + 128 + 1024 = 1536\). Real tokens: \(90 + 130 + 17 + 600 = 837\). Waste: \((1536 - 837)/1536 = 699/1536 \approx 45.5\%\), which padding_waste([90, 130, 17, 600], [128, 256, 512, 1024]) returns. Three buckets are used, so three compiles; without bucketing, four distinct lengths compile four times. Nearly all of the waste comes from the 600-token request padded to 1024: adding a 768 bucket would cut its padding from 424 slots to 168, for one more compile.
Problem 4. A model sees a dynamic sequence dimension with an initial runtime size of 300 and is compiled with dynamic=None and options={"num_dynamic_buckets": 3}, with the default bucket_size. List the bucket ranges, and say what happens when the sequence reaches 700. Then say what changes with mark_dynamic(x, 1, min=300, max=400) and one bucket.
Answer
The first bucket ends at the next multiple of 128 at or after 300, which is 384; the next two end 128 apart: [lower_bound, 384], [385, 512], [513, 640] (the companion model returns [384, 512, 640] for bounded_dynamism_buckets(300, num_buckets=3)). Sizes up to 640 select one of three executables with no Dynamo recompile, because one range guard covers all three. At 700 the size is past the highest bucket's bound, so Dynamo's range guard fails and the function recompiles. With mark_dynamic(x, 1, min=300, max=400) and one bucket, the first bucket is capped at upper_bound: one executable for [300, 400], padded to 400 on every call. That is cheaper per step than padding to 384 or 640 only if your sizes really stay below 400, and anything above 400 recompiles.
Problem 5. You fine-tune on documents whose lengths range from 40 to 2,000 tokens, with batch size 8, under torch.compile(train_step, backend="tpu"). Design the input pipeline so the step compiles a fixed, small number of times, and state how you verify it.
Answer
Bucket on the host. Measure the length histogram; choose buckets on the 128 grid ending at 2048, denser where the histogram is dense (powers of two [128, 256, 512, 1024, 2048] are a reasonable start; use padding_waste to compare alternatives). Group examples of similar length into the same batch, then pad each batch in the collate function to bucket_for(max_len_in_batch, buckets) and set padded labels to the loss's ignore index so they contribute nothing; pass an attention mask so real tokens do not attend to padding. Keep the batch size fixed (drop or pad the last partial batch), or it becomes a second dynamic dimension and the shapes multiply. Compile with dynamic=False (the default). Verify: a counting backend wrapping "tpu" reports one compile per bucket and no more after every bucket has been seen once; TORCH_LOGS="recompiles" is silent after that; per-step time is flat within each bucket; and padding_waste on the real lengths is at the level you chose.
Problem 6. A serving test must fail if any request causes a compile after startup. Write the structure of the test with the tools from this chapter.
Answer
Start the model, compile it, and run one warm-up request per bucket (and per batch-size bucket if the batch varies), so every shape the server will use has been compiled. Then enter torch.compiler.set_stance("fail_on_recompile") and replay a representative mix of requests, including the shortest and longest allowed lengths and one just above each bucket boundary. Any shape that was not warmed raises RuntimeError and fails the test. Add a second assertion that does not depend on Dynamo: time each request with torch.accelerator.synchronize() and check that none is more than a small factor above the median for its bucket, which also catches compiles inside the backend, such as layout compiles, that Dynamo's stance does not see.
Quick questions¶
- Name three things XLA decides at compile time that depend on tensor sizes.
- Which two mechanisms make a new shape trigger a compile under
torch.compileon TorchTPU? - What value of
dynamicdoes TorchTPU use when you do not pass one, and what doesdynamic=Truedo? - In bounded dynamism, what determines the bucket bounds, what are the defaults for
bucket_sizeandnum_dynamic_buckets, and when does Dynamo recompile? - What happens to the padded region of an input at run time, and why does it not change the result?
- Why does the documentation's
dynamic=Noneloop compile three times, and what doesmark_dynamicbefore step 1 change? - Why must a static cache's fill level be a 0-D tensor rather than a Python integer?
- Define padding waste, and explain why more buckets reduce it.
- Which signals detect a recompile, and which of them can miss a compile that happens inside the TorchTPU backend?
Key takeaways¶
- XLA plans memory, tiling and fusion around fixed sizes, and Dynamo guards on exact sizes under
dynamic=False, so on TorchTPU a new shape is a new compile. The documentation's growing-cache loop pays 38 to 50 ms per step for it. - TorchTPU defaults
torch.compiletodynamic=Falsewhen you do not passdynamic. Passdynamic=Noneto opt in to bounded dynamism, ormark_dynamic(t, dim, min=..., max=...)to start with explicit bounds;dynamic=TrueraisesNotImplementedError. - Bounded dynamism compiles one executable per bucket on a 128 grid (default 1 bucket, at most 8), pads to the bucket bound \(U\) with identity values, and recompiles only outside the overall range. You pay compute and HBM for \(U\), executables are not persistently cached, and custom kernels and data-dependent shapes are not supported.
- A static KV cache (preallocated buffers, 0-D length,
index_copy_, a mask) compiles twice for any number of steps and keeps shapes static for Pallas and for the persistent cache. On Muse Glimmer 30B it reached 23.58 ms per token after two compiles, against 24.17 ms after four for the growing cache. - Bucketing turns arbitrary lengths into a few compiled shapes at the price of padding.
bucket_forpicks the bucket andpadding_wastemeasures the price; choose buckets from your own length histogram and warm all of them before timing or serving. - Trust per-step latency first, then a counting backend or
torch._dynamocounters,TORCH_LOGS="recompiles"for the reason, andfail_on_recompileto keep it fixed. Dynamo-level signals can miss compiles inside the backend. - Part I is complete: you now have the model of the chip and the stack, and how execution modes, memory, precision and shapes behave on it. Part II applies this to getting TPU capacity, installing TorchTPU and porting a real model.
References¶
- Dynamic shapes: XLA's static-shape design, bounded dynamism, the bucket rules, identity-value padding, the growing-cache example and its timings, current limitations (current version)
- Muse Glimmer 30B: autoregressive decoding:
StaticCacheandDynamicCache, thedynamic=Falsedefault, the benchmark on one TPU v7x chip (current version) src/torch_tpu/_loader.py: the TorchTPU backend selected by default anddynamic=Falsewhendynamicis not passedsrc/torch_tpu/_internal/compile/_backend.py:num_dynamic_bucketsandbucket_sizeoptions, serialization, the layout recompile and its warning- TorchTPU API Reference:
TORCH_TRACE,torch.tpu.ops.align_jagged_to_multipleandstrip_jagged_padding - TorchTPU Public APIs: the jagged-padding ops as public APIs
- Hugging Face and TorchTPU: TPUs, Natively: the compiled Diffusers transformer with
dynamic=False - Dynamic shapes: PyTorch documentation on automatic dynamic shapes and
mark_dynamic - torch.compiler.set_stance:
fail_on_recompile - torch.compiler troubleshooting:
TORCH_LOGS="recompiles"and the recompile limit - TorchTPU performance: execution modes, XProf and Pallas kernels: every new shape is a new program, the static cache fix, counting compiles
- TorchTPU performance sample code:
StaticCacheAutoregressiveDecoder,CompileCounter - Companion code for this chapter






