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

Matrix multiplication

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

Why this matters for machine learning

Almost all the arithmetic in a neural network is matrix multiplication: it applies a layer to a whole batch at once, chains layers together, and computes attention scores.

  • A layer applied to a whole batch of examples is one product, XW⊤\mathbf{X}\mathbf{W}^\top, so every example and every neuron is handled in a single operation. (P4.5: The forward pass in matrix form, coming soon)
  • Stacking two layers multiplies their matrices. Without a nonlinearity in between, the two collapse into one matrix, which is why networks need activation functions. (P4.3: Multi-layer perceptrons, coming soon)
  • Attention scores for every pair of tokens come from one product, QK⊤\mathbf{Q}\mathbf{K}^\top, followed by a softmax and another product with V\mathbf{V}. (P7.3: Queries, keys and values step by step, coming soon)
  • LoRA fine-tuning stores a weight update as the product of two thin matrices, which is far fewer numbers than the full matrix. (P10.E3: Parameter-efficient fine-tuning, coming soon)
  • The cost of a model is mostly the cost of its matrix products, which is why GPUs and other accelerators are built to do them fast. (P10.B8: Hardware for deep learning, coming soon)

Before this: Dot product and cosine similarity, Matrices as data and as transformations

After this lesson you can

  • Multiply two matrices by hand, entry by entry (row of A\mathbf{A} dotted with column of B\mathbf{B}), after checking the shapes (m×n)(n×p)→(m×p)(m\times n)(n\times p)\to(m\times p)
  • See one product four ways (entries, columns, rows, and a sum of outer products) and use whichever way answers the question at hand
  • Explain AB\mathbf{A}\mathbf{B} as “first B\mathbf{B}, then A\mathbf{A}”, show with a picture that AB≠BA\mathbf{A}\mathbf{B}\neq\mathbf{B}\mathbf{A} in general, and say which rules still hold (associative, distributive, identity)
  • Count the multiply-adds in a product, choose a cheap order for a chain of products, and write products in NumPy with @

In P1.B5 a matrix acted on one vector. Two questions come up at once. What if you have many vectors, such as a whole dataset? And what if you apply one matrix and then another? Both have the same answer: multiply the two matrices. This one operation is the workhorse of machine learning, and this lesson shows how to do it by hand, how to see what it means, and what it costs.

From one vector to many

Start from what you know. Let

A=(123456)\mathbf{A}=\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix} B=(789101112)\mathbf{B}=\begin{pmatrix}7&8\\9&10\\11&12\end{pmatrix}

A\mathbf{A} is 2×32\times3, so it takes 3-entry vectors in and gives 2-entry vectors out (P1.B5). Now look at B\mathbf{B} as two column vectors standing side by side: b1=(7,9,11)\mathbf{b}_1=(7,9,11) and b2=(8,10,12)\mathbf{b}_2=(8,10,12). Apply A\mathbf{A} to each one, using the rows-dotted-with-x\mathbf{x} way from P1.B5:

Ab1=(1⋅7+2⋅9+3⋅114⋅7+5⋅9+6⋅11)=(58139)Ab2=(1⋅8+2⋅10+3⋅124⋅8+5⋅10+6⋅12)=(64154)\begin{aligned} \mathbf{A}\mathbf{b}_1&=\begin{pmatrix}1\cdot7+2\cdot9+3\cdot11\\4\cdot7+5\cdot9+6\cdot11\end{pmatrix}\\ &=\begin{pmatrix}58\\139\end{pmatrix}\\ \mathbf{A}\mathbf{b}_2&=\begin{pmatrix}1\cdot8+2\cdot10+3\cdot12\\4\cdot8+5\cdot10+6\cdot12\end{pmatrix}\\ &=\begin{pmatrix}64\\154\end{pmatrix} \end{aligned}

Put the two results side by side as the columns of a new matrix. That matrix is the product:

AB=(5864139154)\mathbf{A}\mathbf{B}=\begin{pmatrix}58&64\\139&154\end{pmatrix}

So AB\mathbf{A}\mathbf{B} means “apply A\mathbf{A} to every column of B\mathbf{B}”. With a data matrix this is how you process many examples at once.

The recipe: row times column

Look at where each of the four numbers came from. Every entry of AB\mathbf{A}\mathbf{B} is a row of A\mathbf{A} dotted with a column of B\mathbf{B} (P1.B3). In symbols, the entry in row ii and column jj is

(AB)ij=∑k=1nAik Bkj=Ai1B1j+Ai2B2j+⋯+AinBnj\begin{aligned} (\mathbf{A}\mathbf{B})_{ij}&=\sum_{k=1}^{n}A_{ik}\,B_{kj}\\ &=A_{i1}B_{1j}+A_{i2}B_{2j}\\ &\quad+\dots+A_{in}B_{nj} \end{aligned}

(Here A\mathbf{A} has nn columns. (AB)ij(\mathbf{A}\mathbf{B})_{ij} means “the (i,j)(i,j) entry of the product”, and the brackets keep the subscripts attached to the whole product.) For the example, all four entries:

(AB)11=1⋅7+2⋅9+3⋅11=7+18+33=58(AB)12=1⋅8+2⋅10+3⋅12=8+20+36=64(AB)21=4⋅7+5⋅9+6⋅11=28+45+66=139(AB)22=4⋅8+5⋅10+6⋅12=32+50+72=154\begin{aligned} (\mathbf{A}\mathbf{B})_{11}&=1\cdot7+2\cdot9+3\cdot11\\&=7+18+33=58\\ (\mathbf{A}\mathbf{B})_{12}&=1\cdot8+2\cdot10+3\cdot12\\&=8+20+36=64\\ (\mathbf{A}\mathbf{B})_{21}&=4\cdot7+5\cdot9+6\cdot11\\&=28+45+66=139\\ (\mathbf{A}\mathbf{B})_{22}&=4\cdot8+5\cdot10+6\cdot12\\&=32+50+72=154 \end{aligned}

Picture the row sliding across the column: you walk along the row of A\mathbf{A} and down the column of B\mathbf{B} together, multiply each pair, and add up. Try it yourself in the widget. It writes the multiply-add out one product at a time.

Slide a row of A across a column of B

row of A column of B entry of AB
7
8
9
10
11
12
1
2
3
4
5
6

(AB)11 = row 1 of A · column 1 of B

1×7 + 2×9 + 3×11 = 7 + 18 + 33 = 58

Entry in row 1, column 1 of AB = row 1 of A · column 1 of B. Row 1 of A has 3 numbers and column 1 of B has 3, so they can be paired off.

Click an entry of AB to see its row and column. “Step one product” adds one term at a time: the strong blue and pink cells are the pair being multiplied now. Shapes: A is 2×3, B is 3×2, so AB is 2×2.

Row times column. A is at the bottom left, B at the top right, and the product AB at the bottom right. Click an entry of AB to see the row of A (blue) and the column of B (pink) that make it. Use Step one product to add one term at a time, Next entry to move on, or Play to watch every entry in turn. Four example shapes are provided, including a matrix times a vector.

Things to try:

  1. Click each entry of the product in the first example and check it against the four lines above.
  2. Press Step one product repeatedly and watch the running total grow: each step multiplies one entry of the row by the matching entry of the column.
  3. Switch to 3×2 times 2×3. The product is 3×33\times3: nine entries, each a dot product of only two pairs. The size of the result comes from the outer numbers, and the number of terms in each sum comes from the inner number.
  4. Switch to the last example. With one column in B\mathbf{B} the product has one column: this is the matrix-times-vector product from P1.B5, now seen as a special case.

The shape rule

Each entry pairs up a row of A\mathbf{A} with a column of B\mathbf{B}. A dot product needs two lists of the same length (P1.B3). A row of A\mathbf{A} has as many numbers as A\mathbf{A} has columns, and a column of B\mathbf{B} has as many numbers as B\mathbf{B} has rows. So the number of columns of A\mathbf{A} must equal the number of rows of B\mathbf{B}. When it does:

(m×n)⏟A (n×p)⏟B ⟶ (m×p)⏟AB\underbrace{(m\times n)}_{\mathbf{A}}\ \underbrace{(n\times p)}_{\mathbf{B}}\ \longrightarrow\ \underbrace{(m\times p)}_{\mathbf{A}\mathbf{B}}

The two inner numbers (both nn) must match, and they disappear. The two outer numbers, mm and pp, are the shape of the result: one row for each row of A\mathbf{A}, one column for each column of B\mathbf{B}.

Can these two matrices be multiplied?

×=2×33×22×2

AB is defined: the inner dimensions match (3 = 3), so the result has the outer dimensions 2×2. It has 4 entries, each a dot product of 3 pairs, so 12 multiply-adds in all (about 24 floating-point operations). The other order BA is also defined, but its shape is 3×3, not 2×2, so AB and BA cannot be equal.

The numbers touching the “×” are the inner dimensions: green when they match, red when they do not. The product takes the outer ones, rows of the left factor and columns of the right factor.

The shape rule. Set the sizes of A (m by n) and B (rows by p) with the sliders. The picture shows the product when the inner dimensions match, and a crossed-out box when they do not. Tick the checkbox to try the other order, BA, and read what the widget says about it.

Try these: the preset 2×3 and 3×2 (defined, result 2×22\times2); 2×3 and 2×3 (not defined, although the two shapes are equal); then tick the checkbox to see that the other order BA\mathbf{B}\mathbf{A} of the first pair is defined too, but gives a 3×33\times3 matrix.

A table of the cases you will meet most:

LeftRightResultWhat it is
m×nm\times nn×1n\times1m×1m\times1matrix times a vector (P1.B5)
1×n1\times nn×1n\times11×11\times1a row times a column: a single number, the dot product
n×1n\times11×m1\times mn×mn\times ma column times a row: the outer product
n×nn\times nn×nn\times nn×nn\times ntwo square matrices of the same size: always defined

The second row explains a notation from P1.B3. A vector a\mathbf{a} is a column (n×1n\times1), so a⊤\mathbf{a}^\top is a row (1×n1\times n) and a⊤b\mathbf{a}^\top\mathbf{b} is (1×n)(n×1)=(1×1)(1\times n)(n\times1)=(1\times1): the dot product, as a matrix product. The third row is the same two vectors the other way round: ab⊤\mathbf{a}\mathbf{b}^\top is an n×nn\times n grid of all the products aibja_ib_j.

Four ways to see one product

You have seen the product computed entry by entry. The same numbers can be organised three more ways. Each one is useful for a different question. Here they are for the example, AB=(5864139154)\mathbf{A}\mathbf{B}=\begin{pmatrix}58&64\\139&154\end{pmatrix}.

ViewWhat it saysIn the example
Entrieseach entry is a row of A\mathbf{A} dotted with a column of B\mathbf{B}(AB)21=(4,5,6)⋅(7,9,11)=139(\mathbf{A}\mathbf{B})_{21}=(4,5,6)\cdot(7,9,11)=139
Columnscolumn jj of AB\mathbf{A}\mathbf{B} is A\mathbf{A} times column jj of B\mathbf{B}column 2 is A(8,10,12)=(64,154)\mathbf{A}(8,10,12)=(64,154)
Rowsrow ii of AB\mathbf{A}\mathbf{B} is row ii of A\mathbf{A} times B\mathbf{B}row 1 is (1,2,3) B=(58,64)(1,2,3)\,\mathbf{B}=(58,64)
Outer productsAB\mathbf{A}\mathbf{B} is a sum of (column of A\mathbf{A}) times (row of B\mathbf{B})see the Go deeper box below

Columns view. This is how we started: A\mathbf{A} acts on each column of B\mathbf{B} separately, so each column of the result depends only on the matching column of B\mathbf{B}. It is the view for “apply a map to many vectors”.

Rows view. The mirror image. A row vector times a matrix, (1,2,3) B(1,2,3)\,\mathbf{B}, is a combination of the rows of B\mathbf{B}, with the entries of the row vector as weights: 1⋅(7,8)+2⋅(9,10)+3⋅(11,12)=(58,64)1\cdot(7,8)+2\cdot(9,10)+3\cdot(11,12)=(58,64). So each row of the result depends only on the matching row of A\mathbf{A}. This is the view for “each example (a row) is processed on its own”: changing one row of A\mathbf{A} changes only that row of the product.

A useful consequence. Multiplying B\mathbf{B} on the right by a matrix mixes the columns of B\mathbf{B}, and multiplying on the left mixes the rows. Take the swap matrix Q=(0110)\mathbf{Q}=\begin{pmatrix}0&1\\1&0\end{pmatrix} and P=(1234)\mathbf{P}=\begin{pmatrix}1&2\\3&4\end{pmatrix}:

PQ=(2143) (columns swapped)QP=(3412) (rows swapped)\begin{aligned} \mathbf{P}\mathbf{Q}&=\begin{pmatrix}2&1\\4&3\end{pmatrix}\ \text{(columns swapped)}\\ \mathbf{Q}\mathbf{P}&=\begin{pmatrix}3&4\\1&2\end{pmatrix}\ \text{(rows swapped)} \end{aligned}

The two products are different, which is the next big topic. First, what does a product mean?

AB\mathbf{A}\mathbf{B} means: first B\mathbf{B}, then A\mathbf{A}

Here is the reason matrix multiplication is defined this way. Take any vector x\mathbf{x} with pp entries. Apply B\mathbf{B} to it, then apply A\mathbf{A} to the result:

