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 1: Math FoundationsLinear Algebra

Tensors, shapes and broadcasting

P1.B1440 min●●○ IntermediateReviewed Nov 30, 2026

Why this matters for machine learning

Almost every number a model handles lives in an array with several axes (examples, tokens, channels, heads), and almost every bug in model code is a shape that was not what you thought; broadcasting is the rule that lets one small array act on a big one.

  • A batch of images is a 4-axis array, channels-first (N,C,H,W)(N, C, H, W) or channels-last (N,H,W,C)(N, H, W, C), and a layer has to know which axis is which. (P5.1: Images as tensors, coming soon)
  • Adding the bias vector b\mathbf{b} to the output of a layer for every example in a batch is broadcasting, and so is subtracting the column means from a data matrix. (P4.5: The forward pass in matrix form, coming soon)
  • Normalisation layers are defined by the axes they take means and variances over (for example the last axis for layer normalisation). (P4.19: Normalization layers, coming soon)
  • Attention scores for a whole batch are one array with axes batch, head, token, token, and the softmax is taken over the last axis. (P7.3: Queries, keys and values step by step, coming soon)
  • A batch of token embeddings is an array of shape (B,T,d)(B, T, d): examples, tokens in each example, numbers per token. (P4.21: Embedding layers, coming soon)

Before this: Scalars, vectors and spaces, Matrices as data and as transformations, Matrix multiplication, Transpose, symmetric and orthogonal matrices

After this lesson you can

  • Read the shape, number of axes and size of an array, name its axes (also with negative numbers), and say which indexing expressions drop an axis and which keep it
  • Predict the shape after a reduction (sum(axis=...), with and without keepdims), a reshape, a transpose or permute, a stack or concatenate, and a batched matrix product
  • Apply the broadcasting rule (align shapes from the right; sizes must be equal or one of them 1) to decide the result shape or the error, and explain why it is not a copy
  • Spot the classic shape bugs, such as a (n, 1) array minus a (n,) array giving an (n, n) result, and a reshape used where a transpose was meant

A model predicts four house prices, and the true prices are known. In code the predictions come out as a column, shape (4, 1), and the true prices are a plain list, shape (4,):

ypred=(2, 6, 2, 5) as a columny=(3, 5, 2, 4)\begin{aligned} y_{\text{pred}}&=(2,\,6,\,2,\,5)\ \text{as a column}\\ y&=(3,\,5,\,2,\,4) \end{aligned}

The errors are −1,1,0,1-1, 1, 0, 1 and the mean squared error is 0.750.75. But the one-line code ((y_pred - y) ** 2).mean() prints 4.54.5, with no error and no warning. Why? Because NumPy does not subtract the two lists entry by entry. It first stretches them to a common shape and produces a 4×44\times4 table of 1616 differences. This lesson is about shapes: how to read them, how to change them without scrambling the data, and the one rule (broadcasting) that decides what happens when shapes differ. Earlier lessons pointed here several times: a + 10 adding a number to every entry, NumPy stretching arrays in *, np.dot on arrays with more than two axes, and the .T/swapaxes/permute family. Along the way they also used (n,) against (n, 1) and reshape(-1, 1). Here they all get an answer.

Arrays with any number of axes

P1.B1 gave vectors, P1.B5 gave matrices. They are the first members of one family, the arrays, and each is described by its shape: the list of the sizes along each of its axes (an axis is one direction in which you can move along the array).

  • A single number, a scalar: shape (), no axes.
  • A vector with nn entries: shape (n,), one axis.
  • A matrix with mm rows and nn columns: shape (m, n), two axes. The grayscale picture of the digit in P1.B5 is (28, 28).
  • A 3-axis array: shape (a, b, c). A colour picture has height, width and three colour channels: (H, W, 3).
  • And so on. A batch of NN colour pictures is (N, H, W, 3): four axes.

Three numbers describe any array. The shape (the sizes), ndim (the number of axes, which is the length of the shape) and size (the total number of entries, which is the product of the shape). In P1.B1 you met the warning that ndim is not the “dimension” of a vector; the same happens here: a vector with 784 entries has ndim =1=1 and size 784784.

In machine-learning code such an array is called a tensor. That is the only meaning of the word you need on this site: an array of numbers with any number of axes. (In mathematics and physics “tensor” is stricter: it names an object that transforms in a particular way when you change coordinates. Every such object can be written down as an array of numbers, but not every array of numbers is such an object, so do not read more into the word than “N-D array” when you see it in ML.)

Our running example is a small array with three axes, T = np.arange(24).reshape(2, 3, 4). Think of 2 sheets, each with 3 rows and 4 columns:

T[0] = [[ 0  1  2  3]
        [ 4  5  6  7]
        [ 8  9 10 11]]

T[1] = [[12 13 14 15]
        [16 17 18 19]
        [20 21 22 23]]

Its shape is (2, 3, 4), ndim is 33 and size is 2⋅3⋅4=242\cdot3\cdot4=24. The array (B, T, d) of token embeddings and the array of images are the same kind of object with different meanings for the axes: the meaning is yours to remember, NumPy only knows the sizes.

Axes, negative axes and indexing

Axes are numbered from 0, in the order the shape is written. In (2, 3, 4), axis 0 has size 2 (the sheets), axis 1 has size 3 (the rows) and axis 2 has size 4 (the columns). A negative number counts from the end: axis -1 is the last axis, -2 the one before it. So T.shape[-1] is 44. Negative axes are the way to say “the feature axis, whatever the number of leading batch axes”, and that is why they are everywhere in model code.

To pick an entry you give one index per axis, T[1, 2, 3] is 2323 (sheet 1, row 2, column 3, counting from 0). If you give fewer indices, the axes you left out stay whole: T[1, 2] is the row [20 21 22 23]. A slice : keeps a whole axis, and ... (an “ellipsis”) means “all the axes not mentioned”.

The shape after indexing follows three simple rules:

  • An integer index drops its axis: T[0].shape is (3, 4).
  • A slice keeps its axis, even if it has length 1: T[0:1].shape is (1, 3, 4).
  • None (also written np.newaxis) adds a new axis of size 1: T[:, None].shape is (2, 1, 3, 4).

For T (shape (2, 3, 4)) these give: T[:, 1].shape is (2, 4), T[:, 1:2].shape is (2, 1, 4) and T[..., 0].shape is (2, 3). The same holds for the data matrix of P1.B5 (5 houses, 3 features, X.shape is (5, 3)): X[1], one house, has shape (3,) and X[1:2] has shape (1, 3); the column X[:, 0] of areas has shape (5,) and X[:, 0:1] has shape (5, 1). That last pair is how you get a column that is really a column.

Adding up along an axis

A reduction turns many numbers into fewer: sum, mean, max, argmax and more. Called with no axis it uses every entry and returns one number. Called with axis=k it works along axis k: for each position of the other axes it adds up the entries as the index kk runs through its range, and axis k disappears from the shape.

Take M=(123456)\mathbf{M}=\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix} (shape (2, 3)). Then M.sum(axis=0) is [5 7 9] and M.sum(axis=1) is [6 15].

The confusing part is the word “axis 0 means down the rows”. It means that the addition walks down along axis 0, the axis the rows are stacked on, so each column is added up into one number and the result has one number per column, written across. It does not mean that the result is arranged down the rows. A reliable way to remember: the axis you name is the one that vanishes, and the shape tells you what is left. Use the widget to see it on a 3×43\times4 array.

Which axis does sum remove?

123456789101112 15182124
G.sum(axis=0)

Result: [15 18 21 24], shape (4,)

Axis 0 (size 3, the one that runs down the rows) is added over: each column is added up into one number. The shape goes from (3, 4) to (4,), because that axis is removed.

The array is G = np.arange(1, 13).reshape(3, 4). Blue cells are added together; the shading alternates so you can see which cells form one group. The outlined boxes are the result, placed next to the groups it came from.

Axis sums. The array G has 3 rows and 4 columns. Choose axis=0, axis=1 or no axis, and tick keepdims. The blue cells are the ones added together (the shading alternates so you can see the groups), the boxed cells are the result, and the line below gives the code, the printed result and its shape. With axis=0 the three rows are collapsed into one row of column sums; with axis=1 the four columns are collapsed into one column of row sums.

Things to try:

  1. axis=0: each column (e.g. 1+5+9=151+5+9=15) becomes one number. The shape (3, 4) becomes (4,): the 3 vanished.
  2. axis=1: each row (1+2+3+4=101+2+3+4=10) becomes one number: (3, 4) becomes (3,). Notice that a result with shape (3,) is a plain 1-D array: it is neither a row nor a column.
  3. Tick keepdims. The summed axis stays with size 1: (1, 4) and (3, 1). Now the result still has the same number of axes as G, which will matter in a moment.
  4. no axis: all 12 entries add to 78, shape ().

For the 3-axis array T: T.sum(axis=1).shape is (2, 4), T.sum(axis=-1).shape is (2, 3), and several axes at once work too: T.sum(axis=(0, 2)).shape is (3,). The same works for mean: for the 5-house matrix of P1.B5, X.mean(axis=0) is one mean per feature, [102, 2.6, 20]. And argmax(axis=1) gives one index per row.

