view, reshape, permute and squeeze in PyTorch
Reshaping tensors is something you do in nearly every model: flattening images before a linear layer, splitting attention heads, or adding a batch dimension. The main tools are reshape and view (change the shape without changing the order of elements), permute and transpose (reorder dimensions), and squeeze and unsqueeze (remove or add size-one dimensions).
reshape and view
import torch
x = torch.arange(12) # shape (12,)
a = x.reshape(3, 4)
b = x.view(2, 6)
c = x.reshape(2, -1) # -1 means "infer this size": (2, 6)
print(a.shape, b.shape, c.shape)
The total number of elements must stay the same. Use -1 for at most one dimension and PyTorch computes it. Elements are read in row-major order, so reshape(3, 4) fills row by row.
What is the difference?
view always returns a tensor sharing the same memory, and it only works when the memory layout allows it. reshape returns a view when possible and silently makes a copy when not. In everyday code reshape is the safe choice. Use view when you want an error instead of an unexpected copy.
t = torch.arange(6).reshape(2, 3)
tt = t.T # transposed: not contiguous
print(tt.is_contiguous()) # False
# tt.view(6) # RuntimeError: view size is not compatible
print(tt.reshape(6)) # works: tensor([0, 3, 1, 4, 2, 5])
print(tt.contiguous().view(6)) # also works
A tensor is contiguous when its elements are laid out in memory in the same order as its shape implies. Transposing and permuting only change how the data is read, not the memory, so the result is usually not contiguous. Calling .contiguous() makes a compact copy.
flatten
imgs = torch.rand(8, 3, 4, 4)
flat = imgs.flatten(start_dim=1) # keep batch dimension
print(flat.shape) # torch.Size([8, 48])
flatten(start_dim=1) is the standard way to feed a batch of images into a fully connected layer. There is also nn.Flatten() for use inside nn.Sequential, which flattens from dimension 1 by default.
permute and transpose
img = torch.rand(32, 32, 3) # height, width, channels (typical image library layout)
chw = img.permute(2, 0, 1) # channels, height, width
print(chw.shape) # torch.Size([3, 32, 32])
m = torch.rand(2, 5, 7)
print(m.transpose(1, 2).shape) # torch.Size([2, 7, 5])
permute takes the new order of all dimensions. transpose(a, b) swaps just two. These are essential when converting between image libraries (height, width, channel) and PyTorch (channel, height, width), and when arranging attention heads.
squeeze and unsqueeze
v = torch.tensor([1.0, 2.0, 3.0]) # (3,)
batch = v.unsqueeze(0) # (1, 3): add batch dimension
col = v.unsqueeze(1) # (3, 1)
print(batch.shape, col.shape)
s = torch.zeros(1, 3, 1)
print(s.squeeze().shape) # (3,): removes all size-1 dims
print(s.squeeze(0).shape) # (3, 1): only dim 0
unsqueeze(i) inserts a size-one dimension at position i. squeeze() without arguments removes every size-one dimension, which can bite you when a batch happens to have size one: a (1, 10) output becomes (10,). Pass the dimension explicitly in model code.
A realistic example: splitting attention heads
batch, seq, dim, heads = 2, 5, 16, 4
x = torch.rand(batch, seq, dim)
# (2, 5, 16) -> (2, 5, 4, 4) -> (2, 4, 5, 4)
heads_x = x.reshape(batch, seq, heads, dim // heads).permute(0, 2, 1, 3)
print(heads_x.shape) # torch.Size([2, 4, 5, 4])
You will use this exact pattern when building multi-head attention later in the course.
Memory, strides and copies
Under the hood a tensor is a block of memory plus a shape and a set of strides. A stride tells PyTorch how many elements to skip in memory to move one step along a dimension. A freshly created (3, 4) tensor has strides (4, 1): moving down a row skips four elements, moving across a column skips one. Transposing swaps the strides to (1, 4) without moving any data, which is why it is instant, and why the result is no longer contiguous. You can inspect this with t.stride().
This explains the behaviour of the functions above. view needs compatible strides, so it fails on a transposed tensor. reshape checks and copies if needed. contiguous copies into the standard layout. Some operations, such as torch.matmul, work fine on non-contiguous inputs, so you only need contiguous when a function demands it. Do not sprinkle it everywhere, because each call may copy a large tensor.
A useful habit is to check shapes after every reshaping step during development. Add a quick print(x.shape) or an assert x.shape == (batch, seq, dim) after each transformation. These assertions cost almost nothing, document your intent for the next reader, and turn confusing downstream errors into clear failures at the exact line where the shape went wrong.
Common mistakes
- Using
viewafterpermuteortransposewithout.contiguous(). - Using
reshapeto reorder axes. It keeps element order, so it scrambles data when you really wantedpermute. - Calling
squeeze()with no argument and breaking batch size one. - Forgetting that views share memory: editing one changes the other.
Next you will see how tensors convert to and from NumPy arrays.
Comments
No comments yet. Have a question or a tip? Be the first to share it.