x → B  Bx → A  A(Bx)\mathbf{x}\ \xrightarrow{\ \mathbf{B}\ }\ \mathbf{B}\mathbf{x}\ \xrightarrow{\ \mathbf{A}\ }\ \mathbf{A}(\mathbf{B}\mathbf{x})

The claim is that doing both steps is the same as doing one step with the matrix AB\mathbf{A}\mathbf{B}:

(AB) x=A(B x)(\mathbf{A}\mathbf{B})\,\mathbf{x}=\mathbf{A}(\mathbf{B}\,\mathbf{x})

Why? Write x\mathbf{x}‘s effect through B\mathbf{B}‘s columns (Way 2 of P1.B5): Bx=x1b1+⋯+xpbp\mathbf{B}\mathbf{x}=x_1\mathbf{b}_1+\dots+x_p\mathbf{b}_p. Now apply A\mathbf{A}, and use linearity (it passes through sums and constants): A(Bx)=x1 Ab1+⋯+xp Abp\mathbf{A}(\mathbf{B}\mathbf{x})=x_1\,\mathbf{A}\mathbf{b}_1+\dots+x_p\,\mathbf{A}\mathbf{b}_p. But Ab1,…,Abp\mathbf{A}\mathbf{b}_1,\dots,\mathbf{A}\mathbf{b}_p are exactly the columns of AB\mathbf{A}\mathbf{B}, so the right side is (AB)x(\mathbf{A}\mathbf{B})\mathbf{x} by Way 2 again. That is the whole proof, and it is why the product was defined by “apply A\mathbf{A} to each column of B\mathbf{B}”.

Read right to left. In ABx\mathbf{A}\mathbf{B}\mathbf{x}, the vector x\mathbf{x} meets B\mathbf{B} first, because B\mathbf{B} is the matrix next to it. This is the same habit as function notation: in f(g(x))f(g(x)) you compute gg first. The shapes agree: B\mathbf{B} takes pp numbers in and gives nn out, and A\mathbf{A} takes those nn numbers in and gives mm out. So the whole thing takes pp in and gives mm out, which is the shape m×pm\times p of AB\mathbf{A}\mathbf{B}.

A picture with two 2×22\times2 maps

Let R=(0−110)\mathbf{R}=\begin{pmatrix}0&-1\\1&0\end{pmatrix} be a quarter turn (counter-clockwise, P1.B5) and S=(1101)\mathbf{S}=\begin{pmatrix}1&1\\0&1\end{pmatrix} the shear (x,y)↦(x+y, y)(x,y)\mapsto(x+y,\,y). Consider SR\mathbf{S}\mathbf{R}: first rotate, then shear. To find its matrix, read the columns: follow where (1,0)(1,0) and (0,1)(0,1) land.

  • (1,0)(1,0) turns to (0,1)(0,1), and the shear sends (0,1)(0,1) to (1,1)(1,1). Column 1 is (1,1)(1,1).
  • (0,1)(0,1) turns to (−1,0)(-1,0), and the shear leaves (−1,0)(-1,0) alone. Column 2 is (−1,0)(-1,0).

So SR=(1−110)\mathbf{S}\mathbf{R}=\begin{pmatrix}1&-1\\1&0\end{pmatrix}, and multiplying the matrices gives the same: (1101)(0−110)=(1−110)\begin{pmatrix}1&1\\0&1\end{pmatrix}\begin{pmatrix}0&-1\\1&0\end{pmatrix}=\begin{pmatrix}1&-1\\1&0\end{pmatrix}. Now the other order, RS\mathbf{R}\mathbf{S} (shear first, then rotate): (1,0)(1,0) stays at (1,0)(1,0) and turns to (0,1)(0,1); (0,1)(0,1) shears to (1,1)(1,1) and turns to (−1,1)(-1,1). So RS=(0−111)\mathbf{R}\mathbf{S}=\begin{pmatrix}0&-1\\1&1\end{pmatrix}. Different matrices. Look at the two results for the “F” from P1.B5:

Two maps in a row: does the order matter?

−2−112−2−112ABBA
B = 0−110
A = 1101
AB = 1−110
BA = 0−111

AB and BA are different matrices, so the order matters: doing B first and then A (blue F) ends in a different place from doing A first and then B (pink F).

The grey outline is the starting “F”. AB means B first, then A: the blue F. BA means A first, then B: the pink F. The matrix AB is computed by multiplying the matrices, and it does in one step what the two maps do in two.

Two maps applied in a row. B is applied first and A second. The blue F is AB (first B, then A), the pink F is BA (first A, then B). Choose the two maps, swap them, and tick the box to see the halfway step. The status line says whether the order matters for the pair you chose.

Things to try:

  1. Leave the defaults (B = rotate 90°, A = shear). The blue F is the one from the text: rotate, then shear. The pink F is the other order. They end in different places.
  2. Tick Show the halfway step. The dashed blue F is where B alone puts the F (the middle of the blue route). The dashed pink F is where A alone puts it (the middle of the pink route).
  3. Choose Rotate 90° for A and Rotate 30° for B. The two F shapes land on top of each other: turning by 30° then 90° is the same as 90° then 30°.
  4. Choose Double everything for one map and anything for the other. Again they commute.
  5. Choose Project onto the x-axis and Rotate 90°. Both results are flat, but they are different lines.

Intuition

Think of an assembly line with two machines. B\mathbf{B} is the first machine and A\mathbf{A} is the second. A product AB\mathbf{A}\mathbf{B} is a single machine that does the work of both. To build it, you only need to know what the line does to the two test arrows (1,0)(1,0) and (0,1)(0,1), which are the columns. The order matters for the same reason it does when you put on socks and then shoes: swapping the machines gives a different line.

Where the analogy breaks: with socks and shoes, one order is impossible. With matrices of the same shape both orders are possible, and you simply get two different answers (or occasionally the same one).

Math

For A∈Rm×n\mathbf{A}\in\mathbb{R}^{m\times n} and B∈Rn×p\mathbf{B}\in\mathbb{R}^{n\times p}, the product AB∈Rm×p\mathbf{A}\mathbf{B}\in\mathbb{R}^{m\times p} has

(AB)ij=∑k=1nAikBkjAB=(Ab1⋯Abp)\begin{aligned} (\mathbf{A}\mathbf{B})_{ij}&=\sum_{k=1}^{n}A_{ik}B_{kj}\\ \mathbf{A}\mathbf{B}&=\begin{pmatrix}\mathbf{A}\mathbf{b}_1&\cdots&\mathbf{A}\mathbf{b}_p\end{pmatrix} \end{aligned}

and it satisfies (AB)x=A(Bx)(\mathbf{A}\mathbf{B})\mathbf{x}=\mathbf{A}(\mathbf{B}\mathbf{x}) for every x∈Rp\mathbf{x}\in\mathbb{R}^p. Composition of linear maps is a linear map, and its matrix is the product of the matrices in the order they are applied, right to left.

Code

