Matrix Multiplication
The product of two matrices combines rows of with columns of through dot products. It is the most important operation in linear algebra and, measured in machine time, one of the most important operations in all of computing: it is what GPUs are built to do.
The definition
If is and is , the product is the matrix whose entry is the dot product of row of with column of :
The inner sizes must agree (the 's), and the outer sizes give the shape of the result:
A worked times product:
In NumPy the operator is @ (* is entry-wise multiplication, a different thing). SymPy uses * for the matrix product.
Three ways to see a product
- Entries: each entry is a row-times-column dot product (the definition).
- Columns: column of is times column of . In particular, for a column vector , is a linear combination of the columns of with weights . That is why a system of equations can be written as (Linear Combinations).
- Rows: row of is row of times .
from sympy import Matrix
A = Matrix([[1, 2, 0], [-1, 3, 4]])
B = Matrix([[3, 1], [0, -2], [5, 1]])
print("AB =", (A * B).tolist())
print("BA is 3x3:", (B * A).shape)
x = Matrix([2, -1, 3])
combo = 2 * A.col(0) - 1 * A.col(1) + 3 * A.col(2)
print("Ax =", list(A * x), " = 2*col1 - col2 + 3*col3:", list(combo))
try:
A * A
except Exception as e:
print("A*A:", type(e).__name__)AB = [[3, -3], [17, -3]]
BA is 3x3: (3, 3)
Ax = [0, 7] = 2*col1 - col2 + 3*col3: [0, 7]
A*A: ShapeError
The laws, and the ones that fail
| Law | Holds? |
|---|---|
| Associative: | yes |
| Distributive: and | yes |
| Scalars: | yes |
| Identity: for of size | yes |
| Commutative: | no, not even for square matrices |
| No zero divisors: | no |
| Cancellation: | no (unless is invertible) |
from sympy import Matrix, eye
A = Matrix([[1, 1], [0, 0]])
B = Matrix([[0, 1], [0, 1]])
N = Matrix([[1, -1], [-1, 1]])
print("AB =", (A * B).tolist(), " BA =", (B * A).tolist())
print("A*N =", (A * N).tolist(), "(zero, but neither factor is zero)")
C = Matrix([[2, 5], [7, 3]])
print("(AB)C == A(BC):", (A * B) * C == A * (B * C))
print("I*C == C*I == C:", eye(2) * C == C * eye(2) == C)AB = [[0, 2], [0, 0]] BA = [[0, 0], [0, 0]]
A*N = [[0, 0], [0, 0]] (zero, but neither factor is zero)
(AB)C == A(BC): True
I*C == C*I == C: True
Order matters because means "apply first, then " when the matrices act on vectors (). In graphics, "rotate then translate" and "translate then rotate" put an object in different places (Translate, Rotate, Scale).
Cost: why GPUs exist
Computing one entry of an product takes multiplications and about additions, and there are entries, so the product costs about floating-point operations. For two matrices that is : doubling makes the work 8 times larger.
| flops | |
|---|---|
| 100 | 2 million |
| 1 000 | 2 billion |
| 10 000 | 2 trillion |
The triple loop is simple, but every entry is independent of every other entry. That makes the work massively parallel, which is exactly what GPUs (thousands of simple cores) and their tensor cores (hardware that multiplies small matrix tiles in one instruction) are designed for. Libraries such as BLAS, cuBLAS and the kernels inside PyTorch also reorder the loops into cache-sized blocks, so the same operations run many times faster than a naive loop. (Strassen-type algorithms reduce the exponent below 3, but the classic algorithm with good blocking is what is used in practice.)
import time
import numpy as np
def matmul_loops(A, B):
m, n = len(A), len(A[0]); p = len(B[0])
C = [[0.0] * p for _ in range(m)]
for i in range(m):
for k in range(n):
a = A[i][k]
row_b, row_c = B[k], C[i]
for j in range(p):
row_c[j] += a * row_b[j]
return C
rng = np.random.default_rng(0)
n = 60
A, B = rng.random((n, n)), rng.random((n, n))
t0 = time.perf_counter(); C1 = matmul_loops(A.tolist(), B.tolist()); t1 = time.perf_counter()
C2 = A @ B; t2 = time.perf_counter()
print("same result:", np.allclose(C1, C2))
print("flops:", 2 * n**3)
print("NumPy faster than pure Python:", (t2 - t1) < (t1 - t0))same result: True
flops: 432000
NumPy faster than pure Python: True
In software: batching in neural nets
A dense (fully connected) layer with weights () and bias maps one input row to . Feeding a batch of 64 inputs one at a time would mean 64 small vector–matrix products. Stacking them as the rows of a matrix turns the whole batch into one matrix product, , which a GPU executes far more efficiently:
import numpy as np
rng = np.random.default_rng(42)
X = rng.normal(size=(4, 3)) # batch of 4 inputs, 3 features each
W = rng.normal(size=(3, 2)) # layer: 3 inputs -> 2 outputs
b = np.array([0.5, -1.0])
Y_batch = X @ W + b # one matrix product for the whole batch
Y_loop = np.array([x @ W + b for x in X])
print("output shape:", Y_batch.shape)
print("batched == one by one:", np.allclose(Y_batch, Y_loop))
print("first output row:", np.round(Y_batch[0], 4).tolist())output shape: (4, 2)
batched == one by one: True
first output row: [0.3106, -0.4825]
Training a large language model is, to a first approximation, trillions of these products; attention itself is two matrix products per head (Attention as Matrix Products).
Exercises
Exercise 1: Shapes
is , is , is . Which of , , , , are defined, and what are their sizes?
Answer
: ; : undefined; : ; : ; : .
Solution
Exercise 2: Multiply by hand
Compute and for and .
Answer
; , so .
Solution
from sympy import Matrix
P = Matrix([[2, -1], [0, 3]]); Q = Matrix([[1, 4], [-2, 1]])
print((P*Q).tolist(), (Q*P).tolist())[[4, 7], [-6, 3]] [[2, 11], [-4, 5]]
Exercise 3: Column combination
Without multiplying entry by entry, write as a combination of the columns of and evaluate it.
Answer
.
Solution
Exercise 4: Count the flops
A transformer layer multiplies a activation matrix by a weight matrix. Using , how many floating-point operations is that? At 100 teraflop/s, how long does it take?
Answer
About flops, roughly 0.69 ms.
Solution
m, n, p = 2048, 4096, 4096
flops = 2 * m * n * p
print(flops, f"{flops:.3e}")
print("ms at 100 TFLOP/s:", round(flops / 100e12 * 1000, 3))68719476736 6.872e+10
ms at 100 TFLOP/s: 0.687
Exercise 5: Write the loop
Write matmul(A, B) for lists of lists using the definition (three nested loops) and test it on the and example of this lesson.
Answer
It returns [[3, -3], [17, -3]].
Solution
def matmul(A, B):
m, n, p = len(A), len(B), len(B[0])
assert len(A[0]) == n, "inner sizes must match"
return [[sum(A[i][k] * B[k][j] for k in range(n)) for j in range(p)]
for i in range(m)]
print(matmul([[1, 2, 0], [-1, 3, 4]], [[3, 1], [0, -2], [5, 1]]))[[3, -3], [17, -3]]
Test yourself
is and is . What is the size of ?
- Undefined
Which statement about square matrices is true in general?
- implies or
- implies
Roughly how does the cost of multiplying two matrices with the standard algorithm grow?
- Like
- Like
- Like
- Like