Module contents
Lesson 1 of 25Review 70 min

Vectors, linear combinations and the four faces of matrix multiplication

An intensive review of vectors and matrices focused on interpreting products. Read Ax as a combination of columns and as a collection of dot products, and AB in four equivalent ways, including a sum of outer products that anticipates the SVD. Finish with the cost of product chains, a foundational performance decision in any model.

After this lesson you can

  • Interpret Ax as a linear combination of columns and as dot products with rows, and switch between the two views.
  • Calculate AB in four ways by entries, columns, rows, and outer products, and explain when each view helps.
  • Determine geometrically the span of a set of vectors in R² and R³.
  • Apply transpose rules, including (AB)ᵀ = BᵀAᵀ, without shape errors.
  • Choose the evaluation order of a chain of products that minimizes operations.

Before you start

A model is a chain of matrix products

Remove the nonlinearities, normalizations, and softmax from a GPT, and what remains is a sequence of matrix products. A dense layer computes h=σ(Wx+b)\vb{h} = \sigma(\mat{W}\vb{x} + \vb{b}), a matrix-vector product. If you stack the vectors of a batch as rows of a matrix X\mat{X}, the linear part of the same layer is XW⊤\mat{X}\mat{W}\T, a matrix product. Attention computes softmax⁡(QK⊤/dk) V\softmax(\mat{Q}\mat{K}\T/\sqrt{d_k})\,\mat{V}, two more products with a softmax in between.

This is more than a figure of speech. Kaplan et al. (2020) estimate that a forward pass of a transformer with NN parameters, excluding embeddings, costs on the order of 2N2N operations per token, plus a term that grows with context length. Almost all of these are multiplications and additions inside matrix products. AlphaZero’s policy and value network is convolutional, and convolutions are usually implemented on a GPU as matrix products.

Reading matrix products fluently is therefore part of reading models. This lesson is a concentrated review of what you already know, focusing on three skills for designing and accelerating models:

  1. Read Ax\mat{A}\vb{x} in two ways, as a combination of columns and as dot products with rows, and switch between them according to the question.
  2. Read AB\mat{A}\mat{B} in four ways, by entries, columns, rows, and as a sum of outer products, and choose the view that illuminates each problem.
  3. Count the cost of a product and choose the order of a chain of products, which can change the cost by orders of magnitude.

Vectors: arrow, point, and list

The same object has three interpretations. Fluency means switching between them naturally:

  • A list of data. A vector is a record, such as a customer’s features, the closing prices in a portfolio, or a token embedding, which has 768 components in small GPT-2.
  • A point. A position in space. A dataset is a cloud of points in Rd\R^d.
  • An arrow. A displacement that can be drawn from any origin. The arrow from point x\vb{x} to point y\vb{y} is y−x\vb{y} - \vb{x}.

The arrow interpretation gives the geometry of the operations. Addition chains arrows head to tail, the parallelogram rule. Multiplication by cc stretches the arrow by ∣c∣\abs{c} and reverses it if c<0c < 0.

Intuition from R2\R^2 and R3\R^3 applies in R768\R^{768} because any two vectors span at most a plane, and three span at most a three-dimensional space. Anything you draw about two or three vectors is exact within that subspace. Statements about many vectors at once do not necessarily carry over, such as how many can be nearly perpendicular to one another. Those high-dimensional phenomena appear in the lesson on inner products.

Linear combinations and span

Only the two operations of the space, scaling and addition, are involved. Everything else follows from them: the output of a linear layer, the solution of a system, a projection, or a change of coordinates.

The first interpretation: a combination of columns

Linear combinations are so common that they have their own notation. Place the vectors in the columns of a matrix and the weights in a vector.

A\mat{A} is the pantry and x\vb{x} is the recipe specifying how much of each ingredient to use. This interpretation immediately answers which outputs A\mat{A} can produce: exactly the combinations of its columns.

InteractiveAx\mat{A}\vb{x} as a recipe of columns
  • a1\vb{a}_1 and x1a1x_1\vb{a}_1
  • a2\vb{a}_2 and x2a2x_2\vb{a}_2
  • Ax\mat{A}\vb{x}
  • reachable with ∣xi∣≤2\abs{x_i} \le 2
