Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 2: Programming Toolkit

NumPy broadcasting and einsum

P2.340 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Real model code is mostly array expressions over batches, and two tools make them short and checkable: broadcasting (so no Python loops over examples) and einsum (so every axis has a name and every shape can be read off the line).

  • Adding the bias vector to a whole batch, centring and standardising features, and normalising rows are all broadcasting one-liners. (P4.5: The forward pass in matrix form)
  • Distance-based methods such as k-nearest neighbours compute the distance from every query to every training point, and the pairwise-distance pattern is how that is done without loops. (P3.B1: k-Nearest Neighbors)
  • Attention scores are one einsum, batch and token axes kept and the feature axis summed, and padding and causal masks are broadcast comparisons. (P7.3: Queries, keys and values step by step, coming soon)
  • Normalisation layers are written as a mean and a variance over chosen axes with keepdims=True, so that the result broadcasts back. (P4.19: Normalization layers)

Before this: Summation, products and indices, Tensors, shapes and broadcasting, NumPy: arrays and vectorization

After this lesson you can

  • Write the standard broadcasting patterns without loops (centre and standardise columns, normalise rows with keepdims, add a bias to a batch, build outer and difference tables with [:, None], one-hot encode by comparison, build masks)
  • Compute all pairwise squared distances two ways, say how much memory the broadcast version needs, and explain why the faster formula can give small negative numbers
  • Find a silent shape bug by printing and asserting shapes, and read the error message when a broadcast fails
  • Read and write np.einsum specs (letters name axes, a repeated letter is summed, the letters after -> are kept), including implicit mode, batched matrix products and attention scores

You have 3 points on a map and 2 shops. You want the table of squared distances: 3 rows, 2 columns, no for loop. And later you want the scores that say how well each of 5 queries matches each of 6 keys, for a whole batch at once, written in one short line that you can check by reading it.

Both jobs are the same kind of problem: combine arrays so that every row meets every column, and keep track of which axis is which. P1.B14 taught the rule for broadcasting and P2.2 taught arrays and axis operations. This lesson is the practice: the patterns that real ML code is full of, the bugs that go with them, and einsum, a notation that writes axes by name. (P1.A3 promised it: np.einsum('i,i->', a, b) is ∑iaibi\sum_i a_i b_i. You will see why.)

Broadcasting in one paragraph

To combine two arrays of different shapes, NumPy aligns the shapes from the right, treats a missing leading axis as size 1, and requires each pair of sizes to be equal or one of them 1; a size of 1 is stretched to match. Otherwise it raises a ValueError. A row (n,) therefore acts like (1, n), a column must be written (n, 1), and no data is copied for the stretching. If any of that is not fresh, P1.B14 has the rule with a visualiser and shape puzzles. From here on we use it.

Patterns you will write again and again

Every pattern below is one line, has no loop, and is checked by the shapes. The running data is a small table X of shape (4, 3): 4 people, 3 features (height in cm, weight in kg, age in years).

Centre and standardise the columns

The mean of each column is X.mean(axis=0), shape (3,) (the axis you name disappears; P2.2). Subtracting it from X of shape (4, 3) aligns (4, 3) with (3,): the vector is treated as one row and subtracted from every row.

For the data in the code below, the column means are (171.25, 67.5, 32.5)(171.25,\ 67.5,\ 32.5) and the column standard deviations are about (7.395, 9.014, 5.590)(7.395,\ 9.014,\ 5.590). Dividing the centred data by them gives standardised columns: mean 0 and standard deviation 1 in each column. The first person becomes about (−0.169,−0.277,−0.447)(-0.169, -0.277, -0.447).

# centre: every column now has mean 0
Xc = X - X.mean(axis=0)
# standardise: every column now has std 1
Z = Xc / X.std(axis=0)

Why do this? Features measured in different units (centimetres, kilograms, years) have very different sizes, and many methods behave badly when one feature is simply bigger than another (P3.C3 for PCA, P1.F3 for gradient descent). Two cautions. NumPy’s std divides by NN by default (ddof=0), while many statistics tools divide by N−1N-1, so state which you mean. And a constant column has standard deviation 0, so you divide 0/00/0 and get nan; the usual fix is to divide by std + eps with a tiny eps such as 1e-8. When you standardise a test set, reuse the mean and standard deviation of the training set (P3.A11 explains why).

