TExcelTAD
Home › Linear Algebra & Matrix Theory › Matrix Multiplication

Matrix Multiplication

The product ABAB of two matrices combines rows of AA with columns of BB 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 AA is m×nm \times n and BB is n×pn \times p, the product ABAB is the m×pm \times p matrix whose (i,j)(i, j) entry is the dot product of row ii of AA with column jj of BB:

(AB)ij=ai1b1j+ai2b2j+⋯+ainbnj=∑kaikbkj(AB)_{ij} = a_{i1}b_{1j} + a_{i2}b_{2j} + \cdots + a_{in}b_{nj} = \sum_k a_{ik}b_{kj}

The inner sizes must agree (the nn's), and the outer sizes give the shape of the result:

(m×n)⋅(n×p)=(m×p)(2×3)⋅(3×2)=2×2,(3×2)⋅(2×3)=3×3,(2×3)⋅(2×3) undefined(m \times n) \cdot (n \times p) = (m \times p) \qquad (2 \times 3) \cdot (3 \times 2) = 2 \times 2, \quad (3 \times 2) \cdot (2 \times 3) = 3 \times 3, \quad (2 \times 3) \cdot (2 \times 3) \ \text{undefined}

A worked 2×32 \times 3 times 3×23 \times 2 product:

[120−134]⋅[310−251]=[1⋅3+2⋅0+0⋅51⋅1+2(−2)+0⋅1−1⋅3+3⋅0+4⋅5−1⋅1+3(−2)+4⋅1]=[3−317−3]\begin{bmatrix} 1 & 2 & 0 \\ -1 & 3 & 4 \end{bmatrix} \cdot \begin{bmatrix} 3 & 1 \\ 0 & -2 \\ 5 & 1 \end{bmatrix} = \begin{bmatrix} 1 \cdot 3 + 2 \cdot 0 + 0 \cdot 5 & 1 \cdot 1 + 2(-2) + 0 \cdot 1 \\ -1 \cdot 3 + 3 \cdot 0 + 4 \cdot 5 & -1 \cdot 1 + 3(-2) + 4 \cdot 1 \end{bmatrix} = \begin{bmatrix} 3 & -3 \\ 17 & -3 \end{bmatrix}

In NumPy the operator is @ (* is entry-wise multiplication, a different thing). SymPy uses * for the matrix product.

Three ways to see a product

  1. Entries: each entry is a row-times-column dot product (the definition).
  2. Columns: column jj of ABAB is AA times column jj of BB. In particular, for a column vector x\mathbf{x}, AxA\mathbf{x} is a linear combination of the columns of AA with weights x1,…,xnx_1, \ldots, x_n. That is why a system of equations can be written as Ax=bA\mathbf{x} = \mathbf{b} (Linear Combinations).
  3. Rows: row ii of ABAB is row ii of AA times BB.
python · try it yourself
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: (AB)C=A(BC)(AB)C = A(BC) yes
Distributive: A(B+C)=AB+ACA(B + C) = AB + AC and (A+B)C=AC+BC(A + B)C = AC + BC yes
Scalars: c(AB)=(cA)B=A(cB)c(AB) = (cA)B = A(cB) yes
Identity: ImA=A=AInI_mA = A = AI_n for AA of size m×nm \times n yes
Commutative: AB=BAAB = BA no, not even for square matrices
No zero divisors: AB=0⇒A=0 or B=0AB = 0 \Rightarrow A = 0 \text{ or } B = 0 no
Cancellation: AB=AC⇒B=CAB = AC \Rightarrow B = C no (unless AA is invertible)
python · try it yourself
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 ABAB means "apply BB first, then AA" when the matrices act on vectors (ABx=A(Bx)AB\mathbf{x} = A(B\mathbf{x})). 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 (m×n)(n×p)(m \times n)(n \times p) product takes nn multiplications and about nn additions, and there are m⋅pm \cdot p entries, so the product costs about 2⋅m⋅n⋅p2 \cdot m \cdot n \cdot p floating-point operations. For two n×nn \times n matrices that is 2n32n^3: doubling nn makes the work 8 times larger.

nn 2n32n^3 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 2n32n^3 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.)

python · try it yourself
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 WW (inputs×outputs\text{inputs} \times \text{outputs}) and bias b\mathbf{b} maps one input row x\mathbf{x} to xW+b\mathbf{x}W + \mathbf{b}. Feeding a batch of 64 inputs one at a time would mean 64 small vector–matrix products. Stacking them as the rows of a 64×inputs64 \times \text{inputs} matrix XX turns the whole batch into one matrix product, XW+bXW + \mathbf{b}, which a GPU executes far more efficiently:

python · try it yourself
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

AA is 3×43 \times 4, BB is 4×24 \times 2, CC is 2×32 \times 3. Which of ABAB, BABA, BCBC, CACA, ABCABC are defined, and what are their sizes?

