TExcelTAD
Home › Foundations of Algorithm Analysis › Matrix Multiplication and Strassen's Algorithm

Matrix Multiplication and Strassen's Algorithm

For a long time it seemed obvious that multiplying two n×nn \times n matrices needs about n3n^3 multiplications: each of the n2n^2 entries of the product is a dot product of length nn. In 1969 Volker Strassen showed that it is not so. His algorithm multiplies 2×22 \times 2 block matrices with seven block products instead of eight, and applied recursively that one saved product changes the exponent from 3 to lg⁡7≈2.807\lg 7 \approx 2.807. 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 C=ABC = AB with AA, BB of size n×nn \times n,

cij=∑k=0n−1aik bkj,0≤i,j<n.c_{ij} = \sum_{k=0}^{n-1} a_{ik}\, b_{kj}, \qquad 0 \le i, j < n.

Each of the n2n^2 entries takes nn multiplications and n−1n - 1 additions, so the total is exactly n3n^3 multiplications and n2(n−1)n^2(n - 1) additions: Θ(n3)\Theta(n^3).

Divide and conquer, first attempt

Let nn be a power of 2 and cut each matrix into four n/2×n/2n/2 \times n/2 blocks:

A=(A11A12A21A22),B=(B11B12B21B22),C=(C11C12C21C22).A = \begin{pmatrix} A_{11} & A_{12} \\ A_{21} & A_{22} \end{pmatrix}, \quad B = \begin{pmatrix} B_{11} & B_{12} \\ B_{21} & B_{22} \end{pmatrix}, \quad C = \begin{pmatrix} C_{11} & C_{12} \\ C_{21} & C_{22} \end{pmatrix}.

Block multiplication works exactly like the 2×22 \times 2 case: C11=A11B11+A12B21C_{11} = A_{11}B_{11} + A_{12}B_{21}, 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 (n/2)2(n/2)^2. As a recurrence (Writing Recurrences):

T(n)=8T(n/2)+Θ(n2).T(n) = 8T(n/2) + \Theta(n^2).

The watershed is nlog⁡28=n3n^{\log_2 8} = n^3, and n2n^2 is polynomially smaller, so case 1 of the master theorem gives T(n)=Θ(n3)T(n) = \Theta(n^3). 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, Θ(n2)\Theta(n^2)) to save one multiplication (expensive, a whole recursive call). Form these seven products of half-size matrices:

M1=(A11+A22)(B11+B22)M2=(A21+A22) B11M3=A11 (B12−B22)M4=A22 (B21−B11)M5=(A11+A12) B22M6=(A21−A11)(B11+B12)M7=(A12−A22)(B21+B22)\begin{aligned} M_1 &= (A_{11} + A_{22})(B_{11} + B_{22}) \\ M_2 &= (A_{21} + A_{22})\,B_{11} \\ M_3 &= A_{11}\,(B_{12} - B_{22}) \\ M_4 &= A_{22}\,(B_{21} - B_{11}) \\ M_5 &= (A_{11} + A_{12})\,B_{22} \\ M_6 &= (A_{21} - A_{11})(B_{11} + B_{12}) \\ M_7 &= (A_{12} - A_{22})(B_{21} + B_{22}) \end{aligned}

and combine them:

C11=M1+M4−M5+M7,C12=M3+M5,C21=M2+M4,C22=M1−M2+M3+M6.\begin{aligned} C_{11} &= M_1 + M_4 - M_5 + M_7, & C_{12} &= M_3 + M_5, \\ C_{21} &= M_2 + M_4, & C_{22} &= M_1 - M_2 + M_3 + M_6. \end{aligned}

To see why C12C_{12} is right, expand: M3+M5=A11B12−A11B22+A11B22+A12B22=A11B12+A12B22M_3 + M_5 = A_{11}B_{12} - A_{11}B_{22} + A_{11}B_{22} + A_{12}B_{22} = A_{11}B_{12} + A_{12}B_{22}. The other three identities expand the same way, with more cancellation. The identities never use XY=YXXY = YX, 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).

python · try it yourself
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 2×22 \times 2 matrix held in a std::array:

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

T(n)=7T(n/2)+Θ(n2),T(n) = 7T(n/2) + \Theta(n^2),

with watershed nlg⁡7n^{\lg 7}. Since n2=O(nlg⁡7−0.8)n^2 = O(n^{\lg 7 - 0.8}), case 1 applies:

T(n)=Θ(nlg⁡7)=O(n2.81).T(n) = \Theta(n^{\lg 7}) = O(n^{2.81}).

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.

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

cpp · try it yourself
#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 n=2kn = 2^k the multiplications follow M(n)=7M(n/2)M(n) = 7M(n/2), M(1)=1M(1) = 1, so M(n)=7k=nlg⁡7M(n) = 7^k = n^{\lg 7}; at n=32n = 32 that is 16 80716\,807 instead of 32 76832\,768. The additions follow A(n)=7A(n/2)+18(n/2)2A(n) = 7A(n/2) + 18(n/2)^2, A(1)=0A(1) = 0, which solves to A(n)=6(7k−4k)A(n) = 6(7^k - 4^k): for n=32n = 32, 6(16 807−1024)=94 6986(16\,807 - 1024) = 94\,698. So pure Strassen does more additions than the classical method at these sizes, and its total operation count only drops below the classical 2n3−n22n^3 - n^2 at n=1024n = 1024.

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.

python · try it yourself
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 nn. 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 nn, which changes only constant factors.

Beyond Strassen

Strassen's result started a search for the true exponent of matrix multiplication ω\omega, the smallest number such that n×nn \times n matrices can be multiplied in O(nω+ϵ)O(n^{\omega + \epsilon}) operations for every ϵ>0\epsilon > 0. Since every entry of the inputs must be read, ω≥2\omega \ge 2. 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 ω\omega below 2.38, but those algorithms hide constants so large that they are of theoretical interest only. Whether ω=2\omega = 2 is one of the major open questions of the field.

The lesson for divide and conquer is general: in T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n) with a leaves-dominated tree, the number of subproblems aa sets the exponent. Lowering aa from 8 to 7 is worth far more than any constant-factor improvement of f(n)f(n). 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 n/2n/2 plus Θ(n2)\Theta(n^2) additions. What is its running time?

  1. Θ(n2lg⁡n)\Theta(n^2 \lg n)
  2. Θ(nlg⁡7)\Theta(n^{\lg 7})
  3. Θ(n3)\Theta(n^3)
  4. Θ(n2)\Theta(n^2)

How many scalar multiplications does pure Strassen (recursing down to 1×11 \times 1) use for n=16n = 16?

  1. 4096
  2. 2401
  3. 343
  4. 1024

Why can Strassen's 2×22 \times 2 formulas be applied to blocks that are themselves matrices?

  1. Because matrix multiplication is commutative
  2. Because the identities never rely on commutativity of multiplication, only on ring laws that matrices satisfy
  3. Because the blocks are square
  4. Because the blocks are diagonal

In T(n)=aT(n/b)+Θ(n2)T(n) = aT(n/b) + \Theta(n^2) with a>b2a > b^2, which change lowers the exponent of the running time?

  1. Halving the constant in the Θ(n2)\Theta(n^2) term
  2. Reducing the number of subproblems aa
  3. Replacing Θ(n2)\Theta(n^2) by Θ(n2lg⁡n)\Theta(n^2 \lg n)
  4. Changing the base case from n=1n = 1 to n=8n = 8