Normalise each row, and why keepdims is not optional

To make each row have length 1 you divide each row by its own norm. The norms come out as a flat vector of shape (3,) for a (3, 2) matrix, but you need them as a column (3, 1) so that each one is stretched across its row:

# shape (3, 1), not (3,)
norms = np.linalg.norm(R, axis=1, keepdims=True)
unit_rows = R / norms

For R = [[3, 4], [6, 8], [1, 0]] the norms are 5,10,15, 10, 1 and every row becomes (0.6,0.8)(0.6, 0.8) or (1,0)(1, 0). Without keepdims=True the norms have shape (3,), which is aligned with the last axis of size 2: the shapes (3, 2) and (3,) clash and NumPy raises an error. That is the lucky case. For a square matrix the clash does not happen, the division goes the wrong way, and nothing warns you (P1.B14 shows it with row sums). The habit: when a reduction will be combined with the original array, use keepdims=True.

Add a bias to a whole batch

A layer’s output for a batch is Z of shape (B, h) (batch size BB, hh outputs), and its bias is b of shape (h,). Z + b adds the bias to every example. The mirror image, one number per example (say a weight for each row), needs a column: w[:, None] * Z with w of shape (B,).

Tables of all pairs: outer products and differences

To combine every entry of a with every entry of b, make one of them a column and the other a row. For v = [1, 2, 4]:

# (3, 1) and (1, 3) -> (3, 3): every difference
v[:, None] - v[None, :]
# the outer product: every product
v[:, None] * v[None, :]

The difference table is (0−1−310−2320)\begin{pmatrix}0&-1&-3\\1&0&-2\\3&2&0\end{pmatrix} and the product table is (1242484816)\begin{pmatrix}1&2&4\\2&4&8\\4&8&16\end{pmatrix}. Both arrays are stretched, which is a case where that is exactly what you want (P1.B14 showed the same stretching as a bug when it is not what you meant). None and np.newaxis are the same thing.

One-hot encoding by comparison

A class label is an integer such as 2. A one-hot vector for 3 classes is (0,0,1)(0, 0, 1) (P6.1). To turn a whole array of labels into one-hot rows, compare a column of labels with a row of class numbers:

labels = np.array([2, 0, 1, 2])
# (4, 1) == (3,) -> (4, 3)
onehot = (labels[:, None] == np.arange(3)).astype(float)

Row ii is 1 in the column that equals labels[i] and 0 elsewhere, and every row sums to 1. Do not write labels == np.arange(3): that compares labels[i] with class number ii one by one. If the two lengths differ it raises an error, and if they happen to be equal it silently returns a meaningless array of True and False.

Masks

A mask is an array of True and False with the same shape as the data (or a shape that broadcasts to it) that says which entries to use. Two masks appear in language models (P7.8).

A padding mask: sequences in a batch have different lengths and are padded to a common length TT. If lengths = [2, 3] and T=3T=3, then np.arange(3)[None, :] < lengths[:, None] compares a row (1, 3) with a column (2, 1) and gives the (2, 3) mask [[True, True, False], [True, True, True]]: position tt is real if tt is less than the length.

A causal mask: token tt may look only at tokens s≤ts \le t. With i = np.arange(T), i[:, None] >= i[None, :] is a (T, T) array that is True on and below the diagonal (the lower triangle).

Masks are used by np.where(mask, scores, -np.inf): the masked entries become −∞-\infty, so after the softmax they get weight exactly 0 and the others still add to 1. If every entry of a row is masked, the row’s maximum is −∞-\infty, −∞−(−∞)-\infty-(-\infty) is nan, and the whole row becomes nan; keep at least one unmasked entry per row. For the scores (2.0,1.0,0.5)(2.0, 1.0, 0.5) with the last position masked, the weights are about (0.731,0.269,0)(0.731, 0.269, 0). The softmax itself is written with keepdims=True (P1.G2 shows the stable form). One more use: the mean of only the entries that pass a condition is (x * mask).sum() / mask.sum(); for x = [3, 1, 4, 1, 5] and x > 1 it is (3+4+5)/3=4(3+4+5)/3 = 4.

Try it: the patterns, with their shapes

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

All pairwise distances