Answer

ABAB: 3×23 \times 2; BABA: undefined; BCBC: 4×34 \times 3; CACA: 2×42 \times 4; ABCABC: 3×33 \times 3.

Solution
AB:(3×4)(4×2) inner 4=4→3×2BA:(4×2)(3×4) inner 2≠3→undefinedBC:(4×2)(2×3)→4×3CA:(2×3)(3×4)→2×4ABC=(AB)C:(3×2)(2×3)→3×3\begin{aligned} &AB\text{:} && (3 \times 4)(4 \times 2) \ \text{inner } 4 = 4 \to 3 \times 2 \\ &BA\text{:} && (4 \times 2)(3 \times 4) \ \text{inner } 2 \ne 3 \to \text{undefined} \\ &BC\text{:} && (4 \times 2)(2 \times 3) \to 4 \times 3 \\ &CA\text{:} && (2 \times 3)(3 \times 4) \to 2 \times 4 \\ &ABC = (AB)C\text{:} && (3 \times 2)(2 \times 3) \to 3 \times 3 \end{aligned}

Exercise 2: Multiply by hand

Compute PQPQ and QPQP for P=[2−103]P = \begin{bmatrix} 2 & -1 \\ 0 & 3 \end{bmatrix} and Q=[14−21]Q = \begin{bmatrix} 1 & 4 \\ -2 & 1 \end{bmatrix}.

Answer

PQ=[47−63]PQ = \begin{bmatrix} 4 & 7 \\ -6 & 3 \end{bmatrix}; QP=[211−45]QP = \begin{bmatrix} 2 & 11 \\ -4 & 5 \end{bmatrix}, so PQ≠QPPQ \ne QP.

Solution
PQ:[2⋅1+(−1)(−2), 2⋅4+(−1)⋅1]=[4,7][0⋅1+3⋅(−2), 0⋅4+3⋅1]=[−6,3]QP:[1⋅2+4⋅0, 1⋅(−1)+4⋅3]=[2,11][−2⋅2+1⋅0, −2⋅(−1)+1⋅3]=[−4,5]\begin{aligned} PQ\text{:} \quad & [2 \cdot 1 + (-1)(-2),\ 2 \cdot 4 + (-1) \cdot 1] = [4, 7] \\ & [0 \cdot 1 + 3 \cdot (-2),\ 0 \cdot 4 + 3 \cdot 1] = [-6, 3] \\ QP\text{:} \quad & [1 \cdot 2 + 4 \cdot 0,\ 1 \cdot (-1) + 4 \cdot 3] = [2, 11] \\ & [-2 \cdot 2 + 1 \cdot 0,\ -2 \cdot (-1) + 1 \cdot 3] = [-4, 5] \end{aligned}
python · try it yourself
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 A⋅[30−2]TA \cdot \begin{bmatrix} 3 & 0 & -2 \end{bmatrix}^T as a combination of the columns of A=[14205−1]A = \begin{bmatrix} 1 & 4 & 2 \\ 0 & 5 & -1 \end{bmatrix} and evaluate it.

Answer

3⋅col1−2⋅col3=[−1,2]3 \cdot \text{col}_1 - 2 \cdot \text{col}_3 = [-1, 2].

Solution
Ax=3⋅[1,0]+0⋅[4,5]−2⋅[2,−1]=[3,0]+[−4,2]=[−1,2]A\mathbf{x} = 3 \cdot [1, 0] + 0 \cdot [4, 5] - 2 \cdot [2, -1] = [3, 0] + [-4, 2] = [-1, 2]

Exercise 4: Count the flops

A transformer layer multiplies a 2048×40962048 \times 4096 activation matrix by a 4096×40964096 \times 4096 weight matrix. Using 2mnp2mnp, how many floating-point operations is that? At 100 teraflop/s, how long does it take?

Answer

About 6.87×10106.87 \times 10^{10} flops, roughly 0.69 ms.

Solution
python · try it yourself
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 2×32 \times 3 and 3×23 \times 2 example of this lesson.

Answer

It returns [[3, -3], [17, -3]].

Solution
python · try it yourself
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

AA is 5×25 \times 2 and BB is 2×72 \times 7. What is the size of ABAB?

  1. 2×22 \times 2
  2. Undefined
  3. 7×57 \times 5
  4. 5×75 \times 7

Which statement about square matrices is true in general?

  1. AB=BAAB = BA
  2. AB=0AB = 0 implies A=0A = 0 or B=0B = 0
  3. (AB)C=A(BC)(AB)C = A(BC)
  4. AB=ACAB = AC implies B=CB = C

Roughly how does the cost of multiplying two n×nn \times n matrices with the standard algorithm grow?

  1. Like nn
  2. Like n3n^3
  3. Like n2n^2
  4. Like 2n2^n