DL0253 .contiguous() Implicit Copy

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?

A three-panel scenario card. The first panel shows fp32 logits of shape 8 by 2048 by 32768, a transpose of dimensions 0 and 1, and a view to minus one by 32768 that raises a RuntimeError about size and stride. The second panel shows the same code with contiguous added before view, a note that the loss now runs with unchanged values, and two bars of peak allocated memory per step, 19.4 GiB before and 21.4 GiB after, with the extra 2 GiB marked. The third panel lists three open questions about whether the transpose copied data, why view cannot flatten the result, and when contiguous is free or 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 (8, 2048, 32768) 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 O(1), moves zero bytes, and leaves data_ptr() unchanged.
(3) View Needs Mergeable Strides: Flattening adjacent dims k and k+1 requires s_k = s_{k+1} n_{k+1}. 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:
\mathrm{addr}(i_0,\ldots,i_{d-1}) = o + \sum_{k=0}^{d-1} i_k s_k
s_{d-1} = 1
s_k = s_{k+1}\, n_{k+1}
\mathrm{transpose}(a,b):\ (n_a, s_a) \leftrightarrow (n_b, s_b)
M_{\mathrm{copy}} = e \prod_{k=0}^{d-1} n_k

Where:

  • \mathrm{addr}(i_0,\ldots,i_{d-1}) is the position of an element inside the flat storage, counted in elements, o is the storage offset, and i_k is the index along dimension k.
  • s_k is the stride of dimension k (how many storage elements one step along that axis skips), n_k its size, and d the number of dimensions.
  • The two stride equations define row-major contiguity. Dimensions with n_k = 1 are ignored by the check, and the same equation is what .view() tests for every group of dimensions it merges.
  • \mathrm{transpose}(a,b) swaps the size and stride entries of axes a and b and touches no data.
  • M_{\mathrm{copy}} is the number of bytes .contiguous() allocates when the contiguity equations fail, and e is the element size (4 bytes for fp32, 2 for bf16).
Two panels. The left panel shows one flat storage strip of six cells numbered 0 to 5, a 2 by 3 grid A with size 2 by 3 and stride 3 by 1, and a 3 by 2 grid A.t() with size 3 by 2 and stride 1 by 3, both shaded the same color as the storage to show they share it; a note says a row-major walk of A.t() reads storage at 0, 3, 1, 4, 2, 5. The right panel shows a new orange storage strip holding 0, 3, 1, 4, 2, 5 and a 3 by 2 grid B with stride 2 by 1, noting a fresh 24-byte buffer walked sequentially.

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):
L:\ n = (8,\ 2048,\ 32768)
s(L) = (67108864,\ 32768,\ 1)
X = \mathrm{transpose}(L, 0, 1)
s(X) = (32768,\ 67108864,\ 1)
s_0(X) = 32768 \neq 67108864 \cdot 8
M = 4 \cdot 8 \cdot 2048 \cdot 32768
M = 2^{31}\ \text{B} = 2\ \text{GiB}

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 X 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 (16384, 32768) 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.

Line chart of allocated GPU memory in GiB against time within one training step. A blue curve for the native-layout loss rises from 9.4 to 13.4 during forward, steps to 15.4 for logits and 17.4 for the saved log-softmax, peaks at 19.4 in backward and falls back. An orange curve for transpose plus contiguous adds a 2 GiB step at the contiguous call in forward and another 2 GiB step in backward, reaching 21.4. A dashed gray reserved-memory curve climbs to 22 and stays there for the rest of the step.

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 producedResulting layoutCost of .contiguous()
Fresh op output, x[2:5], double transposeRow-major, possibly with a storage offsetFree: returns self, no kernel, no allocation
(8, 1, V).transpose(0, 1)Still contiguous, since size-1 strides are ignoredFree
transpose / permute of real axes, .T, .mTStrides out of decreasing orderFull copy of every element (2 GiB for the scenario logits)
x[:, :100] or x[::2]Gaps between rows or a doubled strideCopy of the slice only, smaller than the storage
x.expand(B, T, D) from (B, 1, D)Stride 0 on the broadcast axisMaterializes T times more memory than the source
channels_last image batchNHWC strides on an NCHW shapeFull copy back to NCHW unless memory_format=torch.channels_last is passed

Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *