The Algorithmic Local Lemma: Moser-Tardos Resampling
The Lovász Local Lemma proves that an assignment avoiding all bad events exists, but the probability that a random assignment works can be exponentially small. For 35 years constructive versions existed only for special cases and with weaker constants (Beck, 1991, was the first). Then Robin Moser (2009) found an astonishingly simple algorithm for -SAT, and Moser and Tardos (2010) extended it to the whole variable setting: resample the variables of any violated event, and repeat. This lesson states the algorithm and its guarantee, implements it for -SAT, and sketches why it works.
The algorithm
The variable setting: there are independent random variables , and each bad event is determined by a subset of them. Two events are neighbours when their variable sets intersect.
MOSER-TARDOS(variables P, events A_0 .. A_{m-1})
0 draw every variable P_j independently from its distribution
1 while some event A_i holds under the current values
2 choose any such i // any rule works, even an adversarial one
3 draw fresh independent values for the variables in vbl(A_i)
4 return the current values // no bad event holdsTheorem (Moser and Tardos, 2010). Suppose there are with for all , where is the set of events sharing a variable with . Then the algorithm terminates with probability 1, and the expected number of times it resamples is at most . In total,
In the symmetric case , the choice gives at most expected resamplings per event and at most overall. So the LLL condition, which only promised existence, actually guarantees an expected linear number of cheap repair steps. The bound holds whichever violated event is chosen in line 2.
Moser-Tardos for -SAT
For a -CNF formula the variables are the Boolean variables, the events are "clause is violated", and resampling a clause means re-flipping its variables. The implementation keeps the set of violated clauses up to date: after resampling, only clauses that share a variable with the resampled clause can change. The instance is a 6-CNF formula with 960 variables, each occurring in 3 clauses, so the LLL condition holds (). A random assignment satisfies it with probability only about .
import random
from math import e
def lll_instance(n, k, occ, rng):
clauses = []
for _ in range(occ):
perm = list(range(n))
rng.shuffle(perm)
clauses += [[(v, rng.random() < 0.5) for v in perm[i:i + k]] for i in range(0, n, k)]
return clauses
def moser_tardos(n, clauses, rng):
occurs = [[] for _ in range(n)]
for i, C in enumerate(clauses):
for v, _ in C:
occurs[v].append(i)
a = [rng.random() < 0.5 for _ in range(n)]
violated = lambda i: all(a[v] != want for v, want in clauses[i])
bad = {i for i in range(len(clauses)) if violated(i)}
initially_bad = len(bad)
resamplings = 0
while bad:
i = min(bad) # the rule does not matter for the theorem
for v, _ in clauses[i]:
a[v] = rng.random() < 0.5
resamplings += 1
for v, _ in clauses[i]: # only neighbours can change status
for j in occurs[v]:
if violated(j):
bad.add(j)
else:
bad.discard(j)
return a, resamplings, initially_bad
rng = random.Random(30)
n, k, occ = 960, 6, 3
clauses = lll_instance(n, k, occ, rng)
m = len(clauses)
vs = [{v for v, _ in C} for C in clauses]
occurs = [[] for _ in range(n)]
for i, s in enumerate(vs):
for v in s:
occurs[v].append(i)
d = max(len({j for v in s for j in occurs[v]}) - 1 for s in vs)
print(f"{m} clauses, k = {k}, d = {d}, e p (d + 1) = {e * 2 ** -k * (d + 1):.3f}, bound m/d = {m / d:.1f}")
counts = []
for run in range(20):
a, r, initially_bad = moser_tardos(n, clauses, rng)
assert all(any(a[v] == w for v, w in C) for C in clauses)
counts.append(r)
if run < 3:
print(f"run {run}: {initially_bad} clauses violated at the start, {r} resamplings, satisfied")
print(f"20 runs: mean {sum(counts) / len(counts):.1f} resamplings, max {max(counts)}")480 clauses, k = 6, d = 12, e p (d + 1) = 0.552, bound m/d = 40.0
run 0: 7 clauses violated at the start, 6 resamplings, satisfied
run 1: 6 clauses violated at the start, 8 resamplings, satisfied
run 2: 12 clauses violated at the start, 12 resamplings, satisfied
20 runs: mean 7.8 resamplings, max 12
The algorithm needs about as many resamplings as there are initially violated clauses: a repair rarely breaks a neighbouring clause (and sometimes fixes one). The average stays well below the guarantee .
In C++
The same resampling loop in C++, with a fixed-seed std::mt19937; the instance is built the same way but from a different random stream, so the counts differ from Python's. Violated clauses are kept in a std::set, whose smallest element is resampled.
#include <algorithm>
#include <cstdio>
#include <random>
#include <set>
#include <vector>
struct Lit { int var; bool want; };
int main() {
std::mt19937 rng(30);
const int n = 960, k = 6, occ = 3;
std::vector<std::vector<Lit>> clauses;
std::vector<int> perm(n);
for (int r = 0; r < occ; ++r) {
for (int i = 0; i < n; ++i) perm[i] = i;
for (int i = n - 1; i > 0; --i) std::swap(perm[i], perm[rng() % (i + 1)]); // Fisher-Yates
for (int i = 0; i < n; i += k) {
std::vector<Lit> c;
for (int j = i; j < i + k; ++j) c.push_back({perm[j], (rng() & 1) == 1});
clauses.push_back(c);
}
}
const int m = clauses.size();
std::vector<std::vector<int>> occurs(n);
for (int i = 0; i < m; ++i)
for (const Lit& l : clauses[i]) occurs[l.var].push_back(i);
long long total = 0;
int worst = 0;
for (int run = 0; run < 20; ++run) {
std::vector<bool> a(n);
for (int v = 0; v < n; ++v) a[v] = rng() & 1;
auto violated = [&](int i) {
for (const Lit& l : clauses[i]) if (a[l.var] == l.want) return false;
return true;
};
std::set<int> bad;
for (int i = 0; i < m; ++i) if (violated(i)) bad.insert(i);
int resamplings = 0;
while (!bad.empty()) {
int i = *bad.begin();
for (const Lit& l : clauses[i]) a[l.var] = rng() & 1;
++resamplings;
for (const Lit& l : clauses[i])
for (int j : occurs[l.var]) {
if (violated(j)) bad.insert(j); else bad.erase(j);
}
}
for (int i = 0; i < m; ++i) if (violated(i)) std::printf("bug\n");
total += resamplings;
worst = std::max(worst, resamplings);
}
std::printf("%d clauses: 20 runs, mean %.1f resamplings, max %d, all satisfied\n", m, total / 20.0, worst);
}480 clauses: 20 runs, mean 7.6 resamplings, max 16, all satisfied
Why it works: witness trees (sketch)
The full proof is short but subtle; here is its structure. Fix the sequence of random values the algorithm will ever draw for each variable in advance (a "resampling table"). Every resampling step , of an event , gets a witness tree: build it backwards in time from step , attaching each earlier resampled event that shares a variable with an event already in the tree as a child of the deepest such node. Two facts drive the proof.
- Each witness tree is unlikely. A tree occurs only if, for every node, the event at that node really held when it was resampled, and those checks read distinct entries of the resampling table. Hence .
- Few trees are likely in total. Summing over all trees rooted at is bounded by the probability that a Galton-Watson branching process generates them, in which a node labelled gets each neighbour as a child with probability . Under the LLL condition this gives at most , and distinct resamplings of have distinct witness trees.
For -SAT, Moser's original argument was an entropy compression proof: if the algorithm ran for a long time, the random bits it consumed could be reconstructed from a short log of which clauses were fixed, compressing random bits below their entropy, which is impossible. Both arguments are in Moser and Tardos, "A constructive proof of the general Lovász Local Lemma", Journal of the ACM 57 (2010).
Beyond the guarantee
The theorem needs the LLL condition; without it, the algorithm may loop forever on an unsatisfiable formula. Still, resampling is a decent heuristic far outside the LLL regime. The program runs it on random 3-CNF formulas with variables and clauses. Up to it succeeds quickly; at it already struggles, and at it fails within its budget, although random formulas of that density are satisfiable with probability tending to 1 as grows (the satisfiability threshold is near ).
import random
def resample_3sat(n, alpha, rng, budget):
m = int(alpha * n)
clauses = [[(v, rng.random() < 0.5) for v in rng.sample(range(n), 3)] for _ in range(m)]
occurs = [[] for _ in range(n)]
for i, C in enumerate(clauses):
for v, _ in C:
occurs[v].append(i)
a = [rng.random() < 0.5 for _ in range(n)]
violated = lambda i: all(a[v] != w for v, w in clauses[i])
bad = {i for i in range(m) if violated(i)}
steps = 0
while bad and steps < budget:
i = min(bad)
for v, _ in clauses[i]:
a[v] = rng.random() < 0.5
steps += 1
for v, _ in clauses[i]:
for j in occurs[v]:
(bad.add if violated(j) else bad.discard)(j)
return (steps if not bad else None)
rng = random.Random(31)
n, budget = 80, 1500
for alpha in [1.5, 2.0, 2.5, 3.0, 3.5]:
res = [resample_3sat(n, alpha, rng, budget) for _ in range(4)]
ok = [r for r in res if r is not None]
mean = f"{sum(ok) / len(ok):7.1f}" if ok else " -"
print(f"alpha = {alpha}: solved {len(ok)}/4 within {budget} resamplings, mean steps when solved {mean}")alpha = 1.5: solved 4/4 within 1500 resamplings, mean steps when solved 29.8
alpha = 2.0: solved 4/4 within 1500 resamplings, mean steps when solved 58.8
alpha = 2.5: solved 4/4 within 1500 resamplings, mean steps when solved 170.5
alpha = 3.0: solved 1/4 within 1500 resamplings, mean steps when solved 237.0
alpha = 3.5: solved 0/4 within 1500 resamplings, mean steps when solved -
The LLL condition for 3-SAT would require each clause to meet at most one other clause (), far sparser than any of these formulas. The witness-tree analysis is tight only in the worst case; in practice the region where resampling works is much larger.
Test yourself
What does one step of the Moser-Tardos algorithm do?
- Flips one random variable of the whole instance
- Chooses a violated event and draws fresh values for all variables that event depends on
- Restarts with a completely new random assignment
- Solves a linear program
Under the symmetric condition with events, what is the bound on the expected total number of resamplings?
Does the Moser-Tardos guarantee depend on which violated event is chosen in each step?
- Yes, it must be chosen uniformly at random
- Yes, it must be the one violated longest
- No, the bound holds for any selection rule
- Only the first violated event may be chosen
What is the role of witness trees in the analysis?
- They store the satisfying assignment
- Each resampling has a distinct witness tree, and the total probability of all trees rooted at an event is bounded by
- They encode the dependency graph as a tree
- They are the recursion tree of the algorithm