import numpy as np

A = np.array([[1, 2, 3],
              [4, 5, 6]])
B = np.array([[ 7,  8],
              [ 9, 10],
              [11, 12]])

A @ B               # array([[ 58,  64], [139, 154]])
A @ B[:, 0]         # array([ 58, 139]): column 1 of the product
A[0] @ B            # array([58, 64]): row 1 of the product

A @ B is the matrix product. The runnable cells at the end of the lesson try everything here.

Order matters: AB≠BA\mathbf{A}\mathbf{B}\neq\mathbf{B}\mathbf{A}

Multiplying numbers is commutative: 3⋅5=5⋅33\cdot5=5\cdot3. Multiplying matrices is not. There are three different ways it can fail.

  1. One order does not exist. With A\mathbf{A} of shape 2×32\times3 and B\mathbf{B} of shape 3×43\times4, the product AB\mathbf{A}\mathbf{B} is 2×42\times4. But BA\mathbf{B}\mathbf{A} would be (3×4)(2×3)(3\times4)(2\times3) and the inner numbers 44 and 22 do not match, so it is not defined.
  2. Both exist but with different shapes. The example from the start: AB\mathbf{A}\mathbf{B} is 2×22\times2, but BA\mathbf{B}\mathbf{A} is (3×2)(2×3)=3×3(3\times2)(2\times3)=3\times3. Different shapes cannot be equal.
  3. Both exist, same shape, different values. The swap example above (PQ\mathbf{P}\mathbf{Q} against QP\mathbf{Q}\mathbf{P}), or rotate-then-shear against shear-then-rotate. Another: with M=(1101)\mathbf{M}=\begin{pmatrix}1&1\\0&1\end{pmatrix} and N=(1011)\mathbf{N}=\begin{pmatrix}1&0\\1&1\end{pmatrix},
MN=(2111)NM=(1112)\begin{aligned} \mathbf{M}\mathbf{N}&=\begin{pmatrix}2&1\\1&1\end{pmatrix}\\ \mathbf{N}\mathbf{M}&=\begin{pmatrix}1&1\\1&2\end{pmatrix} \end{aligned}

Some pairs do commute, and it helps to know which:

  • Anything with the identity: IA=AI=A\mathbf{I}\mathbf{A}=\mathbf{A}\mathbf{I}=\mathbf{A}.
  • A matrix with itself, or with its own powers: AA2=A2A\mathbf{A}\mathbf{A}^2=\mathbf{A}^2\mathbf{A}.
  • A number times the identity, cIc\mathbf{I}, with any matrix of the same size (scaling every direction equally).
  • Two diagonal matrices of the same size (each only stretches the axes).
  • Two rotations of the plane about the origin (the total turn is the sum of the angles, in either order).

What still works

Losing commutativity does not make matrices unruly. These rules all hold whenever the shapes allow the products:

RuleWritten
Associative(AB)C=A(BC)(\mathbf{A}\mathbf{B})\mathbf{C}=\mathbf{A}(\mathbf{B}\mathbf{C}), so we write ABC\mathbf{A}\mathbf{B}\mathbf{C}
DistributiveA(B+C)=AB+AC\mathbf{A}(\mathbf{B}+\mathbf{C})=\mathbf{A}\mathbf{B}+\mathbf{A}\mathbf{C} and (A+B)C=AC+BC(\mathbf{A}+\mathbf{B})\mathbf{C}=\mathbf{A}\mathbf{C}+\mathbf{B}\mathbf{C}
Scalars move freely(cA)B=c(AB)=A(cB)(c\mathbf{A})\mathbf{B}=c(\mathbf{A}\mathbf{B})=\mathbf{A}(c\mathbf{B})
IdentityImA=A=AIn\mathbf{I}_m\mathbf{A}=\mathbf{A}=\mathbf{A}\mathbf{I}_n for A\mathbf{A} of shape m×nm\times n

Associativity is the same fact as “doing three maps in a row has one meaning”: first C\mathbf{C}, then B\mathbf{B}, then A\mathbf{A}, however you group the brackets. It is what lets a stack of linear layers be written as one long product, and it is what makes the choice of bracketing a matter of cost only (next section). The identity I\mathbf{I} has to match the sizes: for a 2×32\times3 matrix, I2A=A\mathbf{I}_2\mathbf{A}=\mathbf{A} and AI3=A\mathbf{A}\mathbf{I}_3=\mathbf{A}.

Careful with the algebra you know from numbers. Because AB≠BA\mathbf{A}\mathbf{B}\neq\mathbf{B}\mathbf{A}, the middle terms do not combine:

(A+B)2=A2+AB+BA+B2\begin{aligned} (\mathbf{A}+\mathbf{B})^2&=\mathbf{A}^2+\mathbf{A}\mathbf{B}\\ &\quad+\mathbf{B}\mathbf{A}+\mathbf{B}^2 \end{aligned}

This is not A2+2AB+B2\mathbf{A}^2+2\mathbf{A}\mathbf{B}+\mathbf{B}^2 in general.

Two more number-habits fail:

  • A product can be zero with neither factor zero. (1000)(0001)=(0000)\begin{pmatrix}1&0\\0&0\end{pmatrix}\begin{pmatrix}0&0\\0&1\end{pmatrix}=\begin{pmatrix}0&0\\0&0\end{pmatrix}.
  • You cannot cancel a factor. Take A=(1000)\mathbf{A}=\begin{pmatrix}1&0\\0&0\end{pmatrix}, B=(1234)\mathbf{B}=\begin{pmatrix}1&2\\3&4\end{pmatrix} and C=(1256)\mathbf{C}=\begin{pmatrix}1&2\\5&6\end{pmatrix}. Then
AB=AC=(1200),yet B≠C.\mathbf{A}\mathbf{B}=\mathbf{A}\mathbf{C}=\begin{pmatrix}1&2\\0&0\end{pmatrix},\quad\text{yet }\mathbf{B}\neq\mathbf{C}.

Both come from the same cause as the projection in P1.B5: this A\mathbf{A} squashes the plane (it throws away the second coordinate), so different inputs end up the same and no step can recover them. (Matrices that can be undone are the subject of P1.B9, and then cancelling is allowed.)

Coming attractions (stated here, proved later): det⁡(AB)=det⁡A⋅det⁡B\det(\mathbf{A}\mathbf{B})=\det\mathbf{A}\cdot\det\mathbf{B}, the areas scale one after the other (P1.B8). For invertible matrices, (AB)−1=B−1A−1(\mathbf{A}\mathbf{B})^{-1}=\mathbf{B}^{-1}\mathbf{A}^{-1}: to undo “first B\mathbf{B}, then A\mathbf{A}” you undo A\mathbf{A} first, like taking off shoes before socks (P1.B9). And the transpose reverses the order too, (AB)⊤=B⊤A⊤(\mathbf{A}\mathbf{B})^\top=\mathbf{B}^\top\mathbf{A}^\top (P1.B10). Note that it is not A⊤B⊤\mathbf{A}^\top\mathbf{B}^\top, whose shapes usually do not even fit.

