Matrix Chain Multiplication
In questa pagina 7
Multiplying a chain of rectangular matrices can cost much or little depending on the order of the products, although the result is always the same (the product is associative but not commutative). Choosing the best order is an optimization problem solved by dynamic programming (Dynamic Programming - Paradigm and Memoizationdynamic programming improves on divide and conquer by storing the solutions of repeated subinstances in a table; Fibonacci shows the gap (F_n - 1 additions recursively, n - 1 with a table), memoization is recursion plus a global table, and optimization problems follow a five-step scheme built on optimal substructure and cut-and-paste.Dynamic Programming - Paradigm and Memoization →).
The problem
Two matrices and are compatible; their product is with .
RECT_MAT(A, B)
p <- rows(A); q <- columns(A); r <- columns(B)
for i <- 1 to p do
for j <- 1 to r do
c_ij <- a_i1 * b_1j
for k <- 2 to q do c_ij <- c_ij + a_ik * b_kj
return CIt performs exactly products between scalars (we count only products).
We want the product of a chain of compatible matrices. Compatibility means numbers suffice: the vector , with .
Parenthesizations
Every execution order is a full parenthesization, represented by a full binary tree: leaves are the matrices, internal nodes are products. A full binary tree with leaves has internal nodes, so every parenthesization performs exactly matrix products. For there are two, for five:
(((A1 A2) A3) A4) ((A1 A2) (A3 A4)) (A1 (A2 (A3 A4))) ((A1 (A2 A3)) A4) (A1 ((A2 A3) A4))The number of scalar products depends on the parenthesization.
Example. , , , i.e. .
- : costs and gives a matrix; then . Total .
- : costs and gives ; then . Total .
Definition (MCM). Given , find the parenthesization of the associated chain requiring the minimum number of scalar products.
The instance is only the vector .
How many parenthesizations?
Let be the number of parenthesizations of matrices. The last product splits the chain into and , :
The first values are (Catalan numbers).
Theorem. for every .
Proof. Base: , . Step: let and assume the claim for smaller values. Then
The sum was bounded below by the terms and , distinct because .
So parenthesizations are exponential and exhaustive search is impractical. Actually (Catalan formula and Stirling).
Optimal substructure
A parenthesization of contains parenthesizations of subchains, so the natural subproblem space is the set of non-empty subchains , : of them. Write , for a parenthesization tree, for its cost and for an optimal one. We look for .
Base cases: a subchain has a single one-node tree, of cost .
Theorem (optimal substructure). Let and optimal for . Then there is with such that the root has as subtrees two optimal trees and , and where minimizes over .
Proof. The tree has at least two leaves, so the root has two subtrees and : the last product is , of dimensions and , costing .
The subtrees are optimal. If one of them (say ) were not optimal, replace it with an optimal : the new parenthesization is still feasible (same dimensions) and costs strictly less than , a contradiction. This is cut-and-paste.
Choice of . For each , joining and under a new root is feasible with cost . If did not minimize it, the minimizer would beat .
The value is the only information needed to rebuild the optimal tree.
Cost recurrence
With :
The answer is .
The divide and conquer algorithm
R_MCM(p, i, j)
if i = j then return 0
m <- +infinity
for k <- i to j-1 do
q <- R_MCM(p, i, k) + R_MCM(p, k+1, j) + p_{i-1} * p_k * p_j
if q < m then m <- q
return mCounting the multiplications between dimensions (two per ), the cost for a chain of matrices is
Exponential lower bound. by induction. Base: , . For , keeping only the term :
Exact value: . For subtract the recurrences of and :
which also holds for . Adding to both sides, , hence . For this is , for it is .
Why? Repeated subinstances. For there are calls to R_MCM(p, i, j) and each subchain appears several times:
| subchain | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| calls | 4 | 5 | 5 | 4 | 2 | 2 | 2 | 1 | 1 | 1 |
The dynamic programming approach
Two tables and , using only the upper triangle (): holds and holds (additional information). Base cases lie on the main diagonal.
Fill order. Computing needs (same row, to the left) and (same column, below), for . Scanning by increasing rows or by increasing columns does not work: in both, would be computed after . But the needed values lie on diagonals closer to the main one. Diagonal contains the cells with , i.e. the subchains of length ; the cells that depends on are shorter subchains, on diagonals . A scan by increasing diagonal length respects the dependencies. On diagonal the row index runs from to and .
MCM(p)
n <- length(p) - 1
for i <- 1 to n do m[i, i] <- 0
for l <- 2 to n do
for i <- 1 to n - l + 1 do
j <- i + l - 1
m[i, j] <- +infinity
for k <- i to j - 1 do
q <- m[i, k] + m[k+1, j] + p_{i-1} * p_k * p_j
if q < m[i, j] then
m[i, j] <- q
s[i, j] <- k
return (m[1, n], s)Cost (exact sum). With cost for each value of :
using Gauss' sum and the sum of squares. So , against of D&C (for : against ).
Other valid scans. By rows from row down to row , each from to ; or by columns, each from the bottom up. Both respect the dependency graph.
Worked example
, i.e. : , , , , .
Table :
| 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| 1 | 0 | 120 | 264 | 1080 | 1344 |
| 2 | 0 | 360 | 1320 | 1350 | |
| 3 | 0 | 720 | 1140 | ||
| 4 | 0 | 1680 | |||
| 5 | 0 |
Table :
| 2 | 3 | 4 | 5 | |
|---|---|---|---|---|
| 1 | 1 | 2 | 2 | 2 |
| 2 | 2 | 2 | 2 | |
| 3 | 3 | 4 | ||
| 4 | 4 |
Diagonal by diagonal:
- : : ; ; ; .
- , cell : : ; : . Minimum with . Similarly and with .
- , cell : : ; : ; : . Minimum with . For : : ; : ; : ; minimum .
- , cell : : ; : ; : ; : . Minimum with .
Optimal cost . Reconstruction: splits into and ; splits the second into and . Parenthesization: . Check: . Of the possible orders this is the only optimal one, and the worst costs .
Printing the parenthesization
PRINT_MCM(s, i, j)
if i = j then
print("A_i")
return
print("(")
PRINT_MCM(s, i, s[i, j])
PRINT_MCM(s, s[i, j] + 1, j)
print(")")The return after the base case is needed (otherwise the code would read the undefined ). It prints one parenthesis per internal node () and one character per leaf (): characters.
The memoized approach
Same substructure, with recursion and a default for uncomputed cells. The sentinel is : it marks cells to compute and correctly initializes the running minimum (base cases are already ).
INIT_MCM(p)
n <- length(p) - 1
if n = 1 then return 0
for i <- 1 to n do
m[i, i] <- 0
for j <- i + 1 to n do m[i, j] <- +infinity
return REC_MCM(p, 1, n)
REC_MCM(p, i, j)
if m[i, j] = +infinity then
for k <- i to j - 1 do
q <- REC_MCM(p, i, k) + REC_MCM(p, k+1, j) + p_{i-1} * p_k * p_j
if q < m[i, j] then m[i, j] <- q
return m[i, j]Cost. Each non-base subinstance is an internal node exactly once, with work , and from every pair is reached. Hence
Unlike LCS, memoization never saves anything: all subinstances must be solved anyway and the top-down phase cannot skip any. Its benefit is not having to design the diagonal fill order.
Typical exam questions
- For (three matrices), how many scalar products does the optimal parenthesization need? Answer: , with (; the other order costs ).
- How many parenthesizations does a chain of matrices have, and how many scalar products does
MCMperform for ? Answer: ; . - Why is D&C exponential and DP cubic? Why does the row scan fail? Answer: repeated subinstances (subchains are but calls are ); depends on in later rows, not ready for increasing rows; ready for diagonals.
Versione ripasso
- Problem. Chain , , instance . A times product costs scalar products. A parenthesization is a full binary tree, always matrix products, variable scalar cost. For : costs , costs .
- Parenthesizations: , (Catalan: ), by induction (keep terms , of ), .
- Substructure (cut-and-paste): in the root splits into and , both optimal, with ; minimizes the sum. Base: one matrix, cost .
- Recurrence: ; . Additional information .
- D&C
R_MCM: , ; exactly , i.e. ( for ). For there are calls and etc. repeat - times. - Bottom-up by diagonals , , : increasing rows or columns fail ( not ready); rows from to or columns bottom-up also work. Cost .
MCM(p): n <- length(p)-1; for i <- 1 to n do m[i,i] <- 0
for l <- 2 to n do for i <- 1 to n-l+1 do
j <- i+l-1; m[i,j] <- +inf
for k <- i to j-1 do
q <- m[i,k] + m[k+1,j] + p_{i-1} p_k p_j
if q < m[i,j] then m[i,j] <- q; s[i,j] <- k
return (m[1,n], s)
PRINT_MCM(s,i,j): if i = j then print A_i, return; print "("; PRINT_MCM(s,i,s[i,j]); PRINT_MCM(s,s[i,j]+1,j); print ")"- Example : ; ; ; . ; ; , ; . Cell : give . Optimum : with costs ; worst of the costs . Printing takes characters.
- Memoized: sentinel ; each is an internal node once with work , all subinstances reached: , never better than bottom-up (unlike LCS).
REC_MCM(p, i, j) { m[i,i] = 0, other cells = +inf }
if m[i,j] = +inf then
for k <- i to j-1 do
q <- REC_MCM(p,i,k) + REC_MCM(p,k+1,j) + p_{i-1} p_k p_j
if q < m[i,j] then m[i,j] <- q
return m[i,j]- Typical questions: : costs , the other ; ; products of
MCMfor : ; D&C against DP for : against . - Typical mistakes: scanning by increasing rows or columns; writing for ; counting also additions; forgetting
returninPRINT_MCM; believing memoization reduces the work (here it does not).