PyTorch primer2 / 6

Lesson 2 · Tensors and linear algebra

Shapes and broadcasting

The problem

In the matrices chapter, each vehicle needed a few minutes before leaving: 5 for the scooter and 7 for the bike. So every delivery's times got b=(5,7)\mathbf{b} = (5, 7) added:

XW+b=(81026272419)+(5,7)=(131731342926)XW + \mathbf{b} = \begin{pmatrix} 8 & 10 \\ 26 & 27 \\ 24 & 19 \end{pmatrix} + (5, 7) = \begin{pmatrix} 13 & 17 \\ 31 & 34 \\ 29 & 26 \end{pmatrix}

In maths, "add b\mathbf{b} to every row" is something you say in words. In PyTorch it's X @ W + b, with shapes (3, 2) + (2,). The shapes differ, yet it works. This chapter explains when that's allowed, and how to fix it when it isn't.

Changing a shape

A tensor's numbers sit in memory in one long line, row after row. The shape says how to read that line as a grid. So you can often change the shape without touching the numbers.

Reshaping, adding an axis, transposing
r = torch.arange(6.0)       # tensor([0., 1., 2., 3., 4., 5.]), shape (6,)
print(r.reshape(2, 3))      # tensor([[0., 1., 2.], [3., 4., 5.]]): filled row by row
print(r.reshape(3, -1).shape)  # torch.Size([3, 2]): -1 means "work this size out"
print(r.view(3, 2).shape)   # torch.Size([3, 2]): like reshape, but never copies
# r.reshape(4, 2)           # RuntimeError: shape '[4, 2]' is invalid for input of size 6
# X.T.view(6)               # RuntimeError: view can't reorder the stored numbers; use reshape

s = torch.tensor([1.0, 2.0, 3.0])  # (3,): one number per delivery
print(s.unsqueeze(0).shape)  # torch.Size([1, 3]): a row
print(s.unsqueeze(1).shape)  # torch.Size([3, 1]): a column
print(s[:, None].shape)      # torch.Size([3, 1]): the same, written with None

print(X.T.shape)             # torch.Size([2, 3])
print(X.transpose(0, 1).shape)  # torch.Size([2, 3]): .T for any two axes you name
  • reshape(2, 3) reads the same 6 numbers as 2 rows of 3, filled row by row. The new shape must hold exactly as many entries. A -1 means "work this size out for me".
  • unsqueeze(d) inserts an axis of size 1 at position d. s.unsqueeze(0) makes (3,) into (1, 3), a row. s.unsqueeze(1) makes it (3, 1), a column. Indexing with None does the same thing: s[:, None] is s.unsqueeze(1).
  • .T swaps the two axes of a matrix. transpose(0, 1) swaps any two axes you name, which matters once tensors have three or more.
Digressionview: reshape without copyingWhy the code also calls view, and why it sometimes refuses. · 1 min

view is like reshape, but it never copies the numbers. It only works when the numbers already sit in memory in the order the new shape needs.

X.T reads X's numbers in a different order without moving them. So X.T.view(6) raises an error, and X.T.reshape(6) makes a copy in the new order. When in doubt, use reshape: it views when it can and copies when it must.

Predict first

r = torch.arange(6.0). What does r.reshape(4, 2) do?

Shapes must fit for @

@ is matrix multiplication, so the inner sizes must match. When they don't, PyTorch names both shapes: mm: mat1 and mat2 shapes cannot be multiplied (3x2 and 3x2). Write out both shapes and compare the inner sizes. Often a .T on one side fixes it.

Broadcasting

* and + work entry by entry. So what does X * w do, when X is (3, 2) and w is (2,)? PyTorch reuses w for every row. This is broadcasting. The rule:

  1. Line the two shapes up from the right. If one shape is shorter, treat its missing sizes as 1.
  2. Compare each pair of sizes. They must be equal, or one of them must be 1.
  3. A size of 1 is reused to match the other. The result takes the bigger size.

Press play to watch the rule work, one axis at a time.

left32
right2
result

Write both shapes.

X * w

Step 0 of 4
Line the shapes up from the right; missing sizes count as 1 (dashed). Each pair must match, or one must be 1. The first pair that clashes is an error.

Notice the last case. An image batch of shape (8, 3, 32, 32) holds 8 colour images: 3 colour channels, each 32 × 32 pixels. A scale of shape (3, 1, 1) has one number per colour channel. It's reused for every image and every pixel.

Predict first

s = (1, 2, 3) has one number per delivery, shape (3,). Does X * s scale each row of X by its own number?

Now see the actual numbers. Try each button below.

X32
w(1)2
✓✓
20
51
32
X (3, 2)
46
46
46
w (2,)
80
206
1212
result (3, 2)

Works: (3, 2) * (2,) → (3, 2)

One weight per column, reused down every row.

Shapes line up from the right, and a size of 1 is reused to fit. Dashed cells are reused values, not stored copies.
  • X * w and X * 2.0 work. A single number has no axes, so it's reused for every entry.
  • X * s and X * X.T fail.
  • X * s.unsqueeze(1) fixes the row scaling: (3, 2) and (3, 1) line up, and each row's number is reused across its columns.
  • s.unsqueeze(1) + s gives (3, 3). It works, but probably isn't what you wanted.

The inputs aren't copied. PyTorch reads the same numbers again for each reuse.

Broadcasting
parts = X * w  # (3, 2) * (2,) -> (3, 2): w is reused for every row
print(parts)   # tensor([[ 8.,  0.], [20.,  6.], [12., 12.]])
print(X * 2.0)  # a plain number has no axes: it is reused for every entry

