TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › Freivalds' Matrix-Product Verification

Freivalds' Matrix-Product Verification

Someone hands you three n×nn \times n matrices and claims AB=CAB = C. Recomputing ABAB costs Θ(n3)\Theta(n^3) arithmetic operations with the schoolbook method and O(n2.37)O(n^{2.37}) with the best known algorithms. Rūsiņš Freivalds (1977) showed that checking is easier than computing: multiply both sides by a random vector, in O(n2)O(n^2) time, and compare. A wrong product is caught with probability at least 1/21/2 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

text
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^-k

If AB=CAB = C, then ABr=CrABr = Cr for every rr, so a correct product is always accepted: the error is one-sided.

Theorem (Freivalds). If AB≠CAB \ne C and rr is uniform on {0,1}n\{0, 1\}^n, then Pr⁡[ABr=Cr]≤12\Pr[ABr = Cr] \le \frac12.

Proof. Let D=AB−C≠0D = AB - C \ne 0, and pick an entry dij≠0d_{ij} \ne 0. If Dr=0Dr = 0, then in particular

(Dr)i=dijrj+∑l≠jdilrl=0,sorj=−1dij∑l≠jdilrl.(Dr)_i = d_{ij} r_j + \sum_{l \ne j} d_{il} r_l = 0, \qquad\text{so}\qquad r_j = -\frac{1}{d_{ij}} \sum_{l \ne j} d_{il} r_l .

Use the principle of deferred decisions: reveal all coordinates rlr_l with l≠jl \ne j first. Whatever they are, the right-hand side is a fixed number, and rjr_j, still uniform on {0,1}\{0, 1\}, equals it with probability at most 1/21/2. Averaging over the revealed coordinates gives the claim. □\square

The same argument with each rlr_l uniform on a set SS of ss values (over a field, so division works) gives Pr⁡[ABr=Cr]≤1/s\Pr[ABr = Cr] \le 1/s. Working modulo a prime qq with r∈{0,…,q−1}nr \in \{0, \ldots, q - 1\}^n therefore gives error 1/q1/q per round with numbers that never exceed qq. That is the degree-1 case of the Schwartz-Zippel lemma.

The bound is tight, and often pessimistic

When DD has a single nonzero entry dijd_{ij}, a round detects it exactly when rj=1r_j = 1: probability exactly 1/21/2. When the error is spread out, detection is much more likely: Dr=0Dr = 0 requires rr to lie in the null space of DD, and if DD has rank ρ\rho, at most 2n−ρ2^{n - \rho} of the 2n2^n vectors do (by the same deferred-decisions argument on ρ\rho independent rows), so the escape probability is at most 2−ρ2^{-\rho}.

python · try it yourself
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 DD of rank 1, yet it is caught almost always: every entry of its nonzero row dd is positive, so d⋅r=0d \cdot r = 0 forces r=0r = 0, which has probability 2−122^{-12} for n=12n = 12. The rank bound 2−ρ2^{-\rho} is only an upper bound; what matters is how many vectors rr the error can hide behind. The worst case 1/21/2 is reached only by very special errors, such as a single wrong entry.

Counting the work

The program counts multiplications: 3n23n^2 per Freivalds round against n3n^3 for recomputing the product. With k=20k = 20 rounds (error at most 2−20<10−62^{-20} < 10^{-6}) the check is cheaper than recomputation once n>60n > 60.

python · try it yourself
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 q=231−1q = 2^{31} - 1, with rr uniform on {0,…,q−1}n\{0, \ldots, q - 1\}^n, so one round errs with probability at most 1/q1/q. Products of two residues fit in 64 bits. The program verifies a correct product of two 150×150150 \times 150 matrices and one with a single corrupted entry, counting multiplications; the random stream comes from a fixed-seed std::mt19937.

cpp · try it yourself
#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 3n2=67 5003n^2 = 67\,500 multiplications instead of n3=3 375 000n^3 = 3\,375\,000.

Test yourself

What does one round of Freivalds' algorithm cost for n×nn \times n matrices?

  1. O(n)O(n)
  2. O(n2)O(n^2)
  3. O(n2.37)O(n^{2.37})
  4. O(n3)O(n^3)

If AB≠CAB \ne C, with what probability does one round with r∈{0,1}nr \in \{0, 1\}^n wrongly accept?

  1. At most 1/21/2
  2. At most 1/n1/n
  3. Exactly 1/21/2 always
  4. At most 2−n2^{-n} always

Which kind of error does Freivalds' algorithm have?

  1. Two-sided
  2. One-sided: it may accept a wrong product, but never rejects a correct one
  3. One-sided: it may reject a correct product
  4. None

Working modulo a prime qq with rr uniform on {0,…,q−1}n\{0, \ldots, q-1\}^n, what is the error per round?

  1. At most 1/21/2
  2. At most 1/q1/q
  3. At most n/qn/q
  4. At most 2−q2^{-q}