Powers of a square matrix

If A\mathbf{A} is square (n×nn\times n), then AA\mathbf{A}\mathbf{A} is defined, since (n×n)(n×n)→(n×n)(n\times n)(n\times n)\to(n\times n). Write A2=AA\mathbf{A}^2=\mathbf{A}\mathbf{A}, A3=AAA\mathbf{A}^3=\mathbf{A}\mathbf{A}\mathbf{A}, and A0=I\mathbf{A}^0=\mathbf{I}. A non-square matrix has no powers: (2×3)(2×3)(2\times3)(2\times3) is not defined. Powers mean “apply the same map again”:

  • The shear S=(1101)\mathbf{S}=\begin{pmatrix}1&1\\0&1\end{pmatrix} gives S2=(1201)\mathbf{S}^2=\begin{pmatrix}1&2\\0&1\end{pmatrix} and S5=(1501)\mathbf{S}^5=\begin{pmatrix}1&5\\0&1\end{pmatrix}: shearing five times in a row is one shear five times as strong.
  • The quarter turn R\mathbf{R} gives R2=(−100−1)=−I\mathbf{R}^2=\begin{pmatrix}-1&0\\0&-1\end{pmatrix}=-\mathbf{I} (a half turn) and R4=I\mathbf{R}^4=\mathbf{I} (a full turn: nothing changed).

Recurrent networks reuse the same weight matrix at every step (P6.5). With a nonlinearity and new inputs in between it is not literally a power, but without them it would be, which is why powers come back later.

How much work is a product?

Count the arithmetic in (m×n)(n×p)(m\times n)(n\times p). There are m⋅pm\cdot p entries. Each is a dot product of nn pairs: nn multiplications and n−1n-1 additions, about nn multiply-adds.

So the product costs m⋅n⋅pm\cdot n\cdot p multiply-adds, which is about 2mnp2mnp floating-point operations (FLOPs).

(A floating-point operation is one addition or multiplication of decimal numbers; “about 2mnp2mnp” counts each multiply-add as two.) For the first example, 2⋅3⋅2=122\cdot3\cdot2=12 multiply-adds. For two 1000×10001000\times1000 matrices, 10003=1091000^3=10^9 multiply-adds, about 2×1092\times10^9 FLOPs, for a single product. Double all three sizes and the work grows 8 times. Compare a matrix times a vector of the same size (p=1p=1): only 10610^6 multiply-adds, a thousand times less.

The order of a chain matters for cost, not for the answer. Associativity says (AB)C=A(BC)(\mathbf{A}\mathbf{B})\mathbf{C}=\mathbf{A}(\mathbf{B}\mathbf{C}), but the two bracketings can do very different amounts of work. Take shapes A\mathbf{A}: 10×10010\times100, B\mathbf{B}: 100×5100\times5, C\mathbf{C}: 5×505\times50.

OrderMultiply-adds
(AB)C(\mathbf{A}\mathbf{B})\mathbf{C}10⋅100⋅5+10⋅5⋅50=5000+2500=10\cdot100\cdot5+10\cdot5\cdot50=5000+2500= 7,500
A(BC)\mathbf{A}(\mathbf{B}\mathbf{C})100⋅5⋅50+10⋅100⋅50=25000+50000=100\cdot5\cdot50+10\cdot100\cdot50=25000+50000= 75,000

(In the first order, AB\mathbf{A}\mathbf{B} is a small 10×510\times5 matrix. In the second, BC\mathbf{B}\mathbf{C} is a larger 100×50100\times50 one.)

Same final 10×5010\times50 matrix, ten times the work. For a long chain, finding the cheapest bracketing is a classic algorithm problem; for three matrices you just compute both totals. Another common case: if the last factor is a vector, multiplying from the right (matrix times vector, then matrix times that) avoids ever building a big matrix-times-matrix product.

Because so much of a neural network is this one operation, processors for deep learning (GPUs and similar chips) are designed to do big products very fast (P10.B8), and the FLOP count of a whole model is built from counts like 2mnp2mnp (P10.B4).

Matrix multiplication in ML

You now have everything needed to read four places where products appear. The details come in later lessons; here the point is to see the shapes.

1. A layer on a whole batch. Let X\mathbf{X} be a data matrix, NN examples as rows and dd features as columns, so X\mathbf{X} is N×dN\times d. A layer with hh outputs has a weight matrix W\mathbf{W} of shape h×dh\times d (P1.B5). Applying it to every example is one product:

X⏟N×d W⊤⏟d×h = XW⊤⏟N×h\underbrace{\mathbf{X}}_{N\times d}\ \underbrace{\mathbf{W}^\top}_{d\times h}\ =\ \underbrace{\mathbf{X}\mathbf{W}^\top}_{N\times h}

Entry (i,j)(i,j) of the result is xi⋅wj\mathbf{x}_i\cdot\mathbf{w}_j: example ii against neuron jj. Row ii is the layer’s output for example ii. This is the product from the last Go deeper box of P1.B5, and now you can see why the shapes work: the inner number dd is the number of features. (The transpose ⊤^\top swaps rows and columns; P1.B10 treats it properly.) With X=(10−1210)\mathbf{X}=\begin{pmatrix}1&0&-1\\2&1&0\end{pmatrix} and W=(123456)\mathbf{W}=\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix} you get

XW⊤=(−2−2413)\mathbf{X}\mathbf{W}^\top=\begin{pmatrix}-2&-2\\4&13\end{pmatrix}

2. Stacking layers, and why we need activations. Two layers in a row apply W1\mathbf{W}_1 and then W2\mathbf{W}_2, which is the product W2W1\mathbf{W}_2\mathbf{W}_1 (first W1\mathbf{W}_1). Take W1=(111−101)\mathbf{W}_1=\begin{pmatrix}1&1\\1&-1\\0&1\end{pmatrix} (3×23\times2), W2=(101011)\mathbf{W}_2=\begin{pmatrix}1&0&1\\0&1&1\end{pmatrix} (2×32\times3) and x=(1,2)\mathbf{x}=(1,2):

W2W1=(1210)W1x=(3−12)W2(W1x)=(51)=(W2W1)x\begin{aligned} \mathbf{W}_2\mathbf{W}_1&=\begin{pmatrix}1&2\\1&0\end{pmatrix}\\ \mathbf{W}_1\mathbf{x}&=\begin{pmatrix}3\\-1\\2\end{pmatrix}\\ \mathbf{W}_2(\mathbf{W}_1\mathbf{x})&=\begin{pmatrix}5\\1\end{pmatrix}=(\mathbf{W}_2\mathbf{W}_1)\mathbf{x} \end{aligned}