Given nn points in A (shape (n, d)) and mm points in B (shape (m, d)), the squared distance between point ii of A and point jj of B is Dij=∑k(Aik−Bjk)2D_{ij}=\sum_k (A_{ik}-B_{jk})^2. All nmnm of them are used by k-nearest neighbours (P3.B1) and k-means (P3.C1). There are two standard ways to compute the whole table.

Way 1: broadcast the differences

Give A a middle axis and B a leading one, subtract, square, and sum over the last axis:

# (n, 1, d) - (1, m, d) -> (n, m, d)
diff = A[:, None, :] - B[None, :, :]
# sum over the feature axis -> (n, m)
D2 = (diff ** 2).sum(axis=-1)

It is easy to read and always accurate. The cost is in diff: it holds n⋅m⋅dn\cdot m\cdot d numbers. For 3 points and 2 centres in 2 dimensions that is 12 numbers; for n=10000n=10000, m=1000m=1000, d=128d=128 it is 1.28×1091.28\times10^9 numbers, about 10 GB in 64-bit floats, while the answer D2 has only 10710^7 numbers (80 MB). Broadcasting copies nothing for the inputs, but the intermediate result is full size.

Way 2: the expansion trick

Expand the square: ∥a−b∥2=∥a∥2+∥b∥2−2 a⋅b\lVert\mathbf{a}-\mathbf{b}\rVert^2 = \lVert\mathbf{a}\rVert^2 + \lVert\mathbf{b}\rVert^2 - 2\,\mathbf{a}\cdot\mathbf{b} (P1.B3, P1.B4). All the dot products at once are the matrix product A @ B.T (P1.B6), and the squared lengths are one number per point:

D2 = (A**2).sum(1)[:, None] + (B**2).sum(1)[None, :] - 2 * A @ B.T

Here the biggest array is (n, m), and the work is done by one matrix product, which is fast. For the small example below both ways give the same table, (01002525274)\begin{pmatrix}0&100\\25&25\\2&74\end{pmatrix} for the points (0,0),(3,4),(1,1)(0,0),(3,4),(1,1) against (0,0),(6,8)(0,0),(6,8).

The numerical caveat. The trick subtracts large, nearly equal numbers (P1.G1, P1.G2), so rounding can leave a tiny negative value where the true answer is 0 or very small, for example for two points that are almost the same. A negative squared distance breaks the next step, np.sqrt, which then returns nan. The cure is one line: D2 = np.maximum(D2, 0). In the cell below, 32-bit numbers near 1000 are used on purpose: their squares are around 3 million, where 32-bit floats can only represent steps of 0.25, so the formula’s error (here about 0.5) is huge compared with the true squared distance (about 0.000003). The cell applies the formula to 200 pairs of almost identical points. (The exact count of negative values you see may change a little with the computer and the NumPy build; that some values are negative is the point.)

Try it: pairwise distances, memory, and the negative-distance trap

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Which way to choose? Use the broadcast version when the arrays are small or you want the easiest code to check; use the trick when nmdnmd would not fit in memory. A third way is to process A in chunks of rows. Libraries such as SciPy (scipy.spatial.distance.cdist) and scikit-learn already do this for you.

When broadcasting goes wrong

The danger of broadcasting is that it is permissive: it accepts any shapes whose sizes are equal or 1, whether or not you meant them to combine. P1.B14 showed the headline bug: (n, 1) minus (n,) is an (n, n) table, no error, and a mean squared error of 4.5 instead of 0.75. Three habits catch almost everything.

  1. Print the shapes of every array the first time you write a line. Print the shape of the result too: if you expected (n,) and see (n, n), you have found it.
  2. Assert shapes where two arrays meet: assert y_pred.shape == y.shape, (y_pred.shape, y.shape). An assert costs nothing and turns a silent wrong number into a loud error that shows both shapes.
  3. Write the axes in a comment: # X: (B, T, d). NumPy does not know what an axis means; you must.

Here are the failure messages you will meet, and what to do with them.

  • np.ones((2, 3)) + np.ones(2) raises ValueError: operands could not be broadcast together with shapes (2,3) (2,). The last axes are 3 and 2. Make the second a column (2, 1) if you meant one number per row.
  • a += b where a is (3, 1) and b is (1, 4) raises ValueError: non-broadcastable output operand with shape (3,1) doesn't match the broadcast shape (3,4). In-place operations cannot grow a: write a = a + b, a new array.
  • (n, 1) - (n,) works and gives (n, n) (P1.B14): assert the shapes.
  • A square matrix divided by its row sums without keepdims divides the wrong way (P1.B14): use keepdims=True.
  • labels == np.arange(k) gives an error, or a meaningless array if the lengths match. Write labels[:, None] == np.arange(k).
