Matrix Multiplication and Strassen's Algorithm
For a long time it seemed obvious that multiplying two matrices needs about multiplications: each of the entries of the product is a dot product of length . In 1969 Volker Strassen showed that it is not so. His algorithm multiplies block matrices with seven block products instead of eight, and applied recursively that one saved product changes the exponent from 3 to . This lesson is a preview: it shows how a recurrence decides the exponent, counts the operations exactly and explains why the idea, brilliant as it is, is used with care in practice.
The obvious algorithm
For with , of size ,
Each of the entries takes multiplications and additions, so the total is exactly multiplications and additions: .
Divide and conquer, first attempt
Let be a power of 2 and cut each matrix into four blocks:
Block multiplication works exactly like the case: , and similarly for the other three blocks. That is 8 products of half-size matrices and 4 additions of half-size matrices, each addition costing . As a recurrence (Writing Recurrences):
The watershed is , and is polynomially smaller, so case 1 of the master theorem gives . Splitting alone gains nothing; the work is the same, just reorganized. To win, the recursion must make fewer than 8 recursive products.
Seven products
Strassen's insight is to spend some extra additions (cheap, ) to save one multiplication (expensive, a whole recursive call). Form these seven products of half-size matrices:
and combine them:
To see why is right, expand: . The other three identities expand the same way, with more cancellation. The identities never use , so they hold when the entries are themselves matrices, which is what makes the recursion legal.
Expanding by hand is error-prone; a computer can test the identities on thousands of random integer inputs in a moment (for polynomial identities with integer coefficients, passing many random tests is very strong evidence, and the expansion above is the proof).
import random
def strassen_2x2(a, b):
(a11, a12), (a21, a22) = a
(b11, b12), (b21, b22) = b
m1 = (a11 + a22) * (b11 + b22)
m2 = (a21 + a22) * b11
m3 = a11 * (b12 - b22)
m4 = a22 * (b21 - b11)
m5 = (a11 + a12) * b22
m6 = (a21 - a11) * (b11 + b12)
m7 = (a12 - a22) * (b21 + b22)
return [[m1 + m4 - m5 + m7, m3 + m5], [m2 + m4, m1 - m2 + m3 + m6]]
def plain_2x2(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(2)) for j in range(2)] for i in range(2)]
rng = random.Random(7)
for trial in range(10_000):
a = [[rng.randint(-50, 50) for _ in range(2)] for _ in range(2)]
b = [[rng.randint(-50, 50) for _ in range(2)] for _ in range(2)]
assert strassen_2x2(a, b) == plain_2x2(a, b)
print("10000 random 2x2 products agree; one example:")
print(strassen_2x2([[1, 2], [3, 4]], [[5, 6], [7, 8]]))10000 random 2x2 products agree; one example:
[[19, 22], [43, 50]]
In C++
In C++, with each matrix held in a std::array:
#include <array>
#include <cassert>
#include <cstdio>
#include <random>
using namespace std;
using M2 = array<array<long long, 2>, 2>;
M2 strassen_2x2(const M2& a, const M2& b) {
auto [a11, a12] = a[0];
auto [a21, a22] = a[1];
auto [b11, b12] = b[0];
auto [b21, b22] = b[1];
long long m1 = (a11 + a22) * (b11 + b22);
long long m2 = (a21 + a22) * b11;
long long m3 = a11 * (b12 - b22);
long long m4 = a22 * (b21 - b11);
long long m5 = (a11 + a12) * b22;
long long m6 = (a21 - a11) * (b11 + b12);
long long m7 = (a12 - a22) * (b21 + b22);
return {{{m1 + m4 - m5 + m7, m3 + m5}, {m2 + m4, m1 - m2 + m3 + m6}}};
}
M2 plain_2x2(const M2& a, const M2& b) {
M2 c{};
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++) c[i][j] += a[i][k] * b[k][j];
return c;
}
int main() {
mt19937 rng(7);
uniform_int_distribution<int> entry(-50, 50);
for (int trial = 0; trial < 10000; trial++) {
M2 a, b;
for (auto& row : a) for (auto& x : row) x = entry(rng);
for (auto& row : b) for (auto& x : row) x = entry(rng);
assert(strassen_2x2(a, b) == plain_2x2(a, b));
}
printf("10000 random 2x2 products agree; one example:\n");
M2 c = strassen_2x2({{{1, 2}, {3, 4}}}, {{{5, 6}, {7, 8}}});
printf("[[%lld, %lld], [%lld, %lld]]\n", c[0][0], c[0][1], c[1][0], c[1][1]);
}10000 random 2x2 products agree; one example:
[[19, 22], [43, 50]]
Counting the block operations: forming the seven products needs 10 additions or subtractions of blocks, and combining them 8 more, so 18 in all, against 4 for the first attempt. The recurrence becomes
with watershed . Since , case 1 applies:
Counting operations exactly
The program below runs the full recursion on random integer matrices, checks the answer against the obvious method and counts scalar multiplications and additions.
import random
ops = {"mul": 0, "add": 0}
def add(X, Y, sign=1):
ops["add"] += len(X) * len(X)
return [[x + sign * y for x, y in zip(r, s)] for r, s in zip(X, Y)]
def classic(A, B):
n = len(A)
ops["mul"] += n ** 3
ops["add"] += n * n * (n - 1)
return [[sum(A[i][k] * B[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
def split(M):
h = len(M) // 2
return [r[:h] for r in M[:h]], [r[h:] for r in M[:h]], [r[:h] for r in M[h:]], [r[h:] for r in M[h:]]
def strassen(A, B):
if len(A) == 1:
return classic(A, B)
a11, a12, a21, a22 = split(A)
b11, b12, b21, b22 = split(B)
m1 = strassen(add(a11, a22), add(b11, b22))
m2 = strassen(add(a21, a22), b11)
m3 = strassen(a11, add(b12, b22, -1))
m4 = strassen(a22, add(b21, b11, -1))
m5 = strassen(add(a11, a12), b22)
m6 = strassen(add(a21, a11, -1), add(b11, b12))
m7 = strassen(add(a12, a22, -1), add(b21, b22))
c11 = add(add(m1, m4), add(m7, m5, -1))
c12 = add(m3, m5)
c21 = add(m2, m4)
c22 = add(add(m1, m2, -1), add(m3, m6))
return [r + s for r, s in zip(c11, c12)] + [r + s for r, s in zip(c21, c22)]
rng = random.Random(7)
print(" n classic: mul add Strassen: mul add same?")
for n in [2, 4, 8, 16, 32]:
A = [[rng.randint(-9, 9) for _ in range(n)] for _ in range(n)]
B = [[rng.randint(-9, 9) for _ in range(n)] for _ in range(n)]
ops.update(mul=0, add=0); C1 = classic(A, B); cm, ca = ops["mul"], ops["add"]
ops.update(mul=0, add=0); C2 = strassen(A, B); sm, sa = ops["mul"], ops["add"]
print(f"{n:3} {cm:13} {ca:8} {sm:14} {sa:8} {C1 == C2}") n classic: mul add Strassen: mul add same?
2 8 4 7 18 True
4 64 48 49 198 True
8 512 448 343 1674 True
16 4096 3840 2401 12870 True
32 32768 31744 16807 94698 True
In C++
The same recursion in C++, on std::vector matrices of long long. The random matrices differ from Python's, but the counts do not depend on the entries:
#include <cstdio>
#include <random>
#include <vector>
using namespace std;
using Matrix = vector<vector<long long>>;
long long mul_ops = 0, add_ops = 0;
Matrix add(const Matrix& X, const Matrix& Y, int sign = 1) {
size_t n = X.size();
add_ops += n * n;
Matrix Z(n, vector<long long>(n));
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < n; j++) Z[i][j] = X[i][j] + sign * Y[i][j];
return Z;
}
Matrix classic(const Matrix& A, const Matrix& B) {
size_t n = A.size();
mul_ops += n * n * n;
add_ops += n * n * (n - 1);
Matrix C(n, vector<long long>(n));
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < n; j++)
for (size_t k = 0; k < n; k++) C[i][j] += A[i][k] * B[k][j];
return C;
}
// the h x h block of M whose top-left corner is (r, c)
Matrix block(const Matrix& M, size_t r, size_t c, size_t h) {
Matrix B(h, vector<long long>(h));
for (size_t i = 0; i < h; i++)
for (size_t j = 0; j < h; j++) B[i][j] = M[r + i][c + j];
return B;
}
Matrix strassen(const Matrix& A, const Matrix& B) {
size_t n = A.size();
if (n == 1) return classic(A, B);
size_t h = n / 2;
Matrix a11 = block(A, 0, 0, h), a12 = block(A, 0, h, h), a21 = block(A, h, 0, h), a22 = block(A, h, h, h);
Matrix b11 = block(B, 0, 0, h), b12 = block(B, 0, h, h), b21 = block(B, h, 0, h), b22 = block(B, h, h, h);
Matrix m1 = strassen(add(a11, a22), add(b11, b22));
Matrix m2 = strassen(add(a21, a22), b11);
Matrix m3 = strassen(a11, add(b12, b22, -1));
Matrix m4 = strassen(a22, add(b21, b11, -1));
Matrix m5 = strassen(add(a11, a12), b22);
Matrix m6 = strassen(add(a21, a11, -1), add(b11, b12));
Matrix m7 = strassen(add(a12, a22, -1), add(b21, b22));
Matrix c11 = add(add(m1, m4), add(m7, m5, -1));
Matrix c12 = add(m3, m5);
Matrix c21 = add(m2, m4);
Matrix c22 = add(add(m1, m2, -1), add(m3, m6));
Matrix C(n, vector<long long>(n));
for (size_t i = 0; i < h; i++)
for (size_t j = 0; j < h; j++) {
C[i][j] = c11[i][j]; C[i][j + h] = c12[i][j];
C[i + h][j] = c21[i][j]; C[i + h][j + h] = c22[i][j];
}
return C;
}
int main() {
mt19937 rng(7);
uniform_int_distribution<int> entry(-9, 9);
printf(" n classic: mul add Strassen: mul add same?\n");
for (size_t n : {2, 4, 8, 16, 32}) {
Matrix A(n, vector<long long>(n)), B(n, vector<long long>(n));
for (auto& row : A) for (auto& x : row) x = entry(rng);
for (auto& row : B) for (auto& x : row) x = entry(rng);
mul_ops = add_ops = 0; Matrix C1 = classic(A, B); long long cm = mul_ops, ca = add_ops;
mul_ops = add_ops = 0; Matrix C2 = strassen(A, B); long long sm = mul_ops, sa = add_ops;
printf("%3zu %13lld %8lld %14lld %8lld %s\n", n, cm, ca, sm, sa,
C1 == C2 ? "True" : "False");
}
} n classic: mul add Strassen: mul add same?
2 8 4 7 18 True
4 64 48 49 198 True
8 512 448 343 1674 True
16 4096 3840 2401 12870 True
32 32768 31744 16807 94698 True
For the multiplications follow , , so ; at that is instead of . The additions follow , , which solves to : for , . So pure Strassen does more additions than the classical method at these sizes, and its total operation count only drops below the classical at .
The crossover, and why libraries hesitate
The cure is a hybrid: recurse with Strassen's scheme while the blocks are large, and switch to the classical method below a cutoff size. The total operation count for each cutoff follows from a recurrence, so it can be tabulated without running anything.
def total_ops(n, cutoff):
if n <= cutoff:
return 2 * n**3 - n**2 # classical: n^3 mul + n^2 (n - 1) add
return 7 * total_ops(n // 2, cutoff) + 18 * (n // 2) ** 2
print(" n classical Strassen down to blocks of 1, 4, 8, 16, 64")
for n in [16, 64, 256, 1024, 4096]:
row = [total_ops(n, c) for c in (1, 4, 8, 16, 64)]
print(f"{n:5} {2 * n**3 - n**2:12} " + " ".join(f"{r / (2 * n**3 - n**2):.3f}" for r in row)) n classical Strassen down to blocks of 1, 4, 8, 16, 64
16 7936 1.924 1.091 0.992 1.000 1.000
64 520192 1.536 0.913 0.839 0.845 1.000
256 33488896 1.193 0.719 0.663 0.667 0.785
1024 2146435072 0.918 0.556 0.513 0.516 0.606
4096 137422176256 0.704 0.427 0.394 0.397 0.466
The table shows each total as a fraction of the classical count. Counting arithmetic operations alone, a cutoff of about 8 is best, and the saving grows with . Real machines are not operation counters, though:
- The classical method has a simple, cache-friendly loop structure that optimized libraries (BLAS) tune to near the hardware's peak. Strassen's scheme allocates temporary blocks and moves more memory. Measured cutoffs are therefore much larger than 8, typically somewhere in the hundreds or more, and depend on the machine.
- In floating-point arithmetic Strassen's algorithm satisfies a weaker error bound than the classical method (it is stable in a normwise sense, but not entrywise), so numerical libraries usually do not use it by default.
- Sizes that are not powers of 2 need padding with zeros or special handling of odd dimensions; padding at most doubles , which changes only constant factors.
Beyond Strassen
Strassen's result started a search for the true exponent of matrix multiplication , the smallest number such that matrices can be multiplied in operations for every . Since every entry of the inputs must be read, . A variant due to Winograd keeps 7 products and uses 15 block additions instead of 18. A long line of increasingly intricate algorithms has pushed the known upper bound on below 2.38, but those algorithms hide constants so large that they are of theoretical interest only. Whether is one of the major open questions of the field.
The lesson for divide and conquer is general: in with a leaves-dominated tree, the number of subproblems sets the exponent. Lowering from 8 to 7 is worth far more than any constant-factor improvement of . Karatsuba's integer multiplication (3 half-size products instead of 4) is the same idea one dimension down; see Divide-and-Conquer Recurrences.
Test yourself
The simple block algorithm makes 8 recursive products of size plus additions. What is its running time?
How many scalar multiplications does pure Strassen (recursing down to ) use for ?
- 4096
- 2401
- 343
- 1024
Why can Strassen's formulas be applied to blocks that are themselves matrices?
- Because matrix multiplication is commutative
- Because the identities never rely on commutativity of multiplication, only on ring laws that matrices satisfy
- Because the blocks are square
- Because the blocks are diagonal
In with , which change lowers the exponent of the running time?
- Halving the constant in the term
- Reducing the number of subproblems
- Replacing by
- Changing the base case from to