keepdims=True is more than a taste. A result that keeps its axes can be combined straight back with the original array by broadcasting (the next big section), as in “subtract each row’s mean from that row”.

Reshape: same numbers, new cutting

Reshape changes how the same entries are cut into axes. It does not change, add or reorder any number. NumPy reads the entries in row-major order (also called C order): last axis changes fastest, like reading a page line by line. Start with 0,1,2,3,4,50,1,2,3,4,5 in a row, cut into 2 rows of 3, or 3 rows of 2:

A = np.arange(6).reshape(2, 3)
 [[0 1 2]
  [3 4 5]]

A.reshape(3, 2)
 [[0 1]
  [2 3]
  [4 5]]

Three rules. The total size must stay the same (2·3 = 3·2 = 6; A.reshape(4, 2) fails with a ValueError, message like “cannot reshape array of size 6 into shape (4,2)”). One of the new sizes may be -1, which means “work this one out”: A.reshape(3, -1) is (3, 2) and A.reshape(-1) is the flat vector (6,). And the order is kept: the flat reading of a reshaped array is the same list as before.

This is how a 28×2828\times28 image becomes a vector of 784 entries (P1.B1, P1.B5), and how a vector of 6 becomes a column: v.reshape(-1, 1) has shape (6, 1). Two other ways to make that column are v[:, None] and np.expand_dims(v, 1); np.squeeze removes axes of size 1 (np.zeros((1, 3, 1)).squeeze().shape is (3,)).

Reshape is not transpose

This is the most common shape mistake. A.reshape(3, 2) and A.T both have shape (3, 2), but the entries are different:

A.reshape(3, 2)     A.T
 [[0 1]              [[0 3]
  [2 3]               [1 4]
  [4 5]]              [2 5]]

The transpose (P1.B10) really flips the matrix: the row (0,1,2)(0,1,2) becomes a column. A reshape keeps reading order and just re-cuts the line. If you reshape when you meant to transpose, the shapes agree, no error appears, and the numbers are scrambled. The same trap hides in images: if a picture is stored channels-first (C, H, W) and you reshape it to (H, W, C) instead of permuting the axes (next section), you get a picture of noise with a perfectly legal shape.

ravel() and flatten() both give the flat 1-D version (A.ravel() is [0 1 2 3 4 5]). flatten always returns a copy; ravel and reshape return a view of the same memory when they can, and a copy when they cannot, so a change to the result may or may not change the original. Keep the rule: do not rely on either; copy explicitly (.copy()) if you plan to change the result.

Joining arrays: stack and concatenate

Two functions join arrays, and the difference is exactly one axis. np.stack([x, y]) joins arrays of the same shape along a new axis: two (3, 4) arrays give (2, 3, 4). np.concatenate([x, y], axis=1) joins along an axis that already exists: two (3, 4) arrays give (3, 8) (and axis=0 gives (6, 4)). Use stack to make a batch out of single examples.

Go deeper Views and copies: when does a change leak?

A view shares the same memory as another array, so writing through one is visible in the other; a copy has its own memory. After A = np.arange(6).reshape(2, 3) the transpose A.T is a view (np.shares_memory(A, A.T) is True) because NumPy only changes how it reads the same entries. A.T.ravel() has to put the entries in a new order, so it is a copy. For a simple array like A, A.ravel() and A.reshape(3, 2) are views: b = A.ravel(); b[0] = 99 changes A too.

When a view is possible is a detail of how the array is laid out in memory, and you should not rely on it either way. The safe habits: use .copy() when you need your own array, and never write into the result of a reshape, ravel or transpose unless you want the original changed too. PyTorch has the same idea (its docs describe permute as returning a view).

Transposing many axes

For two axes .T swaps rows and columns (P1.B10). For more axes there are more ways to rearrange, and three tools cover them:

  • .T reverses all the axes. T.T.shape is (4, 3, 2), and T.T[3, 2, 1] equals T[1, 2, 3]. For a 1-D array it does nothing, which is the trap from P1.B10.
  • np.transpose(a, axes) puts the axes in any order you list: entry kk of the tuple says which old axis goes in place kk. np.transpose(T, (1, 0, 2)).shape is (3, 2, 4).
  • np.swapaxes(a, i, j) swaps just two. T.swapaxes(0, 2).shape is (4, 3, 2), and swapaxes(-1, -2) transposes the last two axes of any stack of matrices.