Go deeper np.broadcast_shapes and np.broadcast_to: check without making data

np.broadcast_shapes((4, 1), (4,)) returns (4, 4), and np.broadcast_shapes((5, 1, 3), (4, 1)) returns (5, 4, 3). It takes shapes, not arrays, so you can test a pair of shapes (or write a unit test for the shapes in a model) without allocating anything. When the shapes clash it raises a ValueError whose message begins with shape mismatch: objects cannot be broadcast to a single shape and names the two shapes. np.broadcast_to(a, shape) returns the stretched array as a read-only view whose stride along each stretched axis is 0, so it uses no extra memory; for np.arange(3) stretched to (2, 3) the strides are (0, 8) (8 bytes per 64-bit integer). Call .copy() if you need a writable array. P1.B14 explained the stride-0 idea.

Try it: shape bugs, checks and error messages

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Einsum: name every axis

So far we have kept axes straight by position: “axis 0”, “the last axis”, [:, None]. That works until a line has three or four axes and a matrix product in the middle. Einsum (Einstein summation) lets you give every axis a letter and write down what to do with the letters. It is the same Σ notation you met in P1.A3, with the sum sign left out.

From Σ to letters

The matrix product of P1.B6 is written with a sum:

(AB)ij=∑kAik Bkj(\mathbf{A}\mathbf{B})_{ij}=\sum_k A_{ik}\,B_{kj}

Look at the indices. ii and jj stay on the left, so they label the result. kk appears twice on the right and not on the left, so it is the one being summed. Einsum writes exactly this, with the inputs on the left of an arrow and the result on the right:

# the same as A @ B
np.einsum('ik,kj->ij', A, B)

Read it aloud: “A has axes ii and kk, B has axes kk and jj; the result has axes ii and jj.” The letter k is not after the arrow, so it is summed over. The same rule covers the dot product from P1.A3: np.einsum('i,i->', a, b) is ∑iaibi\sum_i a_i b_i, with nothing after the arrow, because every letter is summed and the result is a single number.

The rule has three parts, and the tour below uses all of them. Multiply: entries with the same letter value are multiplied. Sum: letters not after the arrow are added up. Keep: letters after the arrow become the axes of the result, in that order.

A tour of small examples

With a = [1, 2, 3], b = [4, 5, 6], M = [[1, 2, 3], [4, 5, 6]] (shape (2, 3)) and S = [[1, 2], [3, 4]]:

  • 'i->' sums all entries: 66 (a.sum()).
  • 'i,i->' is the dot product: 3232 (a @ b).
  • 'i,j->ij' is the outer product, every pair: [[4 5 6] [8 10 12] [12 15 18]] (np.outer(a, b)).
  • 'ij->i' sums over jj, the row sums: [6 15] (M.sum(axis=1)).
  • 'ij->j' sums over ii, the column sums: [5 7 9] (M.sum(axis=0)).
  • 'ij->ji' swaps the axes, the transpose: shape (3, 2) (M.T).
  • 'ii->' adds the diagonal, the trace: 55 for S (np.trace(S)).
  • 'ii->i' is the diagonal: [1 4] for S (np.diag(S)).
  • 'ij,j->i' is matrix times vector: [14 32] for M and a (M @ a).
  • 'ik,kj->ij' is the matrix product: see the cell below (A @ B).
  • 'ij,ij->ij' is the entry by entry product: [[1 4 9] [16 25 36]] (M * M).
  • 'ij,ij->' multiplies entry by entry, then adds everything: 9191 ((M * M).sum()).
  • 'i,ij,j->' is x⊤My\mathbf{x}^\top\mathbf{M}\mathbf{y} with three inputs: 7878 for (1, 2), M, a (x @ M @ y).

A letter repeated inside one input ('ii') means “take the diagonal”: the two axes are tied to the same index. The 'ii->' line is the trace, and 'ii->i' keeps the diagonal as a vector.