# X * s                    # RuntimeError: (3, 2) and (3,) don't line up from the right
print(X * s.unsqueeze(1))  # (3, 2) * (3, 1) -> (3, 2): each row scaled by its own number
print((s.unsqueeze(1) + s).shape)  # (3, 1) + (3,) -> torch.Size([3, 3]): no error, maybe a bug

Broadcasting can hide a bug

Broadcasting never warns you. Add a (3,) vector to a (3, 1) column and you get no error, but a (3, 3) matrix you probably didn't want. When a result has a surprising shape, print .shape and check each line.

Code for a batch

In the matrices chapter, a batch was a group of examples processed together, one per row. So a batch of nn deliveries is an (n, 2) tensor, with the batch axis first.

Write each function for a whole batch, and broadcasting does the rest:

One function, any batch size
def layer(X: torch.Tensor, W: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """Every delivery, every vehicle, plus each vehicle's start-up time."""
    return X @ W + b  # (n, 2) @ (2, 2) -> (n, 2), then + (2,) reused down the rows


print(layer(X, W, b))  # tensor([[13., 17.], [31., 34.], [29., 26.]])

one = torch.tensor([4.0, 3.0])         # a single delivery, shape (2,)
print(layer(one, W, b).shape)          # torch.Size([2])
print(layer(one[None], W, b).shape)    # torch.Size([1, 2]): a batch of 1
torch.manual_seed(0)                   # fix the random numbers so runs repeat
big = torch.rand(1000, 2) * 10         # 1000 random deliveries
print(layer(big, W, b).shape)          # torch.Size([1000, 2]): same code, any batch size

# Code for batches reads axis 0 as "the examples". Without a batch axis, axis 0 means something else.
print(layer(X, W, b).mean(dim=0))         # tensor([24.3333, 25.6667]): each vehicle, averaged over deliveries
print(layer(one, W, b).mean(dim=0))       # tensor(36.): averages the two VEHICLES. A silent bug
print(layer(one[None], W, b).mean(dim=0)) # tensor([39., 33.]): a batch of 1 keeps the meaning
  • X @ W gives (n, 2), and + b reuses b down every row. The same line handles 3 deliveries or 1000.
  • torch.rand(1000, 2) makes random numbers between 0 and 1. torch.manual_seed(0) fixes the random numbers, so every run gives the same ones.
  • One delivery on its own has shape (2,). one[None] adds a batch axis in front, making a batch of 1 with shape (1, 2).
  • The last lines show why the batch axis matters. Batch code reads axis 0 as "the examples". With the batch, .mean(dim=0) averages each vehicle over the deliveries. Without it, axis 0 is the vehicles, so you silently average the scooter and the bike together.

Predict first

layer(X, W, b) returns X @ W + b. You pass a batch of shape (1000, 2). What shape comes back?

nn.Linear stores its weights the other way round

PyTorch's ready-made layer for XW+bXW + \mathbf{b} is nn.Linear. You'll build networks out of it from the Neural-net foundations course on. For now, look at how it stores its numbers:

nn.Linear is x @ weight.T + bias
lin = nn.Linear(in_features=2, out_features=3)  # 2 features in, 3 outputs; random weights to start
print(lin.weight.shape)  # torch.Size([3, 2]): (out_features, in_features), one ROW per output
print(lin.bias.shape)    # torch.Size([3])

out = lin(X)             # (3, 2) -> (3, 3): one row per delivery, one column per output
print(out.shape)         # torch.Size([3, 3])
print(torch.allclose(out, X @ lin.weight.T + lin.bias))  # True: the layer is x @ weight.T + bias
  • nn.Linear(in_features=2, out_features=3) maps 2 numbers in to 3 numbers out. nn is PyTorch's neural-network module. A new layer starts with random weights.
  • Its weight has shape (3, 2): (out_features, in_features). That's one row per output. Our WW had one column per vehicle, so weight plays the part of W⊤W^\top.
  • So the layer computes x @ weight.T + bias. torch.allclose(a, b) checks that two tensors match up to rounding, and it prints True.
  • Calling lin(X) runs the layer on the whole batch: (3, 2) in, (3, 3) out.

Predict first

lin = nn.Linear(in_features=4, out_features=10). What is lin.weight.shape?

The full file is in python/examples/02-pytorch-primer/02-shapes-and-broadcasting/shapes.py. Run it from the python/ folder with uv run python examples/02-pytorch-primer/02-shapes-and-broadcasting/shapes.py.

Common misconceptions

"* and @ are the same for matrices." X * W multiplies matching entries, with broadcasting. X @ W takes dot products of rows with columns. For our (3, 2) and (2, 2), X * W is an error and X @ W is fine.

"Broadcasting lines shapes up from the left." From the right. That's why a (3,) vector meets the columns of a (3, 2) matrix, not its rows.

"reshape and .T do the same thing." X.reshape(2, 3) refills the numbers row by row: [[2, 0, 5], [1, 3, 2]]. X.T swaps rows and columns: [[2, 5, 3], [0, 1, 2]]. Same shape, different tensors.

"nn.Linear's weight is the WW in XWXW." It's W⊤W^\top, with one row per output.

Recap

  • reshape rereads the same numbers as a new shape. unsqueeze adds an axis of size 1.
  • Broadcasting lines shapes up from the right. Each pair must match or contain a 1, and a 1 is reused.
  • Write code for a batch with one example per row, and it works for any batch size.
  • nn.Linear computes x @ weight.T + bias, so its weight has one row per output.
  • PyTorch names: reshape, view, unsqueeze, indexing with None, .T, transpose; broadcasting; torch.rand, torch.manual_seed; nn.Linear and torch.allclose.