PyTorch’s x.permute(...) is the counterpart of np.transpose(x, ...): it takes the new order of all the axes. PyTorch’s x.transpose(i, j) swaps two, like swapaxes. (PyTorch’s own documentation says that .T on tensors that do not have exactly two axes, used to reverse the shape, is deprecated and will become an error; write permute or transpose instead.)

The classic use is the channels question (P5.1). A batch of 8 colour pictures of 32×3232\times32 pixels can be stored channels-last, (8, 32, 32, 3), which is (N, H, W, C), or channels-first, (8, 3, 32, 32), which is (N, C, H, W). Moving between them is a permutation of the axes, not a reshape: x.transpose(0, 3, 1, 2) in NumPy (or x.permute(0, 3, 1, 2) in PyTorch) turns (8, 32, 32, 3) into (8, 3, 32, 32), and transpose(0, 2, 3, 1) goes back. PyTorch’s Conv2d layer expects channels-first input (N, C, H, W) (its documentation says so), while the Keras Conv2D layer takes channels-last (batch, height, width, channels) unless its data_format setting says otherwise (its documentation says that too). Libraries differ, so check the layout before you feed data into a layer.

Broadcasting: stretching the smaller array

P1.B2 noted that NumPy accepts np.array([1, 2, 3]) + 10 and adds 10 to every entry, and that np.array([1, 2]) + np.array([1, 2, 3]) fails with the error “could not be broadcast together”. Both are the same mechanism, called broadcasting: a rule that decides when two arrays of different shapes can be combined entry by entry, and how. The idea is to stretch the smaller array until its shape matches, like a stamp that repeats a row down a page.

The rule, as NumPy’s documentation states it (here in four steps):

  1. Align the two shapes from the right. Compare the last axes first, then the next to last, and so on.
  2. A missing leading axis counts as size 1. If one array has fewer axes, imagine 1s written on the left of its shape.
  3. On each axis the two sizes must be equal, or one of them must be 1. Otherwise NumPy raises a ValueError.
  4. The result has the larger size on each axis (the one that is not 1). An axis of size 1 is stretched to match.

The widget applies exactly this rule.

Broadcasting: can these two shapes be combined?

axis -2axis -1
A 34
B 1 (added)4
Result 34
✓ stretch B✓ equal
A (3, 4)
123456789101112
B (4,) stretched
102030401020304010203040
Result (3, 4)
112233441526374819304152

Solid cells are the real entries (A is 1, 2, 3, … and B is 10, 20, 30, … in reading order). Dashed, faded cells are the copies made by stretching. The stretching copies nothing in memory (only the result is a new array); the picture is how to think of it.

Compatible. The result has shape (3, 4). B has fewer axes, so a leading 1 is added: (4,) is treated as (1, 4). B is stretched along axis -2 from 1 to 3.

A (3, 4)
3
4
B (4,)
4
Broadcasting visualiser. Pick the number of axes and the size of each axis of two arrays A and B (A holds 1, 2, 3, … and B holds 10, 20, 30, … in reading order), and the operation. The table lines the shapes up from the right and marks each axis: equal, one of them stretched, or a clash. Below it, solid cells are the real entries and dashed faded cells are the copies made by stretching, so you see B (or A) fill out to the result shape. The controls are under the picture. A clash shows a red cross, the status gives NumPy's error, and the presets include the failing cases and the (n,1) minus (n,) bug. Grids are drawn for arrays with at most 2 axes; for 3 axes read the table.

Things to try:

  1. Start with the first preset, (3,4) + (4,): a matrix plus a vector. The vector has one axis, so a leading 1 is added: (1, 4). Axis -1 is 44 against 44: equal. Axis -2 is 33 against 11: B is stretched down to 3 rows. The result is (3, 4), and every row of A got the same (10,20,30,40)(10, 20, 30, 40) added.
  2. (3,4) + (3,1): now B is a column. Axis -1 is 44 against 11, so each entry of the column is repeated across the row. This adds one number to each row of A.
  3. (3,1) + (1,4): both arrays are stretched, and the result is (3, 4): every pairing of a number from A with a number from B (the status warns about this).
  4. (2,3) + (2,): the last axes are 33 and 22. Not equal and neither is 1: a red cross, no result, and NumPy’s error. (3,) + (4,) fails the same way. The fix for the first is to make B a column of shape (2, 1).
  5. bug: (4,1) − (4,): this is the opening puzzle. B is treated as (1, 4); both are stretched and the result is (4, 4). There is no error: both shapes are legal.
  6. (3,) + scalar: a scalar has no axes, so it is treated as size 1 on every axis: this is a + 10. (2,3,4) + (3,1): B is treated as (1, 3, 1) and stretched on two axes; the result has 3 axes.
  7. Use the steppers to make your own pair. Try to predict each result shape before you look.

