Linear algebra for LLMsPart 4: Tensors, shapes and einsum
Broadcasting
7 min
The rule
padded on the left to (1, 1, 4)
- Line the shapes up from the right; missing axes on the left count as size 1.
- Each pair of sizes must be equal, or one of them must be 1.
- Size-1 axes stretch to match. Nothing is copied; the same numbers are reused.
Write
Align from the right. Sizes must match or be 1. Size 1 stretches.
Adding a bias to every token
has shape , padded to , then stretched down all 3 rows. Every token gets the same bias. With a batch, works the same way.
Two stretches at once
A column and a row both stretch: . Entry is , an “outer sum”.
Shapes that broadcast, and one that doesn't
- : a bias or gain.
- : the causal mask.
- : one scale per token (norms).
- : an error, unless happens to hold.
Write
Mask broadcasts over . Per-token scale needs .
The silent bug: (T,) is not (T, 1)
You want to subtract each row’s maximum. has shape , which aligns with the last axis: it subtracts from column . With a square matrix the shapes still fit, so nothing complains. Keeping the axis, shape , subtracts per row.
Write
Reductions you broadcast back need
keepdim=True: , not .✏️ Your turn
Broadcast or not?
Line them up from the right and write each result shape, or “error”.
Work it out on paper, then go to the next card to check.
Answer
is padded to ; the 1s stretch. In the second, the last axes are 3 and 2: neither is 1.
In PyTorch
x + bias # (B, T, d) + (d,)
scores + mask # (B, h, T, T) + (T, T)
x / x.norm(dim=-1, keepdim=True) # (B, T, d) / (B, T, 1)
torch.broadcast_shapes((4, 1, 3), (5, 3)) # (4, 5, 3)📌 Recap
Broadcasting in one card
- Align shapes from the right; sizes must match or be 1; size 1 stretches.
- Bias , mask and per-token scale all broadcast.
- aligns with the last axis. Keep reduced axes (
keepdim=True) before broadcasting back.
Write
The three lines above.