Ax=1.5[1.50.5]+1.2[−0.51]=[1.651.95]\mat{A}\vb{x} = \textcolor{#b04e27}{1.5\begin{bmatrix} 1.5 \\ 0.5 \end{bmatrix}} + \textcolor{#14835c}{1.2\begin{bmatrix} -0.5 \\ 1 \end{bmatrix}} = \textcolor{#ae5c7b}{\begin{bmatrix} 1.65 \\ 1.95 \end{bmatrix}}
Weights
1.50
1.20
Ax\mat{A}\vb{x}(1.65, 1.95)
span⁡{a1,a2}\spn\{\vb{a}_1, \vb{a}_2\}all of R2\text{all of } \R^2
Weights that reach b\vb{b}(−1, 2)
The bands show x1a1x_1\vb{a}_1 and x2a2x_2\vb{a}_2 placed head to tail; their sum is Ax\mat{A}\vb{x}. The grid marks combinations with integer weights, and the shaded region marks combinations with weights in [−2,2][-2, 2]. Select «Llegar a b\vb{b}», then «Alinear»: as the columns become parallel, everything collapses onto a line and b\vb{b} can no longer be reached.

Explore three things in the interactive:

  • With nonparallel columns, the grid cells, which are parallelograms, tile the plane. Every b\vb{b} lies in a cell and is reached with unique real weights.
  • If a2\vb{a}_2 is a multiple of a1\vb{a}_1, all combinations lie on a line. For b\vb{b} outside it, Ax=b\mat{A}\vb{x} = \vb{b} has no solution; for a point on the line, it has infinitely many.
  • Near alignment the parallelogram becomes needle-like, and reaching a distant b\vb{b} requires enormous weights. With a1=(1,0)\vb{a}_1 = (1, 0) and a2=(1,0.01)\vb{a}_2 = (1, 0.01), reaching b=(0,1)\vb{b} = (0, 1) requires x=(−100,100)\vb{x} = (-100, 100). This sensitivity is captured by the condition number, which governs how errors are amplified when solving systems and optimizing.

Linear span

Proof

It is a subspace: it contains 0=∑i0 vi\vb{0} = \sum_i 0\,\vb{v}_i; the sum of two combinations is another combination, ∑icivi+∑idivi=∑i(ci+di)vi\sum_i c_i\vb{v}_i + \sum_i d_i\vb{v}_i = \sum_i (c_i + d_i)\vb{v}_i; and λ∑icivi=∑i(λci)vi\lambda \sum_i c_i\vb{v}_i = \sum_i (\lambda c_i)\vb{v}_i. It is the smallest such subspace: if a subspace SS contains each vi\vb{v}_i, closure under scalar multiplication means it contains each civic_i\vb{v}_i, and closure under addition means it contains ∑icivi\sum_i c_i\vb{v}_i.

∎

Using the definition of Ax\mat{A}\vb{x}, the question of whether a system has a solution becomes a geometric question:

Ax=b has a solution  ⟺   b∈span⁡{a1,…,an}.\begin{aligned} &\mat{A}\vb{x} = \vb{b} \text{ has a solution} \\ \iff\ &\vb{b} \in \spn\{\vb{a}_1, \dots, \vb{a}_n\}. \end{aligned}

This follows directly from the definition. The set is the column space of A\mat{A}, the first of the four subspaces that organize everything a matrix does.

What shape can a span have? It always passes through the origin. In R2\R^2 it can only be the origin, a line, or the whole plane; in R3\R^3, the origin, a line, a plane, or the whole space. In R3\R^3:

  • A nonzero vector spans a line. The zero vector spans only the origin.
  • Two vectors span a plane unless they are parallel, in which case they span a line, or just the origin if both are zero.
  • Three vectors span all of R3\R^3 unless they are coplanar. If one is a combination of the others, they remain in a plane, a line, or the origin.

The rule is that adding a vector enlarges the span if and only if it was not already in it. In that case it enlarges the span by exactly one dimension. The next lesson formalizes this using linear independence and dimension.

InteractiveSpan in R3\R^3: line, plane, or space
  • v1\vb{v}_1
  • v2\vb{v}_2
  • v3\vb{v}_3
  • ∑icivi\sum_i c_i\vb{v}_i with 0≤ci≤10 \le c_i \le 1
  • plane of v1\vb{v}_1 and v2\vb{v}_2
Vectors in the set
70°
1.60
Dimension3 (all of R3)3\ (\text{all of } \R^3)
Shapeparallelepiped
v3∈span⁡{v1,v2}\vb{v}_3 \in \spn\{\vb{v}_1, \vb{v}_2\}no
v3\vb{v}_3 leaves the plane: combinations fill a solid parallelepiped and the span is all of R3\R^3.
Drag to rotate the scene or select «Ver de canto». The cloud shows combinations c1v1+c2v2+c3v3c_1\vb{v}_1 + c_2\vb{v}_2 + c_3\vb{v}_3 with 0≤ci≤10 \le c_i \le 1, and the edges mark its boundary: a segment, parallelogram, or parallelepiped, depending on the dimension of the span. Set the height hh of v3\vb{v}_3 to zero. The box flattens into a hexagon in the plane of v1\vb{v}_1 and v2\vb{v}_2, which becomes the span. Then remove v3\vb{v}_3 and close the angle between v1\vb{v}_1 and v2\vb{v}_2 until the parallelogram degenerates into a segment.
Quiz
What is span⁡{(1,0,1), (0,1,1), (1,1,2)}\spn\{(1, 0, 1),\ (0, 1, 1),\ (1, 1, 2)\} in R3\R^3?

The dot product

The norm applies the Pythagorean theorem once per coordinate. The dot product is symmetric (x⋅y=y⋅x\vb{x}\cdot\vb{y} = \vb{y}\cdot\vb{x}), linear in each argument ((ax+bz)⋅y=a x⋅y+b z⋅y(a\vb{x} + b\vb{z})\cdot\vb{y} = a\,\vb{x}\cdot\vb{y} + b\,\vb{z}\cdot\vb{y}), and positive definite (x⋅x>0\vb{x}\cdot\vb{x} > 0 if x≠0\vb{x} \neq \vb{0}). These three properties are the axioms of an inner product. Cauchy-Schwarz, the definition of angle, and projection rely only on them, so they hold for every inner product.

The formula does not immediately reveal the geometry. Explore it in the interactive before reading the theorem.

InteractiveThe dot product as a shadow
  • a\vb{a}
  • b\vb{b}
  • shadow (signed projection)
  • boundary a⋅b=0\vb{a}\cdot\vb{b} = 0
  • line through a\vb{a}
a⋅b\vb{a}\cdot\vb{b} as a function of the angle from a\vb{a} to b\vb{b}, with fixed lengths
−180°−90°0°90°180°7.90−7.9
a⋅b=3⋅1.5+1⋅2=6.5=∥a∥ (∥b∥cos⁡θ)=3.16⋅2.06≈6.5\begin{aligned} \vb{a}\cdot\vb{b} &= 3\cdot1.5 + 1\cdot2 = 6.5 \\ &= \norm{\vb{a}}\,(\norm{\vb{b}}\cos\theta) = 3.16 \cdot 2.06 \approx 6.5 \end{aligned}
Shadow
a⋅b\vb{a}\cdot\vb{b}6.5
∥a∥\norm{\vb{a}}, ∥b∥\norm{\vb{b}}3.162, 2.5
Angle θ\theta34.7°
cos⁡θ\cos\theta0.822
Shadow of b\vb{b} onto a\vb{a}2.055
Rotate b\vb{b} around the origin and watch the sign of a⋅b\vb{a}\cdot\vb{b}. When does it change? When is it greatest? The magenta band, offset as a dimension line, is the signed shadow of one vector on the other's line. Check in the formula below that the product equals this shadow times the length of the base vector. The curve below plots the product against the angle. Turn on «Vectores unitarios» and the product becomes the cosine.

What you just saw, the sign changing exactly at the perpendicular line and the maximum when the vectors align, is expressed by the following theorem.

Proof

The vectors x\vb{x}, y\vb{y}, and x−y\vb{x} - \vb{y} form a triangle with angle θ\theta between the first two sides. By the cosine rule, ∥x−y∥2=∥x∥2+∥y∥2−2∥x∥∥y∥cos⁡θ\norm{\vb{x} - \vb{y}}^2 = \norm{\vb{x}}^2 + \norm{\vb{y}}^2 - 2\norm{\vb{x}}\norm{\vb{y}}\cos\theta. By linearity and symmetry of the dot product, ∥x−y∥2=(x−y)⋅(x−y)=∥x∥2−2 x⋅y+∥y∥2\norm{\vb{x} - \vb{y}}^2 = (\vb{x} - \vb{y})\cdot(\vb{x} - \vb{y}) = \norm{\vb{x}}^2 - 2\,\vb{x}\cdot\vb{y} + \norm{\vb{y}}^2. Equating the two expressions gives x⋅y=∥x∥∥y∥cos⁡θ\vb{x}\cdot\vb{y} = \norm{\vb{x}}\norm{\vb{y}}\cos\theta. If x\vb{x} and y\vb{y} are parallel, the triangle degenerates, but then y=λx\vb{y} = \lambda\vb{x} and both sides equal λ∥x∥2\lambda\norm{\vb{x}}^2, with cos⁡θ=±1\cos\theta = \pm 1 depending on the sign of λ\lambda, so the identity still holds.

∎

In Rn\R^n with n>3n > 3 there is no prior notion of angle, so the formula is used as the definition: cos⁡θ=x⋅y/(∥x∥∥y∥)\cos\theta = \vb{x}\cdot\vb{y}/(\norm{\vb{x}}\norm{\vb{y}}). This is valid because the Cauchy-Schwarz inequality, ∣x⋅y∣≤∥x∥∥y∥\abs{\vb{x}\cdot\vb{y}} \le \norm{\vb{x}}\norm{\vb{y}}, ensures that this quotient lies in [−1,1][-1, 1].

The most useful interpretation is the shadow. The scalar projection of y\vb{y} onto the direction of x\vb{x} is the signed length of its shadow on the line of x\vb{x}, ∥y∥cos⁡θ=x⋅y/∥x∥\norm{\vb{y}}\cos\theta = \vb{x}\cdot\vb{y}/\norm{\vb{x}}. Therefore

x⋅y=∥x∥×(shadow of y on x)=∥y∥×(shadow of x on y),\begin{aligned} \vb{x}\cdot\vb{y} &= \norm{\vb{x}} \times (\text{shadow of } \vb{y} \text{ on } \vb{x}) \\ &= \norm{\vb{y}} \times (\text{shadow of } \vb{x} \text{ on } \vb{y}), \end{aligned}

and the shadow as a vector is x⋅yx⋅x x\frac{\vb{x}\cdot\vb{y}}{\vb{x}\cdot\vb{x}}\,\vb{x}, the orthogonal projection of y\vb{y} onto the line of x\vb{x}.

For nonzero x,y\vb{x}, \vb{y}, the sign of the dot product classifies the relationship between their directions:

  • x⋅y>0\vb{x}\cdot\vb{y} > 0: acute or zero angle, so they point toward the same side.
  • x⋅y=0\vb{x}\cdot\vb{y} = 0: perpendicular. This is the algebraic definition of orthogonality, which works in any dimension.
  • x⋅y<0\vb{x}\cdot\vb{y} < 0: obtuse or straight angle, so they point in opposite directions.

Two applications appear constantly. Cosine similarity, x⋅y/(∥x∥∥y∥)∈[−1,1]\vb{x}\cdot\vb{y}/(\norm{\vb{x}}\norm{\vb{y}}) \in [-1, 1], compares directions while ignoring lengths and is the usual measure for finding similar embeddings. Attention scores are dot products between a query and each key, divided by dk\sqrt{d_k}. The transformer paper itself explains this factor (Vaswani et al., 2017): if the components of q\vb{q} and k\vb{k} are independent with mean 0 and variance 1, then q⋅k\vb{q}\cdot\vb{k} is a sum of dkd_k independent products with variance 1. Its variance is dkd_k, and dividing by dk\sqrt{d_k} returns the scores to a scale that does not depend on dimension. See scaled dot-product attention.

Two interpretations of the matrix-vector product

Rows, columns, and the transpose

To talk about the rows of a matrix as conveniently as its columns, we need to turn vectors sideways.

Using it, the dot product can be written as a matrix product of 1×n1 \times n by n×1n \times 1:

x⋅y=x⊤y=[x1⋯xn][y1⋮yn]=∑ixiyi.\begin{aligned} \vb{x}\cdot\vb{y} = \vb{x}\T\vb{y} &= \begin{bmatrix} x_1 & \cdots & x_n \end{bmatrix}\begin{bmatrix} y_1 \\ \vdots \\ y_n \end{bmatrix} \\ &= \sum_i x_iy_i. \end{aligned}

From here on we use x⊤y\vb{x}\T\vb{y}. We write the rows of A\mat{A} as a~1⊤,…,a~m⊤\tilde{\vb{a}}_1\T, \dots, \tilde{\vb{a}}_m\T, so a~i∈Rn\tilde{\vb{a}}_i \in \R^n is row ii written as a column and (a~i)j=aij(\tilde{\vb{a}}_i)_j = a_{ij}:

A=[a1⋯an]=[a~1⊤⋮a~m⊤].\mat{A} = \begin{bmatrix} \vb{a}_1 & \cdots & \vb{a}_n \end{bmatrix} = \begin{bmatrix} \tilde{\vb{a}}_1\T \\ \vdots \\ \tilde{\vb{a}}_m\T \end{bmatrix}.

The second interpretation: dot products with the rows

Proof

Component ii of ∑jxjaj\sum_j x_j\vb{a}_j is ∑jxj(aj)i=∑jxjaij\sum_j x_j (\vb{a}_j)_i = \sum_j x_j a_{ij}, the dot product of (ai1,…,ain)(a_{i1}, \dots, a_{in}) with x\vb{x}.

∎

These are the same mnmn products aijxja_{ij}x_j summed in a different order: by rows, the outer loop runs over ii; by columns, it runs over jj. They answer different questions:

  • Columns: what can A\mat{A} produce? The set of outputs is the span of the columns. This is the interpretation of a linear decoder, which constructs each output as a mixture of a few patterns.
  • Rows: what does each output measure? Output ii scores how much x\vb{x} resembles the template a~i\tilde{\vb{a}}_i. The preactivation of an artificial neuron is exactly that, w~i⊤x+bi\tilde{\vb{w}}_i\T\vb{x} + b_i, and the linear part of a dense layer with doutd_{\text{out}} neurons consists of doutd_{\text{out}} dot products at once: Wx+b\mat{W}\vb{x} + \vb{b}.

Computing Ax\mat{A}\vb{x} costs mm dot products of length nn: mnmn multiplications and m(n−1)m(n - 1) additions, roughly 2mn2mn floating-point operations (flops).

One linear system, two pictures

In a system Ax=b\mat{A}\vb{x} = \vb{b} the two interpretations produce two geometric pictures of the same problem. By rows, each equation a~i⊤x=bi\tilde{\vb{a}}_i\T\vb{x} = b_i is a line in the plane, a plane in R3\R^3, or a hyperplane in Rn\R^n, perpendicular to the row vector a~i\tilde{\vb{a}}_i and at signed distance bi/∥a~i∥b_i/\norm{\tilde{\vb{a}}_i} from the origin. The solution is their intersection. By columns, the solution consists of the weights combining the columns to reach b\vb{b}.

InteractiveRow picture and column picture
By rows: lines in the (x1,x2)(x_1, x_2) plane
  • equation 1
  • equation 2
  • solution x\vb{x}
x1−x2=1x1+2x2=4\begin{aligned} \textcolor{#205aa1}{x_1 - x_2} &= 1 \\ \textcolor{#4a3ca1}{x_1 + 2x_2} &= 4 \end{aligned}
By columns: combination reaching b\vb{b}
  • x1a1x_1\vb{a}_1
  • x2a2x_2\vb{a}_2
  • b\vb{b}
2[11]+1[−12]=[14]\textcolor{#b04e27}{2\begin{bmatrix} 1 \\ 1 \end{bmatrix}} + \textcolor{#14835c}{1\begin{bmatrix} -1 \\ 2 \end{bmatrix}} = \textcolor{#ae5c7b}{\begin{bmatrix} 1 \\ 4 \end{bmatrix}}
Matrix A\mat{A}
det⁡A\det \mat{A}3
Solution x\vb{x}(2, 1)
b\vb{b}(1, 4)
The lines meet at one point and the columns span the entire plane: a unique solution.
The system x1−x2=1x_1 - x_2 = 1, x1+2x2=4x_1 + 2x_2 = 4, has solution x=(2,1)\vb{x} = (2, 1). Left: each equation is a line perpendicular to its row vector; the solution is their intersection, and its coordinates (orange and teal) are the weights. Right: those same weights combine the columns to reach b\vb{b}. Drag b\vb{b} and watch the lines move. Select «Hacer a2=2a1\vb{a}_2 = 2\vb{a}_1»: the lines become parallel exactly when the columns align.

It is no coincidence that both pictures degenerate at once. In a 2×22 \times 2 matrix, the rows are proportional if and only if the columns are proportional; both are equivalent to a11a22−a12a21=0a_{11}a_{22} - a_{12}a_{21} = 0. More generally, the number of independent rows equals the number of independent columns. This is the row-rank equals column-rank theorem, which we prove in the lesson on rank.

The row picture is typically taught at school, but it does not scale: with a hundred unknowns, nobody can visualize the intersection of a hundred hyperplanes. The column picture does scale: asking whether b\vb{b} lies in the space spanned by these columns makes sense in any dimension. Algorithms for solving systems are the subject of the linear systems lesson.

Four views of matrix multiplication

Where the definition comes from

Matrix multiplication is the unique definition that makes multiplying matrices correspond to composing the functions x↦Ax\vb{x} \mapsto \mat{A}\vb{x}. First, x↦Ax\vb{x} \mapsto \mat{A}\vb{x} is linear: A(x+y)=∑j(xj+yj)aj=Ax+Ay\mat{A}(\vb{x} + \vb{y}) = \sum_j (x_j + y_j)\vb{a}_j = \mat{A}\vb{x} + \mat{A}\vb{y}, and similarly A(cx)=c Ax\mat{A}(c\vb{x}) = c\,\mat{A}\vb{x}. Now take B∈Rn×p\mat{B} \in \R^{n \times p} with columns b1,…,bp\vb{b}_1, \dots, \vb{b}_p, and apply B\mat{B} first and then A\mat{A}. Try to predict each step before revealing it:

A(Bx)=A(x1b1+⋯+xpbp)\mat{A}(\mat{B}\vb{x}) = \mat{A}\big(x_1\vb{b}_1 + \dots + x_p\vb{b}_p\big)
Bx\mat{B}\vb{x} is the combination of the columns of B\mat{B} with weights xjx_j.
1/4

The complete correspondence between matrices and linear maps, with composition as multiplication, is the subject of the linear transformations lesson. Here we focus on how to interpret the formula.

Four interpretations of the same sum

We need one more piece before stating them. The outer product of u∈Rm\vb{u} \in \R^m and v∈Rp\vb{v} \in \R^p is the matrix uv⊤∈Rm×p\vb{u}\vb{v}\T \in \R^{m \times p}, with dimensions (m×1)(1×p)(m \times 1)(1 \times p) and entries (uv⊤)ij=uivj(\vb{u}\vb{v}\T)_{ij} = u_iv_j. Column jj is vjuv_j\vb{u} and row ii is uiv⊤u_i\vb{v}\T. All columns are multiples of the same vector, so if u\vb{u} and v\vb{v} are nonzero, it is a rank-one matrix. Compare this with the dot product: x⊤y\vb{x}\T\vb{y} is a number and xy⊤\vb{x}\vb{y}\T is a matrix, using the same vectors in a different order.

Before stating the four interpretations, see them in action. Computing the formula ∑kaikbkj\sum_k a_{ik}b_{kj} for every entry involves three indices ii, jj, and kk, and each interpretation traverses them in a different order.

InteractiveFour ways to multiply AB\mat{A}\mat{B}
1
2
0
0
1
−1
3
0
1
A\mat{A}
×\times
2
0
1
1
−1
0
0
2
3
B\mat{B}
==
·
·
·
·
·
·
·
·
·
C=AB\mat{C} = \mat{A}\mat{B}
Entry cijc_{ij} = dot product of row ii of A\mat{A} with column jj of B\mat{B}
c11=c_{11} =a11b11a_{11}b_{11}++a12b21a_{12}b_{21}++a13b31a_{13}b_{31}
==1⋅21\cdot2++2⋅12\cdot1++0⋅00\cdot0=4= 4
Log of the 27 multiplications aikbkja_{ik}b_{kj}, grouped by summation index kk
k=1k = 1
k=2k = 2
k=3k = 3
Multiplications0 / 27
Additions0 / 18
Completed entries of C\mat{C}0 / 9
Rank of partial C\mat{C}0
Current step (i,j,k)(i, j, k)none
Loop order
for i in range(3):
  for j in range(3):
    for k in range(3):
      C[i,j] += A[i,k]*B[k,j]
Each step is a multiplication aikbkja_{ik}b_{kj}. The summation index kk is color-coded: column kk of A\mat{A}, row kk of B\mat{B}, and term kk in the formula. The terms already summed are marked below each entry of C\mat{C}, and the log below records all 27 multiplications. Before playing a view, predict which entries of C\mat{C} will be complete halfway through. Then change views halfway: the number of multiplications is the same, but which ones have been done differs. In the outer-product view, follow «Rango de C\mat{C} parcial»: after the first third, C\mat{C} is already a complete rank-one matrix.
Proof

Check that entry (i,j)(i, j) is ∑kaikbkj\sum_k a_{ik}b_{kj} in each interpretation. In (1), a~i⊤bj=∑k(a~i)k(bj)k=∑kaikbkj\tilde{\vb{a}}_i\T\vb{b}_j = \sum_k (\tilde{\vb{a}}_i)_k(\vb{b}_j)_k = \sum_k a_{ik}b_{kj}. The construction in (2) is from the previous derivation, reading Abj\mat{A}\vb{b}_j by columns. In (3), component jj of ∑kaikb~k⊤\sum_k a_{ik}\tilde{\vb{b}}_k\T is ∑kaik(b~k)j=∑kaikbkj\sum_k a_{ik}(\tilde{\vb{b}}_k)_j = \sum_k a_{ik}b_{kj}. Case (4) is the guided exercise that follows.

∎
ProofThe product as a sum of outer products
Prove: If A∈Rm×n\mat{A} \in \R^{m \times n} has columns ak\vb{a}_k and B∈Rn×p\mat{B} \in \R^{n \times p} has rows b~k⊤\tilde{\vb{b}}_k\T, then AB=∑k=1nakb~k⊤\mat{A}\mat{B} = \sum_{k=1}^n \vb{a}_k\tilde{\vb{b}}_k\T.
0
Each term akb~k⊤\vb{a}_k\tilde{\vb{b}}_k\T has dimensions (m×1)(1×p)(m \times 1)(1 \times p), namely m×pm \times p, like AB\mat{A}\mat{B}.

Step 1 of 4. What is sufficient to check?

The four views perform exactly the same mnpmnp multiplications aikbkja_{ik}b_{kj}. Only the order of the three nested loops changes, as you saw in the interactive. With the kk loop innermost, each entry is completed at once: the entrywise view. With kk in the middle, each iteration of the outer loop completes a whole column if the outer index is jj, or a whole row if it is ii. With kk outermost, each iteration adds a complete rank-one matrix: the outer-product view.

The same arithmetic does not guarantee the same result or speed. When written as loops with increasing kk, all four views sum each entry in the same order and produce identical results. An optimized library can divide the sum over kk into blocks and accumulate it in pieces, changing the floating-point result because addition is not associative: in double precision, (0.1+0.2)+0.3≠0.1+(0.2+0.3)(0.1 + 0.2) + 0.3 \neq 0.1 + (0.2 + 0.3) (the standard floating-point model). This is why results are compared with np.allclose rather than ==, and why the last bits of the same product may differ by library, hardware, or block size. Memory access differs too. NumPy stores matrices in row-major order, so the rowwise view visits contiguous memory while the columnwise view jumps between rows (the ndarray memory model and strides). You will measure this in the lab.

CodeThe product as a sum of outer products
Implement matmul_outer(A, B) for 2D arrays, returning AB\mat{A}\mat{B} as a sum of outer products ∑kakb~k⊤\sum_k \vb{a}_k\tilde{\vb{b}}_k\T. You cannot use @, the .dot method, or NumPy's product functions (np.dot, np.matmul, np.outer, np.multiply.outer, np.inner, np.vdot, np.kron, np.tensordot, np.einsum, np.linalg.multi_dot). Construct each outer product using broadcasting. Raise ValueError if the inner dimensions do not match. The tests use nonsquare shapes, row vectors times column vectors, and vice versa.
import numpy as np

def matmul_outer(A, B):
  # tu código aquí
  raise NotImplementedError
Shift+Enter to run

Which view should you use?

ViewQuestion answered and where it appears
EntriesWhat is a particular entry? This is hand calculation and the attention score between token ii and token jj.
ColumnsWhat does AB\mat{A}\mat{B} generate? Its columns lie in the span of the columns of A\mat{A}. This applies A\mat{A} to many vectors at once, arranged as columns of B\mat{B}.
RowsWhat happens to each row of data? The rows of AB\mat{A}\mat{B} are combinations of rows of B\mat{B}. This is a batch of examples in rows passing through a layer: XW⊤\mat{X}\mat{W}\T.
Outer productsWhich rank-one pieces make it up? This is the form of the SVD, LoRA adapters, and the gradient of a linear layer.

Three consequences you will use often:

  • Rank of a product. By the columnwise view, the columns of AB\mat{A}\mat{B} lie in the span of those of A\mat{A}; by the rowwise view, its rows lie in the span of those of B\mat{B}. Hence rank⁡(AB)≤min⁡(rank⁡A,rank⁡B)\rank(\mat{A}\mat{B}) \le \min(\rank\mat{A}, \rank\mat{B}). The outer-product view also gives rank⁡(AB)≤n\rank(\mat{A}\mat{B}) \le n. An nn-dimensional bottleneck limits everything that passes through it.
  • Gradient of a linear layer. If y=Wx\vb{y} = \mat{W}\vb{x} and g=∂L/∂y\vb{g} = \partial L/\partial\vb{y}, then ∂L/∂wij=gixj\partial L/\partial w_{ij} = g_ix_j, or ∂L/∂W=gx⊤\partial L/\partial\mat{W} = \vb{g}\vb{x}\T: an outer product. For a batch this becomes a sum of outer products, one per example. We derive it in detail in linear layer gradients.
  • Low rank. The singular value decomposition writes any matrix as ∑iσiuivi⊤\sum_i \sigma_i\vb{u}_i\vb{v}_i\T. LoRA (Hu et al., 2021) adapts a large model by freezing its weights W\mat{W} and adding a product BA\mat{B}\mat{A}, where B∈Rd×r\mat{B} \in \R^{d \times r} and A∈Rr×k\mat{A} \in \R^{r \times k}. By the fourth view, this is only rr outer products. We discuss its cost in the section on chains.

The four views are special cases of one idea: divide matrices into blocks and multiply the blocks as if they were numbers, preserving their order. Block matrices develop this idea in depth.

Quiz
Let A∈R4×3\mat{A} \in \R^{4 \times 3} and B∈R3×5\mat{B} \in \R^{3 \times 5}. Which expression is the second column of AB\mat{A}\mat{B}?

Algebraic properties

Proof

For associativity, entry (i,j)(i, j) on both sides is the same finite double sum, ∑k∑laikbklclj\sum_k\sum_l a_{ik}b_{kl}c_{lj}, grouped in two ways. Alternatively, both sides represent the function x↦A(B(Cx))\vb{x} \mapsto \mat{A}(\mat{B}(\mat{C}\vb{x})). The other rules follow by checking each entry in the same way.

∎

It is just as important to understand what does not hold:

  • Noncommutativity. AB\mat{A}\mat{B} and BA\mat{B}\mat{A} may not both exist, or they may have different shapes. If A\mat{A} is m×nm \times n and B\mat{B} is n×mn \times m, one is m×mm \times m and the other is n×nn \times n. Even square products generally differ: with A=[0100]\mat{A} = \begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix} and B=[0010]\mat{B} = \begin{bmatrix} 0 & 0 \\ 1 & 0 \end{bmatrix}, we obtain AB=[1000]\mat{A}\mat{B} = \begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix} and BA=[0001]\mat{B}\mat{A} = \begin{bmatrix} 0 & 0 \\ 0 & 1 \end{bmatrix}. Reading by columns, A\mat{A} maps e2\vb{e}_2 to e1\vb{e}_1 and sends e1\vb{e}_1 to zero, while B\mat{B} does the opposite. Applying B\mat{B} then A\mat{A} returns e1\vb{e}_1 to itself, while the other order returns e2\vb{e}_2.
  • Zero divisors. For the same A\mat{A}, AA=0\mat{A}\mat{A} = \mat{0} even though A≠0\mat{A} \neq \mat{0}. Therefore cancellation is not generally valid: AB=AC\mat{A}\mat{B} = \mat{A}\mat{C} does not imply B=C\mat{B} = \mat{C}.

Transpose rules

The first three follow immediately entry by entry. The fourth reverses the order, as the shapes require: if A\mat{A} is m×nm \times n and B\mat{B} is n×pn \times p, then (AB)⊤(\mat{A}\mat{B})\T is p×mp \times m; B⊤A⊤\mat{B}\T\mat{A}\T is (p×n)(n×m)=p×m(p \times n)(n \times m) = p \times m, whereas A⊤B⊤\mat{A}\T\mat{B}\T is (n×m)(p×n)(n \times m)(p \times n) and is undefined unless m=pm = p. Think of socks and shoes: undo them in reverse order. By induction, (A1A2⋯Ak)⊤=Ak⊤⋯A2⊤A1⊤(\mat{A}_1\mat{A}_2\cdots\mat{A}_k)\T = \mat{A}_k\T\cdots\mat{A}_2\T\mat{A}_1\T.

ProofThe transpose of a product
Prove: For A∈Rm×n\mat{A} \in \R^{m \times n} and B∈Rn×p\mat{B} \in \R^{n \times p}, (AB)⊤=B⊤A⊤(\mat{A}\mat{B})\T = \mat{B}\T\mat{A}\T.
0
Prove this from the entrywise definition of the product.

Step 1 of 4. First check the shapes.

The transpose is not the inverse, but it has an equally important role: it moves a matrix to the other side of a dot product. For x∈Rn\vb{x} \in \R^n and y∈Rm\vb{y} \in \R^m,

(Ax)⊤y=x⊤A⊤y=x⊤(A⊤y).(\mat{A}\vb{x})\T\vb{y} = \vb{x}\T\mat{A}\T\vb{y} = \vb{x}\T(\mat{A}\T\vb{y}).

Backpropagation uses this identity. If a layer computes y=Wx\vb{y} = \mat{W}\vb{x} and receives g=∂L/∂y\vb{g} = \partial L/\partial\vb{y} from above, the change in the loss is g⊤ Δy=g⊤W Δx=(W⊤g)⊤Δx\vb{g}\T\,\Delta\vb{y} = \vb{g}\T\mat{W}\,\Delta\vb{x} = (\mat{W}\T\vb{g})\T\Delta\vb{x}. Thus ∂L/∂x=W⊤g\partial L/\partial\vb{x} = \mat{W}\T\vb{g}: the gradient travels backward through the transpose. This is the first example of a vector-Jacobian product.

A matrix is symmetric if A⊤=A\mat{A}\T = \mat{A}. An important example is A⊤A\mat{A}\T\mat{A}, which is always symmetric: (A⊤A)⊤=A⊤(A⊤)⊤=A⊤A(\mat{A}\T\mat{A})\T = \mat{A}\T(\mat{A}\T)\T = \mat{A}\T\mat{A}. Its entries are dot products between columns, (A⊤A)ij=ai⊤aj(\mat{A}\T\mat{A})_{ij} = \vb{a}_i\T\vb{a}_j. It is the Gram matrix of the columns, and appears in least squares, covariance matrices, and kernels.

Rows and columns in NumPy

On paper, a vector is a column. In NumPy, a one-dimensional array of shape (n,) is neither a row nor a column, and operators interpret it according to the operation. Run the cell and read each line of the output:

[ ]1D vectors, rows, and columnsBrowser
import numpy as np

x = np.array([1.0, 2.0, 3.0])            # forma (3,): ni fila ni columna
print("x.shape =", x.shape, "  x.T.shape =", x.T.shape, "  (.T no hace nada en 1D)")
print("x @ x   =", x @ x, "  (producto escalar: un número)")

col = x[:, None]                          # (3, 1): columna explícita
fila = x[None, :]                         # (1, 3): fila explícita
print("col @ fila ->", (col @ fila).shape, "   fila @ col ->", (fila @ col).shape)
print("np.outer(x, x) == col @ fila:", np.allclose(np.outer(x, x), col @ fila))

A = np.arange(6.0).reshape(2, 3)
y = np.array([1.0, -1.0])
print("A @ x =", A @ x, "  (x actúa como columna)")
print("y @ A =", y @ A, "  (y actúa como fila: es A.T @ y)")

# La trampa: (3,) + (3, 1) no da error, da una matriz 3 x 3 por broadcasting
print("forma de x + col:", (x + col).shape)

# * es elemento a elemento; @ es el producto de matrices
B = np.ones((2, 3))
print("A * B   ->", (A * B).shape, "  A @ B.T ->", (A @ B.T).shape)

As a practical rule, keep an explicit batch axis, (B, d), check shapes with assert x.shape == (...), and write the indices using einsum when the operation is not obvious. The full rules are in broadcasting rules.

The cost of multiplication

Proof

There are mpmp entries, each a dot product of length nn: nn multiplications and n−1n - 1 additions.

∎

We use the count 2mnp2mnp, one multiplication and one addition per term, following the usual convention. The exact count changes constants, not orders of magnitude.

Is 2n32n^3 inevitable? No. Strassen (1969) multiplied 2×22 \times 2 block matrices using 7 block products instead of 8. Applied recursively, this gives Strassen’s algorithm, with cost O(nlog⁡27)≈O(n2.807)\bigO(n^{\log_2 7}) \approx \bigO(n^{2.807}). Since the late 1980s it has been known that the optimal exponent ω\omega is less than 2.382.38. The minimum number of multiplications of a bilinear algorithm is the rank of a tensor. AlphaTensor (Fawzi et al., 2022) tackled this problem with an AlphaZero-based agent, finding, for example, an algorithm for 4×44 \times 4 matrices with arithmetic modulo 2 that uses 47 multiplications versus the 49 from applying Strassen twice. We will revisit this in tensor rank. In practice, BLAS libraries almost always use the classical algorithm, organized in blocks to exploit the cache.

Remember this asymmetry. Multiplying two n×nn \times n matrices performs 2n32n^3 flops on 3n23n^2 numbers, reading two matrices and writing one: about 2n/32n/3 operations per number moved from memory, increasing with nn. A matrix-vector product performs 2n22n^2 flops on about n2n^2 numbers: two operations per number regardless of nn. The ratio of operations to data moved is the arithmetic intensity. This is why AB\mat{A}\mat{B} can saturate a GPU’s compute capacity while Ax\mat{A}\vb{x} waits for memory, as formalized by the roofline model. It explains why generating text one token at a time for a single user is limited by memory bandwidth, and why batching requests, which turns matrix-vector products into matrix products, increases throughput.

Product chains: the order of parentheses

Associativity guarantees that every parenthesization of A1A2⋯Ak\mat{A}_1\mat{A}_2\cdots\mat{A}_k gives the same result. It does not guarantee equal cost.

More generally, if Ai\mat{A}_i has dimensions pi−1×pip_{i-1} \times p_i, each parenthesization is a binary tree whose cost is the sum of the costs of its products. Multiplying block Aa+1⋯Ab\mat{A}_{a+1}\cdots\mat{A}_b (pa×pbp_a \times p_b) by block Ab+1⋯Ac\mat{A}_{b+1}\cdots\mat{A}_c (pb×pcp_b \times p_c) costs 2 papbpc2\,p_a p_b p_c. With kk factors there are Ck−1C_{k-1} trees, where Cn=1n+1(2nn)C_n = \frac{1}{n+1}\binom{2n}{n} is the Catalan number: 1, 2, 5, 14, 42… for k=2,3,4,5,6k = 2, 3, 4, 5, 6. They grow exponentially, on the order of 4k/k3/24^k/k^{3/2}, so we do not test them all. Matrix-chain ordering is a classic dynamic programming problem, solved in O(k3)\bigO(k^3) and implemented below.

InteractiveThe order of parentheses
B\mat{B}d×rd \times r4096×16
A\mat{A}r×kr \times k16×4096
x\vb{x}k×1k \times 14096×1
flops
B(Ax)\mat{B}(\mat{A}\vb{x})
(16×4096)(4096×1) → (4096×16)(16×1)
2.6×1052.6 \times 10^{5}
optimal
(BA)x(\mat{B}\mat{A})\vb{x}
(4096×16)(16×4096) → (4096×4096)(4096×1)
5.7×1085.7 \times 10^{8}
× 2176
For one vector, apply the low-rank adapter BA\mat{B}\mat{A} (d×rd \times r by r×kr \times k) as B(Ax)\mat{B}(\mat{A}\vb{x}): it costs 2r(d+k)2r(d + k) instead of 2drk+2dk2drk + 2dk. For large-batch inference, adding BA\mat{B}\mat{A} to W\mat{W} once can pay off: the fixed cost is amortized across tokens.
4096
16
4096
Worst / best× 2176
Best cost2.6×105 flops2.6 \times 10^{5}\ \text{flops}
Worst cost5.7×108 flops5.7 \times 10^{8}\ \text{flops}
Intermediate (worst)4096×4096
Its float32 size64 MiB
Each row is a parenthesization, showing the products performed in order and their flop costs on a logarithmic axis. The green point is optimal, and the gray segment measures how far each order is from it. Start with LoRA and raise rr to dd: when d=kd = k, the order B(Ax)\mat{B}(\mat{A}\vb{x}) still wins by a factor of d(r+1)/(2r)d(r+1)/(2r), always greater than d/2d/2, because the other order forms a matrix product when two matrix-vector products suffice. In linear attention, the ratio between orders is T/dT/d. With four matrices, observe that the balanced order (A1A2)(A3A4)(\mat{A}_1\mat{A}_2)(\mat{A}_3\mat{A}_4) can be the worst.

Three places where this decision changes cost by orders of magnitude:

  • LoRA. The adapter BA\mat{B}\mat{A}, with r≪d,kr \ll d, k, is applied as Wx+B(Ax)\mat{W}\vb{x} + \mat{B}(\mat{A}\vb{x}). For one vector, materializing BA\mat{B}\mat{A} and applying it costs 2drk+2dk2drk + 2dk; the right-hand order costs 2r(d+k)2r(d + k). With d=k=4096d = k = 4096 and r=16r = 16, the ratio is 21762176. The accounting depends on what is reused. During inference, LoRA can add BA\mat{B}\mat{A} to W\mat{W} once (adapter merging). The 2drk2drk flops are amortized over all tokens and the product by W\mat{W} is paid anyway, so for batches of more than dk/(d+k)dk/(d + k) tokens, 2048 in this example, merging is cheaper than applying the adapter separately. During training we retain B(Ax)\mat{B}(\mat{A}\vb{x}): W\mat{W} is frozen and only the gradients of A\mat{A} and B\mat{B} are needed.
  • Linear attention. In softmax⁡(QK⊤)V\softmax(\mat{Q}\mat{K}\T)\mat{V}, with Q,K,V∈RT×d\mat{Q}, \mat{K}, \mat{V} \in \R^{T \times d}, softmax prevents regrouping and requires computing all T2T^2 scores at cost O(T2d)\bigO(T^2d), the transformer’s quadratic barrier. A naive implementation also stores them, using O(T2)\bigO(T^2) memory. FlashAttention avoids materializing them by processing blocks, but does not reduce computation. Katharopoulos et al. (2020) replace softmax with a product of feature maps, ϕ(Q)ϕ(K)⊤\phi(\mat{Q})\phi(\mat{K})\T, and associativity does the rest: ϕ(Q)(ϕ(K)⊤V)\phi(\mat{Q})\big(\phi(\mat{K})\T\mat{V}\big) costs O(Td2)\bigO(Td^2), linear in sequence length. Row normalization replacing softmax is just as cheap, computed as ϕ(Q)(ϕ(K)⊤1)\phi(\mat{Q})\big(\phi(\mat{K})\T\vb{1}\big). This is linear attention.
  • Backpropagation. The gradient of a scalar loss L(f3(f2(f1(x))))L(f_3(f_2(f_1(\vb{x})))) is a product of Jacobians, g⊤J3J2J1\vb{g}\T\mat{J}_3\mat{J}_2\mat{J}_1, whose first factor is a row vector. Evaluating left to right always keeps a row vector and performs only vector-matrix products. Evaluating right to left forms products of full Jacobians. Reverse-mode automatic differentiation literally chooses the cheaper order.

Implementation from scratch

Implement the four views exactly as stated and check that they agree with A @ B. Notice the loop order in each one: it matches the interactive.

[ ]The product four waysBrowser
import numpy as np

def matmul_entradas(A, B):
    """Triple bucle i, j, k: cada entrada es un producto escalar fila-columna."""
    m, n = A.shape
    n2, p = B.shape
    if n != n2:
        raise ValueError(f"dimensiones incompatibles: {A.shape} y {B.shape}")
    C = np.zeros((m, p))
    for i in range(m):
        for j in range(p):
            s = 0.0
            for k in range(n):
                s += A[i, k] * B[k, j]
            C[i, j] = s
    return C

def matmul_columnas(A, B):
    """Bucles j, k: la columna j de AB combina las columnas de A con pesos B[:, j]."""
    m, n = A.shape
    C = np.zeros((m, B.shape[1]))
    for j in range(B.shape[1]):
        for k in range(n):
            C[:, j] += B[k, j] * A[:, k]
    return C

def matmul_filas(A, B):
    """Bucles i, k: la fila i de AB combina las filas de B con pesos A[i, :]."""
    m, n = A.shape
    C = np.zeros((m, B.shape[1]))
    for i in range(m):
        for k in range(n):
            C[i, :] += A[i, k] * B[k, :]
    return C

def matmul_exteriores(A, B):
    """Bucle k: AB es la suma de los productos exteriores (columna k de A)(fila k de B)."""
    m, n = A.shape
    C = np.zeros((m, B.shape[1]))
    for k in range(n):
        C += np.outer(A[:, k], B[k, :])
    return C

rng = np.random.default_rng(0)
A = rng.standard_normal((40, 30))
B = rng.standard_normal((30, 50))
Cs = [f(A, B) for f in (matmul_entradas, matmul_columnas, matmul_filas, matmul_exteriores)]
print("las cuatro coinciden con A @ B (allclose):", all(np.allclose(C, A @ B) for C in Cs))
print("las cuatro son idénticas bit a bit:      ", all(np.array_equal(Cs[0], C) for C in Cs))
print(f"máxima diferencia con A @ B:              {np.abs(Cs[0] - A @ B).max():.1e}")

# la suma en coma flotante no es asociativa: otro orden de suma, otros redondeos
print("(0.1 + 0.2) + 0.3 == 0.1 + (0.2 + 0.3):", (0.1 + 0.2) + 0.3 == 0.1 + (0.2 + 0.3))

The four loops sum each entry in the same order, k=1,2,…,nk = 1, 2, \dots, n, so they agree bit for bit. A @ B need not: with a BLAS library that divides the sum into blocks, the difference is on the order of 10−1510^{-15}. In the browser, where NumPy does not use BLAS, it is often exactly zero. That is why we compare with np.allclose.

Now count operations to verify the formula mp(2n−1)mp(2n - 1) and measure the speed of each version. The arithmetic is identical; the comparison measures how much work remains inside Python loops and how much is delegated to compiled code.

[ ]Counting operations and measuringBrowser
import time

def matmul_contando(A, B):
    """Triple bucle que cuenta multiplicaciones y sumas."""
    m, n = A.shape
    p = B.shape[1]
    mults = sumas = 0
    C = np.zeros((m, p))
    for i in range(m):
        for j in range(p):
            s = A[i, 0] * B[0, j]
            mults += 1
            for k in range(1, n):
                s += A[i, k] * B[k, j]
                mults += 1
                sumas += 1
            C[i, j] = s
    return C, mults, sumas

m, n, p = 5, 7, 3
_, mu, su = matmul_contando(rng.standard_normal((m, n)), rng.standard_normal((n, p)))
print(f"multiplicaciones: {mu} = mnp = {m * n * p}")
print(f"sumas:            {su} = mp(n-1) = {m * p * (n - 1)}")
print(f"total:            {mu + su} = mp(2n-1) = {m * p * (2 * n - 1)}")

def cronometra(f, *args, objetivo=0.02):
    """Mejor tiempo por llamada. Mide tandas de al menos 2 ms (el reloj del navegador solo
    resuelve décimas de milisegundo) hasta acumular unos 20 ms y al menos 3 tandas."""
    reps, mejor, total, tandas = 1, float("inf"), 0.0, 0
    while total < objetivo or tandas < 3:
        t0 = time.perf_counter()
        for _ in range(reps):
            f(*args)
        dt = time.perf_counter() - t0
        total += dt
        if dt < 0.002:                 # tanda demasiado corta para el reloj: se agranda
            reps *= 4
            continue
        mejor, tandas = min(mejor, dt / reps), tandas + 1
    return mejor

n = 60
A = rng.standard_normal((n, n))
B = rng.standard_normal((n, n))
print(f"\nn = {n}: {2 * n**3:,} flops por producto")
for nombre, f in [("entradas (3 bucles)", matmul_entradas), ("columnas (2 bucles)", matmul_columnas),
                  ("filas (2 bucles)", matmul_filas), ("exteriores (1 bucle)", matmul_exteriores),
                  ("A @ B (compilado)", lambda A, B: A @ B)]:
    t = cronometra(f, A, B)
    print(f"{nombre:22s} {t * 1e3:9.3f} ms   {2 * n**3 / t / 1e9:8.3f} GFLOP/s")

The difference between the first and last lines is often three or four orders of magnitude, with the same arithmetic. Each Python loop replaced by a vectorized operation divides the number of interpreter iterations by nn, although the measured gain is less than nn because every NumPy call has a fixed cost of microseconds. A @ B runs the entire triple loop in compiled code. In the browser, NumPy is compiled without BLAS and runs on one thread. In the local lab, NumPy and PyTorch also call an optimized BLAS library using cache blocks, SIMD instructions, and multiple cores. The local cell at the end measures your machine. This is why matrix products are normally delegated to libraries and why it helps to think in operations on whole arrays (vectorization).

Loop order also determines how memory is traversed. By default NumPy stores matrices by rows, in C order: row elements are contiguous and column elements are 8n8n bytes apart, the stride of the first axis. The following cell sums 500 rows and 500 columns of a 2000×20002000 \times 2000 matrix one at a time: the same flops and numbers, traversed in two ways.

[ ]Contiguous rows, strided columnsBrowser
n = 2000
M = rng.standard_normal((n, n))            # orden C: cada fila es contigua
MF = np.asfortranarray(M)                  # mismos números en orden Fortran: cada columna es contigua
print("strides en bytes de M:", M.strides, "  de MF:", MF.strides)
for nombre, X in (("orden C", M), ("orden Fortran", MF)):
    t_filas = cronometra(lambda: [X[i, :].sum() for i in range(0, n, 4)])
    t_cols = cronometra(lambda: [X[:, j].sum() for j in range(0, n, 4)])
    print(f"{nombre:14s} 500 filas {t_filas * 1e3:6.2f} ms   500 columnas {t_cols * 1e3:6.2f} ms")

In C order, traversing columns is several times slower; in Fortran order, the reverse holds. Memory arrives in the cache in 64-byte lines: traversing a row uses all 8 numbers in each line, while traversing a column uses one. The columnwise and rowwise views of the product have exactly this pattern (A[:, k] versus B[k, :]). BLAS libraries account for it when choosing loop order and dividing the product into blocks that fit in cache.

The next experiment measures the effect of parentheses. The theoretical cost of (xy⊤)z(\vb{x}\vb{y}\T)\vb{z} grows as n2n^2, while that of x(y⊤z)\vb{x}(\vb{y}\T\vb{z}) grows as nn. The cost of (AB)x(\mat{A}\mat{B})\vb{x} grows as n3n^3, while A(Bx)\mat{A}(\mat{B}\vb{x}) grows as n2n^2.

[ ]Measuring parenthesization orderBrowser
import matplotlib.pyplot as plt

ns1 = [250, 500, 1000, 2000]
lento1, rapido1 = [], []
for n in ns1:
    x, y, z = (rng.standard_normal((n, 1)) for _ in range(3))
    lento1.append(cronometra(lambda: (x @ y.T) @ z))
    rapido1.append(cronometra(lambda: x @ (y.T @ z)))

ns2 = [50, 100, 200, 400]
lento2, rapido2 = [], []
for n in ns2:
    A2, B2, x = rng.standard_normal((n, n)), rng.standard_normal((n, n)), rng.standard_normal((n, 1))
    lento2.append(cronometra(lambda: (A2 @ B2) @ x))
    rapido2.append(cronometra(lambda: A2 @ (B2 @ x)))

for n, a, b in zip(ns1, lento1, rapido1):
    print(f"x yT z,  n = {n:5d}:  (x yT) z / x (yT z) = {a / b:8.0f}")
for n, a, b in zip(ns2, lento2, rapido2):
    print(f"A B x,   n = {n:5d}:  (A B) x / A (B x)   = {a / b:8.1f}")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.4))