Intuition

Picture the smaller array as a stamp. A row of numbers, (4,), is stamped down on every row of a (3, 4) page; a column, (3, 1), is stamped across on every column. If both are small, as in (3, 1) and (1, 4), each one is stamped in its own direction and the two together fill a whole page, like a multiplication table.

The picture has limits. A stamp makes real copies; NumPy does not (see below). The rule is only about sizes, never about meaning: NumPy will gladly stretch a column of predictions against a row of targets if the sizes allow it, whether or not that makes sense for your problem. It checks that the sizes can be combined, not that you wanted them combined.

Math

Write the aligned shapes as (a1,…,an)(a_1,\dots,a_n) and (b1,…,bn)(b_1,\dots,b_n) (pad the shorter one with 1s on the left). They are compatible when for every kk either ak=bka_k=b_k, or ak=1a_k=1, or bk=1b_k=1, and the result shape has ck=max⁡(ak,bk)c_k=\max(a_k,b_k) (for sizes of at least 11; an axis of size 00 against 11 gives 00).

For a matrix and a vector this is the matrix identity

(A+b)ij=Aij+bj,that isA+1b⊤\begin{gathered} (\mathbf{A}+\mathbf{b})_{ij}=A_{ij}+b_j, \\ \text{that is}\quad\mathbf{A}+\mathbf{1}\mathbf{b}^\top \end{gathered}

where 1\mathbf{1} is the column of all ones: the outer product 1b⊤\mathbf{1}\mathbf{b}^\top is the matrix whose every row is b⊤\mathbf{b}^\top. Adding a column c\mathbf{c} is A+c1⊤\mathbf{A}+\mathbf{c}\mathbf{1}^\top. Adding a (3,1)(3,1) column and a (1,4)(1,4) row gives the 3×43\times4 matrix with entries ci+bjc_i+b_j.

Code

import numpy as np

A = np.arange(12).reshape(3, 4)          # shape (3, 4)
b = np.array([10, 20, 30, 40])           # shape (4,)
c = np.array([[100], [200], [300]])      # shape (3, 1)
print(A + b)       # b is added to every row
print(A + c)       # c is added to every column
print((c + b).shape)   # (3, 4): a (3, 1) and a (4,) fill a table

A + b is [[10 21 32 43] [14 25 36 47] [18 29 40 51]], and A + c is [[100 101 102 103] [204 205 206 207] [308 309 310 311]].

Two examples from machine learning

A bias for the whole batch. A layer’s output on a batch (P1.B6) is XW⊤\mathbf{X}\mathbf{W}^\top, shape (N, h), and the layer then adds its bias b\mathbf{b} (P1.B5), shape (h,), to every example. That is Z + b: (N, h) and (h,) are compatible, and the vector is added to every row. For the 2×22\times2 product of P1.B10, (−2−2413)\begin{pmatrix}-2&-2\\4&13\end{pmatrix}, and b=(10,20)\mathbf{b}=(10,20) the result is (8181433)\begin{pmatrix}8&18\\14&33\end{pmatrix}.

Centering the columns. For the 5-house matrix X of P1.B5, X - X.mean(axis=0) subtracts each column’s mean from that column: (5, 3) and (3,). The first house becomes (18,0.4,−5)(18, 0.4, -5), and every column now adds up to 00 (up to rounding). Subtracting means is how data is centred before PCA (P3.C3) and how normalisation layers (P4.19) start.

Where keepdims earns its keep

Dividing each row of S=(123456789)\mathbf{S}=\begin{pmatrix}1&2&3\\4&5&6\\7&8&9\end{pmatrix} by its own sum should give rows that add to 1. Written with keepdims=True it does: S / S.sum(axis=1, keepdims=True) divides (3, 3) by (3, 1), and every row sums to 1. Written without, S / S.sum(axis=1) divides (3, 3) by (3,), which is treated as a row (1, 3): it divides each column by the vector (6,15,24)(6, 15, 24), rows now sum to 0.425, 1.25, 2.0750.425,\ 1.25,\ 2.075, and no error is raised because the matrix happens to be square. For a (5, 3) matrix the same slip fails with an error, which is the lucky case. This is the same trap as the opening puzzle. The same trick is how softmax is computed along the last axis of a score array: subtract s.max(axis=-1, keepdims=True), exponentiate, divide by e.sum(axis=-1, keepdims=True) (P7.4, P1.G2).

The silent shape bug

