Skip to content
AriadneTechnology

The Middle Ring · Chamber 6 of 9

Vectors and Matrices: Reading the Shapes

Bold letters, transposes, indices and shapes: the notation of linear algebra, before the linear algebra.

40 min 60 XP + 12 questions + 1 challengeNotationVideoPapersProofsCodeLab

In this chamber you will

  • Read x ∈ ℝⁿ, A ∈ ℝᵐˣⁿ, Aᵢⱼ and xᵀ
  • Write dot products and matrix products as sums over indices
  • Check the shapes of any matrix expression
  • Read the shapes in attention and LoRA
DiscoverLearnRead beyondPapers & lecturesYour turn

Discover: counting what you can't yet read

Here is a line from the Transformer paper, the one whose Equation 1 opened Chamber 1:

Spotted in the wild

WiQ∈Rdmodel×dk,WiK∈Rdmodel×dk,WiV∈Rdmodel×dv,WO∈Rhdv×dmodel\begin{gathered} W_i^Q \in \mathbb{R}^{d_{\text{model}} \times d_k}, \quad W_i^K \in \mathbb{R}^{d_{\text{model}} \times d_k}, \\ W_i^V \in \mathbb{R}^{d_{\text{model}} \times d_v}, \quad W^O \in \mathbb{R}^{h d_v \times d_{\text{model}}} \end{gathered}
Vaswani et al. (2017), “Attention Is All You Need”, Section 3.2.2

You don't know yet what a “query projection” is, and you don't need to. Every piece of this line is notation you have already met, and Chamber 2's paper decoder took it apart as set membership. WiQW_i^Q is a capital letter with a subscript and a superscript label (Chamber 1). The symbol ∈\in says “is an element of”, and Ra×b\mathbb{R}^{a \times b} is the set of grids of real numbers with aa rows and bb columns (Chamber 2). So the line is a list of shapes.

Shapes are more informative than they look. The paper sets dmodel=512d_{\text{model}} = 512 in Section 3.1, and a few lines after this one it uses h=8h = 8 heads with dk=dv=64d_k = d_v = 64. That's enough to answer a real question about the model:

Quick check +20 XP

Take a guess before reading on. The Transformer paper declares WO∈Rhdv×dmodelW^O \in \mathbb{R}^{h d_v \times d_{\text{model}}} and uses h=8h = 8, dv=64d_v = 64 and dmodel=512d_{\text{model}} = 512. The hdvh d_v in the superscript is a product, hh times dvd_v. How many numbers does the matrix WOW^O hold?

This chamber teaches you to read vectors and matrices the way researchers do: as named objects with shapes, whose entries you can address one at a time. The next course, Linear Algebra for Machine Learning, explains what these objects do. Here you learn to read and write them.

DiscoverLearnRead beyondPapers & lecturesYour turn

Learn: vectors are columns of numbers

A vector is an ordered list of numbers. Chamber 1's typeface rule says it's printed in bold, and Chamber 2 gave you the set it lives in: x∈Rn\mathbf{x} \in \mathbb{R}^n, read “x in R n”, means x\mathbf{x} is a list of nn real numbers. By convention the list stands up, as a column:

x=[x1x2⋮xn]∈Rn.\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix} \in \mathbb{R}^n.

The entries x1,…,xnx_1, \ldots, x_n are single numbers, so they're printed plain. Columns eat vertical space, so in running text authors lay the vector down and add a transpose sign: x=(x1,…,xn)⊤\mathbf{x} = (x_1, \ldots, x_n)^\top. The little ⊤\top, read “transpose”, turns a row into a column and back. It is never a power.

A few vectors are so common they have their own names:

Vectors
  • x∈Rn\mathbf{x} \in \mathbb{R}^n“x in R n”
    x\mathbf{x} is a list of nn real numbers: a vector with nn entries. Unless a paper says otherwise, it stands as a column, n×1n \times 1.
    x∈R3\mathbf{x} \in \mathbb{R}^{3}
  • xix_i“x sub i”
    The ii-th entry of x\mathbf{x}. It's a single number, so it's printed plain, not bold.
    x=(x1,x2,x3)⊤\mathbf{x} = (x_1, x_2, x_3)^\top
  • x⊤\mathbf{x}^\top“x transpose”
    The same numbers laid out as a row, 1×n1 \times n. Also printed xT\mathbf{x}^T, xT\mathbf{x}^{\mathsf{T}} or x′\mathbf{x}'. It is never a power.
    x⊤=(x1,…,xn)\mathbf{x}^\top = (x_1, \ldots, x_n)
  • 0\mathbf{0}“the zero vector”
    Every entry is 00. Its length comes from context, or a subscript: 0n\mathbf{0}_n.
    x+0=x\mathbf{x} + \mathbf{0} = \mathbf{x}
  • 1\mathbf{1}“the ones vector”
    Every entry is 11. Handy for sums: 1⊤x=x1+⋯+xn\mathbf{1}^\top \mathbf{x} = x_1 + \cdots + x_n.
    1⊤x=∑ixi\mathbf{1}^\top \mathbf{x} = \sum_{i} x_i
  • ei\mathbf{e}_i“e sub i”
    The ii-th standard basis vector: zeros everywhere except a 11 in position ii. In ML it's a one-hot vector.
    e3=(0,0,1,0)⊤∈R4\mathbf{e}_3 = (0, 0, 1, 0)^\top \in \mathbb{R}^4

