Freivalds' Matrix-Product Verification
Someone hands you three matrices and claims . Recomputing costs arithmetic operations with the schoolbook method and with the best known algorithms. Rūsiņš Freivalds (1977) showed that checking is easier than computing: multiply both sides by a random vector, in time, and compare. A wrong product is caught with probability at least per round. The idea, a random linear projection that preserves inequality with good probability, reappears in polynomial identity testing and in many verification and sketching algorithms. A first look is in Randomized Algorithms; this lesson gives the proof, its variants and the operation counts.
The algorithm
FREIVALDS(A, B, C, k) // n x n matrices; k rounds
0 for round = 0 to k - 1
1 choose r in {0, 1}^n uniformly at random
2 x = B r // n^2 multiplications
3 y = A x // n^2 multiplications
4 z = C r // n^2 multiplications
5 if y != z
6 return "AB != C" // always correct: r is a certificate
7 return "AB = C" // wrong with probability at most 2^-kIf , then for every , so a correct product is always accepted: the error is one-sided.
Theorem (Freivalds). If and is uniform on , then .
Proof. Let , and pick an entry . If , then in particular
Use the principle of deferred decisions: reveal all coordinates with first. Whatever they are, the right-hand side is a fixed number, and , still uniform on , equals it with probability at most . Averaging over the revealed coordinates gives the claim.
The same argument with each uniform on a set of values (over a field, so division works) gives . Working modulo a prime with therefore gives error per round with numbers that never exceed . That is the degree-1 case of the Schwartz-Zippel lemma.
The bound is tight, and often pessimistic
When has a single nonzero entry , a round detects it exactly when : probability exactly . When the error is spread out, detection is much more likely: requires to lie in the null space of , and if has rank , at most of the vectors do (by the same deferred-decisions argument on independent rows), so the escape probability is at most .
import random
def mat_vec(M, v):
return [sum(a * b for a, b in zip(row, v)) for row in M]
def mat_mul(A, B):
Bt = list(zip(*B))
return [[sum(a * b for a, b in zip(row, col)) for col in Bt] for row in A]
def freivalds_round(A, B, C, rng):
r = [rng.randrange(2) for _ in range(len(A))]
return mat_vec(A, mat_vec(B, r)) == mat_vec(C, r)
rng = random.Random(60)
n = 12
A = [[rng.randrange(-9, 10) for _ in range(n)] for _ in range(n)]
B = [[rng.randrange(-9, 10) for _ in range(n)] for _ in range(n)]
C = mat_mul(A, B)
one_wrong = [row[:] for row in C]
one_wrong[7][5] += 1 # D has rank 1, one nonzero entry
row_wrong = [row[:] for row in C]
row_wrong[3] = [x + rng.randrange(1, 5) for x in row_wrong[3]] # D has rank 1, a full row
swapped = C[1:] + C[:1] # rows rotated: D has high rank
trials = 800
for name, CC in [("correct product", C), ("one wrong entry", one_wrong),
("one wrong row", row_wrong), ("rows rotated", swapped)]:
accepted = sum(freivalds_round(A, B, CC, rng) for _ in range(trials))
print(f"{name:16}: accepted in {accepted / trials:.3f} of single rounds")correct product : accepted in 1.000 of single rounds
one wrong entry : accepted in 0.510 of single rounds
one wrong row : accepted in 0.000 of single rounds
rows rotated : accepted in 0.000 of single rounds
A wrong row also gives a matrix of rank 1, yet it is caught almost always: every entry of its nonzero row is positive, so forces , which has probability for . The rank bound is only an upper bound; what matters is how many vectors the error can hide behind. The worst case is reached only by very special errors, such as a single wrong entry.
Counting the work
The program counts multiplications: per Freivalds round against for recomputing the product. With rounds (error at most ) the check is cheaper than recomputation once .
print(" n recompute n^3 one round 3n^2 20 rounds rounds that cost one recomputation")
for n in [10, 60, 100, 1000, 10000]:
print(f"{n:5} {n ** 3:14} {3 * n * n:14} {60 * n * n:9} {n / 3:10.1f}") n recompute n^3 one round 3n^2 20 rounds rounds that cost one recomputation
10 1000 300 6000 3.3
60 216000 10800 216000 20.0
100 1000000 30000 600000 33.3
1000 1000000000 3000000 60000000 333.3
10000 1000000000000 300000000 6000000000 3333.3
Freivalds' check is also a good habit in practice: a fast but intricate multiplication routine (Strassen with cut-offs, a GPU kernel, a distributed job) can be checked at the cost of a few matrix-vector products. Practise the product itself with Matrix Multiplication.
In C++
Freivalds' check modulo the prime , with uniform on , so one round errs with probability at most . Products of two residues fit in 64 bits. The program verifies a correct product of two matrices and one with a single corrupted entry, counting multiplications; the random stream comes from a fixed-seed std::mt19937.
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
using u64 = std::uint64_t;
using Mat = std::vector<std::vector<u64>>;
const u64 Q = 2147483647; // 2^31 - 1, prime
std::mt19937 rng(60);
long long mults = 0;
std::vector<u64> mat_vec(const Mat& m, const std::vector<u64>& v) {
std::vector<u64> out(m.size());
for (size_t i = 0; i < m.size(); ++i) {
u64 s = 0;
for (size_t j = 0; j < v.size(); ++j) { s = (s + m[i][j] * v[j]) % Q; ++mults; }
out[i] = s;
}
return out;
}
bool freivalds(const Mat& a, const Mat& b, const Mat& c, int rounds) {
for (int t = 0; t < rounds; ++t) {
std::vector<u64> r(a.size());
for (auto& x : r) x = rng() % Q;
if (mat_vec(a, mat_vec(b, r)) != mat_vec(c, r)) return false;
}
return true;
}
int main() {
const int n = 150;
Mat a(n, std::vector<u64>(n)), b = a, c = a;
for (auto& row : a) for (auto& x : row) x = rng() % Q;
for (auto& row : b) for (auto& x : row) x = rng() % Q;
long long full = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
u64 s = 0;
for (int l = 0; l < n; ++l) { s = (s + a[i][l] * b[l][j]) % Q; ++full; }
c[i][j] = s;
}
std::printf("computing C = AB: %lld multiplications\n", full);
mults = 0;
bool ok = freivalds(a, b, c, 2);
std::printf("correct C accepted: %s (%lld multiplications for 2 rounds)\n", ok ? "yes" : "no", mults);
c[42][17] = (c[42][17] + 1) % Q;
mults = 0;
ok = freivalds(a, b, c, 2);
std::printf("corrupted C accepted: %s (%lld multiplications)\n", ok ? "yes" : "no", mults);
}computing C = AB: 3375000 multiplications
correct C accepted: yes (135000 multiplications for 2 rounds)
corrupted C accepted: no (67500 multiplications)
The corrupted product is rejected in the first round, after multiplications instead of .
Test yourself
What does one round of Freivalds' algorithm cost for matrices?
If , with what probability does one round with wrongly accept?
- At most
- At most
- Exactly always
- At most always
Which kind of error does Freivalds' algorithm have?
- Two-sided
- One-sided: it may accept a wrong product, but never rejects a correct one
- One-sided: it may reject a correct product
- None
Working modulo a prime with uniform on , what is the error per round?
- At most
- At most
- At most
- At most