Back to the opening puzzle. The shape (n, 1) minus (n,) is legal and gives (n, n): entry (i,j)(i, j) of the result is y^i−yj\hat y_i-y_j, every prediction against every target. For n=4n=4 and the numbers above, the 1616 squared differences average to 4.54.5 instead of 0.750.75. The model would still train, just on the wrong loss (PyTorch’s mse_loss can print a warning about a size mismatch like this one, but you should not rely on that). The fixes are to make the shapes agree: y_pred.ravel() or y_pred.squeeze(1), or y.reshape(-1, 1).

The defence is a habit: print the shapes, and assert them (assert y_pred.shape == y.shape) at the place where two arrays meet.

Go deeper Broadcasting does not copy: stride zero

Conceptually, broadcasting stretches the smaller array. In memory, NumPy does not make copies. It reads the one row again and again by using a stride of zero bytes along the stretched axis. You can see it with np.broadcast_to: for b = np.arange(4.0), which holds 8-byte numbers, bb = np.broadcast_to(b, (3, 4)) has bb.strides equal to (0, 8): stepping down a row moves by 0 bytes, stepping along a row moves by 8. It shares memory with b (np.shares_memory(b, bb) is True) and is read-only. Broadcasting a small array against a huge one therefore costs almost no extra memory for the small one (the result of the operation is a new, full-size array, of course).

Shape puzzles

Predicting a shape from a line of code is a skill you build by practice. The puzzles use the arrays and the operations of this lesson. Think first, then choose.

Shape puzzles: what is the shape of the result?

Question 1 of 16 · score 0

import numpy as np
a = np.zeros((2, 3, 4))
result = a.sum(axis=1)

What is result.shape, or does NumPy raise an error?

Shape puzzles. Sixteen questions, each with a line of NumPy. Choose the shape of the result, or an error. You get the explanation right away, and a score at the end.

Batched matrix products

P1.B6 multiplied two matrices. In real code you multiply stacks of matrices. NumPy’s @ (and PyTorch’s) follow the rule: for arrays with more than two axes, the last two axes are the matrices, and all the leading axes are treated as a batch that is broadcast by the rule above. So for each position in the batch a (p, q) matrix meets a (q, r) matrix and gives a (p, r) matrix.

  • (2, 5, 3) @ (3, 7) is (2, 5, 7): a batch of two 5×35\times3 matrices, each multiplied by the same 3×73\times7 matrix. This is a layer on a batch of B=2B=2 sequences of T=5T=5 tokens: X @ W with X of shape (B, T, d).
  • (2, 3, 4) @ (2, 4, 5) is (2, 3, 5): a different matrix for each item of the batch.
  • (2, 1, 3, 4) @ (5, 4, 6) is (2, 5, 3, 6): the batch axes (2, 1) and (5,) broadcast to (2, 5).
  • With a 1-D operand it works like P1.B6: (3, 4) @ (4,) is (3,), and (4,) @ (4,) is a plain number.
  • Attention scores (P7.3): queries Q of shape (B, h, T, d_k) and keys K of the same shape, Q @ K.swapaxes(-1, -2) has shape (B, h, T, T): for every example and every head, all token-against-token dot products at once. The softmax then runs over the last axis (axis=-1), so each row of scores becomes a set of weights adding to 1.

The inner sizes must still agree and the batch sizes must broadcast: (2, 3, 4) @ (3, 4, 5) fails because the batch axes 22 and 33 clash. Do not use np.dot for this. For more than two axes, np.dot does something different (it combines every item of the first array with every item of the second): np.dot of a (2, 3, 4) and a (2, 4, 5) array has shape (2, 3, 2, 5), not (2, 3, 5). This is why P1.B6 recommended @.

Go deeper einsum: naming the axes instead of remembering them

np.einsum writes a product by naming each axis with a letter. The rule: a letter that appears in the inputs but not after the arrow is summed over; letters after the arrow are kept. Matrix product: np.einsum('ij,jk->ik', A, B) equals A @ B (jj is summed). Transpose: np.einsum('ij->ji', A). Sum over rows: np.einsum('ij->j', A) equals A.sum(axis=0). Outer product: np.einsum('i,j->ij', u, v). The attention scores above are np.einsum('bhtd,bhsd->bhts', Q, K): batch b and head h are kept, d is summed, and the two token axes t and s stay apart. Many people find it easier to read than a chain of swapaxes and @. P2.3 teaches it in depth.

Habits that prevent shape bugs

  • Print .shape of every array the first time you write a step. A shape you did not expect is a bug found early.
  • Assert shapes where two arrays meet: assert y_pred.shape == y.shape.
  • Write the axes in a comment: # X: (B, T, d). NumPy does not know what the axes mean; you must.
  • Make columns on purpose with v[:, None] or reshape(-1, 1), and use keepdims=True when the result will be combined with the original array.
  • When a result seems the right shape but wrong, ask: did I reshape where I should have transposed?
  • Broadcast silently only when you meant to. When in doubt, write the shape you expect on paper first.