The one-hot vector ei\mathbf{e}_i is how a class label becomes something a network can use: in a problem with 5 classes, label 3 is e3=(0,0,1,0,0)⊤\mathbf{e}_3 = (0, 0, 1, 0, 0)^\top.

Quick check +20 XP

Let x∈R3\mathbf{x} \in \mathbb{R}^3, a column vector as usual. What is the shape of x⊤\mathbf{x}^\top?

Learn: lengths and dot products

Two vectors of the same length can be combined into a single number by multiplying matching entries and adding. This is the dot product, and it has three common spellings:

x⊤y  =  ⟨x,y⟩  =  x⋅y  =  ∑i=1nxiyi.\mathbf{x}^\top \mathbf{y} \;=\; \langle \mathbf{x}, \mathbf{y} \rangle \;=\; \mathbf{x} \cdot \mathbf{y} \;=\; \sum_{i=1}^{n} x_i y_i.

The first spelling is the one ML papers use most, because it's a matrix product in disguise: a 1×n1 \times n row times an n×1n \times 1 column is 1×11 \times 1, a single number. The Σ\Sigma is Chamber 5's loop, with ii as the dummy index.

A vector also has sizes, called norms. The subscript says which one:

Lengths and products
  • ∥x∥2\|\mathbf{x}\|_2“the two-norm of x”
    The ordinary length, x12+⋯+xn2\sqrt{x_1^2 + \cdots + x_n^2}. Often written just ∥x∥\|\mathbf{x}\|.
    ∥(3,4)∥2=5\|(3, 4)\|_2 = 5
  • ∥x∥1\|\mathbf{x}\|_1“the one-norm of x”
    Add up the sizes of the entries: ∣x1∣+⋯+∣xn∣|x_1| + \cdots + |x_n|.
    ∥(3,−4)∥1=7\|(3, -4)\|_1 = 7
  • ∥x∥22\|\mathbf{x}\|_2^2“the squared two-norm of x”
    ∑ixi2\sum_i x_i^2, with no square root. Squared errors and weight penalties are written this way.
    ∥x∥22=x⊤x\|\mathbf{x}\|_2^2 = \mathbf{x}^\top \mathbf{x}
  • ⟨x,y⟩\langle \mathbf{x}, \mathbf{y} \rangle“the inner product of x and y, in angle brackets”
    Multiply matching entries and add: ∑ixiyi\sum_i x_i y_i. Both vectors need the same length.
    ⟨x,y⟩=∑i=1nxiyi\langle \mathbf{x}, \mathbf{y} \rangle = \sum_{i=1}^{n} x_i y_i
  • x⊤y\mathbf{x}^\top \mathbf{y}“x transpose y”
    The same number as ⟨x,y⟩\langle \mathbf{x}, \mathbf{y} \rangle, written as a matrix product: a 1×n1 \times n row times an n×1n \times 1 column.
    w⊤x+b\mathbf{w}^\top \mathbf{x} + b
  • x⋅y\mathbf{x} \cdot \mathbf{y}“x dot y”
    A third name for the same number, the dot product. Physics and school books prefer this one.
    q⋅k=∑i=1dkqikiq \cdot k = \sum_{i=1}^{d_k} q_i k_i

Notation earns its keep when it makes long things short. Here is a derivation you'll see in the opening pages of many papers: the sum of squared errors, rewritten as a norm.

Let y^∈Rn\hat{\mathbf{y}} \in \mathbb{R}^n hold a model's predictions and y∈Rn\mathbf{y} \in \mathbb{R}^n the true values, and call the difference r=y^−y\mathbf{r} = \hat{\mathbf{y}} - \mathbf{y}, the residual, so ri=y^i−yir_i = \hat{y}_i - y_i. Then

∑i=1n(y^i−yi)2=∑i=1nri2(1)=∑i=1nri ri(2)=r⊤r(3)=∥r∥22(4)=∥y^−y∥22.(5)\begin{aligned} \sum_{i=1}^{n} (\hat{y}_i - y_i)^2 &= \sum_{i=1}^{n} r_i^2 && \text{(1)} \\ &= \sum_{i=1}^{n} r_i \, r_i && \text{(2)} \\ &= \mathbf{r}^\top \mathbf{r} && \text{(3)} \\ &= \|\mathbf{r}\|_2^2 && \text{(4)} \\ &= \|\hat{\mathbf{y}} - \mathbf{y}\|_2^2. && \text{(5)} \end{aligned}

Step (1) uses the definition of r\mathbf{r}, and (2) says a square is a number times itself. Step (3) recognises the dot product of r\mathbf{r} with itself, (4) is the definition of the two-norm, squared, and (5) substitutes r\mathbf{r} back in.