ax[0].loglog(ns1, lento1, "o-", label="(x yᵀ) z")
ax[0].loglog(ns1, rapido1, "o-", label="x (yᵀ z)")
ax[0].set_title("Tres vectores"); ax[0].set_xlabel("n"); ax[0].set_ylabel("segundos")
ax[1].loglog(ns2, lento2, "o-", label="(A B) x")
ax[1].loglog(ns2, rapido2, "o-", label="A (B x)")
ax[1].set_title("Dos matrices y un vector"); ax[1].set_xlabel("n")
for a in ax:
    a.legend()
plt.tight_layout()
plt.show()

In the first experiment the ratio grows as nn, as predicted by the flop count. In the second the count predicts a ratio of (2n3+2n2)/(4n2)≈n/2(2n^3 + 2n^2)/(4n^2) \approx n/2, while measurement depends heavily on the library. With BLAS, as in the local lab, the ratio grows more slowly than n/2n/2 and may even decrease. Matrix multiplication reuses each number brought from memory many times and uses the machine much more effectively per flop than matrix-vector multiplication, the arithmetic intensity discussed above. Beyond a certain size the library also distributes it across cores. In the browser, without BLAS, it can grow faster than n/2n/2 because matrix multiplication without cache blocking loses efficiency as nn grows. Fixed call costs also dominate at small sizes. Theory gives the order of magnitude; measurement reveals the behavior of your machine.