Try it in NumPy

The first cell covers shapes, indexing, reductions, reshape against transpose, and joining arrays.

Try it: shapes, indexing, reshape and axes

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

What to expect: T.shape is (2, 3, 4) with ndim 3 and size 24; the shape of each indexed form is the one in the text; A.reshape(3, 2) is not equal to A.T; and the failing reshape prints a ValueError (its exact wording can differ between NumPy versions). Change a line and predict the shape before you run it.

The second cell is about broadcasting, the silent bug and batched products.

Try it: broadcasting, the (n,1) bug and batched matmul

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

What to expect: the first two lines show A + row and A + column, then the shape (3, 4) of the outer-style sum. The two failures print operands could not be broadcast together with shapes ... (the wording and spacing can differ between versions). The opening puzzle prints (4, 4), then 4.54.5, then 0.750.75. The row sums with keepdims are 11 (up to rounding); without it they are 0.425,1.25,2.0750.425, 1.25, 2.075. The last block prints (2, 5, 7), (2, 3, 5, 5) and (2, 3, 2, 5).

Where you will meet it next

  • The forward pass with a batch (P4.5, P4.10). A layer on (N, d) data is X @ W.T + b, shape (N, h), with the bias broadcast.
  • Embeddings (P4.21) and attention (P7.3 to P7.5). (B, T, d) activations, scores of shape (B, h, T, T), softmax over the last axis, and batched @.
  • Normalisation (P4.19). Batch, layer, group and RMS normalisation differ in which axes they average over, written as mean(axis=..., keepdims=True).
  • Images (P5.1 to P5.5). (H, W, C) for one picture, (N, C, H, W) or (N, H, W, C) for a batch, and the permutation between them.
  • The libraries. P2.2 and P2.3 (NumPy arrays, broadcasting in practice, einsum) and P2.6 (PyTorch tensors) teach the library functions in full; this lesson gives the ideas those lessons use.
  • The map (P1.B15). The next lesson puts Wx+b\mathbf{W}\mathbf{x}+\mathbf{b} and attention on one map, with these shapes.

Common mistakes

Check your understanding

  1. A has shape (5, 3) and b has shape (5,). What does A + b do?

  2. y_pred has shape (8, 1) and y has shape (8,). What is the shape of y_pred - y?

  3. x has shape (2, 3, 4). What is the shape of x.sum(axis=1, keepdims=True)?

  4. A = np.arange(6).reshape(2, 3), so A is [[0 1 2] [3 4 5]]. What is A.reshape(3, 2)?

  5. x has shape (5, 3). Which expression has shape (5, 1)?

  6. X has shape (4, 10, 16) (batch, tokens, features) and W has shape (16, 8). What is the shape of X @ W?

  7. A batch of images has shape (8, 32, 32, 3) (channels last). What turns it into the channels-first shape (8, 3, 32, 32) without scrambling any picture?