Now explore. Pick an example, or type your own spec. Each distinct letter gets a size you can change with the small buttons, the inputs are filled with small whole numbers, and you can select any cell of the result to see exactly which input cells are multiplied and which products are added.

Einsum visualizer: which numbers make one result cell?

np.einsum('ik,kj->ij', A, B)plain NumPy: A @ B

Kept: i, j. Summed away: k.

Explicit mode: the letters after the arrow are kept, in that order. Every other letter is summed.

i 2
k 3
j 2
A ik 2×3
i↓ k→ 012 0 1231 456
B kj 3×2
k↓ j→ 01 0 251 312 42
R ij 2×2
i↓ j→ 01 0 1

Selected: R where i = 0, j = 1. It is built from 3 products; the cells used are marked in the inputs.

R[i,j] = sum over k of A[i,k] × B[k,j]

1 × 5 + 2 × 1 + 3 × 2 = 13

Same numbers as NumPy: this example was run with np.einsum on the same arrays when the lesson was written.

Einsum visualizer. Choose an example or type a spec such as ik,kj->ij. Each letter has a size (change it with the buttons; sizes go from 1 to 4). The input arrays are filled with small whole numbers and their axes are labelled with the letters. Select a cell of the result (the highlighted one) and the cells of the inputs that feed it are marked, with the sum of products written out underneath. For the nine examples the results were checked against NumPy when the lesson was written; for a spec you type, the result is computed by the same rule in your browser and is not checked against NumPy. A spec that is not valid shows a message instead of arrays. Up to 3 inputs, up to 3 axes each, lowercase letters; the ellipsis form is not supported here.

Things to try:

  1. Start with matrix product and select each of the four result cells in turn. For R[i=0, j=1] the marked cells are the whole first row of A and the whole second column of B: 1×5+2×1+3×2=131\times5 + 2\times1 + 3\times2 = 13. The letter k ran over its 3 values, which is why there are 3 products.
  2. Click dot product, then outer product. The dot product has one result cell made from every input cell; the outer product has 6 result cells, each made from one pair and nothing added (no summed letters, so one product per cell).
  3. Click transpose and select a cell: it is built from a single input cell, nothing is multiplied, the number is only moved.
  4. Click trace: the matrix has the letter i twice, so only the diagonal cells are marked.
  5. In batched matrix product, the two slices (b = 0 and b = 1) are separate matrix products; the result cell for b = 1 uses only cells of slice 1.
  6. Type ik,kj (no arrow) and compare with ik,kj->ij: the status line explains the rule for the implicit form. Then type ba: the result is the transpose.
  7. Break it on purpose. Type ij->ijk (a result letter that was never named on the left) and ij,jk->ikk (a letter kept twice), and read the messages.

Intuition

Think of a spreadsheet. Each input array is a sheet, and each letter is the name of a row or column dimension. The result is a new sheet. To fill one cell of the result, you let the summed letters run through all their values, take one product per combination, and add. The letters after the arrow pick which cell of the result you are filling.

Why is that useful? Because the line tells you the shapes. In 'bqd,bkd->bqk' you can see that b (batch) is on both inputs and on the result, d is on both inputs only (so it is summed), and q and k come from one input each. You can read the output shape off the spec: batch, then queries, then keys. The same line with @ needs a transpose and a leading-axes rule in your head. The analogy has a limit: einsum is only for multiply-and-sum patterns. Taking a maximum along an axis, or applying a function such as a softmax, is not an einsum.

Math

Einsum is the sum formula with the summation signs dropped. Write the result entries as a function of the kept indices and sum over every index that does not appear on the left:

Rkept=∑summed  A… B…⋯R_{\text{kept}}=\sum_{\text{summed}}\;A_{\ldots}\,B_{\ldots}\cdots

Examples in the notation of P1.A3 and P1.B6:

  • 'i,i->' is ∑iaibi\sum_i a_i b_i.
  • 'ik,kj->ij' is Rij=∑kAikBkjR_{ij}=\sum_k A_{ik}B_{kj}.
  • 'bik,bkj->bij' is Rbij=∑kAbikBbkjR_{bij}=\sum_k A_{bik}B_{bkj}.
  • 'bqd,bkd->bqk' is Rbqk=∑dQbqdKbkdR_{bqk}=\sum_d Q_{bqd}K_{bkd}.