Finally, the general problem is to find the optimal parentheses given the dimension vector (p0,p1,…,pk)(p_0, p_1, \dots, p_k). With a few factors, it is enough to generate all trees and keep the cheapest. We represent a tree as you would draw it: a leaf is a factor’s index and a product is the tuple (izquierdo, derecho), meaning left and right.

[ ]All trees by brute forceBrowser
def arboles(i, j):
    """Genera todas las formas de poner paréntesis en A_i ... A_j (índices desde 0)."""
    if i == j:
        yield i
        return
    for s in range(i, j):                  # el último producto parte la cadena tras A_s
        for izq in arboles(i, s):
            for der in arboles(s + 1, j):
                yield (izq, der)

def coste(arbol, dims):
    """(primer factor, último factor, flops) de un árbol, con 2pqr flops por producto."""
    if isinstance(arbol, int):
        return arbol, arbol, 0
    i, s, c1 = coste(arbol[0], dims)
    _, j, c2 = coste(arbol[1], dims)
    return i, j, c1 + c2 + 2 * dims[i] * dims[s + 1] * dims[j + 1]

def texto(arbol, nombres):
    if isinstance(arbol, int):
        return nombres[arbol]
    return f"({texto(arbol[0], nombres)} {texto(arbol[1], nombres)})"

