Matrix-Chain Multiplication: The Problem
Matrix multiplication is associative: . The two sides give the same matrix, but they do not cost the same. When a program multiplies a chain of matrices, as graphics pipelines, neural-network layers and statistics code all do, the order of the multiplications can change the work by orders of magnitude. Choosing the best order is the matrix-chain multiplication problem. It is a dynamic program over intervals of the chain, a new shape of subproblem after the one-dimensional rod-cutting table. This lesson sets up the problem and shows why trying every order is hopeless; the next lesson fills the table.
What one multiplication costs
Multiplying a matrix by a matrix with the standard algorithm computes entries, each a sum of products: scalar multiplications in all. The matrices are compatible only if the inner dimensions agree, and the result is .
def matmul(A, B, counter):
p, q, r = len(A), len(B), len(B[0])
assert len(A[0]) == q, "incompatible dimensions"
C = [[0] * r for _ in range(p)]
for i in range(p):
for j in range(r):
for k in range(q):
C[i][j] += A[i][k] * B[k][j]
counter[0] += 1
return C
def matrix(rows, cols, seed):
return [[(seed * (i + 1) + 3 * j) % 7 - 3 for j in range(cols)] for i in range(rows)]
A, B, C = matrix(4, 60, 1), matrix(60, 2, 2), matrix(2, 50, 3)
left = [0]
ab_c = matmul(matmul(A, B, left), C, left)
right = [0]
a_bc = matmul(A, matmul(B, C, right), right)
print("(AB)C:", left[0], "scalar multiplications")
print("A(BC):", right[0], "scalar multiplications")
print("same result:", ab_c == a_bc)(AB)C: 880 scalar multiplications
A(BC): 18000 scalar multiplications
same result: True
Here is , is and is . Computing first costs and gives a small matrix; multiplying it by costs . The other order first builds the matrix for , and then pays to multiply by it. Same answer, 880 against 18,000 multiplications: a factor of more than 20.
The problem statement
You are given a chain where has dimensions , so the whole chain is described by the numbers . Find a full parenthesization of the product , that is, an order of pairwise multiplications, that minimises the total number of scalar multiplications. Only the order is chosen; the matrices themselves are never looked at, and the algorithm only needs the dimensions.
The running example for this section is a chain of five matrices with
| matrix | |||||
|---|---|---|---|---|---|
| dimensions |
so .
How many parenthesizations?
Let be the number of full parenthesizations of a chain of matrices. A single matrix has one. For the last multiplication splits the chain into and for some , and each side is parenthesized independently:
These are the Catalan numbers, shifted by one: , where . They grow like , exponentially. The program enumerates every parenthesization of the running example with its cost.
from math import comb
p = [12, 4, 10, 3, 8, 5]
def all_orders(i, j):
"""every parenthesization of A_i..A_j (1-based) with its cost"""
if i == j:
return [(f"A{i}", 0)]
out = []
for k in range(i, j):
for left, cl in all_orders(i, k):
for right, cr in all_orders(k + 1, j):
out.append((f"({left}{right})", cl + cr + p[i - 1] * p[k] * p[j]))
return out
orders = sorted(all_orders(1, 5), key=lambda t: t[1])
print(len(orders), "parenthesizations of 5 matrices")
for text, cost in orders[:3] + orders[-2:]:
print(f" {text:22} {cost:5}")
print("P(n) for n = 1..12:", [comb(2 * (n - 1), n - 1) // n for n in range(1, 13)])14 parenthesizations of 5 matrices
(A1((A2A3)(A4A5))) 540
((A1(A2A3))(A4A5)) 564
(A1(((A2A3)A4)A5)) 616
((A1A2)((A3A4)A5)) 1720
(((A1A2)(A3A4))A5) 2160
P(n) for n = 1..12: [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
The best order costs 540 and the worst 2160, four times as much. With 12 matrices there are already 58,786 orders, and is about . A cost function that takes per order makes brute force cost .
Optimal substructure
Write for the product , a matrix. Any parenthesization of with ends with one multiplication for some split with . Its cost is
Claim: in an optimal parenthesization of that splits at , the parenthesization of the prefix is optimal for that prefix, and the same for the suffix. Proof by cut and paste: the three terms are independent (the last term depends only on , , ), so if a cheaper way to compute existed, pasting it in would lower the total, a contradiction.
So with the minimum cost for ,
The subproblems are the contiguous subchains : there are of them, polynomially many, even though the parenthesizations are exponentially many. That gap is the whole opportunity.
Naive recursion is still exponential
The recurrence evaluated by plain recursion repeats subproblems, just as rod cutting did. Let be the number of calls for a chain of length . The call for makes two recursive calls for every split, so , which solves to (check: , and ).
calls = 0
def naive_chain(p, i, j):
global calls
calls += 1
if i == j:
return 0
return min(naive_chain(p, i, k) + naive_chain(p, k + 1, j) + p[i - 1] * p[k] * p[j]
for k in range(i, j))
p = [12, 4, 10, 3, 8, 5]
print("best cost:", naive_chain(p, 1, 5), " calls:", calls)
for n in range(2, 12):
q = [(7 * t) % 11 + 2 for t in range(n + 1)]
calls = 0
naive_chain(q, 1, n)
print(f"n = {n:2}: calls {calls:6}, 3^(n-1) = {3 ** (n - 1):6}, distinct subproblems {n * (n + 1) // 2}")best cost: 540 calls: 81
n = 2: calls 3, 3^(n-1) = 3, distinct subproblems 3
n = 3: calls 9, 3^(n-1) = 9, distinct subproblems 6
n = 4: calls 27, 3^(n-1) = 27, distinct subproblems 10
n = 5: calls 81, 3^(n-1) = 81, distinct subproblems 15
n = 6: calls 243, 3^(n-1) = 243, distinct subproblems 21
n = 7: calls 729, 3^(n-1) = 729, distinct subproblems 28
n = 8: calls 2187, 3^(n-1) = 2187, distinct subproblems 36
n = 9: calls 6561, 3^(n-1) = 6561, distinct subproblems 45
n = 10: calls 19683, 3^(n-1) = 19683, distinct subproblems 55
n = 11: calls 59049, 3^(n-1) = 59049, distinct subproblems 66
The call counts are exactly , while there are only distinct subchains. Again: optimal substructure plus overlapping subproblems, the signal for dynamic programming.
In C++
The same naive recursion with a counter, on the running example and a chain of 15 matrices: calls for 120 distinct subproblems.
#include <algorithm>
#include <climits>
#include <cstdio>
#include <vector>
long long calls = 0;
long long naive_chain(const std::vector<int>& p, int i, int j) {
++calls;
if (i == j) return 0;
long long best = LLONG_MAX;
for (int k = i; k < j; ++k)
best = std::min(best, naive_chain(p, i, k) + naive_chain(p, k + 1, j) +
1LL * p[i - 1] * p[k] * p[j]);
return best;
}
int main() {
std::vector<int> p = {12, 4, 10, 3, 8, 5};
long long best5 = naive_chain(p, 1, 5);
std::printf("n = 5: best %lld, calls %lld\n", best5, calls);
std::vector<int> q;
for (int t = 0; t <= 15; ++t) q.push_back((7 * t) % 11 + 2);
calls = 0;
long long best = naive_chain(q, 1, 15);
std::printf("n = 15: best %lld, calls %lld\n", best, calls);
}n = 5: best 540, calls 81
n = 15: best 1364, calls 4782969
Test yourself
How many scalar multiplications does multiplying a matrix by an matrix take?
How many full parenthesizations does a chain of 4 matrices have?
- 3
- 4
- 5
- 6
Which are the subproblems of the matrix-chain DP?
- All subsets of the matrices
- All contiguous subchains
- All prefixes
- All pairs of adjacent matrices
If the best way to compute splits at , what does optimal substructure say?
- and are each computed optimally
- is computed optimally but may not be
- is also the best split of
- The cost is