So the mean squared error, 1n∑i(y^i−yi)2\frac{1}{n}\sum_i (\hat{y}_i - y_i)^2, is written 1n∥y^−y∥22\frac{1}{n}\|\hat{\mathbf{y}} - \mathbf{y}\|_2^2: one symbol for a whole loop. In the same spirit, 1⊤x\mathbf{1}^\top \mathbf{x} adds up the entries of x\mathbf{x}, so the mean of x\mathbf{x} is 1n1⊤x\frac{1}{n}\mathbf{1}^\top \mathbf{x}.

Learn: matrices, entries, rows and columns

A matrix is a grid of numbers. A∈Rm×nA \in \mathbb{R}^{m \times n}, read “A is an m by n matrix”, means mm rows and nn columns, rows first, always. The entry in row ii and column jj is AijA_{ij}:

A=[A11A12A13A21A22A23]∈R2×3.A = \begin{bmatrix} A_{11} & A_{12} & A_{13} \\ A_{21} & A_{22} & A_{23} \end{bmatrix} \in \mathbb{R}^{2 \times 3}.

For example, if

A=[502174],then A23=4.A = \begin{bmatrix} 5 & 0 & 2 \\ 1 & 7 & 4 \end{bmatrix}, \quad \text{then } A_{23} = 4.

Papers often need a whole row or a whole column at once, and have borrowed the colon from code for it: A2,:=(1,7,4)A_{2,:} = (1, 7, 4) is row 2, and A:,3=(2,4)⊤A_{:,3} = (2, 4)^\top is column 3. The transpose A⊤A^\top flips the grid across its diagonal, so the rows become columns:

(A⊤)ij=Aji,[502174]⊤=[510724].(A^\top)_{ij} = A_{ji}, \qquad \begin{bmatrix} 5 & 0 & 2 \\ 1 & 7 & 4 \end{bmatrix}^\top = \begin{bmatrix} 5 & 1 \\ 0 & 7 \\ 2 & 4 \end{bmatrix}.
Matrices
  • A∈Rm×nA \in \mathbb{R}^{m \times n}“A is an m by n matrix”
    A grid of real numbers with mm rows and nn columns: mnmn numbers in all. Rows first, always.
    W∈R512×64W \in \mathbb{R}^{512 \times 64}
  • AijA_{ij}“A sub i j”
    The entry in row ii, column jj. Also written Ai,jA_{i,j}, aija_{ij} or [A]ij[A]_{ij}.
    A23A_{23}
  • Ai,:A_{i,:}“row i of A”
    The whole ii-th row, a 1×n1 \times n row. The colon means “every index here”, just as in NumPy.
    A2,:A_{2,:}
  • A:,jA_{:,j}“column j of A”
    The whole jj-th column, an m×1m \times 1 column.
    A:,1A_{:,1}
  • A⊤A^\top“A transpose”
    Flip across the diagonal: (A⊤)ij=Aji(A^\top)_{ij} = A_{ji}. Rows become columns, so an m×nm \times n matrix becomes n×mn \times m.
    (A⊤)ij=Aji(A^\top)_{ij} = A_{ji}
  • II“the identity matrix”
    Square, with ones on the diagonal and zeros elsewhere, so Ix=xI\mathbf{x} = \mathbf{x}. Written InI_n when the size matters.
    I3I_3
  • diag(d)\mathrm{diag}(\mathbf{d})“diag of d”
    The square matrix with the entries of d\mathbf{d} down its diagonal and zeros everywhere else.
    diag(2,5)=[2005]\mathrm{diag}(2, 5) = \begin{bmatrix} 2 & 0 \\ 0 & 5 \end{bmatrix}
  • X∈Rn×dX \in \mathbb{R}^{n \times d}“the data matrix X”
    A dataset of nn examples with dd features each: one example per row, one feature per column.
    Xi,:=(x(i))⊤X_{i,:} = (\mathbf{x}^{(i)})^\top

The data matrix XX ties this chamber to Chamber 1's bracketed superscripts. With nn examples x(1),…,x(n)\mathbf{x}^{(1)}, \ldots, \mathbf{x}^{(n)}, each a vector of dd features, XX stacks them as rows. The entry XijX_{ij} is feature jj of example ii, the same number as xj(i)x^{(i)}_j.

Learn: products are sums over indices

Here is the most important formula in the chamber. A matrix times a vector is a new vector, and for A∈Rm×nA \in \mathbb{R}^{m \times n} and x∈Rn\mathbf{x} \in \mathbb{R}^n its ii-th entry is a sum over jj:

(Ax)i=∑j=1nAij xj.(A\mathbf{x})_i = \sum_{j=1}^{n} A_{ij}\, x_j.

Read it aloud: “entry ii of A x is the sum over jj of A i j times x j.” Fix a row ii, walk along it with jj, multiply each entry by the matching entry of x\mathbf{x}, and add. In other words, entry ii is row ii of AA dotted with x\mathbf{x}. For instance,