The naive loop visits every combination of values of all the letters (summed or kept) once, so the work is the product of all the sizes. For 'ik,kj->ij' with ii, kk, jj of sizes m,n,pm, n, p that is mnpmnp, the same count as a naive matrix product.

Code

import numpy as np

a = np.array([1, 2, 3]); b = np.array([4, 5, 6])
M = np.array([[1, 2, 3], [4, 5, 6]])
N = np.array([[1, 0], [2, 1], [0, 3]])

np.einsum('i,i->', a, b)        # 32, the dot product
np.einsum('ik,kj->ij', M, N)    # [[5 11] [14 23]], the same as M @ N
np.einsum('ij->ji', M)          # the transpose, shape (3, 2)

torch.einsum takes the same specs (P2.6).

Explicit and implicit mode

When you write -> it is explicit mode: you decide the result axes. When you leave it out, NumPy is in implicit mode and applies a rule: the result keeps the letters that appear exactly once in the whole spec, sorted alphabetically; letters that appear twice or more are summed.

  • 'ij,jk' has i once, j twice, k once, so the result is 'ik': the matrix product. 'ik,kj' gives 'ij', also the matrix product.
  • 'ii' has i twice, so nothing is kept: the trace. 'ij,ij' sums everything: 9191 for M above. 'i,j' keeps both letters: the outer product.
  • 'ba' keeps a and b in alphabetical order, 'ab'. The input’s first axis is labelled b, so the result is the transpose: for M of shape (2, 3) the result has shape (3, 2). Written explicitly, 'ba->ba' returns M unchanged.

The third case is the trap: the names you choose can change the result in implicit mode (the kept letters are sorted alphabetically), but never in explicit mode. So: write -> yourself. It documents the output shape and cannot be changed by a renamed letter.

Batches and attention

The batched matrix product from P1.B14, a stack of BB matrices, is one letter more:

# the same as X @ Y for 3-axis arrays
np.einsum('bik,bkj->bij', X, Y)

b is on both inputs and on the result, so it is kept: the batch items stay separate. k is summed. The attention scores of P7.3 are one more line of the same shape. With queries Q of shape (B, T_q, d) and keys K of shape (B, T_k, d):

# shape (B, T_q, T_k)
scores = np.einsum('bqd,bkd->bqk', Q, K)

For every example b, every query q and every key k, the score is the dot product over the feature letter d. Here the letter k means “key position”, while in the matrix product above it was the summed letter: a letter’s meaning is local to one spec. With a head axis h it becomes 'bhtd,bhsd->bhts' (P1.B14, P7.5), and the scaling by dk\sqrt{d_k} and the softmax over the last axis (P7.4) are separate steps: einsum does the multiply-and-sum only.

Go deeper Three inputs, ellipsis, and the order of the work

An einsum can have any number of inputs. np.einsum('i,ij,j->', x, M, y) is ∑i,jxiMijyj=x⊤My\sum_{i,j} x_i M_{ij} y_j = \mathbf{x}^\top\mathbf{M}\mathbf{y}, a bilinear form. NumPy can do it as one triple loop, or as two smaller steps (first M @ y, then a dot product with x). The cheaper order may be very different from the naive one, which is what optimize=True is for (next section).

An ellipsis ... stands for “any leading axes, whatever they are”, so one spec works with and without batch axes: '...ik,...kj->...ij' is X @ Y for any number of leading axes, and '...ij->...ji' transposes the last two axes of anything. This visualizer does not draw ellipsis specs, but NumPy and PyTorch accept them.

Speed: einsum against @

For the same job, a plain np.einsum call is not always as fast as @. A matrix product with @ is handed to an optimised linear-algebra library; the default einsum runs its own loops. On the computer used to write this lesson, a plain np.einsum('ik,kj->ij', A, B) of two 500×500500\times500 matrices was many times slower than A @ B (25 times there; about 2 times on another computer), and with optimize=True it was about as fast. The gap depends on your machine, so measure.

  • optimize=True (or optimize='optimal') lets NumPy plan the work: it can pick a cheaper order for three or more inputs, and call matrix-product routines where it can. np.einsum_path shows the plan and an estimate of the cost.
  • With three or more inputs the order matters a lot. For 'ij,jk,k->i' it is much cheaper to multiply the matrix by the vector first (about n2n^2 work) than to form the matrix product first (about n3n^3): optimize=True finds the cheap order.
  • Use @ when the operation is a matrix product and the shapes are what @ expects. Use einsum when the line is clearer with names (a transpose in the middle, a batch and head axis, a diagonal), or when no combination of @, .T and sum says it simply.