print("árboles con k = 2, ..., 8 factores:", [sum(1 for _ in arboles(0, k - 1)) for k in range(2, 9)])

ejemplos = {                               # dimensiones y nombres de los factores
    "x yT z (n = 1e6)": ([10**6, 1, 10**6, 1], ["x", "yT", "z"]),
    "LoRA: B A x":      ([4096, 16, 4096, 1], ["B", "A", "x"]),
    "atención: Q KT V": ([4096, 64, 4096, 64], ["Q", "KT", "V"]),
    "cuatro matrices":  ([1024, 16, 1024, 16, 1024], ["A1", "A2", "A3", "A4"]),
}
for nombre, (d, f) in ejemplos.items():
    todos = sorted((coste(a, d)[2], texto(a, f)) for a in arboles(0, len(d) - 2))
    (c_min, e_min), (c_max, _) = todos[0], todos[-1]
    print(f"{nombre:17s} óptimo {e_min:17s} {c_min:.1e} flops   peor / óptimo = {c_max / c_min:,.0f}")

# La versión profesional: np.linalg.multi_dot elige el orden por sí misma
dims = [400, 8, 400, 8, 400]
Ms = [rng.standard_normal((dims[i], dims[i + 1])) for i in range(4)]
t_izq = cronometra(lambda: ((Ms[0] @ Ms[1]) @ Ms[2]) @ Ms[3])
t_md = cronometra(lambda: np.linalg.multi_dot(Ms))
mejor = min(arboles(0, 3), key=lambda a: coste(a, dims)[2])
print(f"\nmismo resultado: {np.allclose(np.linalg.multi_dot(Ms), ((Ms[0] @ Ms[1]) @ Ms[2]) @ Ms[3])}")
print(f"izquierda a derecha: {t_izq * 1e3:.2f} ms   multi_dot: {t_md * 1e3:.2f} ms   óptimo: {texto(mejor, ['A1', 'A2', 'A3', 'A4'])}")

