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 , a matrix-vector product. If you stack the vectors of a batch as rows of a matrix , the linear part of the same layer is , a matrix product. Attention computes , 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 parameters, excluding embeddings, costs on the order of 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:
- Read in two ways, as a combination of columns and as dot products with rows, and switch between them according to the question.
- Read in four ways, by entries, columns, rows, and as a sum of outer products, and choose the view that illuminates each problem.
- 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 .
- An arrow. A displacement that can be drawn from any origin. The arrow from point to point is .
The arrow interpretation gives the geometry of the operations. Addition chains arrows head to tail, the parallelogram rule. Multiplication by stretches the arrow by and reverses it if .
Intuition from and applies in 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.
is the pantry and is the recipe specifying how much of each ingredient to use. This interpretation immediately answers which outputs can produce: exactly the combinations of its columns.
Explore three things in the interactive:
- With nonparallel columns, the grid cells, which are parallelograms, tile the plane. Every lies in a cell and is reached with unique real weights.
- If is a multiple of , all combinations lie on a line. For outside it, has no solution; for a point on the line, it has infinitely many.
- Near alignment the parallelogram becomes needle-like, and reaching a distant requires enormous weights. With and , reaching requires . 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 ; the sum of two combinations is another combination, ; and . It is the smallest such subspace: if a subspace contains each , closure under scalar multiplication means it contains each , and closure under addition means it contains .
∎Using the definition of , the question of whether a system has a solution becomes a geometric question:
This follows directly from the definition. The set is the column space of , 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 it can only be the origin, a line, or the whole plane; in , the origin, a line, a plane, or the whole space. In :
- 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 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.
The dot product
The norm applies the Pythagorean theorem once per coordinate. The dot product is symmetric (), linear in each argument (), and positive definite ( if ). 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.
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 , , and form a triangle with angle between the first two sides. By the cosine rule, . By linearity and symmetry of the dot product, . Equating the two expressions gives . If and are parallel, the triangle degenerates, but then and both sides equal , with depending on the sign of , so the identity still holds.
∎In with there is no prior notion of angle, so the formula is used as the definition: . This is valid because the Cauchy-Schwarz inequality, , ensures that this quotient lies in .
The most useful interpretation is the shadow. The scalar projection of onto the direction of is the signed length of its shadow on the line of , . Therefore
and the shadow as a vector is , the orthogonal projection of onto the line of .
For nonzero , the sign of the dot product classifies the relationship between their directions:
- : acute or zero angle, so they point toward the same side.
- : perpendicular. This is the algebraic definition of orthogonality, which works in any dimension.
- : obtuse or straight angle, so they point in opposite directions.
Two applications appear constantly. Cosine similarity, , 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 . The transformer paper itself explains this factor (Vaswani et al., 2017): if the components of and are independent with mean 0 and variance 1, then is a sum of independent products with variance 1. Its variance is , and dividing by 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 by :
From here on we use . We write the rows of as , so is row written as a column and :
The second interpretation: dot products with the rows
Proof
Component of is , the dot product of with .
∎These are the same products summed in a different order: by rows, the outer loop runs over ; by columns, it runs over . They answer different questions:
- Columns: what can 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 scores how much resembles the template . The preactivation of an artificial neuron is exactly that, , and the linear part of a dense layer with neurons consists of dot products at once: .
Computing costs dot products of length : multiplications and additions, roughly floating-point operations (flops).
One linear system, two pictures
In a system the two interpretations produce two geometric pictures of the same problem. By rows, each equation is a line in the plane, a plane in , or a hyperplane in , perpendicular to the row vector and at signed distance from the origin. The solution is their intersection. By columns, the solution consists of the weights combining the columns to reach .
It is no coincidence that both pictures degenerate at once. In a matrix, the rows are proportional if and only if the columns are proportional; both are equivalent to . 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 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 . First, is linear: , and similarly . Now take with columns , and apply first and then . Try to predict each step before revealing it:
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 and is the matrix , with dimensions and entries . Column is and row is . All columns are multiples of the same vector, so if and are nonzero, it is a rank-one matrix. Compare this with the dot product: is a number and is a matrix, using the same vectors in a different order.
Before stating the four interpretations, see them in action. Computing the formula for every entry involves three indices , , and , and each interpretation traverses them in a different order.
Proof
Check that entry is in each interpretation. In (1), . The construction in (2) is from the previous derivation, reading by columns. In (3), component of is . Case (4) is the guided exercise that follows.
∎Step 1 of 4. What is sufficient to check?
The four views perform exactly the same multiplications . Only the order of the three nested loops changes, as you saw in the interactive. With the loop innermost, each entry is completed at once: the entrywise view. With in the middle, each iteration of the outer loop completes a whole column if the outer index is , or a whole row if it is . With 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 , all four views sum each entry in the same order and produce identical results. An optimized library can divide the sum over into blocks and accumulate it in pieces, changing the floating-point result because addition is not associative: in double precision, (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.
matmul_outer(A, B) for 2D arrays, returning as a sum of outer products . 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 NotImplementedErrorWhich view should you use?
| View | Question answered and where it appears |
|---|---|
| Entries | What is a particular entry? This is hand calculation and the attention score between token and token . |
| Columns | What does generate? Its columns lie in the span of the columns of . This applies to many vectors at once, arranged as columns of . |
| Rows | What happens to each row of data? The rows of are combinations of rows of . This is a batch of examples in rows passing through a layer: . |
| Outer products | Which 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 lie in the span of those of ; by the rowwise view, its rows lie in the span of those of . Hence . The outer-product view also gives . An -dimensional bottleneck limits everything that passes through it.
- Gradient of a linear layer. If and , then , or : 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 . LoRA (Hu et al., 2021) adapts a large model by freezing its weights and adding a product , where and . By the fourth view, this is only 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.
Algebraic properties
Proof
For associativity, entry on both sides is the same finite double sum, , grouped in two ways. Alternatively, both sides represent the function . The other rules follow by checking each entry in the same way.
∎It is just as important to understand what does not hold:
- Noncommutativity. and may not both exist, or they may have different shapes. If is and is , one is and the other is . Even square products generally differ: with and , we obtain and . Reading by columns, maps to and sends to zero, while does the opposite. Applying then returns to itself, while the other order returns .
- Zero divisors. For the same , even though . Therefore cancellation is not generally valid: does not imply .
Transpose rules
The first three follow immediately entry by entry. The fourth reverses the order, as the shapes require: if is and is , then is ; is , whereas is and is undefined unless . Think of socks and shoes: undo them in reverse order. By induction, .
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 and ,
Backpropagation uses this identity. If a layer computes and receives from above, the change in the loss is . Thus : the gradient travels backward through the transpose. This is the first example of a vector-Jacobian product.
A matrix is symmetric if . An important example is , which is always symmetric: . Its entries are dot products between columns, . 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:
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 entries, each a dot product of length : multiplications and additions.
∎We use the count , one multiplication and one addition per term, following the usual convention. The exact count changes constants, not orders of magnitude.
Is inevitable? No. Strassen (1969) multiplied block matrices using 7 block products instead of 8. Applied recursively, this gives Strassen’s algorithm, with cost . Since the late 1980s it has been known that the optimal exponent is less than . 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 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 matrices performs flops on numbers, reading two matrices and writing one: about operations per number moved from memory, increasing with . A matrix-vector product performs flops on about numbers: two operations per number regardless of . The ratio of operations to data moved is the arithmetic intensity. This is why can saturate a GPU’s compute capacity while 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 gives the same result. It does not guarantee equal cost.
More generally, if has dimensions , each parenthesization is a binary tree whose cost is the sum of the costs of its products. Multiplying block () by block () costs . With factors there are trees, where is the Catalan number: 1, 2, 5, 14, 42… for . They grow exponentially, on the order of , so we do not test them all. Matrix-chain ordering is a classic dynamic programming problem, solved in and implemented below.
Three places where this decision changes cost by orders of magnitude:
- LoRA. The adapter , with , is applied as . For one vector, materializing and applying it costs ; the right-hand order costs . With and , the ratio is . The accounting depends on what is reused. During inference, LoRA can add to once (adapter merging). The flops are amortized over all tokens and the product by is paid anyway, so for batches of more than tokens, 2048 in this example, merging is cheaper than applying the adapter separately. During training we retain : is frozen and only the gradients of and are needed.
- Linear attention. In , with , softmax prevents regrouping and requires computing all scores at cost , the transformer’s quadratic barrier. A naive implementation also stores them, using 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, , and associativity does the rest: costs , linear in sequence length. Row normalization replacing softmax is just as cheap, computed as . This is linear attention.
- Backpropagation. The gradient of a scalar loss is a product of Jacobians, , 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.
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, , 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 . 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 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.
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 , although the measured gain is less than 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 bytes apart, the stride of the first axis. The following cell sums 500 rows and 500 columns of a matrix one at a time: the same flops and numbers, traversed in two ways.
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 grows as , while that of grows as . The cost of grows as , while grows as .
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 , as predicted by the flop count. In the second the count predicts a ratio of , while measurement depends heavily on the library. With BLAS, as in the local lab, the ratio grows more slowly than 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 because matrix multiplication without cache blocking loses efficiency as 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 . 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.
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 trees, so brute force quickly becomes impractical. The way out is optimal substructure. The last product splits the chain into and , and each half must itself be computed optimally. Since there are only distinct subchains, it is enough to solve each one once and store the result in a table.
coste_minimo(dims) and parentizacion(dims). Both receive dims = [p0, ..., pk], so factor , indexed from 1, has shape . coste_minimo returns the minimum flops for the chain, counting per product . 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 : 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 NotImplementedErrorThe 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:
| Mathematics | Code |
|---|---|
| , | A @ B, A @ x |
A * B | |
x @ y | |
np.outer(x, y) | |
np.einsum("ik,kj->ij", A, B) | |
np.linalg.multi_dot([A, B, C]) | |
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 , following the data-in-rows convention above. The einsum notation, where the index formula is the program, is covered in Einstein notation and einsum.
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.
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}")npm run lab and open the connection link.Common mistakes
Exercises
More than one answer may be correct.
x = np.array([1.0, 2.0, 3.0]), what does x @ x.T return?Summary
- is both a combination of the columns of and a list of dot products with its rows. has a solution if and only if lies in the span of the columns.
- The span of vectors is the smallest subspace containing them. In 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.
- 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.
- 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 .
- Multiplication costs 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.