Skip to content

Dynamic shapes and recompilation

35 min read

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.compile on TorchTPU, in terms of XLA's static shapes and Dynamo's guards.
  • What dynamic=False, dynamic=None, dynamic=True and torch._dynamo.mark_dynamic do 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._dynamo counters, TORCH_LOGS="recompiles" and fail_on_recompile as 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.

Line chart of per-step latency on a log scale for ten decode steps of the documentation's growing torch.cat loop, sequence length 17 to 26. The orange dynamic=False line stays between about 38 and 50 ms on every step. The green dynamic=None line starts at about 50 ms on step 1, rises to about 207 ms on step 2, falls to about 64 ms on step 3, then drops to about 0.4 ms for steps 4 to 10. Annotations mark step 1 as a static compile for seq_len 16, step 2 as compiling the bucket 17 to 128, and step 3 as compiling again for the padded output layout.

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.

Two dashed containers stacked. Top, a gray container labelled Compile time, drawn for the example S = 300, at most 8 buckets, upper_bound = 700. A horizontal axis, titled Size of the dynamic dimension, has ticks at 384, 512, 640 and 768; it is dashed under the first bucket, which is not to scale. Four adjoining blue bands lie on the axis, the buckets, each named at its right end: U = 384, U = 512, U = 640, U = 768. A neutral band lying across the top of all four reads 4, One range guard. A dot on the axis inside the first bucket is labelled S = 300. A second dot between 640 and 768, joined by a short line to its label, reads 3, upper_bound = 700; the last bucket still runs to 768. Below, a numbered list: 1, Range from mark_dynamic or from S; 2, Buckets every bucket_size (128), at most 8; 3, Cap rounded up to the grid: 768; 4, One range guard over all buckets; 5, One executable per U. Bottom, a green container labelled Every call: an ink pill Runtime size S, an arrow to Pick the bucket, an arrow to a teal box Pad to U, identity values, an arrow to a green box Shape update, no slice copy.

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:

  1. determines a range [lower_bound, upper_bound] for that dimension, from mark_dynamic(..., min=..., max=...) or inferred by Dynamo from the initial runtime size \(S\);
  2. splits the range into contiguous buckets aligned to multiples of bucket_size (default 128, the TPU's 128-lane tile dimension), up to num_dynamic_buckets (default 1, maximum 8). The first bucket runs from lower_bound to \(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], ...;
  3. 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 at upper_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;
  4. registers one range guard across all buckets with Dynamo, so Dynamo recompiles only when the size leaves the overall range;
  5. 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 max of 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 reshape or view. 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 dynamic SymInts 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 with torch.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:

  1. Fixed-size buffers. Keys and values are preallocated as [B, H_kv, max_cache_len, D].
  2. On-device length. The fill level is a 0-D tensor on the TPU, updated in place, not a Python int that Dynamo would guard on.
  3. In-place writes, fixed-shape masks. New entries are written with index_copy_; positions not yet written are masked out of attention.
  4. 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.

An animation in fifteen frames. A top row of 20 slot cells is the static cache; a bottom row is the torch.cat cache, which has only as many cells as tokens so far. Frame 1 shows both empty with compile counters at 0. Frame 2 is the prefill: 8 slots fill in both rows and both counters read 1. Frame 3 is decode step 1: one slot fills in each row and both counters read 2. From decode step 2 to step 12 the static counter stays at 2 while the torch.cat counter climbs by one each step, reaching 13; each torch.cat frame notes the new shape and a failed guard. The last frame shows the totals, 2 against 13, and notes that the docs' TPU loop pays 38 to 50 ms per step under dynamic=False and that bounded dynamism compiles 3 times and then stays flat.

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.

Line chart on a log scale of prefill and per-step decode time for Muse Glimmer 30B on one TPU v7x chip with a cold compilation cache. The blue StaticCache, dynamic=False line is about 21,000 ms at prefill and about 19,800 ms at decode step 1, then about 24 ms from step 2 onward. The purple DynamicCache, dynamic=None line is about 18,300 ms at prefill, about 20,000 ms at step 1, about 22,000 ms at step 2 and about 4,900 ms at step 3, then about 24 ms from step 4 onward. A shaded band marks prefill and step 1 as both compiling and a second band marks steps 2 and 3 as DynamicCache still compiling. A note gives the steady state: StaticCache 23.58 ms over steps 2 to 20 and DynamicCache 24.17 ms over steps 4 to 20.

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.

An animation in twelve frames. Four horizontal lanes are labelled bucket 128, bucket 256, bucket 512 and bucket 1024, each drawn with a width proportional to its size. Ten requests arrive one per frame with lengths 90, 130, 17, 600, 129, 400, 1000, 31, 700 and 1024. In each frame the request fills its bucket's lane in blue up to its length and the rest in light orange labelled with the padding; a bucket's outline turns green and gains the word compiled on its first use. Two counters compare compiles with buckets and without: after the fourth request they read 3 and 4, and at the end 4 and 10. A running figure shows the padding waste so far, 46 percent (699 of 1,536 padded slots) after the fourth request and 25 percent at the end.

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:

\[ \text{waste} = \frac{\sum_i \left(\text{bucket}(n_i) - n_i\right)}{\sum_i \text{bucket}(n_i)} \]

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:

Line chart of padding waste, as a percentage of padded slots, against the number of compiled shapes for 2,000 synthetic lengths drawn log-uniformly from 16 to 2048. Both families start at 79 percent with one bucket of 2048 and 64 percent with two. The orange powers-of-two family falls to 36 percent at 4 shapes and flattens at about 28 percent from 6 to 8 shapes. The blue evenly spaced family, multiples of 128, is higher in the middle, 44.5 percent at 4 shapes and 37 percent at 6, reaches 26.5 percent at 8 and 14 percent at 16.

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:

  1. Collect the length histogram of real traffic or of the training set. The trade-off curve depends on it entirely.
  2. Set the largest bucket at the longest length you will serve or train on. Anything above it needs an explicit policy.
  3. 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_size of 128 encodes the same rule.
  4. 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.
  5. 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:

A chooser with two entry pills along the top, one for each way a dimension can change that needs a choice, leading through white questions to three blue strategy cards. Varies per request or batch leads down to the question Pallas kernels in the graph? Yes leads left and down into the card Pad to buckets, dynamic=False, warm every bucket, on the left. No leads down to the question A new process per job? Yes leads straight left into the same Pad to buckets card; No leads down to the question Known maximum and U affordable? Yes leads down and right to the card Bounded dynamism, dynamic=None or mark_dynamic, at the bottom right. No leads left and up into the Pad to buckets card. Grows step by step leads down to the question Can you change the model code? Yes leads down to the card Static cache, dynamic=False, 2 compiles, Pallas-safe. No leads left, down past the Static cache card and right into the top of the Bounded dynamism card.

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
  1. On the CPU, the compile counts match the predictions. The smoke run reports 10 compiles for ten dynamic=False steps of the growing cache, 2 for dynamic=None, 1 with mark_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 that fail_on_recompile raises on a new shape. If any count differs, your PyTorch version guards differently; find out why before relying on it.
  2. On the TPU, steps 4 onward are flat. Without --cpu-smoke the script runs the documentation's loop under dynamic=False, dynamic=None and mark_dynamic, prints every step's time and Dynamo's count, and checks that the dynamic=None steps from 4 on are all far below step 1. Compare the shape of your output with the chart at the top of this chapter: under dynamic=False every step should be slow; under dynamic=None three steps should be slow and the rest fast. Keep your output as the record for your TorchTPU version and TPU generation.
  3. 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 under dynamic=None with a separate prefill, one per bucket for bucketing).
  4. 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 with TORCH_LOGS="recompiles" once and confirm there are no lines after warm-up.
  5. Check the cost you accepted. For bucketing, compute padding_waste on the real length histogram and confirm the number of compiled buckets. For bounded dynamism, check that max or 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

  1. Name three things XLA decides at compile time that depend on tensor sizes.
  2. Which two mechanisms make a new shape trigger a compile under torch.compile on TorchTPU?
  3. What value of dynamic does TorchTPU use when you do not pass one, and what does dynamic=True do?
  4. In bounded dynamism, what determines the bucket bounds, what are the defaults for bucket_size and num_dynamic_buckets, and when does Dynamo recompile?
  5. What happens to the padded region of an input at run time, and why does it not change the result?
  6. Why does the documentation's dynamic=None loop compile three times, and what does mark_dynamic before step 1 change?
  7. Why must a static cache's fill level be a 0-D tensor rather than a Python integer?
  8. Define padding waste, and explain why more buckets reduce it.
  9. 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.compile to dynamic=False when you do not pass dynamic. Pass dynamic=None to opt in to bounded dynamism, or mark_dynamic(t, dim, min=..., max=...) to start with explicit bounds; dynamic=True raises NotImplementedError.
  • 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_for picks the bucket and padding_waste measures 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._dynamo counters, TORCH_LOGS="recompiles" for the reason, and fail_on_recompile to 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