Try it: an einsum tour, and a speed check

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Common einsum mistakes

  • Using the same letter for two axes that are not the same. If 'ij,ij->ij' was meant to be a matrix product, it is not: both inputs share both letters, so it multiplies entry by entry. Letters link axes: reusing one says “these two axes have the same index”.
  • A size mismatch. 'ik,kj->ij' with A of shape (2, 3) and B of shape (4, 2) raises a ValueError whose message begins “operands could not be broadcast together with remapped shapes”. Read it as “the sizes of a shared letter do not agree”. Note that NumPy’s einsum is lenient about this: an axis of size 1 can stand in for a longer one, so 'ij,jk->ik' with shapes (2, 3) and (1, 2) runs without an error (it gave a result filled with 3s with the NumPy version we tried). The documentation does not promise this, so do not rely on it; check shapes.
  • A letter after the arrow that was never named before it ('ij->ijk'): ValueError: einstein sum subscripts string included output subscript 'k' which never appeared in an input.
  • The wrong number of letters for an input: 'ijk->ij' for a 2-axis array raises “too many subscripts for operand 0”; and giving the wrong number of arrays for the terms in the spec raises a ValueError about operands (NumPy’s wording for this one is confusing, so count your arrays and your commas).
  • Relying on implicit mode. A renamed letter can transpose the result. Write the arrow.
  • Thinking einsum can do anything. It multiplies and sums. A maximum, an average of absolute values or a softmax needs other functions (the mean is a sum divided by the count: divide afterwards).

Where you will meet it next

  • The forward pass (P4.5, P4.10). A layer on a batch is X @ W.T + b, and the bias is the broadcast from this lesson.
  • Normalisation (P4.19). Each normalisation layer is (x - mean) / sqrt(var + eps) with the mean and variance over chosen axes and keepdims=True: the standardise pattern, with the axes changed.
  • Attention (P7.3 to P7.5) and masks (P7.8). The score einsum, the padding mask and the causal mask are the ones you built here.
  • Nearest neighbours and clustering (P3.B1, P3.C1). All pairwise distances.
  • PyTorch (P2.6). torch.einsum has the same notation, and broadcasting follows the same rule.

Common mistakes

Check your understanding

  1. X has shape (100, 5). Which line standardises each column (mean 0, standard deviation 1)?

  2. labels is an integer array of shape (6,) with values from 0 to 3. Which expression gives a (6, 4) array whose row i is the one-hot vector of labels[i]?

  3. A has shape (3, 4) and x has shape (4,). Which call is the same as A @ x?

  4. A and B both have shape (3, 4). What does np.einsum("ij,ij->", A, B) compute?

  5. M has shape (2, 3). What is the shape of np.einsum("ba", M)?

  6. A has shape (n, d) and B has shape (m, d). How many numbers does the intermediate array A[:, None, :] - B[None, :, :] hold?