[21031−1][41]=[2⋅4+1⋅10⋅4+3⋅11⋅4+(−1)⋅1]=[933].\begin{bmatrix} 2 & 1 \\ 0 & 3 \\ 1 & -1 \end{bmatrix} \begin{bmatrix} 4 \\ 1 \end{bmatrix} = \begin{bmatrix} 2 \cdot 4 + 1 \cdot 1 \\ 0 \cdot 4 + 3 \cdot 1 \\ 1 \cdot 4 + (-1) \cdot 1 \end{bmatrix} = \begin{bmatrix} 9 \\ 3 \\ 3 \end{bmatrix}.
Quick check +20 XP

Let A=[1203−14]A = \begin{bmatrix} 1 & 2 & 0 \\ 3 & -1 & 4 \end{bmatrix} and x=[211]\mathbf{x} = \begin{bmatrix} 2 \\ 1 \\ 1 \end{bmatrix}. Using (Ax)i=∑jAijxj(A\mathbf{x})_i = \sum_j A_{ij} x_j, what is (Ax)2(A\mathbf{x})_2?

A matrix times a matrix works the same way, one entry at a time. For A∈Rm×nA \in \mathbb{R}^{m \times n} and B∈Rn×pB \in \mathbb{R}^{n \times p},

(AB)ij=∑k=1nAik Bkj.(AB)_{ij} = \sum_{k=1}^{n} A_{ik}\, B_{kj}.

Look at where the indices sit. The free indices ii and jj pick the entry; the dummy index kk is summed away, running along row ii of AA and down column jj of BB. For that to work, the row of AA and the column of BB must have the same length, nn. That single fact is the shape rule:

(m×n) (n⏟must match×p)  =  m×p.(m \times \underbrace{n)\,(n}_{\text{must match}} \times p) \;=\; m \times p.

The inner sizes must match and disappear; the outer sizes survive. It also shows why order matters. If AA is 2×32 \times 3 and BB is 3×73 \times 7, then ABAB is 2×72 \times 7 while BABA doesn't even exist.

Quick check +20 XP

Let A∈R4×3A \in \mathbb{R}^{4 \times 3} and B∈R3×5B \in \mathbb{R}^{3 \times 5}. Which statement is true?

Two more operations complete the toolkit, and both have a stricter rule. Addition A+BA + B and the Hadamard product A⊙BA \odot B work entry by entry, so the two sides must have exactly the same shape:

(A+B)ij=Aij+Bij,(A⊙B)ij=Aij Bij.\begin{aligned} (A + B)_{ij} &= A_{ij} + B_{ij}, \\ (A \odot B)_{ij} &= A_{ij}\, B_{ij}. \end{aligned}

And watch where the transpose goes on a pair of vectors. x⊤y\mathbf{x}^\top\mathbf{y} is (1×n)(n×1)(1 \times n)(n \times 1), a single number. xy⊤\mathbf{x}\mathbf{y}^\top is (n×1)(1×n)(n \times 1)(1 \times n), a whole n×nn \times n matrix, the outer product. Same letters, same transpose, completely different objects.

