Tensors, shapes and views
A tensor is a strip of numbers plus a shape. Reshaping re-reads the strip; transposing changes the walk.
- Read a tensor's dtype, shape and device, and know why each one matters
- Explain what view, reshape, squeeze, unsqueeze and permute do to memory
- Predict when two tensors share storage, so a write to one changes the other
Everything a network does is arithmetic on tensors: n-dimensional arrays with a data type, a shape and a device. The notebook opens by building one:
matrix = torch.tensor([[1., 2., 3.],
[4., 5., 6.]],
dtype=torch.float32,
device='cuda:0',
requires_grad=True)
The notebook flags the three attributes that cause most bugs: right datatype, shape and device. Two tensors on different devices cannot be added; an integer tensor has no mean (torch.arange(0, 100, 10).mean() raises an error, which is why the notebook converts with .type(torch.float32) first); and a shape mismatch either fails loudly or, worse, broadcasts silently into something unintended.
One strip, many shapes
In memory a tensor is a single contiguous strip of numbers. The shape says how to read it, and the strides say how far to jump in the strip to move one step along each dimension. A (3, 4) tensor has strides (4, 1): one row down is four numbers along, one column across is one.
That is why view is free: it builds a new header over the same storage. The notebook proves it:
x = torch.arange(1., 10.)
z = x.view(1, 9)
z[:, 0] = 5 # changing z changes x (same memory)
After the assignment, x[0] is 5 as well. reshape behaves the same whenever it can, and silently copies when it cannot — after a transpose, for example, the elements are no longer in row order, so .view raises an error and .reshape makes a copy.
Adding and removing dimensions
Layers expect a fixed number of dimensions. A batch of images is \((N, C, H, W)\): batch, channels, height, width. Most of the shape juggling in the rest of this course is one of four moves:
| Operation | Example | Shape |
|---|---|---|
unsqueeze(0) | add a batch dimension | (3, 224, 224) → (1, 3, 224, 224) |
squeeze() | drop every size-1 dimension | (9, 1) → (9,) |
permute(2, 0, 1) | reorder dimensions | (224, 224, 3) → (3, 224, 224) |
stack([x, x], dim=0) | join along a new dimension | (9,) twice → (2, 9) |
The permute example is the notebook’s own: image libraries store pixels as height × width × channels, while PyTorch convolutions want channels first. permute is another stride trick, so it is free too — and leaves the tensor non-contiguous, which is when .contiguous() or .reshape is needed before a .view.
Matrix products
The notebook computes the same product three ways:
tensor1 @ tensor1.T
torch.matmul(tensor1, tensor1.T)
torch.tensordot(tensor1, tensor1.T, dims=1)
For a (2, 3) tensor all three give the (2, 2) Gram matrix of its rows. Keep * for element-wise products: tensor1 * tensor1 is still (2, 3).
Try it yourself. Create a = torch.arange(12).view(3, 4) and print a.stride(), a.T.stride() and a.T.is_contiguous(). Then try a.T.view(12) and a.T.reshape(12): one fails and one succeeds. Predict which before running, and check whether a.T.reshape(12) shares memory with a by writing into it.