With 20 factors there would be C19≈1.8×109C_{19} \approx 1.8 \times 10^9 trees, so brute force quickly becomes impractical. The way out is optimal substructure. The last product splits the chain into A1⋯As\mat{A}_1\cdots\mat{A}_s and As+1⋯Ak\mat{A}_{s+1}\cdots\mat{A}_k, and each half must itself be computed optimally. Since there are only k(k+1)/2k(k+1)/2 distinct subchains, it is enough to solve each one once and store the result in a table.

CodeOptimal parentheses with dynamic programming
Implement coste_minimo(dims) and parentizacion(dims). Both receive dims = [p0, ..., pk], so factor Ai\mat{A}_i, indexed from 1, has shape pi−1×pip_{i-1} \times p_i. coste_minimo returns the minimum flops for the chain, counting 2pqr2pqr per product (p×q)(q×r)(p \times q)(q \times r). parentizacion returns an optimal tree in the previous cell's format: the factor index, starting from 0, at each leaf, and the tuple (izquierdo, derecho) at each product. It must be O(k3)\bigO(k^3): fill a table with the best cost for each subchain, from shortest to longest, instead of testing all trees. The tests compare against brute force on chains of up to 7 factors and measure runtime for up to 16.
def coste_minimo(dims):
  # tu código aquí
  raise NotImplementedError

