Broadcasting and Einsum
Two tools make tensor formulas short and fast. Broadcasting stretches arrays with size-1 axes so that elementwise operations work across batches. Einstein summation (einsum) writes any product-and-sum of tensors as one string of axis labels, mirroring the index notation of the math. Attention, bilinear layers and batched outer products all become one line.
Broadcasting rules
Align shapes from the right. Two axes are compatible if they are equal or one of them is 1; the size-1 axis is (virtually) repeated. Missing leading axes count as 1.
| Shapes | Result |
|---|---|
(B, T, d) + (d,) |
(B, T, d): a bias added to every token |
(B, T, 1) * (B, T, d) |
(B, T, d): a per-token scale |
(T, 1) - (1, T) |
(T, T): all pairwise differences |
(B, T, d) + (T, d) |
(B, T, d): positional encodings added to every sequence |
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(2, 4, 3)) # (B, T, d)
mean = X.mean(axis=-1, keepdims=True) # (B, T, 1): keepdims makes broadcasting work
std = X.std(axis=-1, keepdims=True)
Z = (X - mean) / std # per-token normalization (layer norm without scale)
print("shapes:", X.shape, mean.shape, Z.shape)
print("each token now has mean 0, std 1:", np.allclose(Z.mean(-1), 0), np.allclose(Z.std(-1), 1))
pos = np.arange(4)
print("pairwise offsets i - j:\n", pos[:, None] - pos[None, :])shapes: (2, 4, 3) (2, 4, 1) (2, 4, 3)
each token now has mean 0, std 1: True True
pairwise offsets i - j:
[[ 0 -1 -2 -3]
[ 1 0 -1 -2]
[ 2 1 0 -1]
[ 3 2 1 0]]
Without keepdims=True, mean would have shape (2, 4) and broadcasting against (2, 4, 3) would fail (or, worse, silently align the wrong axes in other shapes).
Einsum: index notation as code
Write the formula with indices, drop the signs, and list the input and output indices. Repeated indices that do not appear in the output are summed.
| Math | einsum |
|---|---|
| (dot product) | "i,i->" |
| (matrix product) | "ik,kj->ij" |
| (outer product) | "i,j->ij" |
| (attention scores) | "btd,bsd->bts" |
"ii->" |
import numpy as np
rng = np.random.default_rng(1)
B, T, d = 2, 5, 4
Q, K, V = rng.normal(size=(3, B, T, d))
S1 = np.einsum("btd,bsd->bts", Q, K) # scores for every pair of tokens
S2 = Q @ K.transpose(0, 2, 1)
print("einsum equals batched matmul:", np.allclose(S1, S2), S1.shape)
P = np.exp(S1 - S1.max(-1, keepdims=True)); P /= P.sum(-1, keepdims=True)
out = np.einsum("bts,bsd->btd", P, V) # weighted sum of values
print("attention output:", out.shape)
A = rng.normal(size=(3, 3))
print("trace:", round(np.einsum("ii->", A), 6), "=", round(np.trace(A), 6))einsum equals batched matmul: True (2, 5, 5)
attention output: (2, 5, 4)
trace: 3.231114 = 3.231114
Reading an einsum string
"bhtd,bhsd->bhts" reads: for every batch b and head h, for every query position t and key position s, sum over the feature index d. The output keeps b, h, t, s. That one string is multi-head attention's score computation (Multi-Head Attention).
In software
np.einsum,torch.einsumandjax.numpy.einsumshare the same syntax;opt_einsumchooses the cheapest contraction order for many operands.- The
einopslibrary adds readable reshapes:rearrange(x, "b t (h d) -> b h t d", h=8)splits heads. - Broadcasting bugs are silent; checking
assert x.shape == (B, T, d)at layer boundaries catches them.
Exercises
Exercise 1: Broadcast or error?
Do the shapes (8, 1, 6) and (7, 1) broadcast? If so, to what?
Answer
Yes, to (8, 7, 6).
Solution
Right-align: (8, 1, 6) and (1, 7, 1). Axis by axis: 8 vs 1 gives 8, 1 vs 7 gives 7, 6 vs 1 gives 6.
Exercise 2: Write the einsum
Write the einsum string for a batched matrix-vector product .
Answer
"ij,bj->bi".
Solution
Inputs carry indices ij and bj; the shared j is summed; the output keeps b and i. It equals x @ W.T.
Exercise 3: Pairwise distances (code)
Use broadcasting to compute all squared distances between 4 points in without loops.
Answer
A symmetric matrix with zeros on the diagonal.
Solution
P[:, None, :] - P[None, :, :] has shape (4, 4, 2); summing the squares over the last axis gives the distances.
import numpy as np
P = np.array([[0.0, 0], [1, 0], [0, 2], [3, 4]])
D = np.sum((P[:, None, :] - P[None, :, :]) ** 2, axis=-1)
print(D)[[ 0. 1. 4. 25.]
[ 1. 0. 5. 20.]
[ 4. 5. 0. 13.]
[25. 20. 13. 0.]]
Test yourself
Which shapes broadcast together?
- (3, 4) and (3,)
- (3, 4) and (4,)
- (3, 4) and (2, 4)
- (3, 4) and (4, 3)
In np.einsum("ik,kj->ij", A, B), the index k…
- is kept in the output
- is summed over because it is repeated and absent from the output
- must have size 1
- is the batch axis
Why use keepdims=True when computing a per-token mean of shape (B, T, d)?
- It is faster
- It keeps the result as (B, T, 1) so it broadcasts correctly against (B, T, d)
- It changes the mean's value
- It is required by einsum