Exercises

  1. Standardise the columns of (110320530)\begin{pmatrix}1&10\\3&20\\5&30\end{pmatrix} (use NumPy’s default standard deviation, dividing by NN). What is the result?
    Show answerThe means are (3,20)(3, 20) and the standard deviations are 8/3≈1.633\sqrt{8/3}\approx1.633 and 200/3≈8.165\sqrt{200/3}\approx8.165. Both columns become (−1.225, 0, 1.225)(-1.225,\ 0,\ 1.225), because the second column is 5 times the first plus 5, and standardising removes a shift and a positive scale. In code: (X - X.mean(axis=0)) / X.std(axis=0).
  2. Write one line that builds the 4×44\times4 table of ∣i−j∣\lvert i-j\rvert for i,j=0,…,3i,j=0,\dots,3.
    Show answeri = np.arange(4); np.abs(i[:, None] - i[None, :]), which is [[0 1 2 3] [1 0 1 2] [2 1 0 1] [3 2 1 0]].
  3. One-hot encode labels = [1, 3, 0] for 4 classes in one line.
    Show answer(np.array([1, 3, 0])[:, None] == np.arange(4)).astype(int) gives [[0 1 0 0] [0 0 0 1] [1 0 0 0]].
  4. For A = [[0, 0], [1, 0]] and B = [[0, 3], [4, 0]], compute the table of squared distances by hand, and say how many numbers A[:, None, :] - B[None, :, :] holds.
    Show answerD=(916109)D=\begin{pmatrix}9&16\\10&9\end{pmatrix} (for example (1,0)−(0,3)=(1,−3)(1,0)-(0,3)=(1,-3) has squared length 1010). The difference array has shape (2, 2, 2), so 2⋅2⋅2=82\cdot2\cdot2=8 numbers. For n=m=1000n=m=1000 and d=100d=100 the same array would hold 10810^8 numbers, 800 MB in 64-bit floats.
  5. Write an einsum for ∑i,jAijBji\sum_{i,j}A_{ij}B_{ji}, which is the trace of the matrix product AB\mathbf{A}\mathbf{B}, without forming the product.
    Show answernp.einsum('ij,ji->', A, B). Letter i is the row of A and the column of B, j the other way round, and both are summed. For A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]] it gives 6969, the same as np.trace(A @ B). ('ij,ij->' would give 70, a different number.)
  6. Shapes (5, 2, 3) and (5, 3, 4): what is the shape of np.einsum('bij,bjk->bik', X, Y)? What happens if Y has shape (5, 4, 3)?
    Show answer(5, 2, 4): the batch letter b and the letters i and k are kept, j is summed. With Y of shape (5, 4, 3) the shared letter j has size 3 in X and size 4 in Y: a ValueError (“operands could not be broadcast together with remapped shapes”).
  7. A has shape (2, 3) and B has shape (4, 3). What does np.einsum('ij,kj', A, B) return, and which ordinary NumPy expression is it?
    Show answerWithout an arrow, the letters that appear once are i and k, so the output is 'ik', shape (2, 4); j appears twice and is summed. It is A @ B.T: every row of A dotted with every row of B.
  8. Code: for the rows of X = [[1, 0], [1, 1], [0, 2]], build the 3×33\times3 table of cosine similarities (P1.B3) using row normalisation and one matrix product.
    Show answerXn = X / np.linalg.norm(X, axis=1, keepdims=True) and Xn @ Xn.T. The result is [[1, 0.707, 0], [0.707, 1, 0.707], [0, 0.707, 1]] (rounded). Normalising the rows first is why a single matrix product gives all the cosines (P1.B3).

Key takeaways

  • Broadcasting jobs you will write again and again: X - X.mean(axis=0) centres columns, / X.std(axis=0) standardises them, X / norm(X, axis=1, keepdims=True) normalises rows, Z + b adds a bias to every example, a[:, None] - b[None, :] builds a table of all pairs, labels[:, None] == np.arange(k) one-hot encodes, and np.arange(n)[None, :] < lengths[:, None] builds a padding mask.
  • All pairwise squared distances between (n, d) and (m, d) points: the broadcast version builds an (n, m, d) array of differences, so memory grows like nmdnmd. The formula ∥a∥2+∥b∥2−2 a⋅b\lVert a\rVert^2 + \lVert b\rVert^2 - 2\,a\cdot b needs only (n, m) arrays and one matrix product, but rounding can leave tiny negative values: clip with np.maximum(D, 0) before a square root.
  • A broadcast that succeeds is not a broadcast that is right. (n, 1) against (n,) gives (n, n) with no error. Print .shape, assert shapes where two arrays meet, and use np.broadcast_shapes to check a pair of shapes without making any data.
  • np.einsum names every axis with a letter. A letter that appears on the input side but not after -> is summed over; the letters after -> are kept. This is the sum ∑kAikBkj\sum_k A_{ik}B_{kj} written as 'ik,kj->ij'. Letters are only names: 'ij,jk->ik' is the same product.
  • Without -> (implicit mode) the output keeps the letters that appear exactly once, sorted alphabetically, so 'ba' is a transpose. Write -> yourself unless you want that rule.
  • Batched matrix product 'bik,bkj->bij' and attention scores 'bqd,bkd->bqk' are the same idea: keep the batch letter, sum the shared letter. Plain einsum can be much slower than @ on big matrices; optimize=True lets NumPy pick a better order, but when a shape matches @, @ is the usual choice.
Found a mistake? Tell us