Memory model, storage and views¶
Prerequisites: The TorchTPU stack and the CUDA translation table, Execution model: eager modes, deferred ops, torch.compile
On CUDA, PyTorch's memory model and the hardware's agree: a storage is a pointer and a byte count, a view is a new set of strides over the same bytes, an in-place op overwrites those bytes, and clone() costs a copy. On a TPU every one of those statements is false underneath, and TorchTPU spends a lot of machinery making them look true. The TPU stores arrays as 2D tiles, not as a flat byte array; XLA's input language never mutates a value; and a buffer is always typed and shaped. The result is that the same PyTorch code computes the same values, but at different costs: views that were free can cost a copy, copies that were expensive can be free, a one-row write can briefly double the memory of a large tensor, and an innocent shape can occupy several times its logical size in HBM. This chapter explains the mechanism behind each of those, shows how to predict padding from a shape, and ends with the measurements that tell you where your HBM and your copies actually went.
What this chapter covers¶
- What
torch.UntypedStorage.data_ptr()points at on TorchTPU, and how aDeviceBufferRefmakes one in-place write visible to every view of a storage. - View decomposition: how TorchTPU turns a strided view into StableHLO ops, and why a view that is free on CUDA can cost a relayout copy on a TPU.
- Functionalization of in-place ops, when buffer donation keeps them in place, and why a partial write can cost a copy of the whole storage.
- Padded shape, padded bytes and utilization of a tensor from the tile rule, and what they mean for shapes and layouts.
- Hidden copies and memory spikes in a step, and verifying a fix with the
torch.acceleratormemory APIs, XProf and HLO dumps.
Two readings of a tensor¶
The TorchTPU memory model documentation starts from a distinction that CUDA lets you ignore. A torch.Tensor is two things at once:
- A physical access pattern. Sizes, strides, a storage offset and an element type, which together map an index tuple to a byte offset in the 1D buffer behind the tensor.
- A logical value. A mathematical array. When you multiply two tensors, what matters is the result's values and shape, not which strides it was produced with.
On CUDA the physical reading is the real one: a CUDA kernel receives the strides and computes byte offsets per thread at run time, and a CUDA buffer is a 1D byte array that any thread can read at any offset. On a TPU neither holds. The documentation is direct about the reasons: TPU memory is laid out as two-dimensional register-aligned tiles, not 1D byte arrays, and the TensorCore has no threads and is poor at random access. XLA's model is declarative instead: a StableHLO program describes the logical output, and XLA compiles it for one TPU generation.
TorchTPU's promise follows from this. The logical behaviour of PyTorch code is preserved; the physical behaviour is not. Shared-storage views, as_strided, in-place updates and out= arguments all produce the same values on a TPU as on CUDA. What changes is what each one costs. The rest of the chapter goes through that cost, starting with where the bytes are.
Storage: what data_ptr() points at¶
A torch.UntypedStorage is, in the documentation's words, little more than a memory address (data_ptr()) and a size in bytes (nbytes()). That is enough for the CPU and CUDA. It is not enough for XLA, where a buffer is always well typed and has a known multi-dimensional shape, because a TPU's memory layout depends on both.
TorchTPU adds one layer of indirection. On a TPU, data_ptr() does not point into device memory. It points at a location in host memory that holds metadata about the TPU buffer. The documentation calls this the key to TorchTPU's operation: everything in this chapter, from view decomposition to buffer donation, works by reading or changing that metadata.
The extra hop on the right is the whole trick: because PyTorch only ever holds a pointer to metadata, TorchTPU can replace the device buffer underneath without PyTorch noticing.
The objects behind the pointer¶
The documentation stops at "metadata". The TorchTPU source (csrc/eager/device_buffer.h) names the objects, and their comments describe the chain:
- PyTorch's
c10::StorageImplholds ac10::DataPtr, and on a TPU that DataPtr holds a pointer to aDeviceBufferRef. Whatdata_ptr()returns is a host address in this chain, never a device address. - A
DeviceBufferRefis "nothing more than" a shared pointer to aDeviceBufferListplus an index into it. A list rather than a single buffer, because one op can have several outputs. - The
DeviceBufferListholds the data, in one of a few states: a DeferredOp that has not run yet, a pending transfer or execution, or a materialized XLAPjRtBufferin HBM.
Two properties of the chain explain most of what follows. A DeviceBufferRef value is immutable: its own interface cannot make it point at a different buffer. An in-place write instead overwrites the DeviceBufferRef stored at the address the storage's c10::DataPtr holds (OverwriteDataPtr in csrc/eager/tensor_to_buffer.cc). The address, and so data_ptr(), stays the same, while the buffer behind every tensor that shares the storage changes.
Everything above the teal box lives in host memory, and data_ptr() returns an address in this chain, never a device address. A tensor and its transposed view share one storage. An in-place write produces a new buffer and replaces the DeviceBufferRef that the storage's c10::DataPtr points at, at the same address, so data_ptr() does not change and every tensor that shares the storage sees the write.
The header gives each state a predicate (is_placeholder(), is_deferred(), is_transferring(), is_executing(), is_materializing(), is_materialized()):
| State | What the buffer list holds | When you see it |
|---|---|---|
| Deferred | A DeferredOp that has not started materializing | Eager ops before a materialization point (chapter 4) |
| Pending transfer | Nothing yet; a host-to-device copy will fill it | A host-to-device transfer held back by a torch.Event.wait() |
| Pending execution | Nothing yet; a compiled executable will fill it | Outputs of a torch.compile executable that has been enqueued |
| Materializing, materialized | One or more PjRtBuffers in HBM, or an error |
After the TPU has produced the data |
| Placeholder | Never any data | Stands for an argument of a compiled executable in compiled mode; a placeholder never materializes |
In the header's own words, a placeholder "represents data that will be provided as an argument to a compiled executable, but is not actually available and will never become materialized".
Two more fields in the same header matter for memory: size_bytes() is the logical size from shape and element type, and pjrt_buffer_size() is "the number of physical bytes backing this buffer". The difference between the two is padding, the subject of the next section.
Tiles: how a TPU lays out an array¶
Chapter 1 introduced the VPU as a 2D SIMD unit of shape (8, 128): 8 sublanes by 128 lanes. That shape is also the natural tile for data. This book models the layout with one rule, the one used in TorchTPU performance: execution modes, XProf and Pallas kernels: the last two dimensions of every array are padded to whole tiles of 8 sublanes by 128 lanes of 32-bit words. Narrower types pack several values into each 32-bit word, so a tile holds more rows of them:
| Element size | Examples | Values per 32-bit word | Tile in elements (rows, lanes) |
|---|---|---|---|
| 4 bytes | float32, int32 |
1 | (8, 128) |
| 2 bytes | bfloat16, float16, int16 |
2 | (16, 128) |
| 1 byte | int8, float8 |
4 | (32, 128) |
Leading dimensions are not padded; each one just multiplies the number of padded 2D slabs. For a shape \((\ldots, R, C)\) and a tile \((t_r, 128)\):
Predict before you look: a (20, 200) float32 tensor holds 4,000 numbers. How many slots does it occupy?
Watch the bottom row of tiles. In float32 it carries 4 of 8 rows; in bfloat16 the tile is 16 rows tall and carries 4 of 16. Halving the bytes per element does not halve the padded footprint: 24,576 bytes in float32, 16,384 in bfloat16.
The answer is 6,144 slots: the shape pads to (24, 256), three tiles down and two across, and 4,000 of the 6,144 slots hold data. Utilization is 65.1%, and the padding overhead (extra bytes over logical bytes) is 53.6%. In bfloat16 the same shape pads to (32, 256), so utilization drops to 48.8%.
The companion script implements the rule exactly as stated and refuses element sizes the rule does not cover:
$ python code/ch05_memory/padding.py --cpu-smoke
1. Tile padding (rule: last two dims padded to (8 * 4 / dtype_bytes, 128) elements)
shape and dtype tile padded shape overhead utilization
(20, 200) float32, example (8, 128) (24, 256) 53.6% 65.10%
(20, 200) bfloat16 (16, 128) (32, 256) 104.8% 48.83%
(4096, 4096) float32, aligned (8, 128) (4096, 4096) 0.0% 100.00%
(4097, 4097) float32, +1 cliff (8, 128) (4104, 4224) 3.3% 96.83%
(1024, 1, 1) float32, worst case (8, 128) (1024, 8, 128) 102300.0% 0.10%
NCHW (32, 512, 7, 7) bfloat16 (16, 128) (32, 512, 16, 128) 4079.6% 2.39%
NHWC (32, 7, 7, 512) bfloat16 (16, 128) (32, 7, 16, 512) 128.6% 43.75%
dtype_bytes=8: rejected (no rule in the model)
from padding import padded_shape, padding_overhead # code/ch05_memory/padding.py
padded_shape((20, 200), 4) # (24, 256)
padding_overhead((20, 200), 4) # 0.536: 2,144 extra elements over 4,000
padded_shape((20, 200), 2) # (32, 256)
Three cases in that table deserve a sentence each. A (4096, 4096) float32 matrix is exactly aligned; adding one row and one column pads it to (4104, 4224) and costs 2,199,548 extra bytes, about 2.1 MiB. A (1024, 1, 1) tensor is the worst case for this rule: each (1, 1) slab is padded to a full tile, so 1 slot in 1,024 holds data. And a convolution activation in NCHW order puts the 7x7 spatial dimensions in the two minor positions, where they waste almost the whole tile. That is the usual reason to use memory_format=torch.channels_last, and the model shows how much it recovers (worked problem 4 goes further).
The chart shows the pattern behind these numbers. Utilization is a sawtooth in each minor dimension: it reaches 100% at every multiple of the tile and drops just after it.
The drops get smaller as the dimension grows, so padding matters most for small minor dimensions: head dimensions, ragged batch tails, short sequences and narrow feature sizes. The right panel is why bf16 and int8 tensors want their second-to-last dimension in multiples of 16 and 32.
The rule is a model; XLA picks the layout
The tile rule is a model of the layout, not a readout of it. XLA chooses each array's layout itself, and for 2-byte and 1-byte types the tiling it uses in HBM can differ from the packed (16, 128) and (32, 128) tiles, so the real HBM footprint of a narrow type may be smaller than the rule predicts. The TorchTPU documentation itself gives no tile sizes. On a TPU, ask XLA what it chose: the Experimental torch.tpu.get_device_layout_if_materialized(t) returns the (minor_to_major, tiles, element_size_in_bits) fields of a materialized tensor's TpuLayout, or None if its buffer does not exist yet. (The TpuLayout docstring's own example uses tiles=[[16, 128], [2, 1]].) The TPU path of padding.py prints the model's tile next to XLA's for five tensors. Use the model to compare shapes; use the layout API when the exact byte count matters.
The practical rules are short: keep the last dimension a multiple of 128 and the second-to-last a multiple of 8 (16 for bf16, 32 for 8-bit types), and squeeze or reshape away trailing singleton dimensions before they reach a hot loop.
Views: decomposition, and why views are not free¶
On CUDA, a view's strides go straight to the kernel. On a TPU a 1D stride description is meaningless for 2D tiled memory, so TorchTPU translates. Most view operations have a direct StableHLO equivalent: reshape, transpose, slice and broadcast. When TorchTPU meets an arbitrary stride pattern, it performs view decomposition: it reinterprets the strides, offset and element type as a sequence of those logical operations that puts every element in the right place.
The memory model documentation's example builds the same tensor two ways:
base = torch.arange(10, dtype=torch.float) # [0., 1., ..., 9.]
physical_view = base.as_strided(size=(2, 2, 2), stride=(2, 3, 0), storage_offset=1)
# StableHLO: slice, reshape, slice, transpose, reshape, broadcast_in_dim
logical_view = base[1:].view(3, 3)[:2, ::2].t().unsqueeze(-1).expand(2, 2, 2)
# both: [[[1., 1.], [4., 4.]], [[3., 3.], [6., 6.]]]
Follow the stride column: each step produces a plain PyTorch view, and the last one has exactly the strides (2, 3, 0) and offset 1 of the as_strided call. The teal cells never change after step 3: decomposition chooses which storage elements to read, and the later steps only rearrange them.
padding.py --cpu-smoke runs the six steps, prints the strides after each one, and checks that the result equals the as_strided view.
Logical equivalence is not equal cost¶
The documentation's warning is the most important sentence about views on TPU: a reshape or transpose may, in some cases, require a full copy to map from one register-aligned layout to another. On CUDA a transpose is new strides over the same bytes. On a TPU, an array tiled along its last two dimensions cannot be read along a different pair of dimensions without moving data into a new tiled layout. Views are not free on TorchTPU, and the documentation's takeaway is to prefer contiguous tensors when possible.
Three places where this shows up in real code:
- Permutes in the forward pass, copies in the backward. The TorchTPU FLUX case study splits a fused QKV projection with
einops.rearrange(qkv, "B L (K H D) -> K B L H D"), which moves the Q/K/V axis to the front. The forward pass returns strided views and moves nothing. In the backward pass, autograd has to route gradients back through the axis reordering, materializes them in a new buffer, and on a TPU that is an HBM-to-HBM copy in every attention block, visible as acopyop in XProf (tt_jit_copy__as_strided_inversein the tutorial's traces). Keeping the size-3 axis next to(H, D)and splitting withqkv.view(B, L, 3, H, D)andtorch.unbind(..., dim=2)makes Q, K and V slices at fixed offsets, so their gradients land in the original layout with no copy. In that case study the effect on step time was small (178.61 ms to 178.30 ms eager, 159.33 ms to 159.08 ms compiled), because the copy was a small part of a 32K-token step, but it was removed at no cost. - Views as compiled-function arguments. Chapter 4 covered this from the execution side: PjRt needs every input of a compiled executable to be contiguous, zero-offset and of a fixed dtype, so a non-trivial view or a bitcast passed to a compiled function gets a temporary eager copy first. Return contiguous tensors from compiled functions that feed each other.
- Reshape round trips. The FLUX case study's reference RoPE builds 2x2 rotation matrices and reshapes the queries and keys into 6D tensors to apply them; the extra stacking and reshaping show up as large copy blocks in XProf. Storing compact
[cos, sin]pairs and rotating elementwise halved the positional embedding footprint and, together with the other changes, took the compiled step from 159.08 ms to 153.60 ms.
In-place writes: functionalization and buffer donation¶
StableHLO never modifies a value. PyTorch modifies values all the time: every op ending in an underscore, every out= argument and every slice assignment overwrites bytes in a storage, and the write is immediately visible to every tensor that shares that storage. TorchTPU reconciles the two through the metadata layer. For an in-place update or out= assignment it:
- describes the logical update to XLA, which produces a new buffer, and
- swaps that buffer into the metadata object the storage points at (the arrow labelled replaced in the storage diagram).
The documentation calls this automatic functionalization: every mutation is expressed as an out-of-place operation. Because the swap happens behind the shared storage, every view of it sees the new values, just as on CUDA.
Writing through a view needs one more step. To know which elements of the base storage a view covers, TorchTPU runs view decomposition backwards, which it calls view inversion. For a partial write, it then uses stablehlo.dynamic_update_slice to build one merged output that holds both the overwritten and the untouched values. View inversion only works for views that do not overlap. A write into a broadcast view is ambiguous, because several logical positions map to one physical element; CUDA treats it as undefined behaviour that may or may not fail, while TorchTPU always fails explicitly.
Donation, and when it fails¶
An out-of-place update has a cost: for a moment the old and the new buffer both exist, which doubles the peak memory of that tensor. To avoid it, TorchTPU opportunistically uses XLA's closest equivalent of an in-place write, buffer donation. When the last reference to the old buffer is removed, TorchTPU annotates the StableHLO program to donate that input, and XLA may reuse its memory for the output.
The orange branch is the expensive one: its memory cost is set by the size of the base storage, not by the size of the write. The dynamic_update_slice box applies to partial writes; a write that replaces a whole contiguous tensor reaches the same split without it.
Donation is best effort. When TorchTPU cannot prove that a buffer is safe to donate, it falls back to an out-of-place update, and the documentation spells out the trap: for a small write into a large buffer, the out-of-place update copies the whole base storage, not just the part being written. Writing one row of a 4 GiB tensor can briefly need another 4 GiB. Its takeaways turn this into two rules:
- Overwriting a contiguous tensor is usually memory-efficient, because it can usually be donated when all old values are erased.
- Partial writes are sometimes memory-expensive: without donation, the cost of a write is proportional to the size of the storage, not of the data written. The documentation's advice is to prefer many small tensors over slices of one large one.
The KV cache in a decoder is the canonical partial write. A static cache writes each new token with index_copy_ at a tensor position into a contiguous, preallocated buffer, which lowers to a dynamic_update_slice on a contiguous buffer, the case where donation works (chapter 7 builds that cache).
Copy-on-write: why clone() is cheap¶
Functionalization has an upside. On CUDA, x.clone() allocates a new buffer and copies the data immediately. On TorchTPU the original value is immutable, so a copy can simply be a second reference to it. No memory is allocated and nothing moves until one side is written in place.
When that write comes, it must change only the storage that was written, not the other one. The old value is still needed, so donation is impossible: the update runs out of place and allocates new memory at that moment. The documentation's summary is that TorchTPU pays for a copy lazily, only if a write happens, where CUDA pays up front. Its takeaway reads "copies are inexpensive": copying a tensor into contiguous form is often free.
Put next to the previous sections, this inverts a few CUDA habits:
| CUDA habit | On TorchTPU |
|---|---|
| Views are free, copies cost | clone() and .contiguous() copies are often free (copy-on-write); views can force a relayout |
| Slice one big buffer and write into it | Prefer many small tensors; a partial write may copy the whole storage |
| Any stride pattern works | Contiguous tensors avoid relayouts and keep donation possible |
| A write through a broadcast is "undefined" | It raises, always |
When neither the translation nor donation is good enough, the documentation's escape hatch is a custom kernel, which specifies TPU buffer behaviour by hand and can guarantee in-place updates (chapter 12).
Budgeting HBM¶
HBM is per PyTorch device: 32 GiB on a v6e device and 96 GiB on each of a v7x chip's two devices (chapter 1). torch.tpu.get_device_properties().hbm_bytes_per_device reports the capacity and torch.accelerator.get_memory_info() returns free and total bytes. A budget that holds on a TPU has three terms beyond the usual weights, gradients, optimizer state and activations:
- Padded bytes, not logical bytes. Size each large tensor with
padded_bytes(shape, dtype_bytes). For aligned transformer weights the difference is zero; for small minor dimensions, NCHW activations or trailing singletons it can dominate. - One extra copy of the largest storage that gets a partial write without donation. If a step writes into a slice of a large buffer while another reference keeps the old value alive (a view, a clone, a tensor kept for logging), budget a second full copy of that buffer at peak.
- The compiler's temporaries. XLA allocates intermediate buffers inside each program. They cannot be computed from Python; measure them with peak memory. The TorchTPU announcement notes that DeferAndFuse lowers peak HBM because fused ops need fewer temporary buffers (chapter 4).
Copy-on-write works in your favour here: a clone() that is never written costs nothing, so defensive clones are cheaper than on CUDA, until something writes to them.
What the memory APIs report on TorchTPU¶
TorchTPU implements PyTorch's device allocator interface in csrc/eager/tensor_to_buffer.cc, and every number comes from the PjRt allocator's statistics. The mapping matters when you read the numbers:
API (Stable, torch.accelerator) |
On TorchTPU |
|---|---|
memory_allocated() |
PjRt bytes in use plus bytes reserved |
max_memory_allocated() |
PjRt peak allocated bytes |
memory_reserved(), max_memory_reserved() |
PjRt bytes reserved, and its peak |
memory_stats() |
The same fields (allocated, active, reserved bytes and the allocation count) as a dict |
reset_peak_memory_stats() |
Clears the PjRt allocator's statistics |
get_memory_info() |
(limit - bytes in use, limit) from PjRt |
empty_cache() |
Does nothing: "PjRt handles memory management" |
torch.accelerator.memory.reset_accumulated_memory_stats is not implemented for TPU and only warns. The allocator TorchTPU registers, TpuAllocator, keeps no pools of its own: it leaves memory management to PjRt.
Hidden copies and where to find them¶
Collecting the mechanisms above, a TorchTPU step can move or duplicate data in places the code does not show:
| Source | Mechanism | What it costs |
|---|---|---|
| Reshape or transpose of a tiled array | Relayout from one tiled layout to another | An HBM-to-HBM copy of the tensor |
| Backward through a permuted view | Autograd materializes the gradient in a new buffer | A copy per use, every step |
| Non-contiguous view or bitcast into a compiled function | PjRt needs contiguous, zero-offset inputs | A temporary eager copy per call |
| Partial write that cannot be donated | Out-of-place update of the whole base storage | A full copy at peak, sized by the storage |
In-place write to one side of a clone() |
Copy-on-write ends | A new buffer of the tensor's size |
| Small or unaligned minor dimensions | Tile padding | Not a copy, but more bytes stored and moved |
Three tools find them, in increasing order of detail:
- XProf. The Op Profile lists the most expensive ops; relayouts and materialized views appear as
copyops, as in the FLUX traces. The Memory Profile shows HBM use over time and is where a non-donated partial write appears as a spike. Chapter 10 covers capture and reading. - HLO dumps. Setting
XLA_FLAGS="--xla_dump_hlo_as_text --xla_dump_to=DIR"before Python starts writes one*after_optimizations.txtfile per compiled module, the final HLO graph.count_copy_ops(DIR)in the companion code counts thecopyinstructions in those files. It is a heuristic for comparing two versions of one step, not a full account: a relayout fused into another op will not appear as a separatecopy. - Peak memory around one action. Synchronize, call
torch.accelerator.reset_peak_memory_stats(), readmemory_allocated(), run the action, synchronize again and readmax_memory_allocated(). A peak increase close to the size of the base tensor means a second full buffer existed during the action.
Failure modes¶
| Symptom | Likely cause | Fix |
|---|---|---|
OOM, although the sum of numel() * element_size() fits |
Tile padding of small or unaligned minor dimensions; NCHW activations; trailing singleton dimensions | Size with padded bytes; pad or choose dimensions to multiples of 128 and 8, 16 or 32; channels_last; squeeze singletons |
| OOM or a memory spike on a step that writes one slice | Partial write without donation copies the whole base storage | Keep a single reference to the buffer; drop views and logged copies before the write; split into smaller tensors; write into a contiguous preallocated buffer |
copy ops in XProf that the code never asks for |
A permute or reshape forced a relayout, often in the backward pass | Reorder dimensions so splits are view plus unbind at fixed offsets; keep tensors contiguous |
A copy before every call of a compiled function |
A non-contiguous view or bitcast passed in | Return and pass contiguous tensors between compiled functions |
| Memory jumps when a cloned tensor is modified | Copy-on-write: the clone was free until the write | Expected; budget it, or avoid writing to clones |
An error when writing through expand() output |
View inversion refuses overlapping views | Materialize the tensor (.clone() or .contiguous()) before writing, or write to the base |
empty_cache() does not lower reported memory |
It is a no-op on TorchTPU | Free tensors by dropping references; check with memory_allocated() |
| Lower MXU utilization than expected | Tensor dimensions not aligned to 128 (the XProf guide's red flag) | Pad dimensions to multiples of 128 |
Verifying the result¶
A memory change has worked when you can show four things, and padding.py does the measuring on a TPU.
- The footprint matches the prediction. Compute
padded_bytesfor the tensors that matter, then compare with what XLA chose: the TPU path ofpadding.pyprints the model's tile next totorch.tpu.get_device_layout_if_materialized(t)for five tensors, including the(20, 200)example in float32, bfloat16 and int8. If XLA's tile differs from the model's, trust XLA and recompute. - Peak memory behaves as the documentation says. The script measures peak and held HBM, in units of one base tensor, for five actions on an
(8192, 8192)float32 tensor:clone()(expected near zero),clone()followed by a one-row write (a second buffer), a whole-tensormul_(donation when it is the last reference), a one-row write (donation if provable), and a one-row write while a view of the tensor is alive. A peak near 1.0x on a write you expected to be donated is the full-storage copy, and the place to look for an extra reference. - The copies are gone. Dump HLO for the step before and after a change and compare
count_copy_ops; then confirm in XProf's Op Profile that thecopyops you targeted no longer appear, and in the Memory Profile that the spike has gone. - The values did not change. A view or layout change must not change results. Compare outputs before and after with
torch.equalwhere the arithmetic is identical (aviewplusunbindsplit against arearrange, as the FLUX case study does) and withtorch.allclosewhere the computation order changed.
python code/ch05_memory/padding.py --cpu-smoke # laptop: the rule and the views
python code/ch05_memory/padding.py --shape 4097,4097 --dtype-bytes 4
python code/ch05_memory/padding.py # TPU VM: layouts and memory probes
Keep your own output: it tells you how your TorchTPU version handles each case.
Worked problems¶
Problem 1. On CUDA, y = x.t(); y[0, 0] = 1.0 changes x[0, 0] with no data movement. On TorchTPU, x[0, 0] also changes. Explain how, naming the objects involved.
Answer
x and y share one torch.UntypedStorage, whose data_ptr() points at a DeviceBufferRef in host memory. The write is functionalized: TorchTPU runs view inversion on y to find which elements of the base it covers, and builds a new buffer with dynamic_update_slice that holds the old values plus the written one. It then replaces the DeviceBufferRef behind the storage with one that refers to the new buffer, at the same address. Because both tensors read through the same storage, both see the new value. Whether the old buffer is donated or copied depends on whether TorchTPU can prove it is no longer needed.
Problem 2. A colleague says "views are free and clones are expensive, so avoid .contiguous() and .clone() in the TPU port". Correct the statement in three sentences.
Answer
On TorchTPU a view is a logical operation that becomes StableHLO slices, reshapes, transposes and broadcasts, and a transpose or reshape of a tiled array can need a relayout copy, so views are not free. A clone is copy-on-write: it is a reference to the same immutable value until one side is written in place, so .clone() and .contiguous() are often free. Contiguous tensors are what the documentation recommends, because they avoid relayouts, keep buffer donation possible and are what compiled functions need as inputs.
Problem 3. Using the tile rule, compute the padded shape, padded bytes and utilization of (a) a (4097, 4097) float32 matrix and (b) a (2, 8, 1000, 64) bfloat16 attention tensor (batch, heads, sequence, head dimension). For (b), what change to the shape removes most of the padding?
Answer
(a) Rows pad to \(\lceil 4097/8 \rceil \times 8 = 4104\) and columns to \(\lceil 4097/128 \rceil \times 128 = 4224\). Padded bytes: \(4104 \times 4224 \times 4 = 69{,}341{,}184\) against \(67{,}141{,}636\) logical, so 2,199,548 extra bytes; utilization 96.8%. (b) The minor dimensions are (1000, 64) with a bf16 tile of (16, 128): rows pad to 1008, lanes to 128, so the padded shape is (2, 8, 1008, 128) and utilization is \(\frac{1000 \times 64}{1008 \times 128} = 49.6\%\). The 64-wide head dimension wastes half of every tile. Keeping the activation in its projection layout (B, S, H * D) = (2, 1000, 512) wherever the heads do not need to be separate puts 512 values in the lane dimension: it pads to (2, 1008, 512), 99.2% utilization, and a sequence length that is a multiple of 16 removes the rest. A head dimension of 128 would also remove the lane padding. Check: padding.py --shape 2,8,1000,64 --dtype-bytes 2 and --shape 2,1000,512 --dtype-bytes 2.
Problem 4. A ConvNeXt-style block keeps bf16 activations of shape (32, 512, 7, 7) in NCHW order. Compute utilization for NCHW, for the same tensor in channels_last order (32, 7, 7, 512), and for the (32 * 7 * 7, 512) matrix a pointwise (1x1) convolution actually multiplies. What does this say about the usual channels_last advice?
Answer
NCHW: the minor dimensions are (7, 7), padded to (16, 128), so utilization is \(49 / 2048 = 2.39\%\); the 1.6 MB activation occupies 64 MiB under the model. NHWC: the minor dimensions are (7, 512), padded to (16, 512): \(7/16 = 43.75\%\). The (1568, 512) matrix: 1,568 is a multiple of 16 and 512 of 128, so it is fully aligned, 100%. channels_last is a large improvement because it moves the 512 channels into the lane dimension, but the 7-wide spatial dimension still sits in the sublane position and wastes more than half the rows. Code that flattens the spatial dimensions into one axis before a pointwise matmul keeps the data aligned. These are model numbers; confirm with get_device_layout_if_materialized on the TPU.
Problem 5. A training step keeps a (65536, 4096) bf16 buffer (512 MiB) and writes 32 rows into it each step with buf[i:i+32] = new_rows. A debugging hook keeps last = buf[i-32:i] from the previous step. Peak memory is about 512 MiB higher than expected. Explain, and give two fixes and the measurement that confirms them.
Answer
The write is a partial write, so it becomes a dynamic_update_slice producing a new buffer. Donation would let XLA reuse the old buffer, but last is a view that keeps the old storage alive, so TorchTPU cannot prove the buffer is safe to donate and falls back to an out-of-place update, which copies the whole 512 MiB base storage. Fix 1: do not hold a view of the buffer across the write. Compute what the hook needs from last (a norm, a checksum) before the write and del last, so the buffer has a single reference when it is written. Fix 2: keep the buffer as smaller tensors (for example one per block of rows), so a non-donated write copies only the small tensor. Confirm with peak memory around the write: synchronize, torch.accelerator.reset_peak_memory_stats(), record memory_allocated(), run the step, synchronize, read max_memory_allocated(); the increase should drop from about 1.0x of the buffer to near zero. The XProf Memory Profile should lose the spike.
Problem 6. An XProf Op Profile of a training step shows a copy op in every attention block's backward pass. The forward code splits a fused projection with q, k, v = qkv.reshape(B, L, 3, H, D).permute(2, 0, 1, 3, 4). Rewrite the split, and say how you will confirm the copy is gone and the results are unchanged.
Answer
The permute moves the size-3 axis to the front, so the gradients of Q, K and V have to be put back into the projection's layout, and autograd materializes them through a new buffer, which on a TPU is an HBM-to-HBM copy. Keep the 3 axis adjacent to (H, D) and in the order the projection produces it: q, k, v = torch.unbind(qkv.view(B, L, 3, H, D), dim=2). Q, K and V are then slices at fixed offsets and their gradients land in place. Confirm with count_copy_ops on HLO dumps before and after, and in XProf's Op Profile; check torch.equal on Q, K and V between the old and the new split, as the FLUX case study does.
Quick questions¶
- What does
torch.UntypedStorage.data_ptr()return on TorchTPU, and why can it not be a device address? - Name the TorchTPU objects between a storage and an HBM buffer, and the state a buffer list is in before materialization.
- What is view decomposition, which four kinds of StableHLO op does it use, and why does logical equivalence not imply equal cost?
- What are functionalization and view inversion, and why does writing through
expand()output fail on TorchTPU? - When does buffer donation fail, and what does the fallback cost for a one-row write into a large tensor?
- Why is
clone()cheap on TorchTPU, and when does it stop being cheap? - State the tile rule for 4-, 2- and 1-byte types, and the utilization of a
(20, 200)float32 tensor. - Which
torch.acceleratorcalls do you use to measure the peak memory of one action, and which one does nothing on TorchTPU?
Key takeaways¶
- PyTorch code gives the same logical results on TorchTPU as on CUDA; the cost of views, copies and in-place writes is what changes.
- On a TPU,
data_ptr()points at host metadata: aDeviceBufferRefinto aDeviceBufferListthat holds a DeferredOp or an HBM buffer. Swapping that reference is how in-place writes reach every view. - Strided views are rebuilt as slice, reshape, transpose and broadcast ops (view decomposition). A transpose or reshape of a tiled array can need a relayout copy, so views are not free; prefer contiguous tensors.
- In-place ops are functionalized and kept in place by buffer donation when TorchTPU can prove it is safe. Otherwise a partial write copies the whole base storage. Overwrite whole contiguous tensors, avoid extra references during writes, and prefer many small tensors over slices of one big one.
clone()is copy-on-write: free until one side is written, then the write allocates.- In this book's model, arrays are padded to tiles in their last two dimensions: (8, 128) for 4-byte types, (16, 128) for 2-byte and (32, 128) for 1-byte types. The rule is a model: XLA picks the real layout. Budget padded bytes, and check XLA's actual layout with
torch.tpu.get_device_layout_if_materialized. - Find hidden copies with XProf (
copyops, Memory Profile spikes), HLO dumps, and peak memory around one action using the Stabletorch.acceleratormemory APIs, which TorchTPU fills from PjRt's allocator.
References¶
- TorchTPU and the TPU memory model: storage and the metadata indirection, physical and logical tensors, view decomposition, functionalization and view inversion, buffer donation, copy-on-write (current version)
csrc/eager/device_buffer.h:DeviceBufferRef,DeviceBufferList, the buffer states,size_bytesandpjrt_buffer_sizecsrc/eager/tensor_to_buffer.cc:TpuAllocatorand the memory statistics it reports from PjRtsrc/torch_tpu/_internal/device_utils/annotations.py:TpuLayout,LayoutContextandget_device_layout_if_materialized- TorchTPU Public APIs: Stable
torch.acceleratormemory APIs and the Experimental layout APIs - TorchTPU execution model: contiguous, zero-offset inputs for compiled functions
- TorchTPU API Reference:
XLA_FLAGSHLO dumps - Performance profiling with XProf: Op Profile, Memory Profile and the unaligned-dimension red flag
- FLUX optimization: the zero-copy QKV split, RoPE reshapes and their step times
- FLUX Performance Optimization Tutorial on Google Cloud TPUs: the
tt_jit_copy__as_strided_inversecopies in its traces - Introducing TorchTPU: DeferAndFuse lowers peak HBM through fewer temporary buffers
- How to Think About TPUs: the VPU's (8, 128) shape, lanes and sublanes
- TorchTPU performance: execution modes, XProf and Pallas kernels: 2D tiles and the tile rule per dtype, view decomposition, donation and copy-on-write
- TorchTPU performance sample code:
tile_padding_report - Companion code for this chapter




![An animation in eight frames. At the top, the call base.as_strided(size=(2, 2, 2), stride=(2, 3, 0), storage_offset=1) and a storage strip of ten cells 0 to 9. On the left, a list of six steps with their StableHLO ops: base[1:] slice, .view(3, 3) reshape, [:2, ::2] slice, .t() transpose, .unsqueeze(-1) reshape, .expand(2, 2, 2) broadcast_in_dim. Each frame highlights one step, draws the resulting tensor as a grid of values with its shape, stride and offset, says whether it is contiguous, and colors teal the storage cells it reads. After base[1:] the tensor is 1 to 9; after view(3, 3) it is a 3 by 3 grid, contiguous, stride (3, 1); after the strided slice it is [[1, 3], [4, 6]], stride (3, 2), not contiguous, reading cells 1, 3, 4 and 6; after the transpose it is [[1, 4], [3, 6]], stride (2, 3); after unsqueeze it has shape (2, 2, 1); after expand it has shape (2, 2, 2) with stride (2, 3, 0) and offset 1. The last frame says the values and strides match as_strided and that torch.equal is True, and the footer says logically equal is not equally cheap: on a TPU a transpose or reshape can need a relayout copy.](../../../assets/ch05/view-decomposition.gif)