Exercises

  1. For np.zeros((4, 5, 6)) give the shape, ndim and size.
    Show answerShape (4, 5, 6), ndim 3, size 4⋅5⋅6=1204\cdot5\cdot6=120.
  2. For x = np.zeros((4, 5, 6)) give the shapes of x[2], x[:, 2], x[..., 2], x[:, 2:3] and x[None].
    Show answer(5, 6), (4, 6), (4, 5), (4, 1, 6) and (1, 4, 5, 6). The integer indices drop an axis, the slice 2:3 keeps one, and None adds one.
  3. Which of x.reshape(20, -1), x.reshape(-1, 10) and x.reshape(7, -1) work for the same x (120 entries)?
    Show answerThe first gives (20, 6) and the second (12, 10). The third fails: 120/7120/7 is not a whole number.
  4. Give the shapes of x.sum(axis=0), x.sum(axis=(0, 2)) and x.sum(axis=1, keepdims=True).
    Show answer(5, 6), (5,) and (4, 1, 6).
  5. Give the result shape, or say it fails: (a) (5, 1, 4) + (3, 1), (b) (2, 3) + (3, 2), (c) (8,) + (8, 1), (d) (4, 1, 1) + (3, 1).
    Show answer(a) (5, 3, 4): (3, 1) is treated as (1, 3, 1). (b) fails: the last axes are 3 and 2. (c) (8, 8): the silent-bug pattern. (d) (4, 3, 1).
  6. A has shape (3, 4) and b has the three numbers (1,2,3)(1, 2, 3) in a 1-D array. A + b fails. Write the fix so that bib_i is added to row ii.
    Show answerA + b[:, None] (or b.reshape(-1, 1)). The column has shape (3, 1) and is stretched across the 4 columns.
  7. A loss function receives y_pred of shape (6, 1) and y of shape (6,). Give two correct ways to compute the squared errors, each of shape (6,), and an assertion that would have caught the mistake.
    Show answer(y_pred.ravel() - y) ** 2 or (y_pred[:, 0] - y) ** 2; or make y a column and keep (6, 1). The assertion: assert y_pred.shape == y.shape (it fails with (6, 1) against (6,)).
  8. X is an N×dN\times d data matrix. Write one line that subtracts each column’s mean, and one that divides each column by its standard deviation after that. What shape does the mean have, and does keepdims=True change the result?
    Show answerXc = X - X.mean(axis=0) and Xs = Xc / Xc.std(axis=0). The mean has shape (d,); with keepdims=True it is (1, d) and the result is the same, because both are stretched down the rows.
  9. Normalise the rows of S=(123456789)\mathbf{S}=\begin{pmatrix}1&2&3\\4&5&6\\7&8&9\end{pmatrix} so each adds to 1. What is the first row?
    Show answerS / S.sum(axis=1, keepdims=True); the first row is (1,2,3)/6≈(0.167,0.333,0.5)(1,2,3)/6\approx(0.167, 0.333, 0.5).
  10. What is the shape of np.zeros((2, 1, 3, 4)) @ np.zeros((5, 4, 6))?
    Show answer(2, 5, 3, 6): the matrices are (3, 4) @ (4, 6) giving (3, 6), and the batch axes (2, 1) and (5,) broadcast to (2, 5).
  11. Queries and keys both have shape (2, 3, 5, 4) (batch, heads, tokens, head size). Write the scores, give their shape, and say along which axis the softmax is taken.
    Show answerQ @ K.swapaxes(-1, -2) has shape (2, 3, 5, 5). The softmax is taken over the last axis, axis=-1, so each token’s row of scores adds up to 1.
  12. Pictures are stored as (N, C, H, W) and a library wants (N, H, W, C). Give the NumPy line.
    Show answerx.transpose(0, 2, 3, 1). A reshape would keep the shape but scramble the pixels.
  13. Code: show that np.stack and np.concatenate differ by one axis, using two arrays of shape (2, 3).
    Show answernp.stack([a, b]).shape is (2, 2, 3); np.concatenate([a, b]).shape is (4, 3) and with axis=1 it is (2, 6). Stack makes a new axis, concatenate uses an existing one.
  14. Challenge: for a vector v of length 3 give one expression that builds the 3×33\times3 table of all differences vi−vjv_i-v_j. Check it with v=(1,2,4)v=(1,2,4).
    Show answerv[:, None] - v[None, :] (shapes (3, 1) and (1, 3)). For v=(1,2,4)v=(1,2,4) the rows are (0,−1,−3)(0,-1,-3), (1,0,−2)(1,0,-2) and (3,2,0)(3,2,0).

Key takeaways

  • An array has a shape (the size of each axis), a number of axes ndim and a size (the number of entries, the product of the shape). A scalar has shape (), a vector (n,), a matrix (m, n). In ML code a tensor is an array with any number of axes; in maths and physics the word means something stricter.
  • Axes are numbered from 0, and negative numbers count from the end: -1 is the last axis. An integer index drops its axis, a slice such as i:i+1 keeps it, and None (np.newaxis) adds an axis of size 1.
  • sum(axis=k) adds along axis k and removes that axis from the shape; keepdims=True leaves it behind with size 1. axis=0 means “add down the rows, one result per column”, not “the result lies down the rows”.
  • reshape keeps the same entries in the same row-major order and only changes how they are cut into axes; the total size must stay equal, and one size may be -1 (worked out for you). It is not a transpose: A.reshape(3, 2) and A.T have the same shape and different entries.
  • .T reverses all axes; np.transpose(a, axes) or PyTorch permute puts them in any order; swapaxes swaps two. np.stack joins arrays along a new axis, np.concatenate along an existing one.
  • Broadcasting rule: align the shapes from the right, treat missing leading axes as 1, and on each axis the sizes must be equal or one of them 1; the result takes the size that is not 1. Otherwise NumPy raises an error. The stretching itself copies nothing (the result is a new array).
  • The silent bug: (n, 1) against (n,) is a valid broadcast and gives an (n, n) result. @ on arrays with more than two axes treats the last two axes as matrices and broadcasts the others. Print .shape and assert it.
Found a mistake? Tell us