Batched tensors, broadcasting and einsum
Track shapes through reshapes, transposes, broadcasting and batched matmuls. Examples: [B, T, d] for a batch of sequences of token vectors, and [B, T, h, d_head] when each vector is split into h chunks, one per attention head. Write batched contractions such as all pairwise dot products between two sets of vectors with einsum.
Builds on: What an LLM computes, end to end, Attention in plain words
What the animation says
Axes with names; reshape into heads
Inside an LLM, one step runs on many sequences, every position, and every head at once. So we treat an array as a grid whose axes have names: batch, time, and model width. Take two sequences of three tokens, each token a vector of eight numbers. Eight is two heads times four. Reshape regroups the same numbers: the first four are head zero, the last four head one. Nothing moves in memory. Only the grouping changes. Now we want heads before positions. After the transpose, what is the shape?
Transpose, then batched matmul
Two, two, three, four: the head axis and the position axis swapped places. Read it as two sequences times two heads: four independent little tables, three rows by four numbers. A batched matrix multiply works on the last two axes, and treats every leading axis as separate copies. Multiply each table by its own transpose, and each copy gives a three by three table of dot products. Four copies, nine dot products each: thirty-six, from one line.
einsum: letters for axes
Einsum says the same thing with letters, one letter per axis. Letters shared by the inputs line up, and matching entries are multiplied. A letter kept after the arrow stays an axis. A letter missing from the output is summed away. Here the four-number axis is missing, so it is summed: that is each dot product. The output shape follows the letters after the arrow, in that order, each taking its size from the inputs. Your turn: in this projection, tap the letter that gets summed away.
Broadcasting the mask
Now add a three by three mask: zero where a position may look back, minus infinity where it would look ahead. Broadcasting aligns shapes from the right. Each pair must be equal, or one of them must be one. Three matches three, three matches three. The missing axes count as one. So the mask is repeated across both sequences and both heads. What if we added a two by three table instead?
The whole recipe
It fails. From the right, three meets three, but two meets three, and neither is one. So the whole recipe: name every axis and track it. Reshape to split the width into heads, then transpose to put heads before positions. In einsum, letters missing from the output are summed, and the output follows the arrow. Broadcasting aligns from the right and stretches size-one axes.
Arrays whose axes have names
einsum and broadcasting rules
Tracking shapes with real numbers
Split heads, all pairwise dot products
import numpy as np
B, T, h, dh = 2, 3, 2, 4
d = h * dh
X = np.random.default_rng(0).standard_normal((B, T, d)) # [B,T,d]
Xh = X.reshape(B, T, h, dh).transpose(0, 2, 1, 3) # [B,h,T,dh]
S = np.einsum('bhik,bhjk->bhij', Xh, Xh) # [B,h,T,T]
S2 = Xh @ Xh.swapaxes(-1, -2) # swap last two axes, then batched matmul
print(S.shape, np.allclose(S, S2)) # (2, 2, 3, 3) True
mask = np.triu(np.full((T, T), -np.inf), k=1) # [T,T]
print((S + mask).shape) # (2, 2, 3, 3)
What to remember
On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.
Bytewise
All courses