So two layers with nothing in between are one layer with the matrix W2W1\mathbf{W}_2\mathbf{W}_1. Adding biases changes nothing important: W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)\mathbf{W}_2(\mathbf{W}_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}_2=(\mathbf{W}_2\mathbf{W}_1)\mathbf{x}+(\mathbf{W}_2\mathbf{b}_1+\mathbf{b}_2) is still one matrix plus one bias. Ten stacked linear layers are still one. The fix is the squashing step from P1.B5. Put ReLU(z)=max⁡(0,z)\mathrm{ReLU}(z)=\max(0,z) (entry by entry, P4.4) between them: ReLU(W1x)=(3,0,2)\mathrm{ReLU}(\mathbf{W}_1\mathbf{x})=(3,0,2), and then W2(3,0,2)=(5,2)\mathbf{W}_2(3,0,2)=(5,2), which is not (5,1)(5,1). So the single matrix W2W1\mathbf{W}_2\mathbf{W}_1 no longer reproduces the network here. Nonlinearity is what makes depth useful (P4.3).

3. Attention scores. In attention (P7.3) there are TT tokens, each with a query vector and a key vector of length dkd_k, stacked as the rows of Q\mathbf{Q} and K\mathbf{K}, each T×dkT\times d_k. The scores for every pair of tokens come from one product:

Q⏟T×dk K⊤⏟dk×T=QK⊤⏟T×T\underbrace{\mathbf{Q}}_{T\times d_k}\ \underbrace{\mathbf{K}^\top}_{d_k\times T}=\underbrace{\mathbf{Q}\mathbf{K}^\top}_{T\times T}

Entry (i,j)(i,j) is qi⋅kj\mathbf{q}_i\cdot\mathbf{k}_j, the score of token ii looking at token jj. With Q=(100211)\mathbf{Q}=\begin{pmatrix}1&0\\0&2\\1&1\end{pmatrix} and K=(101101)\mathbf{K}=\begin{pmatrix}1&0\\1&1\\0&1\end{pmatrix}, the scores are

QK⊤=(110022121)\mathbf{Q}\mathbf{K}^\top=\begin{pmatrix}1&1&0\\0&2&2\\1&2&1\end{pmatrix}

Real attention then rescales the scores, applies a softmax to each row, and multiplies by a value matrix V\mathbf{V} (T×dvT\times d_v) to get a T×dvT\times d_v result: (T×T)(T×dv)→(T×dv)(T\times T)(T\times d_v)\to(T\times d_v). P7.3 does that step by step; the point here is that it is products all the way, and the T×TT\times T matrix is why attention cost grows with the square of the sequence length.

4. LoRA: a big matrix as a product of thin ones. Fine-tuning a big weight matrix W\mathbf{W} of shape d×dd\times d means learning a change of the same shape, which is d2d^2 numbers. LoRA (Hu et al., 2021) keeps W\mathbf{W} frozen and learns the change as a product BA\mathbf{B}\mathbf{A} of two thin matrices (the paper’s letters: here A\mathbf{A} and B\mathbf{B} are new matrices, and A\mathbf{A} acts first), shapes d×rd\times r and r×dr\times d with a small rr: (d×r)(r×d)→(d×d)(d\times r)(r\times d)\to(d\times d), the right shape to add to W\mathbf{W}. (Real weight matrices are often not square, d×kd\times k; then the factors are d×rd\times r and r×kr\times k.) For the example sizes d=1000d=1000 and r=8r=8 that is 1000⋅8+8⋅1000=16,0001000\cdot8+8\cdot1000=16{,}000 numbers instead of 1,000,0001{,}000{,}000. A product of thin matrices cannot do everything a full matrix can: its rank is at most rr (P1.B7). P10.E3 covers the method.

Go deeper The outer-product view: a product as a sum of simple pieces

There is a fourth way to compute a product. Take column kk of A\mathbf{A} and row kk of B\mathbf{B}, multiply them as a column times a row (an m×1m\times1 times a 1×p1\times p gives a whole m×pm\times p matrix, the outer product), and add over kk:

AB=∑k=1nak rk⊤\begin{aligned} \mathbf{A}\mathbf{B}&=\sum_{k=1}^{n}\mathbf{a}_k\,\mathbf{r}_k^\top \end{aligned}

where ak\mathbf{a}_k is column kk of A\mathbf{A} and rk⊤\mathbf{r}_k^\top is row kk of B\mathbf{B} (written as a transpose, like the data rows in P1.B5).

For the example with n=3n=3:

AB=(14)(78)+(25)(910)+(36)(1112)=(782832)+(18204550)+(33366672)=(5864139154)\begin{aligned} \mathbf{A}\mathbf{B}&=\begin{pmatrix}1\\4\end{pmatrix}\begin{pmatrix}7&8\end{pmatrix}\\ &\quad+\begin{pmatrix}2\\5\end{pmatrix}\begin{pmatrix}9&10\end{pmatrix}\\ &\quad+\begin{pmatrix}3\\6\end{pmatrix}\begin{pmatrix}11&12\end{pmatrix}\\ &=\begin{pmatrix}7&8\\28&32\end{pmatrix}+\begin{pmatrix}18&20\\45&50\end{pmatrix}\\ &\quad+\begin{pmatrix}33&36\\66&72\end{pmatrix}\\ &=\begin{pmatrix}58&64\\139&154\end{pmatrix} \end{aligned}

Each piece has a very simple shape (all its rows are multiples of one row). The reason is the sum in the entry formula: entry (i,j)(i,j) is ∑kAikBkj\sum_kA_{ik}B_{kj}, and the kk-th term of every entry together forms the kk-th piece. Two reasons to know it: it shows that a product of an m×rm\times r and an r×pr\times p matrix is a sum of only rr such pieces, which is the idea behind LoRA above and behind low-rank approximation (P1.B13); and it is the view you want when the inner dimension is small.

Go deeper Why associativity holds, and block multiplication

Associativity, by entries. Write out entry (i,j)(i,j) of both sides. It is the same sum of triple products AikBklCljA_{ik}B_{kl}C_{lj} (over all kk and ll), added in a different order:

((AB)C)ij=∑l(AB)il Clj=∑l(∑kAikBkl)Clj=∑kAik(∑lBklClj)=(A(BC))ij\begin{aligned} ((\mathbf{A}\mathbf{B})\mathbf{C})_{ij}\\ &=\sum_{l}(\mathbf{A}\mathbf{B})_{il}\,C_{lj}\\ &=\sum_{l}(\sum_{k}A_{ik}B_{kl})C_{lj}\\ &=\sum_{k}A_{ik}(\sum_{l}B_{kl}C_{lj})\\ &=(\mathbf{A}(\mathbf{B}\mathbf{C}))_{ij} \end{aligned}

