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 matrices and , the product has entries .
| Method | Recurrence | Running time |
|---|---|---|
| three nested loops | none | |
| block divide and conquer, 8 half-size products | ||
| Strassen, 7 half-size products, 18 block additions |
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 of matrix multiplication are now just below 2.372, from algorithms of purely theoretical interest; whether is open.
Two parallel multiplications
The classical algorithm parallelizes easily, because the entries are independent:
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 , span , parallelism . 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 and four into a temporary matrix , then add into with a doubly nested parallel loop:
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 , while the work stays . The program evaluates both with the composition rules of Work, Span and Parallelism, counting one step per multiply-add and per loop split.
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 work, the recursive one about four times as much in this cost model (the additions of and the overhead of the tiny leaf calls). Its span is only 151 steps for , against 1044 for the loops, but in practice the loop version's parallelism of about 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 and work .
Checking a product in
Someone claims that . Recomputing costs , or with Strassen. Freivalds' algorithm (1977) checks the claim with high probability in time per trial:
- Pick a random vector .
- Compute and : three matrix-vector products, each.
- If , the claim is certainly false. If , accept.
If , the test always accepts. If , then has a nonzero entry , and the test accepts only when . Fix all coordinates of except : at most one of the two values of makes zero. So a wrong product survives one trial with probability at most , and independent trials with probability at most .
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 , 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.
#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 loop?
Why does the recursive parallel multiplication use a temporary matrix ?
- To save memory
- So that the eight products can run in parallel without two of them writing the same block of
- Because Strassen's algorithm needs it
- To make the work smaller
If , with what probability at most does one trial of Freivalds' algorithm accept?
How much time does one trial of Freivalds' algorithm take for matrices?