def parentizacion(dims):
  # tu código aquí
  raise NotImplementedError
Shift+Enter to run

The professional version

In practice the library performs the product. What matters is knowing which operation you request and how it corresponds to the mathematics. A @ B is np.matmul(A, B); A * B multiplies entry by entry; multi_dot chooses the order of the chain itself. In PyTorch the names are the same after replacing np with torch:

MathematicsCode
AB\mat{A}\mat{B}, Ax\mat{A}\vb{x}A @ B, A @ x
(aijbij)ij(a_{ij}b_{ij})_{ij}A * B
x⊤y\vb{x}\T\vb{y}x @ y
xy⊤\vb{x}\vb{y}\Tnp.outer(x, y)
∑kaikbkj\sum_k a_{ik}b_{kj}np.einsum("ik,kj->ij", A, B)
ABC\mat{A}\mat{B}\mat{C}np.linalg.multi_dot([A, B, C])
XW⊤+b\mat{X}\mat{W}\T + \vb{b}torch.nn.Linear(d_in, d_out)

Two details cause errors. First, for arrays with more than two axes, @ treats the last two as matrices and broadcasts the others: a batch of shape (B, T, d) times a matrix of shape (d, d_out) yields (B, T, d_out), the same layer applied to each token. Second, torch.nn.Linear stores weights with shape (d_out, d_in) and computes XW⊤+b\mat{X}\mat{W}\T + \vb{b}, following the data-in-rows convention above. The einsum notation, where the index formula is the program, is covered in Einstein notation and einsum.

