How it works: execution, memory, compilation and distributed mechanics¶
Related chapters
Section 2.1 is chapter 4, 2.2 is chapter 5, 2.3 is chapter 6, 2.4 is chapter 7, 2.5 is chapter 13 and 2.6 is chapter 20.
This page covers how PyTorch operations map onto TPU silicon: how eager and compiled graphs execute, how UntypedStorage, DeviceBufferRef states, views, and \((8, 128)\) tiles behave in HBM/VMEM, how MXU precision emulation works, how dynamic shapes are bucketed, and how 6D parallelism and disaggregated KV transfers operate across ICI and DCN.
2.1 Eager execution modes and the torch.compile pipeline¶
Prerequisites: the six-layer ecosystem map (section 1.2) and core glossary (section 1.3 A/B) in Fundamentals.
Covers: how an ATen operation travels through
Strict(-O1),Debug(LAUNCH_BLOCKING),DeferAndFuse(-O2with refcount liveness pruning and repeated-op loop heuristics), andtorch.compile(backend="tpu")(custom FX passes, the 192-bit three-tier cache, and the MLIR passes that run only after a Tier 1 miss).
In one sentence¶
Unlike legacy torch_xla (a lazy-tensor execution model in which a missing xm.mark_step() let graphs grow without bound), torch_tpu defaults to true asynchronous Strict eager execution while offering opt-in Debug (synchronous per-op) and DeferAndFuse (-O2 fusion of deferred ops, which the documentation reports as up to 50% faster than Strict eager) modes, and reserving whole-graph XLA fusion for explicit torch.compile(backend="tpu").
Note
How it works: the PJRT enqueue cost and microbubbles (TorchTPU execution model):
In Strict eager mode, torch_tpu compiles each single-op StableHLO module at -O1 across a background C++ threadpool and enqueues the resulting PJRT_LoadedExecutable onto the TPU async device queue in \(\le 50\;\mu\text{s}\).
- If a single TPU op takes \(> 50\;\mu\text{s}\) on silicon (e.g., a large \(4096 \times 4096\) matmul), the host CPU runs ahead of the TPU and device utilization stays high (though each op still reads/writes HBM without VMEM fusion).
- If a model executes dozens of tiny elementwise ops taking \(1\text{ to }5\;\mu\text{s}\) each on silicon, the \(\sim 20\text{ to }50\;\mu\text{s}\) host dispatch cost exceeds the device execution time, starving the TPU and creating "microbubbles" (idle gaps between kernels on the XProf timeline).
DeferAndFuse(TORCH_TPU_DEFER_AND_FUSE=1) eliminates microbubbles in eager mode by holding ops in aDeferredOpDAG until a materialization point or a detected loop repetition and compiling them together at-O2, whiletorch.compile(backend="tpu")eliminates both microbubbles and HBM round-trips across the entire forward/backward step.
Warning
Common pitfalls: eager vs. lazy vs. compiled
- Pitfall 1: "Is
DeferAndFusejustPyTorch/XLA's old lazy tensor mode under a new name?" Fact: No. LegacyPyTorch/XLAaccumulated unbounded graphs until an explicitxm.mark_step()and materialized every intermediate Python tensor back to HBM.DeferAndFusematerializes at the next host sync point or detected loop repetition, uses Python reference-count liveness analysis (live_data_ptrs()) to avoid materializing dead intermediates to HBM, and includes a Repeated Ops Heuristic (TORCH_TPU_INTERNAL_DETECT_REPEATED_OPS="safe") that automatically detectsfor-loop bodies and flushes them per iteration so unrolled loops never trigger compilation explosions. - Pitfall 2: "Do side-effecting ops (like
all_reduce) get pruned byDeferAndFuseif their output tensor is unused?" Fact: No.DeferAndFuse's liveness pruner explicitly marks distributed collectives and in-place storage mutations as side-effecting roots that are never skipped even if no Python variable holds their return value.
Eager modes and the torch.compile pipeline¶
The same four ATen ops become four single-op executables in Strict and Debug and one fused executable in DeferAndFuse. Strict and Debug differ mainly in whether the host waits for each op; DeferAndFuse waits for a host sync or a repeated loop body and then compiles at -O2.
The cache lookup comes before the MLIR stage: a Tier 1 hit skips building StableHLO altogether, and the TorchTPU MLIR passes run only after that miss, ahead of the Tier 2 and Tier 3 lookups and the XLA compile. Each graph AOTAutograd hands over, forward and backward, takes this path once; the three-tier cache section below shows the tiers.
The three eager modes¶
Sources: TorchTPU execution model, csrc/eager/.
| Execution Mode | Activation Environment Variable / API | Internal C++ Execution Path & XLA Opt Level | Pros & Cons | Primary Use Case |
|---|---|---|---|---|
Strict (Default) |
Default (torch.tpu.EagerMode.DEFER_NEVER) |
Each ATen op lowers to a 1-op StableHLO module, compiles at -O1 in parallel across the C++ threadpool (or hits cache), and asynchronously enqueues a PJRT_LoadedExecutable (in about 50 µs or less). |
Pros: True PyTorch eager semantics; no hidden lazy graphs; fast host return. Cons: Every op reads/writes HBM; tiny ops (\(< 50\;\mu\text{s}\)) cause microbubbles. |
Model initialization, weight loading, preprocessing, interactive debugging, and gluing torch.compile blocks. |
Debug (Blocking) |
export TORCH_TPU_LAUNCH_BLOCKING=1 (EagerMode.DEFER_NEVER_AND_LAUNCH_BLOCKING) |
Disables async queuing; forces synchronous PJRT compilation, calls BlockHostUntilReady() after every op, and enables TORCH_TPU_ENABLE_DEBUG_CHECKS=1. |
Pros: Pinpoints exact failing Python line on HBM OOM, XLA error, or NaN. Cons: High host-device synchronization overhead. |
Root-cause debugging of runtime crashes, shape mismatches, or custom op failures. |
DeferAndFuse |
export TORCH_TPU_DEFER_AND_FUSE=1 (EagerMode.DEFER_AND_FUSE) |
Records ops in a DeferredOp DAG (DeviceBufferRef in Deferred state). Prunes dead intermediates via live_data_ptrs() and compiles fused subgraph at -O2. |
Pros: up to 50% faster than Strict eager; fuses elementwise chains without torch.compile.Cons: Longer compiles than Strict; a host sync such as .item() ends the fused region. |
Eager workloads or legacy scripts that cannot yet use torch.compile due to dynamic Python control flow. |
DeferredOp materialization triggers and the repeated-op heuristic¶
In DeferAndFuse mode (csrc/eager/deferred_execution.cc), a deferred tensor's DAG is immediately pruned via live_data_ptrs(), topologically sorted, lowered to a single fused StableHLO module, compiled at -O2, and executed when one of these triggers occurs:
- Repeated-Op Loop Boundary Heuristic (
TORCH_TPU_INTERNAL_DETECT_REPEATED_OPS): When a Pythonforloop executes the same sequence of operations repeatedly before a final.cpu()or.item()call, fusing the whole loop would produce one large unrolled graph.DeferAndFusemonitors repeating operator signatures and automatically flushes at the exact loop iteration boundary ("safe"mode by default;"aggressive"flushes even earlier on partial pattern repeats). - Host Value Inspection: Calling
.item(),.numpy(),bool(tensor),int(tensor),float(tensor), orprint(tensor). - Device-to-Host Copy: Calling
tensor.cpu()ortensor.to("cpu"). - Explicit Synchronization: Calling
torch.accelerator.synchronize().
Triggers and mode selection
TorchTPU execution model names two conditions: an action that forces execution (most often a device-to-host transfer or an explicit synchronize) and a detected repetition in the dispatched ops. The modes are the torch.tpu.EagerMode members DEFER_AND_FUSE, DEFER_NEVER and DEFER_NEVER_AND_LAUNCH_BLOCKING, selected with TORCH_TPU_DEFER_AND_FUSE, TORCH_TPU_LAUNCH_BLOCKING or torch.tpu.set_eager_mode. Strict is the default, and DeferAndFuse is reported as up to 50% faster than Strict eager (chapter 4).
Custom FX passes and C++ MLIR passes¶
torch.compile(backend="tpu") runs two optimization stages, in src/torch_tpu/_internal/compile/ and csrc/mlir/, before handing StableHLO to OpenXLA. The FX passes run on every compiled graph; the MLIR passes run only after a Tier 1 cache miss, when the StableHLO module is built:
| Stage | Pass Name / Pattern Flag | Source File | What It Optimizes on TPU Silicon |
|---|---|---|---|
| Stage 1: Python FX Graph Passes | fold_gqa & detect_causal_mask |
compile/fx_passes/fold_gqa.py, compile/fx_passes/detect_causal_mask.py |
Reshapes Grouped-Query Attention (GQA) heads into hardware-friendly \((8, 128)\) groups without repeat_interleave HBM copies, and replaces materialized \([S, S]\) causal mask tensors with symbolic causal mask attributes for Tokamax SplashAttention. |
| Stage 1: Python FX Graph Passes | mark_activation_checkpoints |
compile/fx_passes/mark_activation_checkpoints.py |
Preserves torch.utils.checkpoint rematerialization boundaries through AOTAutograd into XLA HLO optimization barriers. |
| Stage 1: Python FX Graph Passes | scan & associative_scan |
compile/scan.py |
Lowers torch.tpu.compile.scan and associative_scan into native StableHLO while loops and parallel prefix scans (preventing \(L\)-layer Transformer compile-time unrolling). |
| Stage 1: Python FX Graph Passes | nested_compile_region & flex_attention_redirect |
compile/nested_compile_region.py, compile/flex_attention_redirect.py |
Compiles repeated submodules once as reusable HLO Call functions and redirects torch.nn.attention.flex_attention score_mod/mask_mod graphs to TPU Pallas/XLA kernels. |
| Stage 2: C++ StableHLO MLIR Passes | fold_concat_softmax |
csrc/mlir/passes/fold_concat_softmax.cc |
Fuses concat + softmax patterns (common in attention sink / multi-branch routing) to avoid materializing concatenated buffers in HBM. |
| Stage 2: C++ StableHLO MLIR Passes | reassociate_norm_weights |
csrc/mlir/passes/reassociate_norm_weights.cc |
Reassociates (x / rms) * weight into x * (weight / rms) or fuses weight multiplication into the downstream dot_general MXU pass. |
| Stage 2: C++ StableHLO MLIR Passes | lower_separable_gather_to_dot |
csrc/mlir/passes/lower_separable_gather_to_dot.cc |
Converts small-table embedding gather operations into one-hot dot_general matrix multiplications when the MXU is faster than random HBM gather indices. |
| Stage 2: C++ StableHLO MLIR Passes | guard_zero_operand_custom_calls |
csrc/mlir/passes/guard_zero_operand_custom_calls.cc |
Injects scheduling tokens onto zero-operand custom calls (e.g., RNG or barrier ops) so XLA dead-code elimination (DCE) never strips them. |
Note
The FX passes live in src/torch_tpu/_internal/compile/fx_passes/, one file per pass (fold_gqa.py, detect_causal_mask.py, mark_activation_checkpoints.py and others). They, and torch.tpu.compile.scan, are internal rather than listed in TorchTPU Public APIs, so they can change (chapter 4).
The three-tier compilation cache and the 192-bit CacheKey¶
Because OpenXLA + LLO whole-graph optimization takes seconds to minutes for large Transformer graphs, torch_tpu implements a hierarchical 3-Tier Compilation Cache (csrc/common/compilation_cache.h). Every tier is looked up with the same key, a CompilationCacheKey (csrc/common/cache_key.h): a GraphKey made of a ShapelessKey and a DimensionsKey, plus a CompileOptionsKey, each a 64-bit fingerprint.
Three 64-bit fingerprints make the key: two describe the graph and one the compiler settings. A new size inside a bucket keeps the shapeless and options words; the bounded-dynamic entry is found by the shapeless word and stored under the bucket's dimensions, so one executable serves the bucket. The same three words, in hex, name the Tier 2 and Tier 3 files.
- Shapeless key: a fingerprint of the deferred-op graph signature (op names, op parameters, wiring, dtypes, argument layouts, donated inputs). No StableHLO exists yet when it is computed.
- Dimensions key: the tensor dimensions (or the shape-dynamism metadata).
- Options key:
XLA_FLAGS,LIBTPU_INIT_ARGSand the XLA compile options (build options, overrides, argument layouts).
Besides the three uint64_t fingerprints (192 bits), the key holds an int id_key (default -1) that tells dynamic-kernel variants of one graph apart.
By default, with world size 1 and no Tier 3, a Tier 1 miss compiles at once; Tier 2 under /dev/shm/torch_tpu_cache/ comes on when TORCH_TPU_TIER2_COMPILATION_CACHE names a cache or, when it is unset, for world size above 1 or when Tier 3 is set, and a per-entry file lock lets one process compile while the others wait and load. With Tier 3 set, a local compile starts alongside the Tier 3 read; a compiled or Tier 3 result is written to Tier 2, and every path ends with the executable in Tier 1.
- Tier 1: a process-local in-memory map from
CompilationCacheKeyto the loaded executable, always enabled, with no LRU eviction. - Tier 2:
TORCH_TPU_TIER2_COMPILATION_CACHE=<name>(a directory name under/dev/shm/torch_tpu_cache/) or"disabled". It is enabled by default whenever world size is above 1, and also (name"default") whenever Tier 3 is set. The first process to take the per-entry file lock compiles; the others wait on the lock and load the.binfile. - Tier 3: disabled until
TORCH_TPU_TIER3_COMPILATION_CACHE_ROOTis set. It persists serialized executables across hosts, preemptions and later runs, so new hosts and restarted jobs load cached executables instead of recompiling. A local backup compile starts alongside the Tier 3 read, and the first to finish is used.
2.2 Memory: UntypedStorage, DeviceBufferRef states, views and tile alignment¶
Prerequisites: section 2.1's execution modes and PJRT compilation pipeline.
Covers: why
torch.UntypedStorage.data_ptr()points to CPU metadata (DeviceBufferRef) rather than raw 1D HBM bytes, the five states of aDeviceBufferRef, howtorch_tpudecomposes and invertsas_stridedviews, and the arithmetic of \((8, 128)\) tile padding and packing waste.
In one sentence¶
PyTorch exposes TPU memory as a flat byte-addressed heap where tensors can be arbitrarily sliced and viewed at zero cost, whereas TPU silicon accesses memory strictly as 2D \((8 \times 128)\) tiles (8 sublanes \(\times\) 128 lanes) moved via explicit DMAs between off-chip HBM and on-chip VMEM; torch_tpu bridges this gap through PjRt-managed buffers, DeviceBufferRef / DeviceBufferList storage indirection, compiler View Decomposition & View Inversion, and buffer donation.
Note
How it works: why UntypedStorage.data_ptr() is a CPU metadata pointer, and the five DeviceBufferRef states (TorchTPU and the TPU memory model, csrc/eager/device_buffer.h):
On a GPU, tensor.untyped_storage().data_ptr() returns a 64-bit virtual address in flat 1D GDDR/HBM memory, so any strided view can be accessed by adding storage_offset + sum(i_k * stride_k) in a CUDA thread. On a TPU, OpenXLA's PjRtBuffer is an opaque, 2D-tiled HBM object managed by libtpu that cannot be indexed via arbitrary 1D byte pointer arithmetic.
Therefore, in torch_tpu, torch.UntypedStorage.data_ptr() points to a CPU-side C++ handle (DeviceBufferRef or DeviceBufferList) inside c10::StorageImpl that moves through the five states in the figure below; six overlapping predicates track them (is_placeholder, is_deferred, is_materializing, is_executing, is_transferring, is_materialized), and is_executing turns true in the same step as is_materialized.
Amber states live on the host: a buffer is still a DeferredOp, or is scheduled for execution. Materialized means the PjRt buffers are attached as soon as the work is enqueued, not that the TPU has finished; Placeholder and Transferring are separate entry points, and a placeholder never gains data.
Placeholder: stands for data that will be provided as an argument to a compiled executable; a placeholder never materializes.Deferred: points to an unmaterializedDeferredOpnode in theDeferAndFuseC++ DAG (csrc/eager/deferred_execution.h).Transferring: a host-to-device copy that waits for atorch.Event; when the event fires the copy starts and the buffer becomesMaterialized. A copy with nothing to wait for is createdMaterializedat once.Materializing: scheduled into an execution task after its graph compiles; theDeferredOpis dropped (the output of a compiled-mode call also starts here). When the executable is enqueued on PjRt, its outputPjRtBuffers are attached and the buffer isMaterializedin the same step, while the TPU may still be computing.Materialized: itsPjRtBuffers are attached (owned asstd::unique_ptr<xla::PjRtBuffer>, or held as aDeviceBufferListofDeviceBufferRefs for multi-buffer and sharded storages); the device work that fills them may still be running, and a failed materialization also ends here, holding the error (SetAsError).
Warning
Common pitfalls: views, clones, partial writes and channels_last
-
Pitfall 1: "Creating and using tensor views (
x[::2, 1:],.transpose(0, 1)) is always free on TPU, while.clone()is expensive, just like on CUDA." Fact: On TPU, the opposite is often true in eager mode. -
.clone()is free (Lazy Copy-on-Write): Callingy = x.clone()intorch_tpusimply shares the underlyingDeviceBufferRef(PjRtBuffer) with Copy-on-Write semantics: no HBM allocation or DMA copy occurs untilxoryis mutated. - Non-contiguous views can be expensive: Because TPU registers hold \(8 \times 128\) 2D tiles, strided views or transposes require VPU register relayout instructions (
Transpose/Slice/DynamicSlice), and passing a non-contiguous view across atorch.compileboundary forces a contiguous HBM copy unless fused inside the graph (or enabled via experimentalTORCH_TPU_INTERNAL_STORAGE_AWARE_PLACEHOLDERS=true). - Pitfall 2: "Writing to a small slice of a tensor (
x[0] = 1.0) only touches that slice in HBM." Fact: BecausePjRtBufferis immutable in SSA form, a partial write (slice_scatter/select_scatter) without buffer donation must copy the entire baseUntypedStoragebuffer in HBM and overwrite the slice. Keep partial-write updates (like KV cache updates) insidetorch.compileso buffer donation can update it in place. - Pitfall 3: "PyTorch's default
NCHWlayout is fine for Vision / CNN / ConvNeXt models on TPU." Fact: InNCHW((N, C, H, W)), the two most-minor dimensions are(H, W), which are often small (\(7\times 7\), \(14\times 14\), \(28\times 28\)) and waste up to \(90\%\) of the \((8, 128)\) tile while starving the MXU along the channel dimensionC. Converting models and inputs tomemory_format=torch.channels_last(NHWC) places the large channel dimensionC(\(128, 256, 512, 1024\)) in the most-minor128-laneposition, which keeps the MXU fully fed.
Physical \((8, 128)\) tile layout¶
Allocator
The allocator TorchTPU registers, TpuAllocator in csrc/eager/tensor_to_buffer.cc, leaves memory management to PjRt, and its emptyCache is a no-op (chapter 5).
A tile is 8 sublanes by 128 lanes; each lane is a 32-bit word, so 8 × 128 × 4 B = 4 KiB. Narrower types pack 2, 4 or 8 values into each lane, so the same 4 KiB covers 16, 32 or 64 rows: this is the VMEM tiling that Pallas and the compiler use, and XLA's HBM layouts can differ.
How torch_tpu handles views and in-place mutations¶
In standard PyTorch on CPU/CUDA, a generic as_strided view (y = torch.as_strided(base, size=(2, 2, 2), stride=(2, 3, 0), storage_offset=1)) simply creates a new TensorImpl with modified stride metadata. Because OpenXLA has no single as_strided HLO instruction, TorchTPU and the TPU memory model resolves views and mutations via 5 coordinated mechanisms:
| Mechanism | Pipeline Stage | How It Works Under the Hood | Performance Impact |
|---|---|---|---|
| 1. View Metadata Tracking | Eager Runtime (DeviceBufferRef) |
Views share a single StorageImpl (DeviceBufferRef) and record size, stride, and storage_offset. No HBM copy happens when a view is created. |
Zero-copy until read/mutated by an op. |
2. as_strided View Decomposition |
Eager / FX Lowering | Decomposes any arbitrary torch.as_strided(base, size, stride, offset) into a canonical chain of elementary XLA-representable view primitives: offset slice \(\to\) reshape (view) \(\to\) strided slice \(\to\) permutation (t/permute) \(\to\) unsqueeze \(\to\) broadcast (expand). |
Enables lowering arbitrary strided views to StableHLO Slice + Reshape + Transpose + BroadcastInDim. |
| 3. View Inversion | torch.compile |
Instead of materializing a strided view buffer, rewrites downstream consumers (and scatter writers) to index directly into the base tensor via invert_view (fusing the view into the consumer's VMEM load/store). |
Zero HBM overhead inside torch.compile (or with TORCH_TPU_INTERNAL_STORAGE_AWARE_PLACEHOLDERS=true). |
| 4. Auto-Functionalization | AOTAutograd / FX Pass | Converts in-place mutations (x.add_(1), kv_cache[slot] = k) into pure functional SSA nodes (x_new = aten.add(x, 1)) in the FX graph. |
Pure SSA required by StableHLO. |
| 5. Buffer Donation | fx_to_mlir \(\to\) XLA HLO |
When the last reference to the old buffer is gone, TorchTPU annotates the StableHLO to donate the input x to the functionalized output x_new; when donation is not provably safe it falls back to an out-of-place update. XLA updates the HBM buffer in place without allocating a second buffer. |
True zero-copy in-place execution in HBM. |
Worked example: decomposing as_strided into six XLA primitives¶
Source: TorchTPU and the TPU memory model.
# Given a 1D base tensor of 10 elements on TPU:
base = torch.arange(10, device="tpu")
# A non-contiguous, transposed and broadcast view:
v1 = torch.as_strided(base, size=(2, 2, 2), stride=(2, 3, 0), storage_offset=1)
# Under the hood, torch_tpu decomposes `v1` into 6 elementary StableHLO-compatible steps:
v2 = (
base[1:] # 1. Storage offset slice (offset=1) -> StableHLO Slice
.view(3, 3) # 2. Reshape into 2D grid -> StableHLO Reshape
[:2, ::2] # 3. Strided slice along rows & cols -> StableHLO Slice (stride=2)
.t() # 4. Transpose to handle decreasing strides -> StableHLO Transpose
.unsqueeze(-1) # 5. Insert singleton dimension for stride=0 -> StableHLO Reshape
.expand(2, 2, 2) # 6. Broadcast along stride=0 dimension -> StableHLO BroadcastInDim
)
assert torch.equal(v1, v2)
Tile padding and sublane/lane alignment¶
Every 2D+ tensor stored in TPU HBM or VMEM has its last two physical dimensions (second-most-minor = sublanes, most-minor = lanes) padded up to multiples of the hardware tile size:
$\(\text{PaddedShape}(D_{\text{sublane}}, D_{\text{lane}}) = \left( \left\lceil \frac{D_{\text{sublane}}}{8} \right\rceil \times 8, \;\; \left\lceil \frac{D_{\text{lane}}}{128} \right\rceil \times 128 \right)\)$
Because the physical lane width is \(128 \times 4\text{ Bytes} = 512\text{ Bytes}\), narrow data types (bfloat16, fp8, int4) pack multiple elements into each 32-bit lane word (packing factor \(P = 32 / \text{bitwidth}\)), which scales the effective sublane alignment requirement in VMEM to \((8 \times P, 128)\) unless laid out along the lane dimension:
| Data Type | Bitwidth | Packing Factor \(P = 32 / \text{bits}\) | Fundamental VMEM Tile (Sublanes, Lanes) |
Tile Size in Bytes | Alignment Rule for Zero Padding Waste |
|---|---|---|---|---|---|
float32 / int32 |
32-bit | \(1\) | \((8, 128)\) | \(4,096\text{ B}\) (\(4\text{ KiB}\)) | \(D_{-2} \equiv 0 \pmod 8\), \(D_{-1} \equiv 0 \pmod{128}\) |
bfloat16 / int16 |
16-bit | \(2\) | \((8, 128)\) (HBM) / \((16, 128)\) (packed VMEM) | \(2,048\text{ B}\) / \(4,096\text{ B}\) | \(D_{-2} \equiv 0 \pmod{16}\) (or \(8\)), \(D_{-1} \equiv 0 \pmod{128}\) |
float8_e4m3fn / int8 |
8-bit | \(4\) | \((8, 128)\) (HBM) / \((32, 128)\) (packed VMEM) | \(1,024\text{ B}\) / \(4,096\text{ B}\) | \(D_{-2} \equiv 0 \pmod{32}\) (or \(8\)), \(D_{-1} \equiv 0 \pmod{128}\) |
int4 / fp4 (e2m1) |
4-bit | \(8\) | \((64, 128)\) (packed VMEM) | \(4,096\text{ B}\) (\(4\text{ KiB}\)) | \(D_{-2} \equiv 0 \pmod{64}\), \(D_{-1} \equiv 0 \pmod{128}\) |
HBM tiles for narrow types
The TorchTPU documentation gives no tile sizes. This table lists \((8, 128)\) in HBM for 2-byte and 1-byte types; for bfloat16 that matches the XLA layout an HLO line shows in the TPU Agent Suite's profiling playbook, bf16[8,1024,16384]{2,1,0:T(8,128)(2,1)S(1)}: \((8, 128)\) tiles in which each 32-bit word holds a packed pair of bfloat16 values. By contrast, the tile_padding_report() helper in TorchTPU Performance: Execution Modes, XProf and Pallas Kernels uses \((16, 128)\) for bfloat16 and \((32, 128)\) for 8-bit types. On a TPU, torch.tpu.get_device_layout_if_materialized(t) (Experimental) returns the tiles XLA chose for a materialized tensor (chapter 5).
Worked examples: padding waste¶
Example 1: one extra row and column (\(4096 \times 4096 \to 4097 \times 4097\) in float32)¶
Suppose you allocate a float32 matrix of shape \((4096, 4096)\) vs. \((4097, 4097)\):
- Aligned \((4096, 4096)\): Since \(4096 = 512 \times 8 = 32 \times 128\), both dimensions are exact multiples of \((8, 128)\). $\(\text{Logical Bytes} = \text{Physical HBM Bytes} = 4096 \times 4096 \times 4\text{ B} = \mathbf{67,108,864\text{ B}} \; (64.00\text{ MiB}) \implies \mathbf{0\%\text{ Waste}}\)$
- Unaligned \((4097, 4097)\):
- Sublane dimension pads up to \(\lceil 4097 / 8 \rceil \times 8 = 513 \times 8 = \mathbf{4104}\).
- Lane dimension pads up to \(\lceil 4097 / 128 \rceil \times 128 = 33 \times 128 = \mathbf{4224}\). $\(\text{Physical HBM Bytes} = 4104 \times 4224 \times 4\text{ B} = \mathbf{69,341,184\text{ B}} \; (66.13\text{ MiB})\)$ $\(\text{Padding Waste} = 69,341,184 - (4097^2 \times 4) = \mathbf{2,199,548\text{ B}} \; (\mathbf{2.10\text{ MiB}}\text{ in FP32})\)$ Adding a single row and column wastes over \(2.1\text{ MiB}\) of HBM and adds a partial tile to every row and column of MXU passes.
Example 2: GPT-2 vocabulary padding (\(50,257 \to 50,304\))¶
In GPT-2 (d_model = 768, vocab_size = 50,257), the LM head weight matrix has shape \((50257, 768)\). While \(768 = 6 \times 128\) is lane-aligned, \(50,257\) is not divisible by \(8\), \(64\), or the MXU dimension \(128\). Padding vocab_size to \(50,304 = 393 \times 128\) adds only \(47 \times 768 \times 2\text{ B} = \mathbf{72\text{ KiB}}\) of parameters while eliminating unaligned tail tiles.
Example 3: a tensor of shape \((B, 1, 1)\)¶
A tensor of logical shape \((1024, 1, 1)\) in float32 has each \((1, 1)\) slice padded to a full \((8, 128) = 1,024\)-element tile:
$\(\text{Utilization} = \frac{1 \times 1}{8 \times 128} = \frac{1}{1024} = \mathbf{0.097\%} \quad (\mathbf{99.9\%}\text{ of HBM and DMA bandwidth wasted})\)$
Squeeze or reshape singleton trailing dimensions so the two minor dimensions carry real extent (\(\ge 8\) and \(\ge 128\)).
2.3 Numerical precision and MXU arithmetic¶
Prerequisites: the MXU/VPU hardware specs (section 1.1 in Fundamentals) and section 2.2's data-type packing rules.
Covers: the Henry-Tang-Heinecke 9-term \((a+b+c)(d+e+f)\)
bfloat16expansion forfloat32matrix multiplication, global and scopedtorch.tpu.Precisionmodes withouttorch.compilegraph breaks, and intermediate mantissa retention undertorch.tpu.allow_excess_precision.
In one sentence¶
The TPU MXU is a native bfloat16/fp8/fp4-input, float32-accumulating systolic engine; when asked to multiply float32 matrices, XLA emulates higher mantissa precision via the Henry-Tang-Heinecke algorithm: decomposing each float32 operand into 1, 2, or 3 bfloat16 residual slices and executing 1, 3, or 6 MXU passes (medium/DEFAULT, high/HIGH, highest/HIGHEST), trading about \(3\times\) to \(6\times\) MXU cost for IEEE-754 mantissa bits.
Note
How it works: the nine-term \((a+b+c)(d+e+f)\) expansion (Manage numerical precision in TorchTPU):
An IEEE-754 float32 number has \(24\) significand bits (\(1\) implicit leading bit + \(23\) fraction bits), whereas bfloat16 has \(8\) significand bits (\(1\) implicit + \(7\) fraction bits). Any float32 scalar \(x\) can be decomposed into three non-overlapping bfloat16 components \(x \approx a + b + c\) where \(|b| \le 2^{-8}|a|\) and \(|c| \le 2^{-16}|a|\).
Multiplying two decomposed float32 numbers \(x = a + b + c\) and \(y = d + e + f\) yields 9 cross-terms, with \(a, d\) the High parts, \(b, e\) the Med parts and \(c, f\) the Low parts:
Each cell is one product of the bf16 parts of each float32 input and names the cheapest mode that computes it, with its size relative to High × High. A mode computes whole anti-diagonals: DEFAULT one product, HIGH three, HIGHEST six; the three smallest fall below float32 precision and no mode computes them.
| Cross-Term | Relative Magnitude vs. \(a \cdot d\) | Included in Precision.DEFAULT ("medium", 1 Pass)? |
Included in Precision.HIGH ("high", 3 Passes)? |
Included in Precision.HIGHEST ("highest", 6 Passes)? |
|---|---|---|---|---|
\(a \cdot d\) (High \(\times\) High) |
\(2^{0}\) (Bits \(0\text{ to }7\)) | Yes | Yes | Yes |
\(a \cdot e\) (High \(\times\) Med) |
\(2^{-8}\) (Bits \(8\text{ to }15\)) | Dropped | Yes | Yes |
\(b \cdot d\) (Med \(\times\) High) |
\(2^{-8}\) (Bits \(8\text{ to }15\)) | Dropped | Yes | Yes |
\(a \cdot f\) (High \(\times\) Low) |
\(2^{-16}\) (Bits \(16\text{ to }23\)) | Dropped | Dropped | Yes |
\(b \cdot e\) (Med \(\times\) Med) |
\(2^{-16}\) (Bits \(16\text{ to }23\)) | Dropped | Dropped | Yes |
\(c \cdot d\) (Low \(\times\) High) |
\(2^{-16}\) (Bits \(16\text{ to }23\)) | Dropped | Dropped | Yes |
| \(b \cdot f\), \(c \cdot e\), \(c \cdot f\) | \(2^{-24}\) to \(2^{-32}\) (below float32 precision) | Dropped | Dropped | Dropped (below float32 precision next to \(a \cdot d\); no mode computes them) |
Warning
Common pitfalls: the precision context manager and allow_excess_precision
- Pitfall 1: "I can freely enter and exit
with torch.tpu.precision(torch.tpu.Precision.HIGH):inside atorch.compile-decorated function." Fact: Entering or exitingwith torch.tpu.precision(...):inside a compiled region triggers atorch.compilegraph break. Wrap thewith torch.tpu.precision(...):context manager outside the compiledmodel(x)call, or settorch.set_float32_matmul_precision("high")globally before compilation. - Pitfall 2: "I can toggle
torch.tpu.allow_excess_precision = Falsedynamically mid-training after XLA has already compiled my model." Fact:torch.tpu.allow_excess_precision(default:False) sets the--xla_allow_excess_precisioncompiler flag and locks on the first XLA compilation in the process. Setting a different value after that raises aRuntimeError; setting the same value again does nothing. (chapter 6)
MXU dataflow and the multi-pass float32 decomposition¶
A bf16 matmul is one MXU pass; a float32 matmul is split into bf16 parts and costs 1, 3 or 6 passes depending on the precision mode. Every pass accumulates in float32, and the float32 accumulator is rounded to the matmul's output dtype; with allow_excess_precision=True XLA may keep it in float32 through fused elementwise ops. The MXU is 128 wide before v6e and 256 wide on v6e and v7x.
Note
Manage numerical precision in TorchTPU puts "high" at about 3 times the MXU cost of "medium" and "highest" at about 6 times, so "high" runs at roughly a third of peak. It describes the precision as the top 8 bits of significand for "medium", the first 16 bits for "high" and all 24 bits for "highest": 8, 16 and 24 significand bits multiplied, from one, two and three bfloat16 parts (chapter 6). The MXU is a \(128 \times 128\) array below generation 6 and \(256 \times 256\) on v6e and v7x (the TPU Agent Suite's chip constants).
Precision and low-bit format reference¶
Sources: Manage numerical precision in TorchTPU, TPU v7x (Ironwood) Specification, and the torch_tpu precision APIs.
| Precision Format / Mode | PyTorch API / Scoped Context Manager | Sign / Exp / Mantissa Bits | Block Scaling Metadata | MXU Passes | Relative MXU Speed (vs BF16) | Hardware Support & Key Engineering Rules |
|---|---|---|---|---|---|---|
FP32 "medium" (DEFAULT) |
torch.set_float32_matmul_precision("medium") or with torch.tpu.precision(Precision.DEFAULT): |
\(1 / 8 / 23\) (rounded to \(1/8/7\)) | None | 1 pass | \(1.0\times\) | Rounds float32 inputs to bfloat16 before one MXU pass. TorchTPU default for FP32 matmuls. |
FP32 "high" (HIGH) |
torch.set_float32_matmul_precision("high") or with torch.tpu.precision(Precision.HIGH): |
16 significand bits multiplied | None | 3 passes | about \(0.33\times\) (about \(3\times\) the cost) | 3-term BF16 sum (\(a d + a e + b d\)). |
FP32 "highest" (HIGHEST) |
torch.set_float32_matmul_precision("highest") or with torch.tpu.precision(Precision.HIGHEST): |
24 significand bits multiplied | None | 6 passes | \(0.16\times\) (\(6\times\) slower) | 6-term BF16 sum (\(a d + a e + b d + a f + b e + c d\)). Use only for numerical unit tests against CPU FP64/FP32 references. |
Native bfloat16 |
torch.bfloat16 |
\(1 / 8 / 7\) | None | 1 pass | \(1.0\times\) (\(1,153.5\text{ TFLOPS}\)/v7x dev) | Identical dynamic range to FP32 (\(10^{\pm 38}\)); The MXU always accumulates in FP32; out_dtype only sets how the output is rounded. |
allow_excess_precision |
torch.tpu.allow_excess_precision = True (default False) |
Keeps FP32 intermediates in a fused program | None | 1 pass | \(1.0\times\) + fewer VPU casts | Skips redundant FP32 -> BF16 -> FP32 rounding casts between fused BF16 elementwise ops; locks on first XLA compile. |
Standard FP8 |
torch.float8_e4m3fn / torch.float8_e5m2 |
e4m3fn: \(1/4/3\)e5m2: \(1/5/2\) |
Tensorwise or Rowwise FP32 scale | 1 pass | \(2.0\times\) (\(2,307\text{ TFLOPS}\)/v7x dev) | Native \(2\times\) rate on v7x/v8 (the speed column is for v7x); v6e runs FP8 at its bf16 rate (918 TFLOPS) and INT8 at twice it. Use e4m3fn for weights/activations and e5m2 for gradients. |
Microscaling MXFP8 |
OCP mxfp8 (e4m3fn elements) |
\(1 / 4 / 3\) | 32-element block shared 8-bit E8M0 scale |
1 pass | \(2.0\times\) (native on v7x/v8) |
Supported in TorchTitan (Float8Linear) & v7x MXU; eliminates expensive global amax reductions. |
Microscaling MXFP4 |
OCP mxfp4 (e2m1 elements) |
\(1 / 2 / 1\) | 32-element block shared 8-bit E8M0 scale |
1 pass | \(2.0\times\) compute / \(4\times\) HBM BW vs BF16 | Native in v7x (Ironwood) & v8 MXU (\(4,614\text{ TFLOPS}\)/chip). Emulated via VPU dequant on v6e/v5p. |
NVIDIA NVFP4 |
torch.float4_e2m1fn_x2 |
\(1 / 2 / 1\) (2 vals/byte) | 16-element group fp8_e4m3fn scale + global FP32 scale |
1 pass | \(2.0\times\) on v7x/v8 (after scale unpack) |
Supported in SGLang-TorchTPU (nvfp4_quant.py) for direct serving of Blackwell NVFP4 checkpoints on TPU. |
Integer INT8 / INT4 |
torch.int8 / torch.uint4 (W8A8, W4A16) |
8-bit / 4-bit signed/unsigned | Per-channel or group-128 scale/zero | 1 pass | \(2.0\times\) (INT8 MXU) / \(4\times\) BW (W4A16) |
W4A16 (GPTQ/AWQ) is ideal for HBM-bandwidth-bound decode where VPU dequantizes 4-bit weights to BF16 on-the-fly. |
Low-bit formats
The low-bit formats come from the serving engines and TorchTitan rather than from TorchTPU itself. vLLM TorchTPU quantization lists FP8 weights and KV cache (static per-tensor, per-channel and block-wise), mxfp4 (e2m1 with e8m0 scales, block size 32), nvfp4, and AWQ and GPTQ int4/int8 checkpoints. The speed column gives peak MXU ratios; measure on your own workload.
Worked example: mantissa retention under torch.tpu.allow_excess_precision¶
Why does a chain of bfloat16 operations inside torch.compile sometimes produce more accurate results on TPU than on eager CPU/CUDA? Because, when torch.tpu.allow_excess_precision = True (the default is False), the compiler may keep fused intermediates in float32 instead of rounding them to bfloat16 (Manage numerical precision in TorchTPU):
import torch
import torch_tpu
# Consider two exact bfloat16 numbers: x = 1 + 2^-6, y = 1 + 2^-7 (both fit in 7-bit BF16 mantissa).
# Their exact product is: x * y = 1 + 2^-6 + 2^-7 + 2^-13.
# The 2^-13 term sits at mantissa bit 13: beyond BF16's 7-bit mantissa, inside FP32's 23-bit mantissa.
# Subtract (1 + 2^-6 + 2^-7) in a fused graph:
@torch.compile(backend="tpu")
def fused_residual(x: torch.Tensor, y: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:
prod = x * y # rounded to bfloat16 here, the 2^-13 term is lost
return prod - bias # Subtracting (1 + 2^-6 + 2^-7) reveals whether bit 13 survived in float32
x = torch.tensor([1.0 + 2**-6], dtype=torch.bfloat16, device="tpu")
y = torch.tensor([1.0 + 2**-7], dtype=torch.bfloat16, device="tpu")
bias = torch.tensor([1.0 + 2**-6 + 2**-7], dtype=torch.bfloat16, device="tpu")
# Exact arithmetic for the two rounding choices:
# • prod rounded to bfloat16 before the subtraction -> 0.0
# • prod kept in float32 -> 2^-13 = 0.0001220703125
# Only allow_excess_precision = True (set before the first compilation) lets the
# compiler keep prod in float32; it is permitted to, not required to.
Documented example
Manage numerical precision in TorchTPU shows the effect with a matmul, a @ b * c, which returns 1.0234375 with excess precision off and 1.0235595703125 with it on. Running fused_residual on a TPU under each setting is a quick way to see which of the two values above the compiler produces (chapter 6).
Tip
Stochastic rounding for bfloat16 master weights
When storing master weights directly in bfloat16 (to save \(4\text{ Bytes/param}\) of FP32 master weights), deterministic round-to-nearest-even causes small weight updates (\(|\Delta w| < 2^{-8} |w|\)) to stagnate at zero. Enabling Stochastic Rounding in XLA/Pallas adds a uniform hardware PRNG bit sequence before truncating FP32 \(\to\) BF16 so that \(\mathbb{E}[\text{SR}(w + \Delta w)] = w + \Delta w\) remains unbiased.
2.4 Dynamic shapes, bounded dynamism and serving buckets¶
Prerequisites: section 2.1's 192-bit
CacheKeyand section 2.2's \((8, 128)\) tile layout.Covers:
torch._dynamo.mark_dynamicwith contiguous bucketing (bucket_size=128,num_dynamic_buckets), the three warmup compilations of autoregressive decode (and how to skip the first), and howKVFreeFenceholds freed KV pages until the result of the forward that still writes them is processed.
In one sentence¶
Because OpenXLA statically bakes tensor dimensions into VMEM \((8, 128)\) tile loop bounds and DMA descriptors at compile time, any unbucketed shape change triggers a multi-second XLA recompilation; torch_tpu avoids runtime recompilations through bounded symbolic dynamism (mark_dynamic with min/max + contiguous 128-multiples bucketing) and serving engine token/batch bucketing (vLLM-TorchTPU token paddings / SGLang-TorchTPU Bucketer) paired with CPU-resident KVFreeFence page allocation.
Note
How it works: contiguous bucketing and metadata-only output resizing (Dynamic shapes):
When a dimension \(S\) is marked dynamic via torch._dynamo.mark_dynamic(x, dim, min=lower_bound, max=upper_bound) (or auto-detected under dynamic=None), torch_tpu compiles once per bucket and then, on every call, picks the bucket and pads:
Compile time splits the dynamic dimension's range into buckets on the 128 grid (bucket_size, default 128; num_dynamic_buckets, default 1, at most 8), guards the whole range once and compiles one executable per bucket upper bound U. Each call only picks its bucket: XLA pads to U with identity values, and the output comes back with its shape metadata set to S, so FLOPs and memory follow U, not S.
At runtime TorchTPU selects the compiled bucket executable from the actual size \(S\) of the dimension. XLA pads the input to the bucket bound \(U\) and resets the padded region to its algebraic identity (\(0\) for sum and matmul, \(-\infty\) for max and softmax), so padding never corrupts reductions; TorchTPU lowers the graph with bounded tensor types that carry both the bound and the runtime size. The single range guard means a new \(S\) inside the range never re-triggers Python bytecode tracing. If Dynamo shape constraints, such as divisibility from a reshape, rule out the bucket bounds, torch_tpu falls back to a single bucket with upper bound \(2S\), twice the initial runtime size.
Warning
Current limits of bounded dynamism (Dynamic shapes)
- Bucket limit and unbounded dynamism: At most 8 buckets (
num_dynamic_buckets <= 8) are compiled per trace. If a dynamic dimension grows past the highest bucket's upper bound, it recompiles. - Dynamo shape constraints: Bucket upper bounds must satisfy Dynamo's shape constraints (such as divisibility from
reshapeorview); otherwise TorchTPU falls back to a single bucket with upper bound \(2S\). - Compute and HBM up to the bucket bound: FLOPs and HBM scale with the upper bound \(U\), not the runtime size, so an oversized
bucket_sizeormax=Ucosts compute and memory. - XLA layout changes: A change in an input buffer's XLA physical layout triggers a bucket recompile even when the shape fits.
- No persistent compilation cache: Bounded-dynamic executables are not serialized to
AOTAutogradCacheyet, so each new process recompiles them. - Operator coverage: Not all PyTorch operators support bounded dynamic shapes yet.
- Views as model inputs: Passing tensor views directly as compiled-model inputs has limited support.
- Data-dependent dynamism: Ops whose output shapes depend on tensor values (such as
torch.nonzero) are not supported. - Custom kernels: Bounded dynamic shapes are not supported with custom TPU kernels, such as Pallas kernels registered through
torch.tpu.pallas.jax_op. dynamic=True:torch.compile(..., dynamic=True)is not supported. Usedynamic=Noneormark_dynamic(..., min=..., max=...).
These limits follow Dynamic shapes (chapter 7).
Unbounded shapes compared with bounded and bucketed shapes¶
Four calls, each with a new size. Static shapes compile before every call; bounded dynamism with mark_dynamic(x, 2, min=16, max=128) compiles once, on the first call, for the whole range (an input that arrives in XLA's padded layout costs one more compile); a serving engine compiles every bucket at startup and pads each batch on the host to the next bucket, for example 190 tokens to 256. Block widths are not measured.
With dynamic=False, every step of the documented growing loop recompiles, at about 38 to 50 ms per step (Dynamic shapes). Serving engines choose their buckets themselves: vLLM-TorchTPU's token paddings double from 16 and end at max_num_batched_tokens, giving \(B \in \{16, 32, 64, \dots, \texttt{max\_num\_batched\_tokens}\}\) (4096 is the last bucket only when the token budget is 4096), and SGLang-TorchTPU pads with its Bucketer / PowerBucketer.
Worked example: the decode warmup sequence¶
Why does an autoregressive decoding loop (kv_cache growing from \(S=16 \to 17 \to 18 \to 19\)) without explicit pre-marking exhibit three distinct compilation spikes before reaching steady state (Dynamic shapes)?
Step latency of the documented loop on a log scale: three compiles, then about 0.4 ms per step from step 4.
| Decode Step | KV length (in to out) | Observed Step Latency | What Happens Inside TorchDynamo + torch_tpu + OpenXLA |
|---|---|---|---|
| Step 1 (Initial Call) | 16 to 17 | 49.59 ms |
Dynamo assumes \(S=16\) is static and compiles a specialized static executable for shape=[B, H, 16, D]. |
| Step 2 (1st Shape Change) | 17 to 18 | 206.68 ms |
Guard fails (\(17 \neq 16\)); Dynamo automatic dynamism triggers, marks dim=2 dynamic in bucket \([17, 128]\), and compiles a bounded-dynamic executable taking a standard PyTorch input layout and returning an XLA-padded [B, H, 128, D] output buffer. |
| Step 3 (Padded Buffer Reuse) | 18 to 19 | 64.29 ms |
Step 2's output kv_cache now has XLA's internal padded [B, H, 128, D] physical storage layout (different from Step 2's fresh [B, H, 17, D] input layout), triggering one final layout-specialized compilation. |
| Step 4+ (Steady State) | 19 to 26 in the documented run (any length up to 128) | ~0.40 ms (about \(100\times\) faster) |
In-memory cache hit. Both logical shape (\(S \in [17, 128]\)) and physical padded buffer layout ([B, H, 128, D]) match Step 3's executable. |
# To skip step 1's static compilation, mark the KV cache dimension dynamic
# before step 1, so that step 1 compiles the [16, 128] bucket directly.
torch._dynamo.mark_dynamic(kv_cache, dim=2, min=16, max=128)
Note
The documented run goes from 49.59 ms on step 1 to about 0.4 ms from step 4, about 100 times faster (Dynamic shapes). When dynamic is not passed, TorchTPU's loader (_loader.py) sets dynamic=False for the TPU backend, so this behaviour needs an explicit dynamic=None or mark_dynamic (chapter 7).
Dynamic shape and bucketing strategies¶
Sources: Dynamic shapes, tpu_runner.py, tpu_compiler.py and bucketer.py.
| Strategy | API / Flag / Environment Variable | How It Works Internals | Constraints & Default Bounds | Ideal Workload |
|---|---|---|---|---|
| 1. Explicit Bounded Dynamism | torch._dynamo.mark_dynamic(t, dim, min=m, max=M) |
Traces dim as a symbolic SymInt \(s \in [m, M]\). Allocates upper-bound buffer \(M\) (rounded to 128) and lowers dynamic bounds via StableHLO GetDimensionSize / SetDimensionSize. |
Must specify max=M (num_dynamic_buckets \(\le 8\)). |
Variable-length forward passes or KV cache growth within a known ceiling. |
| 2. Automatic Compiler Bucketing | torch.compile(fn, backend="tpu", dynamic=None) |
When Dynamo detects a changing dimension on Step 2, torch_tpu automatically buckets that dimension in increments of bucket_size = 128 (or a single bucket bounded by \(2S\) when shape constraints rule that out). Pass dynamic=None explicitly: omitting it gives dynamic=False on TPU. |
bucket_size=128 (aligned to TPU lane width), default 1 bucket (max 8). |
General PyTorch models with mild input shape variation. |
| 3. vLLM Static Bucket Grid & Peer Replay | CompilationConfig.get_compile_ranges() -> [] / TPU_TOKEN_BUCKET_LINEAR=1 / VLLM_TPU_BUCKET_PADDING_GAP / TPU_PRECOMPILE_PEER_REPLAY=1 |
Disables TorchDynamo dynamic range tracing; pre-generates static compile_sizes (\([16, 32, 64, \dots, \text{max\_num\_batched\_tokens}]\)) and num_reqs_paddings (MIN_NUM_SEQS=8). Under TPU_PRECOMPILE_PEER_REPLAY=1, snake-deals buckets across 8 host ranks so 1 rank compiles and 7 peers replay from Tier-2 cache. |
Pads token array + slot mappings with dummy -1 / page-0 slots; TPU_PARALLEL_PRECOMPILE=1, TPU_PRECOMPILE_BIGGEST_FIRST=1. |
High-throughput vLLM-TorchTPU continuous batching & fast multi-rank warmup. |
4. SGLang Dual-Mode Bucketer & TpuGraphRunner |
Bucketer (PaddingMode.PAD_TOKENS vs PaddingMode.PAD_BATCH) + torch.compiler.set_stance("fail_on_recompile") |
Prefill (PAD_TOKENS): pads ragged total tokens (extend_num_tokens) to token buckets.Decode ( PAD_BATCH): pads active running requests (bs) to batch-size buckets. Enforces fail_on_recompile after warmup. |
Pre-warmed at server startup (--disable-preconnect-warmup to skip); uses cpu_export_jax_op for CPU-only JAX MLIR tracing. |
Low-latency SGLang-TorchTPU serving & speculative decoding (EAGLE). |
TPU KV cache layouts (5D, 6D, 4D SEQ_ALONG_LANE) and megakernels¶
Because TPU VMEM tiles are physically organized as 8 sublanes \(\times\) 128 lanes (HEAD_DIM_ALIGNMENT = 128), storing KV caches in naive GPU [num_blocks, 2, page_size, num_kv_heads, head_dim] format triggers unaligned VPU relayouts or wastes \(87.5\%\) of HBM when num_kv_heads_per_rank == 1 in FP8. Both SGLang-TorchTPU and vLLM-TorchTPU implement specialized TPU KV pool layouts:
| KV Pool Layout Variant | Engine Class & Flag | Physical Tensor Shape in TPU HBM | Hardware Tile Alignment & Memory / DMA Advantage |
|---|---|---|---|
1. 5D Token-Major (HEAD_ALONG_SUBLANE / BLNHC) |
SGLang: TpuFusedMHATokenToKVPool (default)vLLM: LBNHC / BLNHC (kv_packing = 32 // bits: 2 for BF16, 4 for FP8) |
[num_blocks, page_size, (2 * num_kv_heads) // kv_packing, kv_packing, head_dim_padded] |
Interleaves \(K\) and \(V\) along the sublane-packed head axis (num_kv_heads_x2) and pads head_dim to a multiple of 128 lanes for single-instruction VMEM vector loads in ragged_paged_attention_v3. |
2. 6D Block-Major (BlockMajorPoolLayout) |
SGLang: TpuBlockMajorMHATokenToKVPool (SGLANG_TPU_USE_BLOCK_MAJOR_KV=1)vLLM: BlockMajorPoolLayout |
[num_blocks, num_layers, page_size, (2 * num_kv_heads) // kv_packing, kv_packing, head_dim_padded] |
Places num_layers inside num_blocks so all layers of a KV page reside in one contiguous HBM row. Enables single-DMA cross-layer P/D transfer in Raiden and unifies Gated DeltaNet (GDN v3) recurrent state into the same paged pool in vLLM. |
3. 4D Sequence-Along-Lane (SEQ_ALONG_LANE / HND) |
SGLang: TpuSeqAlongLaneKVPool (SGLANG_TPU_USE_SEQ_ALONG_LANE_KV=1, page_size >= 256)vLLM: SEQ_ALONG_LANE (PallasBatchedRPAAttentionBackend) |
[num_blocks, 2 * num_kv_heads, head_dim_padded, page_size] |
Maps page_size (\(\ge 256\)) onto the 128-lane axis and head_dim onto the 8-sublane axis. When a model has 1 KV head per TP rank in FP8 (e.g., MLA / GQA at TP=8), avoids padding 1 head to 8 sublanes: cutting FP8 KV memory by \(50\%\) (\(256\text{ B/token}\) vs. \(512\text{ B/token}\)). |
4. Multi-Group Hybrid Pool (DeepseekV4 / Qwen3-Next) |
vLLM: DeepseekV4 5-Group KV Cache (sal/has/xla)SGLang: TpuUnifiedSWAKVPool + TpuMambaPool |
Separate typed pools for Full Attention, Sliding-Window Attention (SWA), and Recurrent/Linear State (GDN/KDA/Mamba) |
Prevents allocating full sequence pages for sliding-window layers or constant-size recurrent state buffers, and pairs with Raiden's 3-Engine Multi-Port DMA. |
Tip
Whole-Decoder Pallas Megakernels (Kimi-K3, GLM-5.3-Flash, Muse Spark, Qwen 3.5-397B-A17B):
Beyond individual @jax_op kernels (RPA v3, fused_ep_moe v2 with SparseCore ragged_gather_reduce_v2 via USE_MOE_SPARSE_CORE=1 / SGLANG_TPU_FUSED_MOE_SC_GATHER=1, and dual-chiplet TPU_MOE_HIERARCHICAL_EP=1), vLLM-TorchTPU compiles Whole-Decoder Pallas Megakernels (whole_decoder_megakernel) that fuse RMSNorm + QKV/MLA + RoPE + Attention + AllReduce + MoE/MLP into a single VMEM-resident persistent Pallas program. Google reports more than 700 tokens per second for a single user on Kimi-K3 (2.8T MoE) on Ironwood v7x, and 2.01 cents per million tokens for Qwen 3.5-397B-A17B on SemiAnalysis InferenceX 8K/1K, the lowest cost on that benchmark at publication (Announcing New vLLM and SGLang Inference Engines on TPU).
Why serving engines use CPU-resident page allocators and KVFreeFence¶
In GPU serving engines (vLLM/SGLang on CUDA), the paged KV cache allocator often stores free-page indices in a GPU tensor (torch.nonzero / boolean masks). On TPU, a free-page list kept as a device tensor would change shape at every page boundary and trigger recompiles, so SGLang-TorchTPU keeps it on the host. (chapter 19)
SGLang-TorchTPU solves this with two tightly coupled primitives:
TpuPagedTokenToKVPoolAllocator(CPU-Resident Page Table inallocator_tpu.py): All page allocation (alloc_extend,alloc_decode) and RadixCache prefix tree bookkeeping execute purely in CPU RAM (numpy/ CPUtorch.Tensor), passing static padded page-table indices (req_to_token) asynchronously to TPU SMEM via Host-to-Device DMA.KVFreeFence(held pages inkv_free_fence.py): Under overlap scheduling the scheduler processes result N-1 while forward N runs. A request that finished at N-1 is still in forward N's batch, so forward N still writes its last pages when they are freed. DMAs (HiCache host-to-device loads, KV arriving on a PD decode server) are not ordered after device compute, so a DMA into such a page could land first and be overwritten.KVFreeFenceholds pages freed while a forward is in flight (HeldPagesinallocator.held_pages, tagged with the latest formed forward) and releases them back tofree_pagesonce that forward's result is processed; allocations for a forward may borrow held pages, and any other allocation that runs short waits for the in-flight forwards:
Under overlap scheduling the scheduler handles result N-1 while forward N runs, and forward N still writes the last pages of a request that finished at N-1. KVFreeFence holds those pages until result N is processed: without the hold, a DMA into them (a HiCache host-to-device load, or KV arriving on a PD decode server) could land before forward N's write and be overwritten.
2.5 Distributed collectives and 6D parallelism¶
Prerequisites: the 2D/3D ICI torus topology (section 1.1) and the distributed primitives (section 1.3 B) in Fundamentals.
Covers: the three architectural differences between
tpu_distandNCCL,TORCH_TPU_SPMD_HANDSHAKE_STAGE("OFF","COMPILE_STAGE","DISPATCH_STAGE") and@spmd_safefor inlining collectives without ICI deadlocks, 6D parallelism withTorchTitan'sTPUTrainer/TpuGraphTrainer/LayerLoop, and RLHF/GRPO withMiles.
In one sentence¶
Cloud TPUs scale by separating high-bandwidth Inter-Chip Interconnect (ICI) torus rings (used for inner TP, CP, EP, and FSDP collectives) from Data Center Network (DCN) Ethernet (used for outer DP/PP over multi-pod slices), while torch_tpu exposes standard two-sided c10d collectives (tpu_dist), a one-sided window API (WindowTPU, whose peer ICI transfers are currently emulated with two-sided send and receive) and in-kernel remote copies (Pallas make_async_remote_copy).
Note
How it works: three differences between NCCL and tpu_dist collectives (TorchTPU distributed support):
- Pre-Initialization SliceBuilder Topology Discovery: Unlike
NCCL(which discovers peer GPUs dynamically insidedist.init_process_group),libtpu's PJRT client must know the physical ICI chip topology before the PJRT runtime initializes.torchrun(or callingtorch.tpu.distributed.set_tpu_launch_env()before starting the processes) exchangesTORCH_TPU_TOPOLOGYandTORCH_TPU_SLICEBUILDER_ADDRESSESacross hosts so every process binds to the global ICI torus at startup. - Sub-Group Collectives Lower to Global
replica_groups: InNCCL, creating a subgroup (dist.new_group(ranks)) allocates a separate isolated NCCL communicator. On TPU, the ICI routing tables are managed globally across the slice; when a subgroup collective executes,ProcessGroupTpulowers it to a single XLA collective instruction annotated withreplica_groups=[[r_0, r_1, ...], ...]across the global PJRT client. - SPMD Single-Program Requirement vs. MPMD Skinny Collectives: In
NCCL, Rank 0 can run anall_reduceinside a compiled graph while Rank 1 runs the matchingall_reduceeagerly, because both simply launch the same standalone CUDA ring kernel. On TPU, XLA embeds a compile-timechannel_idand collective schedule into thePJRT_LoadedExecutable. If Rank 0 runs an inlined collective inside a compiled graph while Rank 1 recompiles a different graph (or runs a standalone 1-op Skinny Collective), their XLA programs will mismatch and deadlock on ICI.
Warning
Common pitfall: why unsynced dynamic shapes deadlock inlined collectives
Suppose model = torch.compile(ddp_model, backend="tpu") is run with @spmd_safe (inlined collectives), and on Step 5:
- Rank 0 receives a batch of length \(S = 128\) (already cached \(\implies\) Cache Hit, immediately launches
Executable_128). - Rank 1 receives a batch of length \(S = 192\) (Cache Miss \(\implies\) compiles
Executable_192, or executes a different HLO schedule). Because Rank 0 is already waiting in theall_reducefused intoExecutable_128while Rank 1 is compilingExecutable_192, the slice will hang or time out. Solution: Either (a) ensure all ranks pad inputs to identical bucket shapes per step, or (b) when rank control flow or shapes can diverge dynamically, take the step out of@spmd_safeand setTORCH_TPU_SPMD_HANDSHAKE_STAGE="DISPATCH_STAGE", which recompiles with split collectives when the ranks disagree, or leave its collectives skinny.
Step 5 with both ranks inside @spmd_safe: rank 0 is already waiting in the all_reduce inside Executable_128 while rank 1 is still compiling a different executable, and the two collectives never match, so the slice hangs, times out or corrupts memory. Block widths are not measured.
Skinny collectives and @spmd_safe inlined collectives¶
By default each collective runs as its own skinny module between graph breaks, so the TensorCore waits while ICI works. Fused into one module, XLA can run the collective under compute that does not depend on it, and the step ends earlier; widths are not measured.
The three TORCH_TPU_SPMD_HANDSHAKE_STAGE modes¶
As described in TorchTPU distributed support and distributed.py, torch_tpu governs collective inlining via @torch.tpu.distributed.spmd_safe and TORCH_TPU_SPMD_HANDSHAKE_STAGE:
| Handshake Mode | Env Var / Decorator | Runtime Behavior | Host Overhead | When to Use |
|---|---|---|---|---|
"OFF" (Default Outside @spmd_safe) |
export TORCH_TPU_SPMD_HANDSHAKE_STAGE="OFF" (or @spmd_safe decorator) |
Outside @spmd_safe, collectives cause a graph break and run as Skinny Collectives (which can be offloaded to SparseCore via TORCH_TPU_INTERNAL_SKINNY_SC_OFFLOAD=1). Inside @spmd_safe, collectives are inlined with zero host handshake. |
Zero inside @spmd_safe; graph break outside @spmd_safe. |
Default mode; use @spmd_safe on verified SPMD training/serving steps. |
"COMPILE_STAGE" (Compile-Time Handshake) |
export TORCH_TPU_SPMD_HANDSHAKE_STAGE="COMPILE_STAGE" |
Inlines collectives into torch.compile and performs a cross-rank TCPStore verification once at compilation time to guarantee all ranks compiled the exact same HLO collective signature. It times out if only one rank recompiles, for example after a rank-specific shape change. |
Zero runtime host overhead after compilation; full XLA async overlap. | Recommended for production training (TorchTitan) and serving. |
"DISPATCH_STAGE" (Every-Step Handshake) |
export TORCH_TPU_SPMD_HANDSHAKE_STAGE="DISPATCH_STAGE" |
Compiles with fused collectives and checks agreement every time the executable is dispatched; if the ranks disagree, it recompiles with split (skinny) collectives. | Higher per call than COMPILE_STAGE. |
Debugging suspected rank divergence, dynamic shape mismatches, or collective hangs. |
Note
When the fingerprints differ, DISPATCH_STAGE recompiles with split collectives (split_compiler.py, _maybe_handshake_and_recompile); it does not raise an exception. The launcher is torch.tpu.distributed.set_tpu_launch_env() (TorchTPU distributed support, chapter 13).
6D parallelism (TorchTitan, vLLM, SGLang)¶
Sources: TorchTPU distributed support and the TorchTitan repository.
| Parallelism Axis | Variants Implemented in Stack | Collective Primitives Used | Optimal Hardware Placement | Key Architectural Advantage on TPU |
|---|---|---|---|---|
1. Data Parallel (DP / DDP) |
DDP, HSDP (Hybrid Sharded DP) |
all_reduce (bucketed gradients in backward) |
Outer mesh axis (DCN across slices or slow ICI wrap axis) | Tolerates higher latency via backward gradient bucketing overlap. |
2. Fully Sharded (FSDP) |
SimpleFSDP (DTensor graph) vs. FSDP2 (fully_shard eager hooks) |
all_gather (fwd/bwd weights) + reduce_scatter (bwd grads) |
Mid-tier ICI Torus Rings (1D or 2D sub-mesh) | SimpleFSDP traces all sharded parameters as DTensors inside a single XLA graph (SingleTraceTrainer), allowing XLA to schedule weight prefetches across the entire layer stack. |
3. Tensor Parallel (TP) |
Standard TP (ColwiseParallel/RowwiseParallel) & AsyncTP |
all_gather / reduce_scatter (or all_reduce) per attention/MLP block |
Innermost Mesh Axis (e.g., v7x intra-package \(600\text{ GB/s}\) D2D link + local ICI ring) |
AsyncTP splits [M, K] @ [K, N] into pipelined strips so ICI all_gather/reduce_scatter executes completely hidden behind MXU compute. |
4. Pipeline Parallel (PP) |
1F1B, Interleaved1F1B, DualPipeV, ZBVZeroBubble, PPWave, PPRing |
Point-to-point send / recv (collective_permute over ICI or DCN) |
Cross-pod DCN or long-hop Z-axis ICI | ZBVZeroBubble and DualPipeV decouple backward input gradients (\(B\)) from weight gradients (\(W\)) to drive pipeline bubble fraction toward \(0\%\). |
5. Context Parallel (CP) |
Ulysses (all_to_all heads), Ring (KV ring), HeadTail, PTRR, PCP (Prefill CP), DCP (Decode CP) |
all_to_all (Ulysses), collective_permute (Ring), all_gather (PCP) |
Fast intra-host or local 2D ICI sub-mesh | HeadTail and PTRR eliminate the \(50\%\) causal mask load imbalance of standard Ring Attention by pairing early and late sequence chunks on every rank. |
6. Expert Parallel (EP) |
Standard EP & Wide-EP (\(EP \in [8, 256]\)) with fused_ep_moe |
ragged_all_to_all (variable token counts per expert) + Pallas gmm |
2D/3D ICI Torus (SparseCore + TensorCore DMA) | Native XLA/Pallas ragged_all_to_all transfers only active tokens per expert over ICI without wasteful worst-case capacity padding. |
TorchTitan TPU trainers (TPUTrainer, TpuGraphTrainer) and the Miles RL loop¶
Sources: the TorchTitan repository and SGLang-TorchTPU: PyTorch-Native Production Serving on TPUs.
| Component / Optimization | Source File & Config Flag | Architectural Mechanism & Memory / Speed Impact |
|---|---|---|
TPUTrainer (Split Fwd/Bwd Mode) |
torchtitan/experiments/tpu/train.py (materialize_forward_before_backward=True) |
Inserts torch.ops.tpu.synchronize(loss, wait=False) between forward and loss.backward() in DeferAndFuse / hybrid mode so forward and backward compile into two bounded HLO graphs, plus CompiledGradNorm to keep L2 gradient clipping on-device. |
TpuGraphTrainer (Single-Graph AoT/JIT) |
tpu_graph_trainer.py (optimizer_compile="in_graph"|"separate_graph") |
Traces fwd + bwd (and optionally the functional optimizer step) into a single XLA HLO graph with buffer donation and TORCH_TPU_SPMD_HANDSHAKE_STAGE="COMPILE_STAGE". |
LayerLoop (scan) & scan_backward_patch |
layer_loop.py, scan_backward_patch.py (compile.enable_layer_loop=True) |
Stacks homogeneous Transformer layer weights along dim 0 and compiles 1 layer body via torch.ops.higher_order.scan (reducing compile time from \(O(L)\) to \(O(1)\)). scan_backward_patch replaces PyTorch's default torch.flip backward scan with direct reverse-indexed slicing, saving \(4.2\text{ to }10\text{ GB}\) of peak HBM. |
apply_bld_layout & tpu_flags.py |
bld_layout.py, tpu_flags.py |
Annotates [B, L, D] activations with custom layout [2, 1, 0] (L sublane-contiguous, D lane-contiguous) and enables XLA flags (SPARSECORE_COLLECTIVE_OFFLOAD, AsyncCollectiveFusion, LatencyHidingScheduler). |
Miles + SGLang-TorchTPU + TorchTitan (GRPO RL) |
SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs | Runs distributed GRPO RL where SGLang-TorchTPU generates rollouts (matching \(6\times\) H200 GPU reward curves on TPU v7x), TorchTitan updates policy weights, and updated weights synchronize via shared memory or disk; a direct ICI path is planned, measured at about 50 times faster than shared memory in a test (chapter 15). |
WindowTPU and rank-aligned Pallas meshes¶
Traditional two-sided collectives (send/recv, all_to_all) require both sender and receiver ranks to participate synchronously in the collective schedule. For irregular MoE routing, RL weight updates, or low-latency token dispatch, torch_tpu offers a one-sided programming interface at two levels (csrc/distributed/window_tpu.h, TorchTPU distributed support):
- Host/PyTorch level (
WindowTPU/SharedMemoryPool): Allocates a symmetric HBM buffer across the ranks of aProcessGroupTpuviaSharedMemoryPooland implements PyTorch'sc10d::Windowinterface (put,signal,wait_signal,map_remote_tensor). Host-to-device transfers are true one-sided DMA. Peer transfers over ICI are currently emulated with two-sided send and receive: the destination rank's CPU must callwait_signal()to receive the data, and non-zero target offsets are not supported for peer transfers. True one-sided RDMA over ICI is planned inwindow_tpu.h. - Kernel Level (
torch.tpu.pallas.get_pallas_mesh+pltpu.make_async_remote_copy): Inside a Pallas kernel, raw XLA physical device IDs may not match PyTorchdist.get_rank()indices unless aligned. Callingmesh = torch.tpu.pallas.get_pallas_mesh(axis_names=("x",))constructs a PyTorch-rank-aligned JAX/Pallas mesh so your kernel can passdevice_id_type=pltpu.DeviceIdType.LOGICALtopltpu.make_async_remote_copy(src_ref, dst_ref, send_sem, recv_sem, device_id=target_rank, device_id_type=pltpu.DeviceIdType.LOGICAL)and synchronize viapltpu.get_barrier_semaphore().
2.6 Distributed serving, routing and KV cache disaggregation (llm-d 1.0, vLLM, SGLang)¶
Prerequisites: the serving primitives (section 1.3 D/E in Fundamentals) and section 2.4's 5D/6D/
SEQ_ALONG_LANEKV cache layouts.Covers: an inference request across the seven functional pillars of
llm-d1.0 (Router,Model Servers,Disaggregation,KV Cache Management,Model Server Orchestration,Autoscaling, andBatch & Async Serving),Raiden(tpu-sync) three-engine multi-port DMA, and production TPU fleet benchmarks.
In one sentence¶
Modern LLM serving separates compute-bound Prefill from HBM-bandwidth-bound Decode across specialized TPU pools (DisaggregatedSet + LeaderWorkerSet) orchestrated by llm-d 1.0's Envoy + Endpoint Picker (EPP), which combines 3-tier FlowControl, online XGBoost LatencyPredictor sidecars, and real-time ZMQ KV-Cache Indexer + P2P KV-Cache Sharing, while Raiden (tpu-sync) streams and dynamically reshards multi-group KV caches across heterogeneous TP topologies over DCN/ICI.
Note
How it works: the seven functional pillars of llm-d 1.0 (llm-d Architecture):
- Router (
InferencePool+Proxy+EPP): Envoy Gateway invokes theEPP(ext_procFULL_DUPLEX_STREAMED), which runs 4 internal subsystems:Request Handler, 3-TierFlowControl(with in-flight eviction),Request Scheduler(ProfileHandler\(\to\)Filter\(\to\)Score\(\to\)Pick+ XGBoostLatencyPredictor), and the pluggableDataLayer(Source -> Extract -> Attribute). - Model Servers (
vLLM-TorchTPU,SGLang-TorchTPU,TRT-LLM): Expose OpenAI-compatible HTTP endpoints, Prometheus saturation metrics (kv_cache_usage_perc, waiting/running queues), and ZMQ KV-Events (:5557/:5556). In multi-process DP mode,EPProutes directly to individual per-rank ports (8000..8007). - Disaggregation (
P/D Disaggregation&Wide-EP): Splits Prefill (TP/PCP) and Decode (TP/DP-attention +Wide-EPMoE) across specialized pools coordinated by a Decode Pod Routing Proxy Sidecar (vLLM nixlv2sequential 2-phase vs.SGLangconcurrentbootstrap_room). - KV Cache Management (
KV-Cache Indexer,KV Offloader,P2P KV-Cache Sharing): Tracks global prefix hashes in real time, offloads evicted blocks to Host CPU DRAM / Lustre / Mooncake, and pulls cached blocks CPU-to-CPU across peers (P2P KV-Cache Sharing) over NIXL/UCX RDMA without interrupting the source pod's TPU/GPU. - Model Server Orchestration (
LeaderWorkerSet&DisaggregatedSet): Gang-schedules multi-host TPU slices (exclusive-topology), manages independent role scaling across rolling updates viaDisaggregatedSetRoleScaler, and accelerates cold starts to \(<10\text{ s}\) viaFMA+ModelExpress. - Autoscaling (
KEDA + EPP Metrics+Kueuevs. DeprecatedWVA): Scales replicas using 5 real-time EPP signals (inflight,queue,saturation,token backlog,estimated latency) with cross-workload quota borrowing via Kueue. - Batch & Async Serving (
Batch Gateway&Async Processor): Processes asynchronous/v1/batchesworkloads through a 6-stagellm-d-asyncpipeline with 12 gate types and RL Co-operative Time-Slicing.
The seven pillars of the list are the router, the model servers, disaggregation (drawn inside the model servers), KV cache management, orchestration, autoscaling, and batch and async serving. Requests from clients and the batch layer reach the proxy, which asks the EPP for a pod and forwards to the model servers; the indexer turns the servers' KV events into prefix matches, and autoscaling scales the orchestrated roles from the EPP's metrics.
Warning
Common pitfalls: llm-d 1.0 in production
- Pitfall 1: "I should deploy
Workload Variant Autoscaler (WVA)for newllm-d 1.0production clusters." Fact: Inllm-d 1.0,WVAis deprecated (Workload Variant Autoscaler (WVA): Deprecated). The recommended production autoscaling stack is KEDA with EPP Metrics + Kueue (KEDA with EPP Metrics), which scales directly on EPP's 5 request/token/latency signals and rebalances hardware quota across priority cohorts. - Pitfall 2: "Strict cache-affinity routing (
prefix-cache-scoreralone) is always optimal when KV caches are offloaded." Fact: Strict affinity concentrates long-prefix requests onto a single hot replica, spiking its queue wait time and TTFT. EnablingP2P KV-Cache Sharing(p2p-source-producerwithminCachedTokenDelta) +prefix-cache-affinity-filter(\(\epsilon\)-greedy exploration + TTFT load gate) allows less-loaded replicas to pull cached KV blocks CPU-to-CPU from the peer's DRAM over RDMA: achieving \(1.4\times\) higher throughput than load-aware routing and \(2.2\times\) higher than strict affinity (P2P KV-Cache Sharing). -
Pitfall 3: "vLLM and SGLang use the same P/D orchestration handshake inside the Decode Routing Proxy Sidecar." Fact: The Decode Pod's Routing Proxy Sidecar (Disaggregated Serving) implements two distinct engine protocols:
-
vLLM(nixlv2, Sequential 2-Phase): Sidecar sends request (max_tokens=1) to Prefill \(\to\) Prefill computes KV and returnskv_transfer_params\(\to\) Sidecar forwards original request +kv_transfer_paramsto local Decode worker, which pulls KV over NIXL/Raiden. SGLang(bootstrap_room, Concurrent): Sidecar generates a uniquebootstrap_roomID and dispatches the request concurrently to both Prefill (bootstrap_host,bootstrap_port,bootstrap_room) and local Decode, which find each other through the prefill's bootstrap server (/route) and then move the KV directly between the pods.
The routing sidecar runs in the decode pod. For vLLM it waits for the prefill's kv_transfer_params before it sends the request to its decode worker; for SGLang it sends both requests at once with the same bootstrap_room, and the two workers find each other through the prefill's bootstrap server.
Request path through llm-d 1.0: routing, flow control and disaggregated P/D¶
The proxy asks the EPP where to send each request and gets back a decode pod plus the chosen prefill pod in a header; the sidecar in that decode pod then runs the P/D handshake with the prefill worker, and tokens flow back the way the request came. The EPP's data layer is fed by the pods' metrics and KV events, not by the request, and the latency predictor gives the scheduler predicted TTFT and TPOT.
KV moves from prefill to decode, and the decode pulls it: over NIXL on GPUs, and on TPU over Raiden, whose three-engine layout (below) is SGLang-TorchTPU's.
llm-d router internals: EPP, FlowControl, DataLayer and LatencyPredictor¶
Sources: Endpoint Picker (EPP), Flow Control, llm-d Data Layer and Latency Predictor.
When flow control is enabled it decides which request goes next, by priority band, then fairness between flows, then order within a flow, and holds it until the saturation detector says the pool has capacity; the scheduler then decides where it goes. Both read the endpoint attributes the data layer keeps up to date, and the latency predictor adds predicted TTFT and TPOT for the filters and scorers.
| Router Subsystem | Core Pipeline / Formula | Key Plugins, Headers & Parameters | Architectural Behavior & SLO Guarantee |
|---|---|---|---|
1. FlowControl (3-Tier Dispatch & In-Flight Eviction) |
Tier 1: Priority Band (InferenceObjective.priority)Tier 2: FairnessPolicy on FlowKey = (FairnessID, Priority)Tier 3: OrderingPolicy within flow queue |
• Header: x-llm-d-inference-fairness-id• Tier 2: round-robin-fairness-policy, global-strict-fairness-policy• Tier 3: fcfs-ordering-policy, edf-ordering-policy, slo-deadline-ordering-policy• Detector: utilization-detector vs. concurrency-detector• enableEviction: true |
Holds requests in EPP queues when SaturationDetector reports pool saturation. When enableEviction: true, incoming high-priority requests (priority >= 0) evict in-flight sheddable requests (priority < 0), returning HTTP 429 with x-llm-d-request-dropped-reason: evicted. |
2. DataLayer (Source -> Extract -> Attribute) |
Decouples telemetry collection from scheduling plugins via typed endpoint attributes | • PollingDataSource (metrics-data-source Prometheus scraper)• NotificationSource (k8s-notification-source Pod/CRD informer)• EndpointSource (endpoint-notification-source)• core-metrics-extractor |
Continuously populates per-pod KV usage, active request counts, waiting queue depth, and loaded LoRA adapters with zero lock contention on the hot scheduling path. |
3. LatencyPredictor (Online XGBoost Sidecars) |
Colocated 1 Training Server + \(N\) Prediction Servers inside the EPP pod training online XGBoost regression models | • Env: LATENCY_RETRAINING_INTERVAL_SEC=10, MODEL_SYNC_INTERVAL_SEC=30, streamingMode: true\|false• Headers: x-prediction-ttft-slo, x-prediction-tpot-slo• Plugins: prefix-cache-affinity-filter, slo-headroom-tier-filter, latency-scorer (least bin-pack vs most spread), latency-slo-admitter, weighted-random-picker |
Predicts per-pod \(\widehat{\text{TTFT}}(p)\) and \(\widehat{\text{TPOT}}(p)\) from (kv_cache_perc, input_tokens, waiting_reqs, running_reqs, prefix_hit_ratio) using stratified residual bucketing; admits/scores pods by headroom \(\Delta = \text{SLO} - \widehat{L}(p)\). |
4. Request Scheduler (Filter -> Score -> Pick) |
$\(S(p) = \sum_i w_i s_i(p)\)$ across Prefix Cache, KV Utilization, Queue, and Latency scorers | • prefix-cache-scorer (gpu=1.0, cpu=0.8 tier weights)• kv-cache-utilization-scorer, queue-scorer, lora-affinity-scorer• disagg-profile-handler + Decider (prefix-based-pd-decider, always-disagg-pd-decider) |
Evaluates whether to disaggregate (e.g., if uncached prompt tokens \(>\) threshold), picks the optimal Prefill and Decode pods, and injects x-llm-d-prefiller-host-port for the Decode sidecar. |
KV cache management: KV-Cache Indexer, KV Offloader and P2P KV-Cache Sharing¶
Sources: KV-Cache Indexer, KV-Cache Offloading and P2P KV-Cache Sharing.
With vLLM's OffloadingConnector, blocks reach the secondary tiers only through host DRAM, and come back the same way. The PCIe hop (32 GB/s on v6e) is roughly 50 to 500 times slower than HBM (1,638 GB/s on v6e to 7,380 GB/s on v7x).
| KV Subsystem | Architecture & Protocol Mechanics | Supported Backends / Connectors & Critical Flags |
|---|---|---|
KV-Cache Indexer (ZMQ :5557 / :5556) |
1. token-producer: Calls vLLM /v1/chat/completions/render (or local HF tokenizer) to obtain exact token IDs and multimodal extra_keys.2. precise-prefix-cache-producer: Computes cumulative rolling block hashes (including LoRA adapter ID) and queries the global index; supports speculativeIndexing: true (inserts speculative entries with speculativeTTL: 2s before BlockStored arrives to prevent thundering-herd misses).3. ZMQ Event Stream: Pods publish BlockStored, BlockRemoved, and AllBlocksCleared over ZMQ (:5557 default / :5556, centralized vs. pod-discovery mode).4. prefix-cache-scorer: Scores pods by longest consecutive causal block chain weighted by memory tier (gpu: 1.0, cpu: 0.8). |
3 Index Backends: • Two-Level LRU In-Memory (default fast concurrent map) • Cost-Aware Ristretto (TinyLFU admission + memory bound) • Redis / Valkey (shared state across multi-replica EPPs) |
KV Offloader (3-Tier Storage Hierarchy) |
Asynchronously offloads evicted KV blocks from Tier-1 TPU HBM (1,638 to 7,380 GB/s per chip, v6e to v7x) \(\to\) Tier-2 Host CPU DRAM (PCIe, about 16 GB/s per TPU, 32 GB/s on v6e) \(\to\) Tier-3 secondary tiers (a shared filesystem such as Lustre, an object store, peers' CPU RAM, or a Mooncake store; throughput depends on the system), overlapping prefix prefetching with layer-0 compute. | 4 Connector Paths: • Native vLLM OffloadingConnector: CPUOffloadingSpec + TieringOffloadingSpec (fs, obj, p2p) + background PVC Evictor (note: pass --no-disable-hybrid-kv-cache-manager for hybrid models like Gemma 4).• SGLang HiCache: TpuDMAHiCacheController async HBM \(\leftrightarrow\) Host DRAM DMA.• MooncakeStoreConnector: embedded or standalone-store RDMA/TCP pool (requires PYTHONHASHSEED=0 across all pods); its transfer engine moves registered accelerator or CPU regions directly into the pool, not through host DRAM as the tiers above.• TPURaidenOffloadingConnector: vLLM-TorchTPU's own offloading connector, registered by its TPU platform. |
P2P KV-Cache Sharing (CPU-to-CPU RDMA Pull) |
When Pod \(A\) has a cached prefix in its Host CPU DRAM (MEDIUM_CPU) but is compute-saturated, EPP's p2p-source-producer (minCachedTokenDelta) routes the request to an idle Pod \(B\) along with Pod \(A\)'s source metadata (x-p2p-kv-source). Pod \(B\) pulls the KV blocks CPU-to-CPU over NIXL/UCX RDMA from Pod \(A\)'s DRAM into its own TPU/GPU without touching Pod \(A\)'s accelerator. |
Delivers \(1.4\times\) higher throughput than load-aware routing and \(2.2\times\) higher than strict cache affinity under skewed shared-prefix workloads. |
Disaggregated prefill/decode and Raiden (tpu-sync) three-engine transfers¶
Sources: sglang_tpu/disaggregation/raiden/conn.py and vllm_torchtpu/distributed/kv_transfer/. The three-engine layout and the two cases below are SGLang-TorchTPU's; vLLM-TorchTPU's Raiden connector names its pools by tag and reshards through its Raiden controller (or the in-engine store).
-
Why
Raidenruns three transfer engines per worker: Modern frontier models (DeepSeek-V3.2/V4,Qwen3-Next,Gemma 4,GPT-OSS) combine multiple attention/state mechanisms with incompatible tensor shapes. In SGLang-TorchTPU,Raidenstarts up to threetpu_syncKVCacheManagerengines per rank on consecutive port offsets from a base port ofSGLANG_RAIDEN_KV_PORT(default 31000) + 6 × the rank's node worker rank:- Engine 1 (Base Port
+0/+1, Primary Full Attention KV Pool): Transfers standard 5D/6D/SEQ_ALONG_LANEpaged KV blocks. During chunked prefill, Decode pulls each chunk's KV pages incrementally as each chunk commits (overlapping DCN transfer with subsequent prefill chunks) and automatically skips prefix pages that Decode already holds in its local RadixCache. - Engine 2 (Port
+2/+3, Hybrid Sliding-Window AttentionSWAKV Pool): Transfers compact sliding-window KV pages (the SWA sub-pool's layers) without padding to full sequence length. - Engine 3 (Port
+4/+5, Hybrid Recurrent / Linear Attention State Pool): Transfers constant-size recurrent state buffers (GDN or KDA state rows inTpuMambaPool, or DeepSeek-V4 compressor state).
Each rank runs one Raiden engine per KV pool it has, each on its own pair of control and data ports, so a hybrid model's sliding-window pages and recurrent or compressor state travel separately from its full-attention pages. The base port defaults to 31000, ranks on one host sit six ports apart, and each engine stages HBM to host, moves pages over the network, then copies host to HBM.
- Engine 1 (Base Port
-
Consumer pull for matching topologies, strided push resharding for different TP sizes:
- Case 1, the same attention TP on both sides (for example TP=8 into TP=8): consumer pull, staged through host memory on both sides. Prefill rank i registers its pages for reading; decode rank i sends a pull request, gets back the page ids and the prefill's Raiden endpoint, and starts the read as each prefill chunk commits.
- Case 2, decode attention TP smaller than prefill attention TP (for example TP=16 into TP=8, or attention TP 8 into attention TP 4 with DP=2): strided push resharding along the KV head dimension. With 16 KV heads, prefill rank r (TP=16) holds head r and decode rank k (TP=8) holds heads 2k and 2k+1. Prefill rank 2k pushes its head to decode rank k at offset 0, and prefill rank 2k+1 pushes its head one head further on (one head's K and V bytes); the per-token stride is two heads, so the pages arrive already in the decode layout. Push resharding moves full-attention and sliding-window pages only (no MLA, GDN or KDA state) and needs whole 32-bit head packs, so FP8 KV needs an even head count per rank. A decode attention TP larger than the prefill's is not covered.
When both sides shard the heads the same way, each decode rank pulls its peer's pages whole. When the decode has fewer ranks, two prefill ranks feed each decode rank and push their head into its pages at offset 0 or one head further on (this needs BF16 KV: FP8 packs two heads per word), so the pages arrive in the decode layout; both paths stage through host memory.
Model server orchestration (LWS, DisaggregatedSet), autoscaling and batch serving¶
Sources: LeaderWorkerSet (LWS), DisaggregatedSet, KEDA with EPP Metrics, Batch Gateway Architecture and Async Processor Architecture.
| Pillar | Core CRD / Component | Key Spec Fields, Policies & Operational Mechanics |
|---|---|---|
1. LeaderWorkerSet (LWS) |
leaderworkerset.x-k8s.io/v1 |
• Atomic Multi-Host Gang Unit: Composes a leader + \(N-1\) workers (StatefulSet or Hash Deployment mode) with startupPolicy: LeaderCreated\|LeaderReady and RecreateGroupOnPodRestart.• TPU Topology Pinning: Annotate leaderworkerset.sigs.k8s.io/exclusive-topology: cloud.google.com/gke-nodepool and subGroupPolicy (subGroupSize, LeaderWorker|LeaderExcluded) for sub-slice TP/PP placement.• Rollout deadlock: When simultaneously halving size per group and doubling replicas on a full cluster, scale down or use maxSurge: 0 first to avoid gang-scheduling deadlock. |
2. DisaggregatedSet |
disaggregatedset.x-k8s.io/v1 & DisaggregatedSetRoleScaler |
• Multi-Role Slice Orchestration (KEP-766/846/848/849/960/1022): Manages child LWS per role named <ds>-<slice>-<rev>-<role> (prefill, decode) with spec.slices, subRoles (heterogeneous hardware mixes), and placementPolicy: None\|ExclusiveSlice\|ExclusiveTopology.• Coordinated Rolling Updates: Drains Decode pods before terminating paired Prefill pods; disaggregatedset-rollout-screener isolates revisions in EPP; DisaggregatedSetRoleScaler provides a stable scaleTargetRef across revision rollouts. |
3. Autoscaling (KEDA + EPP + Kueue) |
KEDA ScaledObject + EPP Metrics (Recommended) vs. WVA (Deprecated) |
• KEDA + EPP (5 Signals): Scales Prefill and Decode DisaggregatedSetRoleScaler targets using inflight_requests, queue_size, saturation, token_backlog, and estimated_latency.• Kueue Cohort Quota Rebalancing: Dynamically lends spare TPU quota from batch/low-priority cohorts to interactive P/D pools during traffic spikes. • WVA (Deprecated): Legacy 4-stage (Collect \(\rightarrow\) Analyzer \(\rightarrow\) Optimizer \(\rightarrow\) Enforcer) controller using V1 percentage / V2 token min(k1, k2) saturation and Kalman-filter M/M/1/k SLO analyzers. |
4. Batch Gateway & Async Processor |
/v1/files, /v1/batches + llm-d-async (6-Stage Pipeline) |
• Batch Gateway: Stateless OpenAI Batch API server backed by PostgreSQL/Redis/S3 with two-level (global + per-model) concurrency limits and tenant isolation.• Async Processor (llm-d-async): 6-stage pipeline (Queue Gate & Poll -> Merge [random-robin / 6-lane tier-priority] -> Worker Pool Admission Gate -> Transform -> Dispatch -> Result) with 12 gate types (prometheus-saturation, redis-leased-rate, wait-on-refuse, tier-priority-admission).• RL Co-operative Time-Slicing: Interleaves async batch/RL rollout traffic into online serving troughs via tier-priority negative priority bands + FlowControl eviction. |
Gates act twice, before messages are polled and before a worker pool admits them, so batch work only reaches the router when there is room; a refused message goes back to its queue. A retryable failure is re-queued with backoff, while a success or a final error is written to the result queue.
Published fleet results (llm-d 1.0, vLLM-TorchTPU, SGLang-TorchTPU)¶
Sources: Announcing llm-d 1.0: Open distributed inference for agents on Google Cloud TPUs and GPUs, Introducing vLLM TorchTPU and SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs.
| Workload / Production Deployment | Hardware & Stack Configuration | Throughput, Latency & Cost |
|---|---|---|
Agentic Coding (Qwen3-Coder-480B) |
Ironwood TPU v7x + llm-d 1.0 (Prefix-Aware Routing + Host DRAM KV Offload) |
>85% reduction in median TTFT and 2.4x higher throughput vs. standard Kubernetes Service load balancing. Measured (June to July 2026) on the JAX tpu_inference backend; vLLM-TorchTPU results are still being collected (chapter 20). |
Cost-Efficiency & Agentic Benchmark (Qwen 3.5-397B-A17B) |
Ironwood TPU v7x + vLLM-TorchTPU (fused_ep_moe + Pallas Megakernels) |
2.01 cents / 1M tokens on SemiAnalysis InferenceX 8K/1K and 0.83 cents on AgentX, each the lowest cost per million tokens on that benchmark at publication (Introducing TorchTPU). |
Interactive MoE (Kimi-K3 2.8T) |
Ironwood TPU v7x + vLLM-TorchTPU Whole-Decoder Pallas Megakernel |
>700 tokens/sec per user single-stream/low-batch interactivity. |
| Google Cloud Vertex AI / Gemini on GKE Inference Gateway | GKE Inference Gateway (llm-d EPP + KV-Cache Indexer) |
Doubled prefix cache hit rate from 35% to 70%, cut coding agent TTFT by >35%, and cut P95 TTFT by >50%. |
| 17,000-Node Multi-Region MoE Fleet | 3-Cluster Multi-Region GKE + llm-d 1.0 + LeaderWorkerSet |
2.9x throughput scaling across 3 regions with 99.9% request success rate and <1% routing overhead. |
| ZenteiQ Production TPU Fleet | 1,000 Cloud TPU v6e (Trillium) accelerators + llm-d |
>4x higher aggregate throughput (1.47B \(\to\) 5.97B tokens/day). |
Reinforcement Learning (GRPO with Miles) |
Ironwood TPU v7x + SGLang-TorchTPU (Rollouts) + TorchTitan (Trainer) |
Matches \(6\times\) H200 GPU reward convergence curves. Weights sync through shared memory or disk; a direct ICI sync is planned (chapter 15). |





