The picture version: both sides mean “first C\mathbf{C}, then B\mathbf{B}, then A\mathbf{A}”.

Blocks. You may cut matrices into rectangular blocks and multiply the blocks as if they were numbers, as long as the cuts line up so every block product has matching shapes: cut A\mathbf{A}‘s columns and B\mathbf{B}‘s rows in the same places. For example, (PQRS)(EFGH)=(PE+QGPF+QHRE+SGRF+SH)\begin{pmatrix}\mathbf{P}&\mathbf{Q}\\\mathbf{R}&\mathbf{S}\end{pmatrix}\begin{pmatrix}\mathbf{E}&\mathbf{F}\\\mathbf{G}&\mathbf{H}\end{pmatrix}=\begin{pmatrix}\mathbf{P}\mathbf{E}+\mathbf{Q}\mathbf{G}&\mathbf{P}\mathbf{F}+\mathbf{Q}\mathbf{H}\\\mathbf{R}\mathbf{E}+\mathbf{S}\mathbf{G}&\mathbf{R}\mathbf{F}+\mathbf{S}\mathbf{H}\end{pmatrix}. Splitting a big product into small block products is how software and hardware organise large products into pieces that fit in fast memory or can be done in parallel.

Go deeper Is the plain recipe the fastest possible?

The recipe above uses about n3n^3 multiply-adds for two n×nn\times n matrices. In 1969 Volker Strassen showed that two 2×22\times2 matrices can be multiplied with 7 multiplications instead of 8, and applying this idea repeatedly to blocks gives about nlog⁡27≈n2.81n^{\log_2 7}\approx n^{2.81} operations. Faster methods with smaller exponents have been found since, and the best possible exponent is a research question. Whether such methods help in practice depends on matrix size and hardware, so this lesson (and most FLOP counting in deep learning, P10.B4) uses the plain count mnpmnp.

Matrix multiplication in NumPy

Run the cell and read each line against the text. It covers the product, the four views, order, powers, * versus @, and the shape error.

Try it: matrix products in NumPy

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

A few things to take from it:

  • @, np.matmul and np.dot. For 2-D arrays all three give the matrix product. @ is the one to use: it is short, and np.dot behaves differently for arrays with more than two dimensions (P1.B14).
  • * is not the matrix product. P * P multiplies entry by entry (the Hadamard product, which appears in ML for masks and gates). It needs equal shapes (or shapes NumPy can stretch to match, P1.B14). P @ P is the matrix product.
  • Shape errors. A @ A with A\mathbf{A} of shape (2,3)(2,3) raises an error whose first words are matmul: Input operand 1 has a mismatch in its core dimension 0. The exact wording varies between NumPy versions, but it always means the inner dimensions do not match. Read it as: “the 3 columns of the left array do not match the 2 rows of the right one”.

The second cell is about plain 1-D arrays, where @ quietly does something sensible.

Try it: @ with 1-D arrays, and what a product costs

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

Here A @ v treats the 1-D array v\mathbf{v} as a column, and v @ A.T treats it as a row on the left, so the result has no leftover dimension. Two 1-D arrays give a single number. A plain number is not allowed in @ (A @ 2 raises an error): use 2 * A to scale.

Common mistakes

Check your understanding

  1. A\mathbf{A} is 5×35\times3 and B\mathbf{B} is 3×73\times7. What is the shape of AB\mathbf{A}\mathbf{B}?

  2. Let A=(1234)\mathbf{A}=\begin{pmatrix}1&2\\3&4\end{pmatrix} and B=(5678)\mathbf{B}=\begin{pmatrix}5&6\\7&8\end{pmatrix}. What is the entry in row 2, column 1 of AB\mathbf{A}\mathbf{B}?

  3. R\mathbf{R} turns the plane by a quarter turn and S\mathbf{S} is a shear. What does the matrix SR\mathbf{S}\mathbf{R} do to a vector?

  4. A\mathbf{A} is 10×10010\times100, B\mathbf{B} is 100×5100\times5 and C\mathbf{C} is 5×505\times50. Which statement is true?

  5. A network has two linear layers with matrices W1\mathbf{W}_1 and W2\mathbf{W}_2 and no activation function or bias between them. What is the pair equivalent to?