Products and the shape rule
  • AxA\mathbf{x}“A times x”
    A new vector whose ii-th entry is row ii of AA dotted with x\mathbf{x}. Needs AA's column count to equal x\mathbf{x}'s length.
    (Ax)i=∑j=1nAijxj(A\mathbf{x})_i = \sum_{j=1}^{n} A_{ij} x_j
  • ABAB“A times B”
    (AB)ij=∑kAikBkj(AB)_{ij} = \sum_k A_{ik} B_{kj}. Shapes: (m×n)(n×p)=m×p(m \times n)(n \times p) = m \times p. The inner sizes must match; the outer ones survive.
    (AB)ij=∑k=1nAikBkj(AB)_{ij} = \sum_{k=1}^{n} A_{ik} B_{kj}
  • A⊙BA \odot B“A Hadamard B”
    Multiply entry by entry: (A⊙B)ij=AijBij(A \odot B)_{ij} = A_{ij} B_{ij}. Both must have the same shape. Also called the element-wise product.
    (A⊙B)ij=AijBij(A \odot B)_{ij} = A_{ij} B_{ij}
  • A+BA + B“A plus B”
    Add entry by entry. As with ⊙\odot, both must have exactly the same shape.
    (A+B)ij=Aij+Bij(A + B)_{ij} = A_{ij} + B_{ij}
  • xy⊤\mathbf{x}\mathbf{y}^\top“the outer product of x and y”
    A column times a row makes a whole matrix: (xy⊤)ij=xiyj(\mathbf{x}\mathbf{y}^\top)_{ij} = x_i y_j. For x∈Rm\mathbf{x} \in \mathbb{R}^m and y∈Rn\mathbf{y} \in \mathbb{R}^n it is m×nm \times n.
    (xy⊤)ij=xiyj(\mathbf{x}\mathbf{y}^\top)_{ij} = x_i y_j
  • (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top“the transpose of A B is B transpose A transpose”
    Transposing a product reverses the order of the factors. Proved in this chamber, entry by entry.

Learn: the transpose of a product

Now a proof, entirely by indices. It's short, but it's a model for how most matrix facts are proved: check the shapes, then compare one arbitrary entry.

Claim. For any A∈Rm×nA \in \mathbb{R}^{m \times n} and B∈Rn×pB \in \mathbb{R}^{n \times p}, (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top.

Proof. First the shapes. ABAB is m×pm \times p, so (AB)⊤(AB)^\top is p×mp \times m. On the other side, B⊤B^\top is p×np \times n and A⊤A^\top is n×mn \times m: the inner sizes match, so B⊤A⊤B^\top A^\top exists and is p×mp \times m too. Two matrices of the same shape are equal when every entry agrees, so take any row ii and column jj:

((AB)⊤)ij=(AB)ji(1)=∑k=1nAjk Bki(2)=∑k=1nBki Ajk(3)=∑k=1n(B⊤)ik (A⊤)kj(4)=(B⊤A⊤)ij.(5)\begin{aligned} \big((AB)^\top\big)_{ij} &= (AB)_{ji} && \text{(1)} \\ &= \textstyle\sum_{k=1}^{n} A_{jk}\, B_{ki} && \text{(2)} \\ &= \textstyle\sum_{k=1}^{n} B_{ki}\, A_{jk} && \text{(3)} \\ &= \textstyle\sum_{k=1}^{n} (B^\top)_{ik}\, (A^\top)_{kj} && \text{(4)} \\ &= (B^\top A^\top)_{ij}. && \text{(5)} \end{aligned}

Step (1) is the definition of the transpose and (2) the definition of the product. Step (3) swaps two numbers, which is allowed because multiplication of numbers commutes. Step (4) uses the definition of the transpose twice, and (5) recognises the definition of the product. Since ii and jj were arbitrary, every entry agrees, and (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top. ■\blacksquare

The step that does the work is (3). To recognise a product in step (5), we need the pattern “row index ii, summed index kk, column index jj”, and that pattern only appears once BB comes first. Swapping the two numbers is what reverses the order of the matrices. It's the same as socks and shoes: you put on socks, then shoes, and to undo it you take off the shoes first.

Learn: become a shape detective

Every matrix expression in a paper can be checked in a few seconds, and experienced readers do it without thinking. The routine:

  1. 1

    Write the shape under every symbol

    Vectors are n×1n \times 1 columns unless the paper says otherwise. A transpose swaps the two numbers.

  2. 2

    Multiply left to right with the shape rule

    Inner sizes must match and vanish; outer sizes survive. Products are associative, so for the shape it doesn't matter which pair you do first.

  3. 3

    Sums and ⊙ need identical shapes

    If they differ, the expression is undefined in mathematics, even if NumPy would happily broadcast it (more on that below).

  4. 4

    Read the result

    1×11 \times 1 is a number, n×1n \times 1 a vector, anything else a matrix.

Try it on the heart of LoRA, the paper you'll read later in this chamber. With B∈Rd×rB \in \mathbb{R}^{d \times r}, A∈Rr×kA \in \mathbb{R}^{r \times k} and x∈Rk\mathbf{x} \in \mathbb{R}^k:

B⏟d×r  A⏟r×k  x⏟k×1  =  BAx⏟d×1.\underbrace{B}_{d \times r}\;\underbrace{A}_{r \times k}\;\underbrace{\mathbf{x}}_{k \times 1} \;=\; \underbrace{BA\mathbf{x}}_{d \times 1}.

Both junctions match (r=rr = r, k=kk = k), so the result is a dd-dimensional vector. Swap the first two and ABxAB\mathbf{x} fails immediately: (r×k)(d×r)(r \times k)(d \times r) needs k=dk = d. Now it's your turn.

Interactive lab

Shape detective

Four objects are declared below. Vectors are columns, so x∈R2x \in \mathbb{R}^{2} has shape 2 × 1. For each expression, pick its shape, rows × columns, or say it's undefined. Then check the picture.
GivenA∈R3×2A \in \mathbb{R}^{3 \times 2}B∈R2×4B \in \mathbb{R}^{2 \times 4}x∈R2x \in \mathbb{R}^{2}y∈R3y \in \mathbb{R}^{3}
Expressions0 / 8 solved

Expression 1 of 8: what is the shape of

ABA B
Rows
Columns
? × ?
Challenge: Shape detectivePredict the shape of eight matrix expressions.+40 XP

Learn: tensors, batches and code

Real models push notation one step further. A tensor is a grid with three or more indices. A batch of BB sentences, each nn tokens long, each token a dd-dimensional vector, is a single tensor X∈RB×n×dX \in \mathbb{R}^{B \times n \times d}, with entries Xb,i,jX_{b,i,j}. Code almost always puts the batch dimension first, so that Xb,:,:X_{b,:,:} is one whole example.

This is also where papers and code part ways on rows and columns. PyTorch's nn.Linear documentation states its formula as y=xA⊤+by = xA^\top + b, with a weight of shape (out_features, in_features) and inputs whose last axis holds the features. That's the row convention, and the transpose is exactly the one from the insight box above.

The third difference is broadcasting. In strict matrix algebra, adding a vector to a matrix is undefined. Deep-learning writing relaxes this on purpose. Goodfellow, Bengio and Courville's Deep Learning allows C=A+bC = A + \mathbf{b}, meaning Cij=Aij+bjC_{ij} = A_{ij} + b_j: add b\mathbf{b} to every row. NumPy does the same automatically. It compares shapes from the right, and two sizes are compatible when they are equal or one of them is 1, which is then stretched to fit.

Tensors, batches and broadcasting
  • X∈RB×n×dX \in \mathbb{R}^{B \times n \times d}“X is B by n by d”
    A tensor: a grid with three indices. Here, a batch of BB sequences, each of nn tokens, each token a dd-dimensional vector.
    X∈R16×64×256X \in \mathbb{R}^{16 \times 64 \times 256}
  • Xb,:,:X_{b,:,:}“X b colon colon”
    Fix the first index and keep the rest: example bb of the batch, an n×dn \times d matrix.
    X3,:,:∈R64×256X_{3,:,:} \in \mathbb{R}^{64 \times 256}
  • A+bA + \mathbf{b}“A plus b, broadcast”
    Deep-learning shorthand (and NumPy behaviour): add the vector b\mathbf{b} to every row of AA. Strict matrix algebra would call it undefined.
    Cij=Aij+bjC_{ij} = A_{ij} + b_j
DiscoverLearnRead beyondPapers & lecturesYour turn

Read beyond the course

These all use exactly the notation of this chamber. Read them with a pencil, writing the shape under each symbol as you go.

Book · free online · ~30 min

Deep Learning, Chapter 2: Linear Algebra

Ian Goodfellow, Yoshua Bengio & Aaron Courville · Sections 2.1–2.3

Scalars, vectors, matrices and tensors, the matrix product as a sum, the transpose of a product, and the broadcasting convention quoted in this chamber. It's the notation most deep-learning papers copy, written by people who use it every day.

Lecture notes · free online · ~35 min

Linear Algebra Review and Reference

Zico Kolter, updated by Chuong Do (Stanford CS229) · Sections 1–2, then 3.1–3.2

Famously compact. Section 1 is a notation page much like this chamber's tables, and Section 2 shows four different ways to read a matrix product. Stop before the determinant; the Linear Algebra course picks up from there.

Book · free online · ~30 min

Mathematics for Machine Learning

Marc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Section 2.2: Matrices

Matrix addition, multiplication, transposes and the identity, with small worked examples. A gentler pace than the CS229 notes, and the book you'll keep using in the Linear Algebra course.

Tool · free online · ~15 min

Broadcasting

NumPy documentation

The official rules, with pictures of arrays being stretched. Ten minutes here prevents hours of debugging. Try each example in a Python shell and predict the shape before you run it.

Article · free online · ~20 min

Einsum is All you Need: Einstein Summation in Deep Learning

Tim Rocktäschel

Index formulas like (AB)ij=∑kAikBkj(AB)_{ij} = \sum_k A_{ik}B_{kj} translate almost letter for letter into code with einsum. This post shows how, and it will change how you read every formula in this chamber.

DiscoverLearnRead beyondPapers & lecturesYour turn

Papers and lectures

You can read a real paper's shapes today. Open the LoRA paper and look first at Figure 1 on page 1: the frozen weights are drawn as a big square, and the two small trainable matrices AA and BB as thin slabs. Then read the first paragraph of Section 4.1, which ends in Equation (3). It's a string of ∈R⋅×⋅\in \mathbb{R}^{\cdot \times \cdot} statements followed by one equation, and you now know everything in it. Skip the experiments (Sections 5 onwards) for now. Afterwards, open the Transformer paper at Section 3.2.2 and read the last paragraph, where the Discover line comes from.

LoRA: Low-Rank Adaptation of Large Language ModelsEdward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen · ICLR, 2022

Fine-tunes giant language models by training two thin matrices per layer instead of the full weights. Its central idea is stated almost entirely in shapes, which makes it a perfect first paper to read for notation.

Attention Is All You NeedAshish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin · NIPS, 2017

The Transformer. Section 3.2 declares the shape of every matrix in multi-head attention, and footnote 4 writes a dot product as the sum ∑iqiki\sum_i q_i k_i. Chamber 9 decodes its Equation 1.

Decode the paper · Eq. (3), Section 4.1

LoRA: Low-Rank Adaptation of Large Language Models

Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen · ICLR, 2022

+30 XP
h=W0x+ΔWx=W0x+BAxh = W_0 x + \Delta W x = W_0 x + BAx

Just before this equation the paper declares its shapes: W0∈Rd×kW_0 \in \mathbb{R}^{d \times k}, B∈Rd×rB \in \mathbb{R}^{d \times r}, A∈Rr×kA \in \mathbb{R}^{r \times k}, with the rank r≪min⁡(d,k)r \ll \min(d, k). The equation is the forward pass of one adapted layer. Match each symbol to its meaning.

hh
xx
W0W_0
ΔW\Delta W
BB
AA

Options

Watch

Essential Matrix Algebra for Neural Networks, Clearly Explained!!!StatQuest with Josh Starmer · 30 min

The video starts at 15:18, where transposes come in. Watch how a neural network becomes one matrix equation, then how the same shapes explain PyTorch's nn.Linear documentation and its error messages. The first fifteen minutes (linear transformations) are good preparation for the Linear Algebra course.

Mathematical Notation for Deep Learning Explained | Part 2 | Vectors MatricesMirror Neuron · 7 min

A short recap of the same notation from a different teacher. Pause whenever a symbol appears and say it aloud before the narrator does.

DiscoverLearnRead beyondPapers & lecturesYour turn

Your turn

Translate between symbols, words and code, then prove two shape facts and compute your way through three problems, one of them straight from LoRA.

Match · Symbols ↔ Read aloud as

Say it aloud

+25 XP

Match each piece of notation to the way you'd read it, and what it means.

x∈Rn\mathbf{x} \in \mathbb{R}^n
AijA_{ij}
A:,jA_{:,j}
x⊤y\mathbf{x}^\top \mathbf{y}
xy⊤\mathbf{x}\mathbf{y}^\top
∥x∥2\|\mathbf{x}\|_2
A⊙BA \odot B

Options

Match · Maths ↔ NumPy

From notation to NumPy

+25 XP

Match each piece of notation to the NumPy that computes it. Remember that papers count from 1 and Python counts from 0, and that in NumPy * is entry by entry while @ is the matrix product.

A⊤A^\top
ABAB
A⊙BA \odot B
AijA_{ij}
A:,jA_{:,j}
InI_n
∥x∥1\|\mathbf{x}\|_1

Options

Proofs

Both proofs use the same two moves: check the shapes, then expand into indices. The puzzle has a line or two that don't belong.

Proof puzzle

Adding up every entry

+25 XP

Claim

For any A∈Rm×nA \in \mathbb{R}^{m \times n}, with 1m∈Rm\mathbf{1}_m \in \mathbb{R}^m and 1n∈Rn\mathbf{1}_n \in \mathbb{R}^n the all-ones vectors, 1m⊤A1n=∑i=1m∑j=1nAij.\mathbf{1}_m^\top A \mathbf{1}_n = \sum_{i=1}^{m} \sum_{j=1}^{n} A_{ij}.

Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.

Your proof

  1. Pick the first line below.

Available lines

Prove it yourself

A number is its own transpose

+40 XP

Claim

For any x∈Rm\mathbf{x} \in \mathbb{R}^m, A∈Rm×nA \in \mathbb{R}^{m \times n} and y∈Rn\mathbf{y} \in \mathbb{R}^n: x⊤Ay=y⊤A⊤x.\mathbf{x}^\top A \mathbf{y} = \mathbf{y}^\top A^\top \mathbf{x}.

Preview

Your typeset proof appears here.

Code it up

Each problem has a single answer. The index formulas from this chamber are all you need, plus a loop or two. NumPy is available in the browser runner if you want it.

Problem 16·Warm-up

One attention score

+20 XP

Attention compares a query vector qq with a key vector kk using their dot product. Footnote 4 of the Transformer paper writes it as a sum,

q⋅k=∑i=1dkqiki,q \cdot k = \sum_{i=1}^{d_k} q_i k_i,

and Equation 1 then divides by dk\sqrt{d_k}.

Take dk=64d_k = 64 and, for i=1,2,…,64i = 1, 2, \ldots, 64,

qi=(i2 mod 11)−5,ki=(3i mod 11)−5.\begin{aligned} q_i &= (i^2 \bmod 11) - 5, \\ k_i &= (3i \bmod 11) - 5. \end{aligned}

Compute the scaled score q⊤kdk\dfrac{q^\top k}{\sqrt{d_k}}. It comes out exact: give it as a decimal with 3 decimal places.

A number, rounded to 3 decimal places

Problem 17·Standard

LoRA's budget, from shapes alone

+35 XP

Section 4.1 of the LoRA paper keeps a pre-trained weight matrix W0∈Rd×kW_0 \in \mathbb{R}^{d \times k} frozen and learns an update ΔW=BA\Delta W = BA, where B∈Rd×rB \in \mathbb{R}^{d \times r} and A∈Rr×kA \in \mathbb{R}^{r \times k}. So fine-tuning W0W_0 directly would train dkdk numbers, while LoRA trains the entries of BB and AA instead.

A 12-layer Transformer the size of BERT-base has, in every layer, four attention matrices Wq,Wk,Wv,Wo∈R768×768W_q, W_k, W_v, W_o \in \mathbb{R}^{768 \times 768} and two feed-forward matrices W1∈R3072×768W_1 \in \mathbb{R}^{3072 \times 768} and W2∈R768×3072W_2 \in \mathbb{R}^{768 \times 3072}. Apply LoRA with rank r=8r = 8 to all six matrices in all 12 layers. (The paper itself adapts only WqW_q and WvW_v; here we adapt all six.)

What fraction of the entries of those 72 matrices does LoRA train? That is, compute

total entries of every B and Atotal entries of every W0.\frac{\text{total entries of every } B \text{ and } A}{\text{total entries of every } W_0}.

Give it as a reduced fraction, like 3/7.

An exact integer (or a fraction like 7/12)

Problem 18·Challenge

Where to put the brackets

+50 XP

Multiplying a p×qp \times q matrix by a q×sq \times s matrix with the index formula (AB)ij=∑k=1qAikBkj(AB)_{ij} = \sum_{k=1}^{q} A_{ik} B_{kj} takes qq multiplications for each of the psps entries: pqspqs scalar multiplications in all.

Matrix products are associative, so a chain can be bracketed however you like. The answer never changes, but the cost does. LoRA is the classic case: with B∈Rd×rB \in \mathbb{R}^{d \times r}, A∈Rr×kA \in \mathbb{R}^{r \times k} and x∈Rkx \in \mathbb{R}^{k}, computing (BA)x(BA)x costs drk+dkdrk + dk multiplications, while B(Ax)B(Ax) costs only rk+drrk + dr.

Now take the chain M1M2⋯M8M_1 M_2 \cdots M_8, where Mi∈Rpi−1×piM_i \in \mathbb{R}^{p_{i-1} \times p_i} and

(p0,p1,p2,p3,p4)=(40,300,10,500,20),(p5,p6,p7,p8)=(200,5,400,50).\begin{aligned} (p_0, p_1, p_2, p_3, p_4) &= (40, 300, 10, 500, 20), \\ (p_5, p_6, p_7, p_8) &= (200, 5, 400, 50). \end{aligned}

Over all ways of bracketing the product, what is the smallest number of scalar multiplications needed to compute it? Give an integer.

An exact integer (or a fraction like 7/12)

Key takeaways

  • x∈Rn\mathbf{x} \in \mathbb{R}^n is a column of nn numbers. xix_i is one entry, x⊤\mathbf{x}^\top is the same numbers as a row, and 0\mathbf{0}, 1\mathbf{1} and ei\mathbf{e}_i are the named vectors.
  • A∈Rm×nA \in \mathbb{R}^{m \times n} has mm rows and nn columns, rows first. AijA_{ij} is an entry, Ai,:A_{i,:} a row, A:,jA_{:,j} a column, and (A⊤)ij=Aji(A^\top)_{ij} = A_{ji}.
  • Products are sums over indices: (Ax)i=∑jAijxj(A\mathbf{x})_i = \sum_j A_{ij}x_j and (AB)ij=∑kAikBkj(AB)_{ij} = \sum_k A_{ik}B_{kj}. x⊤y\mathbf{x}^\top\mathbf{y} is a number; xy⊤\mathbf{x}\mathbf{y}^\top is a matrix.
  • The shape rule: (m×n)(n×p)=m×p(m \times n)(n \times p) = m \times p, while ++ and ⊙\odot need identical shapes. Transposing a product reverses it: (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top.
  • Code differs from papers: batch first, examples as rows (XW⊤XW^\top rather than WxW\mathbf{x}), and broadcasting stretches shapes that mathematics would reject. Check shapes on paper and with .shape.

Checkpoint

Prove it to the labyrinth

Answer every question to clear this chamber. First-try answers earn the most XP.

0/8
Question 1 of 8 +20 XP

Let x=(1,−2,3)⊤\mathbf{x} = (1, -2, 3)^\top and y=(4,0,−1)⊤\mathbf{y} = (4, 0, -1)^\top. What is x⊤y\mathbf{x}^\top \mathbf{y}?

Question 2 of 8 +20 XP

Let x=(3,−4,12)⊤\mathbf{x} = (3, -4, 12)^\top. What is ∥x∥2\|\mathbf{x}\|_2?

Question 3 of 8 +20 XP

A paper writes A:,2A_{:,2}. What does it mean?

Question 4 of 8 +20 XP

Let A=[1234]A = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} and B=[0110]B = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}. What is A⊙BA \odot B?

Question 5 of 8 +20 XP

Let A∈R3×2A \in \mathbb{R}^{3 \times 2} and B∈R2×5B \in \mathbb{R}^{2 \times 5}. Which expression equals (AB)⊤(AB)^\top?

Question 6 of 8 +20 XP

In NumPy, a has shape (3,) and b has shape (3, 1). What is the shape of a + b?

Question 7 of 8 +20 XP

LoRA writes a weight update as ΔW=BA\Delta W = BA with B∈Rd×rB \in \mathbb{R}^{d \times r} and A∈Rr×kA \in \mathbb{R}^{r \times k}. For d=k=1024d = k = 1024 and r=4r = 4, how many numbers do BB and AA hold together?

Question 8 of 8 +20 XP

A batch X∈R32×128×512X \in \mathbb{R}^{32 \times 128 \times 512} holds 32 sequences of 128 tokens, each token a 512-dimensional vector. What is the shape of X5,:,:X_{5,:,:}?

End of the chamber

Clear this chamber

+60 XPVector NotationMatrix NotationThe TransposeShape Checking