After a transpose, your custom loss throws a contiguity error. Adding .contiguous() makes the error go away, but the profiler now shows a VRAM spike. What silent allocation did you trigger, how do strides and storage explain it, and when is .contiguous() free versus a full copy?

The Problem: A custom token loss transposes fp32 logits of shape (8, 2048, 32768) into time-major order and crashes on .view(-1, 32768). Appending .contiguous() makes it run, but the profiler shows allocated memory jumping by 2.0 GiB at that line and the step peak rising from 19.4 to 21.4 GiB on a 24 GiB GPU.
Answer
A PyTorch tensor is a view: a flat storage buffer plus metadata giving sizes, strides, and an offset. transpose(0, 1) allocates nothing, because it only swaps two sizes and two strides, so the result walks the same storage in a jumping order. .view() may rewrite metadata but never data, and no single stride can merge two swapped axes, which is exactly the contiguity error your loss raised. .contiguous() then does the only thing left: it allocates a fresh storage of numel times element size and runs a strided gather into row-major order. For fp32 logits of shape that silent buffer is exactly 2 GiB. In backward the gradient comes back as a transposed view, which the output layer’s reshape typically copies a second time.
(1) Storage Versus Metadata: The bytes live in one flat storage, and sizes, strides, and offset only describe how to index it. Many tensors can share one storage.
(2) Transpose Is Metadata-Only: Swapping two sizes and two strides is , moves zero bytes, and leaves
data_ptr() unchanged.
(3) View Needs Mergeable Strides: Flattening adjacent dims and
requires
. A transpose breaks that condition, so
.view() errors instead of copying.
(4) Contiguous Is Conditional: If the tensor is already row-major it returns self with no kernel and no allocation. Otherwise it is a full copy of every element plus a read and a write pass over HBM.
(5) Reshape Hides The Same Copy: reshape() and flatten() return a view when they can and silently copy when they cannot, so the error you hit was the only loud warning.
(6) Fix The Layout, Not The Symptom: Flatten the big tensor in its native order and reorder the small ones, or let a stride-aware or fused kernel read the transposed layout directly.
Mathematical Formulation:
Where:
is the position of an element inside the flat storage, counted in elements,
is the storage offset, and
is the index along dimension
.
is the stride of dimension
(how many storage elements one step along that axis skips),
its size, and
the number of dimensions.
- The two stride equations define row-major contiguity. Dimensions with
are ignored by the check, and the same equation is what
.view()tests for every group of dimensions it merges. swaps the size and stride entries of axes
and
and touches no data.
is the number of bytes
.contiguous()allocates when the contiguity equations fail, andis the element size (4 bytes for fp32, 2 for bf16).

Figure 1: Left, A and A.t() are two index maps over one 6-float storage, so the transpose allocates nothing and its row-major walk jumps through addresses 0, 3, 1, 4, 2, 5. Right, .contiguous() allocates a new buffer and gathers the values into that order, which buys strides (2, 1) at the price of a full copy.
Worked Example (fp32 logits, batch 8, 2048 tokens, vocab 32768):
Nothing in the first four lines touched memory: X.data_ptr() == L.data_ptr(), and both tensors report the same 2 GiB storage. The failed merge test is the whole error message. Consecutive rows of a flattened would sit 67,108,864 elements apart within a time step but jump backward when the time step advances, and one integer stride cannot express both. The copy also costs time: it reads 2 GiB and writes 2 GiB, about 4 GiB of HBM traffic, which is roughly 2 to 3 ms on an A100-class GPU before the uncoalesced strided reads slow it further. Once the loss function returns, the buffer goes back to PyTorch’s caching allocator rather than to the driver, so
nvidia-smi keeps reporting it as used until torch.cuda.empty_cache() runs.
Backward adds a second, less visible copy. Autograd treats contiguous as an identity, so the gradient of the copy passes straight through, but the transpose’s backward then hands the output layer a gradient that is a transposed view of a contiguous 2 GiB buffer. In the usual 3-D linear path the layer flattens that gradient to for its matrix multiply, the merge test fails again, and reshape quietly allocates another 2 GiB. The forward copy is the spike you see first, while the backward copy is what actually lifts the step peak.

Figure 2: Schematic allocated memory for one step with the scenario’s logits. The .contiguous() copy adds 2 GiB in forward, the transposed gradient is copied again by reshape in backward to set the new 21.4 GiB peak, and reserved memory stays at the high-water mark because the caching allocator keeps freed blocks.
.contiguous() is free whenever is_contiguous() already holds. It then returns self, launches no kernel, and allocates nothing. That covers fresh outputs of most ops, slices along the first dimension, a transpose that only moves a size-1 axis, and a double transpose that restores the original order. It becomes a full copy for any permutation of non-singleton axes, for inner or stepped slices, and for broadcast views, where the copy can be far larger than the source storage. The cheap fix here is to keep the 2 GiB tensor in its native order: logits.view(-1, 32768) and targets.view(-1) are both free, and any time-indexed weights can be flattened the same way.
| How the tensor was produced | Resulting layout | Cost of .contiguous() |
|---|---|---|
| Fresh op output, x[2:5], double transpose | Row-major, possibly with a storage offset | Free: returns self, no kernel, no allocation |
| (8, 1, V).transpose(0, 1) | Still contiguous, since size-1 strides are ignored | Free |
| transpose / permute of real axes, .T, .mT | Strides out of decreasing order | Full copy of every element (2 GiB for the scenario logits) |
| x[:, :100] or x[::2] | Gaps between rows or a doubled stride | Copy of the slice only, smaller than the storage |
| x.expand(B, T, D) from (B, 1, D) | Stride 0 on the broadcast axis | Materializes T times more memory than the source |
| channels_last image batch | NHWC strides on an NCHW shape | Full copy back to NCHW unless memory_format=torch.channels_last is passed |
Leave a Reply