Exercises

  1. Compute (102−131)(312110)\begin{pmatrix}1&0&2\\-1&3&1\end{pmatrix}\begin{pmatrix}3&1\\2&1\\1&0\end{pmatrix}.
    Show answerThe shapes are (2×3)(3×2)(2\times3)(3\times2), so the result is 2×22\times2. (1,0,2)⋅(3,2,1)=5(1,0,2)\cdot(3,2,1)=5, (1,0,2)⋅(1,1,0)=1(1,0,2)\cdot(1,1,0)=1, (−1,3,1)⋅(3,2,1)=−3+6+1=4(-1,3,1)\cdot(3,2,1)=-3+6+1=4, (−1,3,1)⋅(1,1,0)=−1+3=2(-1,3,1)\cdot(1,1,0)=-1+3=2. The product is (5142)\begin{pmatrix}5&1\\4&2\end{pmatrix}.
  2. A\mathbf{A} is 4×24\times2, B\mathbf{B} is 2×52\times5 and C\mathbf{C} is 5×45\times4. Which of AB\mathbf{A}\mathbf{B}, BA\mathbf{B}\mathbf{A}, AC\mathbf{A}\mathbf{C}, CA\mathbf{C}\mathbf{A}, BC\mathbf{B}\mathbf{C}, CB\mathbf{C}\mathbf{B} are defined, and what are their shapes?
    Show answerAB\mathbf{A}\mathbf{B}: (4×2)(2×5)→4×5(4\times2)(2\times5)\to4\times5. CA\mathbf{C}\mathbf{A}: (5×4)(4×2)→5×2(5\times4)(4\times2)\to5\times2. BC\mathbf{B}\mathbf{C}: (2×5)(5×4)→2×4(2\times5)(5\times4)\to2\times4. The other three are not defined: BA\mathbf{B}\mathbf{A} (5≠45\ne4), AC\mathbf{A}\mathbf{C} (2≠52\ne5), CB\mathbf{C}\mathbf{B} (4≠24\ne2).
  3. For A=(1234)\mathbf{A}=\begin{pmatrix}1&2\\3&4\end{pmatrix} and B=(2013)\mathbf{B}=\begin{pmatrix}2&0\\1&3\end{pmatrix}, find only the second column of AB\mathbf{A}\mathbf{B} and only the first row of AB\mathbf{A}\mathbf{B}.
    Show answerColumn 2 is A(0,3)=(6,12)\mathbf{A}(0,3)=(6,12). Row 1 is (1,2)B=1⋅(2,0)+2⋅(1,3)=(4,6)(1,2)\mathbf{B}=1\cdot(2,0)+2\cdot(1,3)=(4,6). (The full product is (461012)\begin{pmatrix}4&6\\10&12\end{pmatrix}, which agrees.)
  4. Find the matrix of “scale xx by 2 (first), then quarter turn counter-clockwise (second)”, by tracking where (1,0)(1,0) and (0,1)(0,1) land. Then check it by multiplying matrices, and find the matrix for the opposite order.
    Show answerTracking: (1,0)→(2,0)→(0,2)(1,0)\to(2,0)\to(0,2) and (0,1)→(0,1)→(−1,0)(0,1)\to(0,1)\to(-1,0), so the columns are (0,2)(0,2) and (−1,0)(-1,0): (0−120)\begin{pmatrix}0&-1\\2&0\end{pmatrix}. Multiplying: RD=(0−110)(2001)=(0−120)\mathbf{R}\mathbf{D}=\begin{pmatrix}0&-1\\1&0\end{pmatrix}\begin{pmatrix}2&0\\0&1\end{pmatrix}=\begin{pmatrix}0&-1\\2&0\end{pmatrix}. The opposite order DR=(0−210)\mathbf{D}\mathbf{R}=\begin{pmatrix}0&-2\\1&0\end{pmatrix} is different.
  5. Show that M=(1101)\mathbf{M}=\begin{pmatrix}1&1\\0&1\end{pmatrix} and N=(1011)\mathbf{N}=\begin{pmatrix}1&0\\1&1\end{pmatrix} do not commute.
    Show answerMN=(2111)\mathbf{M}\mathbf{N}=\begin{pmatrix}2&1\\1&1\end{pmatrix} but NM=(1112)\mathbf{N}\mathbf{M}=\begin{pmatrix}1&1\\1&2\end{pmatrix}.
  6. How many multiply-adds does (200×300)(300×400)(200\times300)(300\times400) need, and roughly how many floating-point operations is that?
    Show answer200⋅300⋅400=24,000,000200\cdot300\cdot400=24{,}000{,}000 multiply-adds, so about 48,000,00048{,}000{,}000 FLOPs (using 2mnp2mnp).
  7. A\mathbf{A} is 50×250\times2, B\mathbf{B} is 2×502\times50 and C\mathbf{C} is 50×150\times1. Compare the cost of (AB)C(\mathbf{A}\mathbf{B})\mathbf{C} and A(BC)\mathbf{A}(\mathbf{B}\mathbf{C}).
    Show answer(AB)C(\mathbf{A}\mathbf{B})\mathbf{C}: 50⋅2⋅50+50⋅50⋅1=5000+2500=750050\cdot2\cdot50+50\cdot50\cdot1=5000+2500=7500. A(BC)\mathbf{A}(\mathbf{B}\mathbf{C}): 2⋅50⋅1+50⋅2⋅1=100+100=2002\cdot50\cdot1+50\cdot2\cdot1=100+100=200. Doing the vector C\mathbf{C} first is 37.5 times cheaper, and the answer (a 50×150\times1 vector) is the same.
  8. Find a non-zero 2×22\times2 matrix N\mathbf{N} with N2=0\mathbf{N}^2=\mathbf{0}.
    Show answerN=(0100)\mathbf{N}=\begin{pmatrix}0&1\\0&0\end{pmatrix}: Row 1 of N2\mathbf{N}^2 is (0,1)N=1⋅(0,0)=(0,0)(0,1)\mathbf{N}=1\cdot(0,0)=(0,0) and row 2 is (0,0)N=(0,0)(0,0)\mathbf{N}=(0,0), so N2=0\mathbf{N}^2=\mathbf{0}. A non-zero matrix can square to zero, which no non-zero number does.
  9. A dataset X\mathbf{X} has 32 examples and 10 features. A layer has 4 outputs. What are the shapes of W\mathbf{W} and of the layer’s output on the whole dataset (before any bias or activation)?
    Show answerW\mathbf{W} is 4×104\times10 (rows are outputs, columns are inputs). The product is XW⊤\mathbf{X}\mathbf{W}^\top: (32×10)(10×4)→32×4(32\times10)(10\times4)\to32\times4, one row of 4 outputs per example.
  10. In the composition widget, find two different maps (neither the identity) that commute, and a pair that does not, and explain each with one sentence.
    Show answerFor example, Rotate 30° and Rotate 90° commute: turning by one angle then another gives the same total turn either way. Rotate 90° and Shear do not commute: the two orders give different matrices and different F shapes. (Other commuting pairs: any two of the diagonal maps, or Double everything with anything.)
  11. Code: for P = np.array([[1, 2], [3, 4]]) and Q = np.array([[0, 1], [1, 0]]), predict P * Q and P @ Q, then run them.
    Show answerP * Q is [[0, 2], [3, 0]] (entry by entry). P @ Q is [[2, 1], [4, 3]]: multiplying by the swap matrix on the right swaps the columns of P.

Key takeaways

  • The entry in row ii and column jj of AB\mathbf{A}\mathbf{B} is row ii of A\mathbf{A} dotted with column jj of B\mathbf{B}: (AB)ij=∑kAikBkj(\mathbf{A}\mathbf{B})_{ij}=\sum_k A_{ik}B_{kj}.
  • Shapes: (m×n)(n×p)→(m×p)(m\times n)(n\times p)\to(m\times p). The inner dimensions must be equal, and the outer ones give the shape of the result. A matrix times a vector is the case p=1p=1, and a row times a column is a dot product.
  • The columns of AB\mathbf{A}\mathbf{B} are A\mathbf{A} times the columns of B\mathbf{B}, and the rows of AB\mathbf{A}\mathbf{B} are the rows of A\mathbf{A} times B\mathbf{B}.
  • AB\mathbf{A}\mathbf{B} means first B\mathbf{B}, then A\mathbf{A}: (AB)x=A(Bx)(\mathbf{A}\mathbf{B})\mathbf{x}=\mathbf{A}(\mathbf{B}\mathbf{x}). Matrix multiplication is composition of linear maps, read right to left.
  • Order matters: AB≠BA\mathbf{A}\mathbf{B}\neq\mathbf{B}\mathbf{A} in general (and one of them may not even exist). But (AB)C=A(BC)(\mathbf{A}\mathbf{B})\mathbf{C}=\mathbf{A}(\mathbf{B}\mathbf{C}), products distribute over sums, and I\mathbf{I} does nothing. You cannot cancel: AB=AC\mathbf{A}\mathbf{B}=\mathbf{A}\mathbf{C} does not force B=C\mathbf{B}=\mathbf{C}.
  • An (m×n)(n×p)(m\times n)(n\times p) product costs mnpmnp multiply-adds (about 2mnp2mnp floating-point operations). Associativity lets you pick the cheapest order for a chain.
  • In NumPy, A @ B is the matrix product and A * B is entry by entry. Two linear layers with no nonlinearity between them collapse into one matrix, which is why networks put an activation function in between.
Found a mistake? Tell us