TExcelTAD

Matrix Multiplication Revisited

Matrix operations are the workhorses of scientific computing, graphics, statistics and machine learning, and they connect several threads of this course. This section starts from multiplication, revisits Strassen's algorithm from the first course, measures the work and span of two parallel versions, and ends with a surprising fact: checking a product is much cheaper than computing one. The following lessons build on it to solve linear systems and invert matrices.

Recap: three ways to multiply

For n×nn \times n matrices AA and BB, the product C=ABC = AB has entries cij=∑kaikbkjc_{ij} = \sum_k a_{ik} b_{kj}.

Method Recurrence Running time
three nested loops none Θ(n3)\Theta(n^3)
block divide and conquer, 8 half-size products T(n)=8T(n/2)+Θ(n2)T(n) = 8T(n/2) + \Theta(n^2) Θ(n3)\Theta(n^3)
Strassen, 7 half-size products, 18 block additions T(n)=7T(n/2)+Θ(n2)T(n) = 7T(n/2) + \Theta(n^2) Θ(nlg⁡7)=O(n2.81)\Theta(n^{\lg 7}) = O(n^{2.81})

The lesson Matrix Multiplication and Strassen's Algorithm derives the seven products, counts the operations exactly and explains why libraries switch to the classical method below a cutoff of a few hundred. The best known bounds on the exponent ω\omega of matrix multiplication are now just below 2.372, from algorithms of purely theoretical interest; whether ω=2\omega = 2 is open.

Two parallel multiplications

The classical algorithm parallelizes easily, because the n2n^2 entries are independent:

text
P-MAT-MUL-LOOPS(A, B, C, n)
1  parallel for i = 0 to n - 1
2      parallel for j = 0 to n - 1
3          C[i][j] = 0
4          for k = 0 to n - 1                // serial: all iterations write C[i][j]
5              C[i][j] = C[i][j] + A[i][k] * B[k][j]

Work Θ(n3)\Theta(n^3), span Θ(lg⁡n)+Θ(lg⁡n)+Θ(n)=Θ(n)\Theta(\lg n) + \Theta(\lg n) + \Theta(n) = \Theta(n), parallelism Θ(n2)\Theta(n^2). The inner loop stays serial to avoid a determinacy race on C[i][j] (Parallel Loops and Determinacy Races).

The block algorithm does better on span. Spawn all eight half-size products, four of them into CC and four into a temporary matrix TT, then add TT into CC with a doubly nested parallel loop:

text
P-MAT-MUL-REC(A, B, C, n)        // C = A B, n a power of 2
1  if n == 1
2      C[0][0] = A[0][0] * B[0][0]
3      return
4  T = a new n x n matrix
5  partition A, B, C, T into n/2 x n/2 blocks
6  spawn the 8 products: C11 = A11 B11, C12 = A11 B12, C21 = A21 B11, C22 = A21 B12,
                         T11 = A12 B21, T12 = A12 B22, T21 = A22 B21, T22 = A22 B22
7  sync
8  parallel for i, j: C[i][j] = C[i][j] + T[i][j]

The products run in parallel, so T∞(n)=T∞(n/2)+Θ(lg⁡n)=Θ(lg⁡2n)T_\infty(n) = T_\infty(n/2) + \Theta(\lg n) = \Theta(\lg^2 n), while the work stays Θ(n3)\Theta(n^3). The program evaluates both with the composition rules of Work, Span and Parallelism, counting one step per multiply-add and per loop split.

python · try it yourself
from functools import lru_cache
from math import ceil, log2

def ploop(n, w, s):                      # parallel loop of n bodies (work w, span s each)
    return n * w + (n - 1), s + ceil(log2(n))

def loops(n):
    w_inner, s_inner = n, n              # serial k loop
    w_j, s_j = ploop(n, w_inner, s_inner)
    return ploop(n, w_j, s_j)