[ ]Product views with einsumBrowser
A = rng.standard_normal((4, 3))
B = rng.standard_normal((3, 5))

print("einsum ik,kj->ij == A @ B:", np.allclose(np.einsum("ik,kj->ij", A, B), A @ B))

# Sin sumar sobre k: las tres matrices de rango uno a_k b_k^T, apiladas
capas = np.einsum("ik,kj->kij", A, B)
print("forma de la pila:", capas.shape, "  su suma es A @ B:", np.allclose(capas.sum(axis=0), A @ B))
print("rango de cada capa:", [int(np.linalg.matrix_rank(M)) for M in capas])

# Lotes: @ multiplica los dos últimos ejes y hace broadcasting en el resto
X = rng.standard_normal((8, 10, 3))     # 8 secuencias de 10 vectores de dimensión 3
print("(8, 10, 3) @ (3, 5) ->", (X @ B).shape)

If your local lab is running, this cell checks the nn.Linear convention, measures matrix multiplication throughput with a real BLAS on the CPU, which you can compare with the browser cell’s GFLOP/s, and repeats the parenthesization experiment on the GPU, where matrix products are proportionally cheaper and memory more expensive.

[ ]nn.Linear and parenthesization order on the GPULocal GPU
import time
import torch

torch.manual_seed(0)
capa = torch.nn.Linear(in_features=768, out_features=3072)
X = torch.randn(32, 768)                  # lote de 32 vectores fila
print("forma de los pesos:", tuple(capa.weight.shape), "(d_out, d_in)")
print("nn.Linear == X @ W.T + b:", torch.allclose(capa(X), X @ capa.weight.T + capa.bias, atol=1e-5))

import numpy as np
An, Bn = np.random.default_rng(0).standard_normal((2, 1024, 1024))
An @ Bn                                   # calentamiento
t0 = time.perf_counter()
for _ in range(5):
    An @ Bn
t_np = (time.perf_counter() - t0) / 5
print(f"NumPy con BLAS en la CPU, n = 1024: {2 * 1024**3 / t_np / 1e9:.0f} GFLOP/s")

dev = "cuda" if torch.cuda.is_available() else "cpu"
n = 4096 if dev == "cuda" else 1024
A = torch.randn(n, n, device=dev)
B = torch.randn(n, n, device=dev)
x = torch.randn(n, 1, device=dev)

def tiempo(f, rep=10):
    f()                                   # calentamiento
    if dev == "cuda":
        torch.cuda.synchronize()
    t0 = time.perf_counter()
    for _ in range(rep):
        f()
    if dev == "cuda":
        torch.cuda.synchronize()          # las llamadas a la GPU son asíncronas
    return (time.perf_counter() - t0) / rep

t1, t2 = tiempo(lambda: (A @ B) @ x), tiempo(lambda: A @ (B @ x))
print(f"{dev}, n = {n}: (AB)x {t1 * 1e3:.3f} ms   A(Bx) {t2 * 1e3:.3f} ms   cociente {t1 / t2:.0f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Common mistakes

Exercises

QuizWhich products are defined?
Let A∈R3×2\mat{A} \in \R^{3 \times 2}, B∈R2×4\mat{B} \in \R^{2 \times 4}, and x∈R4\vb{x} \in \R^4. Select the expressions that are defined and have the indicated shape.

More than one answer may be correct.

NumericInside or outside the plane?
For what value of tt is (1,t,3)(1, t, 3) in span⁡{(1,0,1), (0,1,1)}\spn\{(1, 0, 1),\ (0, 1, 1)\}?
NumericThe cost of parentheses
Let A∈R1000×10\mat{A} \in \R^{1000 \times 10}, B∈R10×1000\mat{B} \in \R^{10 \times 1000}, and C∈R1000×10\mat{C} \in \R^{1000 \times 10}. How many times as many scalar multiplications does (AB)C(\mat{A}\mat{B})\mat{C} require as A(BC)\mat{A}(\mat{B}\mat{C})?
NumericFlops of a dense layer
A dense layer in small GPT-2 projects 768-dimensional vectors to dimension 3072. How many flops does it cost to apply it to a batch of 32 tokens, using the 2mnp2mnp count and excluding bias?
NumericAngle between two vectors
Calculate the angle in degrees between u=(1,2,2)\vb{u} = (1, 2, 2) and v=(2,−1,2)\vb{v} = (2, -1, 2).
QuizThe 1D array trap
Given x = np.array([1.0, 2.0, 3.0]), what does x @ x.T return?
QuizA bottleneck
Let A∈R1000×8\mat{A} \in \R^{1000 \times 8} and B∈R8×1000\mat{B} \in \R^{8 \times 1000}. What is the maximum possible rank of AB∈R1000×1000\mat{A}\mat{B} \in \R^{1000 \times 1000}?
QuizWhich view should you use?
Assign each task the most direct view of a product. (a) Show that every column of AB\mat{A}\mat{B} lies in the column space of A\mat{A}. (b) See what happens to each example in a batch X\mat{X}, with one example per row, when computing XW⊤\mat{X}\mat{W}\T. (c) Write the batch gradient ∂L/∂W\partial L/\partial\mat{W} as a sum of contributions, one per example. (d) Read the attention score between tokens 3 and 7 in QK⊤\mat{Q}\mat{K}\T.
QuizThe order of backpropagation
You want the row vector g⊤J3J2J1\vb{g}\T\mat{J}_3\mat{J}_2\mat{J}_1, with g∈R1000\vb{g} \in \R^{1000} and Ji∈R1000×1000\mat{J}_i \in \R^{1000 \times 1000}. Which evaluation is cheapest using the 2mnp2mnp count?

Summary

Key idea
A matrix product is one sum, ∑kaikbkj\sum_k a_{ik}b_{kj}, and its four views, entries, columns, rows, and outer products, traverse it in four orders. Choosing the right view helps you understand a model, and choosing the right order for a chain makes it fast.
  • Ax\mat{A}\vb{x} is both a combination of the columns of A\mat{A} and a list of dot products with its rows. Ax=b\mat{A}\vb{x} = \vb{b} has a solution if and only if b\vb{b} lies in the span of the columns.
  • The span of vectors is the smallest subspace containing them. In R3\R^3 it is the origin, a line, a plane, or all of space. A new vector enlarges it only if it was not already in it.
  • x⊤y=∥x∥∥y∥cos⁡θ\vb{x}\T\vb{y} = \norm{\vb{x}}\norm{\vb{y}}\cos\theta is one vector’s length times the other’s shadow. Its sign indicates whether they point to the same side, and its normalized version is cosine similarity.
  • AB\mat{A}\mat{B} can be read by entries, columns, rows, or as a sum of rank-one outer products, foreshadowing the SVD, LoRA, and linear-layer gradients. Matrix multiplication is associative and noncommutative, and (AB)⊤=B⊤A⊤(\mat{A}\mat{B})\T = \mat{B}\T\mat{A}\T.
  • Multiplication costs 2mnp2mnp flops. Since a product is associative, you can choose the parentheses in a chain, and the right choice saves orders of magnitude in LoRA, linear attention, and backpropagation.