All courses

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

▶ Watch this lesson Start the whole course

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.

Many sequences, positions, heads at once

Inside an LLM, one computation runs on many sequences, every position and every head at the same time. Attention alone needs, for each head of each sequence, the dot product of every position's query with every position's key. Loops over all of that are slow and error-prone. How do you write such computations as single array operations, and keep track of what every axis means?

Arrays whose axes have names

Treat an array as a grid whose axes have meanings. $[B, T, d]$ means $B$ sequences, $T$ positions each, and a $d$-number vector per token. **Reshape** regroups numbers without moving them. Since $d = h\cdot d_{head}$, you can view each vector as $h$ chunks: $[B, T, h, d_{head}]$. **Transpose** reorders axes, for example to $[B, h, T, d_{head}]$. A batched matmul multiplies over the last two axes and treats all leading axes as independent copies.

einsum and broadcasting rules

**einsum** labels each axis with a letter. Matching entries are multiplied. Letters kept in the output stay as axes, and letters missing from the output are summed away. With $Q, K$ stacked as $[B,h,T,d_{head}]$, all query–key dot products are $$S_{bhij}=\sum_k Q_{bhik}K_{bhjk}$$ This is `einsum('bhik,bhjk->bhij', Q, K)`, with shape $[B,h,T,T]$. **Broadcasting**: align shapes from the right. Each pair of sizes must be equal, or one must be 1. A size-1 or missing axis is repeated to fit.

Tracking shapes with real numbers

Take $B=2$, $T=3$, $d=8$, $h=2$, so $d_{head}=4$. $X$ is $[2,3,8]$. Reshape to $[2,3,2,4]$: numbers 0–3 of each vector are head 0, and numbers 4–7 are head 1. Transpose to $[2,2,3,4]$. The scores are $[2,2,3,3]$: one $3\times3$ table per head per sequence, so $2\cdot2\cdot9=36$ dot products. Now add a $[3,3]$ table with one entry per (query, key) pair, for example marking which positions each position may look back at. Broadcasting treats it as $[1,1,3,3]$ and repeats it over $B$ and $h$.

Split heads, all pairwise dot products

Here $X$ plays both the queries and the keys, just to show the shapes. The einsum and the batched matmul `@` agree. The $[T,T]$ table holds $-\infty$ where a position would look ahead, above the diagonal, and 0 elsewhere. A later step turns the $-\infty$ entries into zero attention weight. The table broadcasts across batch and heads.
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

Name every axis and track it: $[B,T,d]$ → reshape to $[B,T,h,d_{head}]$ → transpose to $[B,h,T,d_{head}]$. In einsum, letters missing from the output are summed. Broadcasting aligns shapes from the right and stretches size-1 axes.

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.