@lru_cache(maxsize=None)
def rec(n):
    if n == 1:
        return 1, 1
    w, s = rec(n // 2)
    w_add, s_add = ploop(n, *ploop(n, 1, 1))     # C = C + T
    return 8 * w + w_add + 7, s + s_add + 3      # 7 spawns: about lg 8 = 3 levels

print("    n   loops: work      span   par.  |  recursive: work      span     par.")
for n in [16, 64, 256, 1024]:
    wa, sa = loops(n)
    wb, sb = rec(n)
    print(f"{n:5} {wa:15} {sa:9} {wa / sa:6.0f}  | {wb:15} {sb:9} {wb / sb:8.0f}")
    n   loops: work      span   par.  |  recursive: work      span     par.
   16            4351        24    181  |           15286        37      413
   64          266239        76   3503  |         1002934        67    14969
  256        16842751       272  61922  |        64581046       105   615058
 1024      1074790399      1044 1029493  |      4139478454       151 27413765

Both versions do Θ(n3)\Theta(n^3) work, the recursive one about four times as much in this cost model (the additions of TT and the overhead of the tiny leaf calls). Its span is only 151 steps for n=1024n = 1024, against 1044 for the loops, but in practice the loop version's parallelism of about n2n^2 is already more than enough, and it needs no temporary matrices. Strassen's algorithm parallelizes the same way as the recursive version: seven spawned products, then parallel additions, for span Θ(lg⁡2n)\Theta(\lg^2 n) and work Θ(nlg⁡7)\Theta(n^{\lg 7}).

Checking a product in O(n2)O(n^2)

Someone claims that C=ABC = AB. Recomputing ABAB costs Θ(n3)\Theta(n^3), or Θ(n2.81)\Theta(n^{2.81}) with Strassen. Freivalds' algorithm (1977) checks the claim with high probability in O(n2)O(n^2) time per trial:

  1. Pick a random vector r∈{0,1}nr \in \{0, 1\}^n.
  2. Compute x=A(Br)x = A(Br) and y=Cry = Cr: three matrix-vector products, Θ(n2)\Theta(n^2) each.
  3. If x≠yx \ne y, the claim is certainly false. If x=yx = y, accept.

If C=ABC = AB, the test always accepts. If C≠ABC \ne AB, then D=AB−CD = AB - C has a nonzero entry dijd_{ij}, and the test accepts only when (Dr)i=0(Dr)_i = 0. Fix all coordinates of rr except rjr_j: at most one of the two values of rjr_j makes (Dr)i=∑kdikrk(Dr)_i = \sum_k d_{ik} r_k zero. So a wrong product survives one trial with probability at most 1/21/2, and tt independent trials with probability at most 2−t2^{-t}.

python · try it yourself
import random

def mat_vec(M, v):
    return [sum(row[k] * v[k] for k in range(len(v))) for row in M]

def freivalds(A, B, C, trials, rng):
    for _ in range(trials):
        r = [rng.randint(0, 1) for _ in range(len(A))]
        if mat_vec(A, mat_vec(B, r)) != mat_vec(C, r):
            return False
    return True

rng = random.Random(42)
n = 60
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)]
C = [[sum(A[i][k] * B[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
print("correct product accepted:", freivalds(A, B, C, 20, rng))

wrong = [row[:] for row in C]
wrong[17][42] += 1                              # a single wrong entry
caught = sum(not freivalds(A, B, wrong, 1, rng) for _ in range(1000))
print(f"one trial catches the single wrong entry in {caught} of 1000 runs")
print("20 trials accept it:", freivalds(A, B, wrong, 20, rng))
print(f"cost per trial about {3 * n * n} multiplications, recomputing costs {n ** 3}")
correct product accepted: True
one trial catches the single wrong entry in 510 of 1000 runs
20 trials accept it: False
cost per trial about 10800 multiplications, recomputing costs 216000

With a single wrong entry, one trial catches it exactly when r42=1r_{42} = 1, about half the time, matching the bound. Twenty trials reduce the chance of being fooled below one in a million, at a cost still far below one multiplication. Checking is easier than computing, a theme that returns in this course's last section: the class NP is defined by efficient verification (Verification and the Class NP).

In C++

Freivalds' check in C++, on random integer matrices and a product with one corrupted entry.

cpp · try it yourself
#include <cstdio>
#include <random>
#include <vector>
using Matrix = std::vector<std::vector<long long>>;
using Vec = std::vector<long long>;

Vec mat_vec(const Matrix& M, const Vec& v) {
    Vec out(M.size(), 0);
    for (size_t i = 0; i < M.size(); i++)
        for (size_t k = 0; k < v.size(); k++) out[i] += M[i][k] * v[k];
    return out;
}

bool freivalds(const Matrix& A, const Matrix& B, const Matrix& C, int trials, std::mt19937& rng) {
    for (int t = 0; t < trials; t++) {
        Vec r(A.size());
        for (auto& x : r) x = rng() & 1;
        if (mat_vec(A, mat_vec(B, r)) != mat_vec(C, r)) return false;
    }
    return true;
}

int main() {
    std::mt19937 rng(42);
    const int n = 100;
    Matrix A(n, Vec(n)), B(n, Vec(n)), C(n, Vec(n, 0));
    for (auto& row : A) for (auto& x : row) x = int(rng() % 19) - 9;
    for (auto& row : B) for (auto& x : row) x = int(rng() % 19) - 9;
    for (int i = 0; i < n; i++)
        for (int k = 0; k < n; k++)
            for (int j = 0; j < n; j++) C[i][j] += A[i][k] * B[k][j];
    std::printf("correct product accepted: %s\n", freivalds(A, B, C, 20, rng) ? "yes" : "no");
    C[3][77] -= 5;
    int caught = 0;
    for (int run = 0; run < 1000; run++) caught += !freivalds(A, B, C, 1, rng);
    std::printf("one trial catches the wrong entry in %d of 1000 runs\n", caught);
    std::printf("20 trials accept it: %s\n", freivalds(A, B, C, 20, rng) ? "yes" : "no");
}
correct product accepted: yes
one trial catches the wrong entry in 528 of 1000 runs
20 trials accept it: no

Practise matrix products with Matrix Multiplication.

Test yourself

What is the span of the parallel-loops matrix multiplication with a serial inner kk loop?

  1. Θ(lg⁡n)\Theta(\lg n)
  2. Θ(lg⁡2n)\Theta(\lg^2 n)
  3. Θ(n)\Theta(n)
  4. Θ(n2)\Theta(n^2)

Why does the recursive parallel multiplication use a temporary matrix TT?

  1. To save memory
  2. So that the eight products can run in parallel without two of them writing the same block of CC
  3. Because Strassen's algorithm needs it
  4. To make the work smaller

If C≠ABC \ne AB, with what probability at most does one trial of Freivalds' algorithm accept?

  1. 00
  2. 1/n1/n
  3. 1/21/2
  4. 1−1/n1 - 1/n

How much time does one trial of Freivalds' algorithm take for n×nn \times n matrices?

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