TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › Matrix-Chain Multiplication: The Problem

Matrix-Chain Multiplication: The Problem

Matrix multiplication is associative: (AB)C=A(BC)(AB)C = A(BC). 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 p×qp \times q matrix by a q×rq \times r matrix with the standard algorithm computes prpr entries, each a sum of qq products: pqrpqr scalar multiplications in all. The matrices are compatible only if the inner dimensions agree, and the result is p×rp \times r.

python · try it yourself
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 AA is 4×604 \times 60, BB is 60×260 \times 2 and CC is 2×502 \times 50. Computing ABAB first costs 4⋅60⋅2=4804 \cdot 60 \cdot 2 = 480 and gives a small 4×24 \times 2 matrix; multiplying it by CC costs 4⋅2⋅50=4004 \cdot 2 \cdot 50 = 400. The other order first builds the 60×5060 \times 50 matrix BCBC for 60⋅2⋅50=600060 \cdot 2 \cdot 50 = 6000, and then pays 4⋅60⋅50=12,0004 \cdot 60 \cdot 50 = 12{,}000 to multiply AA by it. Same answer, 880 against 18,000 multiplications: a factor of more than 20.

The problem statement

You are given a chain A1,A2,…,AnA_1, A_2, \ldots, A_n where AiA_i has dimensions pi−1×pip_{i-1} \times p_i, so the whole chain is described by the n+1n + 1 numbers p0,p1,…,pnp_0, p_1, \ldots, p_n. Find a full parenthesization of the product A1A2⋯AnA_1 A_2 \cdots A_n, 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 A1A_1 A2A_2 A3A_3 A4A_4 A5A_5
dimensions 12×412 \times 4 4×104 \times 10 10×310 \times 3 3×83 \times 8 8×58 \times 5

so p=(12,4,10,3,8,5)p = (12, 4, 10, 3, 8, 5).

How many parenthesizations?

Let P(n)P(n) be the number of full parenthesizations of a chain of nn matrices. A single matrix has one. For n≥2n \ge 2 the last multiplication splits the chain into A1⋯AkA_1 \cdots A_k and Ak+1⋯AnA_{k+1} \cdots A_n for some 1≤k<n1 \le k < n, and each side is parenthesized independently:

P(1)=1,P(n)=∑k=1n−1P(k) P(n−k)for n≥2.P(1) = 1, \qquad P(n) = \sum_{k=1}^{n-1} P(k)\, P(n - k) \quad \text{for } n \ge 2.

These are the Catalan numbers, shifted by one: P(n)=Cn−1P(n) = C_{n-1}, where Cm=1m+1(2mm)C_m = \frac{1}{m+1}\binom{2m}{m}. They grow like 4mm3/2π\frac{4^m}{m^{3/2}\sqrt{\pi}}, exponentially. The program enumerates every parenthesization of the running example with its cost.

python · try it yourself
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 P(30)P(30) is about 101510^{15}. A cost function that takes Θ(n)\Theta(n) per order makes brute force cost Ω(4n/n3/2)\Omega(4^n / n^{3/2}).

Optimal substructure

Write Ai..jA_{i..j} for the product AiAi+1⋯AjA_i A_{i+1} \cdots A_j, a pi−1×pjp_{i-1} \times p_j matrix. Any parenthesization of Ai..jA_{i..j} with i<ji < j ends with one multiplication Ai..k⋅Ak+1..jA_{i..k} \cdot A_{k+1..j} for some split kk with i≤k<ji \le k < j. Its cost is

cost(Ai..k)+cost(Ak+1..j)+pi−1 pk pj.\text{cost}(A_{i..k}) + \text{cost}(A_{k+1..j}) + p_{i-1}\, p_k\, p_j .

Claim: in an optimal parenthesization of Ai..jA_{i..j} that splits at kk, the parenthesization of the prefix Ai..kA_{i..k} 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 ii, kk, jj), so if a cheaper way to compute Ai..kA_{i..k} existed, pasting it in would lower the total, a contradiction.

So with m[i,j]m[i, j] the minimum cost for Ai..jA_{i..j},

m[i,j]={0if i=j,min⁡i≤k<j(m[i,k]+m[k+1,j]+pi−1 pk pj)if i<j.m[i, j] = \begin{cases} 0 & \text{if } i = j, \\ \min\limits_{i \le k < j} \left( m[i, k] + m[k+1, j] + p_{i-1}\, p_k\, p_j \right) & \text{if } i < j. \end{cases}

The subproblems are the contiguous subchains Ai..jA_{i..j}: there are (n2)+n=n(n+1)2\binom{n}{2} + n = \frac{n(n+1)}{2} 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 T(n)T(n) be the number of calls for a chain of length nn. The call for A1..nA_{1..n} makes two recursive calls for every split, so T(n)=1+∑k=1n−1(T(k)+T(n−k))=1+2∑k=1n−1T(k)T(n) = 1 + \sum_{k=1}^{n-1} (T(k) + T(n-k)) = 1 + 2 \sum_{k=1}^{n-1} T(k), which solves to T(n)=3n−1T(n) = 3^{n-1} (check: T(1)=1T(1) = 1, and 1+2(1+3+⋯+3n−2)=1+(3n−1−1)1 + 2(1 + 3 + \cdots + 3^{n-2}) = 1 + (3^{n-1} - 1)).

python · try it yourself
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 3n−13^{n-1}, while there are only n(n+1)2\frac{n(n+1)}{2} 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: 314=4,782,9693^{14} = 4{,}782{,}969 calls for 120 distinct subproblems.

cpp · try it yourself
#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 5×85 \times 8 matrix by an 8×38 \times 3 matrix take?

  1. 4040
  2. 6464
  3. 120120
  4. 1515

How many full parenthesizations does a chain of 4 matrices have?

  1. 3
  2. 4
  3. 5
  4. 6

Which are the subproblems of the matrix-chain DP?

  1. All subsets of the matrices
  2. All contiguous subchains Ai..jA_{i..j}
  3. All prefixes A1..jA_{1..j}
  4. All pairs of adjacent matrices

If the best way to compute A1..6A_{1..6} splits at k=2k = 2, what does optimal substructure say?

  1. A1..2A_{1..2} and A3..6A_{3..6} are each computed optimally
  2. A1..2A_{1..2} is computed optimally but A3..6A_{3..6} may not be
  3. k=2k = 2 is also the best split of A1..5A_{1..5}
  4. The cost is p0 p2 p6p_0\, p_2\, p_6