Algorithmresearch
SAT-based design debugging
Also called Smith-Veneris debugging, SAT-based error localization.
Smith, Veneris and coauthors' method that adds a multiplexer at each suspect gate and asks a SAT solver which few gates can be changed to fix all failing traces.
- Time
- O(G^k 2^V V) worst
- Space
- O(V) extra
- Where
- G = the number of suspect gates; V = the number of variables and literals of the debug instance; k = the size of the corrections found
- Model
- Word RAM
- Properties
- completedeterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alexander Smith, Andreas Veneris, Moayad Fahim Ali, Anastasios Viglas, 2005
SAT-based design debugging finds where a circuit that fails a set of tests can be changed so that it passes them. Smith, Veneris, Ali and Viglas (2005) build one formula. It holds a copy of the circuit for each test, with the inputs fixed to the test vector and the outputs fixed to the expected values. At each suspect gate a multiplexer chooses between the gate's own value and a free value. The select line of the multiplexer is one variable shared by all copies, and a cardinality constraint allows at most selects to be true. A model of the formula names gates and gives new values for them in each test that make every test pass. The gates are the places to look for the bug. Blocking each answer and solving again lists all sets of gates, and raising from 0 finds the least number of changes that explains the failures. The proof on this page shows that a select set makes the formula satisfiable exactly when those gates have new values that fix all tests.
In plain words
A circuit gives the wrong answer on some tests. You want to know which gates to look at.
Put a switch at every gate. When a switch is on, the gate's output is cut and replaced by any value you like. When it is off, the gate works as normal. Now ask a SAT solver: with at most one switch on, is there a choice of replacement values that makes every test give the right answer? Each switch is the same in all tests, but the replacement value may differ from test to test.
If the answer is yes, the switch that is on names a gate that can explain all the failures. Forbid that answer and ask again to find the others. If no single gate works, allow two switches, and so on.
The problem
Given a combinational circuit with gates in topological order, a set of suspect gates, tests for , each an input vector and the expected outputs, and a bound . A set has correction values if there are values for such that, for every test , simulating on with each forced to gives . Find the least for which a set of suspects has correction values, and all such sets of size . When the test inputs are pairwise distinct, has correction values exactly when the gates of can be replaced by new logic of the primary inputs that passes all tests. Usually the tests are the failing vectors that verification found, often with some passing vectors added so that the fix does not break them.
The algorithm
SAT-DEBUG(C, Σ, tests, k_max)- 1
for each test (v_j, y_j) do make a copy C_j of the circuit, with units for the inputs v_j and the expected outputs y_j - 2
for each suspect g in Σ do replace g in C_j by MUX(s_g, w_{g,j}, op_g(fanins in C_j)), with s_g shared and w_{g,j} free - 3
write every other gate of C_j with its Tseitin clauses; F ← the conjunction of all copies - 4
for k ← 0 to k_max do - 5
F_k ← F ∧ (at most k of the selects s_g are true), by a sequential counter - 6
while F_k has a model M do - 7
S ← {g in Σ : s_g is true in M} - 8
report S; add the clause ∨_{g in S} ¬s_g to F_k ▷ block S and its supersets - 9
if some S was reported then return k and the reported sets - 10
return no set of at most k_max suspects explains the tests
The multiplexer of line L2 is four clauses: and , where is the gate's own value in copy . Line L5 uses the sequential counter of Sinz. The code of this page calls a small DPLL solver that decides the selects first, false before true.
Example
The intended circuit has inputs and gates , , and , with outputs and . The implementation has the bug . It fails on the four vectors with . Take the two failing tests and .
| test | expected | circuit |
|---|---|---|
With all four gates suspect, the instance has 36 variables and 72 clauses. For the units propagate through both copies, and the outputs contradict the expected values, so line L6 finds no model. For :
- . With , both copies compute the intended values. This is the model that line L6 finds, and line L8 blocks .
- alone. It can fix in both tests, but in the first test stays wrong.
- alone. It fixes , but stays wrong in both tests.
- alone. Setting in the first test fixes , but stays wrong.
After the blocking clause the formula is unsatisfiable, so the answer is and the one set , with the correction value 1 in both tests. If were asked, the sets and would also explain the tests, besides the supersets of .
Correctness
Two facts carry the proof. First, for a fixed select set , a model of the formula is the same thing as a set of correction values for : by induction over the topological order, each variable of copy equals the value of its signal in the simulation of test with the gates of forced to , and the output units say that this simulation passes. Second, correction values are monotone: a set that works stays working when gates are added, by forcing each added gate to the value it has anyway. So at the first with a model, every model has exactly selects true, the blocking clause of line L8 removes exactly one set, and each set of size that works is a model of all the other blocking clauses. The loop therefore lists exactly the sets of size with correction values. When the test inputs are distinct, these are exactly the sets of gates that new logic can fix for the tests. The full proof, with the Tseitin clauses and the counter, is in the proof file.
The tests compare the result with brute force on 120 random circuits of 4 inputs and 10 gates, each with one gate of the wrong type and up to 3 failing tests. The brute force tries every single gate with every vector of values over the tests. The sets agree, the real error site is in a reported set, and the correction values of each set pass the tests in simulation. On 40 circuits with two wrong gates, the least and the sets of size agree with brute force over all pairs. The Tseitin clauses of every gate type and the counter for up to 5 variables are checked against their truth tables.
Proof: The debug instance is satisfiable exactly when the selected gates can fix the tests, and the loop reports all fixes of least sizefull
Setting. The circuit has inputs , gates in topological order, each with a Boolean function of earlier signals, and a list of outputs. The tests are pairs , , of an input vector and the expected output values. is the set of suspect gates. For :
- Correction values for are values for and every test such that, for every , simulating on with the value of each replaced by gives at the outputs.
- A fix for is a family of Boolean functions , , such that the circuit , in which each is replaced by new logic that computes of the primary inputs, gives on for every test.
The debug formula of lines L1 to L3 has, for each test , a variable for every signal , unit clauses and for the outputs , the Tseitin clauses of for , and for the Tseitin clauses of and the four multiplexer clauses
which say if and otherwise. The selects are shared by all tests, and the are free.
Lemma 1 (Tseitin clauses). For fixed values of the inputs and the output of a gate, its clauses, with their auxiliary variables, are satisfiable if and only if .
Proof. For AND, the clauses for each input and say and . OR is dual, NAND and NOR use in place of , and NOT and BUF are two clauses of an equivalence. For XOR and XNOR, each auxiliary gets four clauses, one per row of the truth table of , which force . So the auxiliaries are determined, the last one is the XOR of all inputs, and the two final clauses say equals it or its negation. The tests check all gate types on all input values.
Theorem 2 (selects and correction values). For , together with the units for and for is satisfiable if and only if has correction values.
Proof. () Take a model and put . Fix a test and let be the simulation of on with the values of replaced by . By induction over the topological order, in the model for every signal . The inputs agree by the unit clauses. For a gate , Lemma 1 gives of the fanin variables, which agree with by induction. For , is false, so in the same way. For , . The output units then say that gives .
() Set by , for and for the other suspects, each to of test , each to of the fanin values, and the auxiliaries as in Lemma 1. The gate clauses hold by Lemma 1, the multiplexer clauses hold because for and for the other suspects, and the unit clauses hold because the inputs are and is a set of correction values.
Theorem 3 (correction values and fixes). If has a fix, it has correction values. If the input vectors are pairwise distinct, the converse holds.
Proof. Given a fix, simulate on and put . The simulation of with these replaced values computes the same values at every signal, by induction over the topological order, so it gives . Conversely, with distinct the definition , and on the other input vectors, is a function, and the same induction shows that gives on each .
Without distinct vectors the converse fails: two tests with the same inputs and different expected outputs have correction values for the set of output gates, but no circuit passes both. The tests show this case.
Lemma 4 (monotone). If has correction values and , then has correction values.
Proof. For put equal to the value of in the simulation of test with the replaced values of . Replacing a value by itself changes nothing.
Lemma 5 (sequential counter). For , the counter clauses of line L5 on with auxiliaries (, ) are satisfiable together with a 0-1 assignment of the if and only if . For they are the units , and for there are none.
Proof. The clauses are , for , and for : , , for , and , and last . Let . () Put . Each implication holds because and when . for holds as . The clause fails only if , which excludes. () In any model, is true whenever , by induction on with the implications. If , let be the index of the -th true . Then (for ), gives , and contradicts a clause.
Theorem 6 (the loop). Let be the first value of line L4 at which line L6 finds a model. Then lines L6 to L8 report, each once, exactly the sets with that have correction values, and no smaller set has correction values. If no finds a model, no set of at most suspects has correction values.
Proof. For the formula is unsatisfiable. If a set with had correction values, Theorem 2 and Lemma 5 would give a model. So no set of size below has correction values, which also proves the last claim.
At , a model has a select set with by Lemma 5, and the model itself satisfies the formula of Theorem 2 for , so has correction values. Hence . The blocking clause of line L8 excludes exactly the models whose select set contains , and among sets of size at most that is alone. So no set is reported twice. Conversely, let have size and correction values. By Theorem 2 there is a model of with select set exactly . It satisfies the counter by Lemma 5, and every blocking clause of a reported set , because gives some with false. So the loop cannot stop at line L6 before is reported. Each round adds a clause that removes the reported set, there are finitely many sets, and so the loop ends.
Corollary. With pairwise distinct test inputs, the sets of Theorem 6 are exactly the sets of suspects that have a fix for the tests (Theorem 3), and by Lemma 4 every superset of a reported set also has one. A fix for the tests need not be a fix for the specification on inputs outside the tests.
Complexity
Let be the number of gates and pins of . The instance has variables and literals: one copy of the circuit per test, two extra variables and four clauses per suspect and test, and for the counter. Building it is linear in . Each call of the solver at line L6 takes time in the worst case. The number of calls is at most plus the number of reported sets, which is at most for . Space is .
The worst case cannot be avoided in general. Deciding whether a set of at most suspects has correction values is NP-complete. It is in NP, since and can be checked by simulation. It is NP-hard by a reduction from circuit satisfiability: put a buffer with constant input 0 in front of each input of a circuit , make the buffers the suspects, and use one test with output 1 and equal to the number of inputs. Correction values are then exactly a satisfying assignment of . In practice the inputs of each copy are fixed, so unit propagation decides most of the formula once the selects are chosen.
Properties
- Deterministic. The solver decides the variables in a fixed order, so the reported sets come in a fixed order.
- Exact and complete for the tests. The reported sets are exactly the minimum-size sets of suspects with correction values. They say nothing about inputs outside the tests.
- Not a repair. The result names locations and per-test values, not new gate functions. Finding the new logic is a separate step.
Variants and improvements
- Sequential circuits. Ali, Veneris, Smith, Safarpour, Drechsler and Abadir (2004) unroll the circuit over the cycles of each failing trace, as in time-frame expansion. The select of a gate is shared by all cycles, and the free value is per cycle.
- Maximum satisfiability. Chen, Safarpour, Marques-Silva and Veneris (2010) make the hard part the test copies and each a soft clause. A correction set is then a minimal correction subset, and the least is the MaxSAT optimum. This drops the counter and allows core-guided solvers.
- Unsatisfiable cores. Without multiplexers, the gates whose clauses appear in a minimal unsatisfiable subset of the test copies are candidates, which is cheaper but coarser.
- Incremental solving. The copies do not change with . An incremental SAT solver keeps learned clauses and adds the counter and the blocking clauses with assumptions.
- Fault diagnosis. With the tests of a failing chip in place of a specification, the same formula locates defects, as in effect-cause diagnosis. Smith and coauthors treat both uses.
When to use it
Use it after verification has found failing traces and the design has a reference: a golden model, a specification, or the expected values of a regression. It is the step between the miter or simulation that says "wrong" and the engineer who has to change the RTL. It fits when the bug is in few places. Many simultaneous errors need large , and the number of candidate sets grows like . For a first ranking, cheaper path-tracing or simulation-based methods find a superset of the candidates quickly, and the SAT step then prunes them.
Pitfalls
- Too few tests. With one failing test, many gates can explain it, often every gate on the paths to the wrong outputs. Add more failing vectors, and passing vectors to keep the fix from breaking working behavior.
- Equal inputs, different outputs. The free values are per test, so two tests with the same input vector and conflicting expected outputs still give a model. No circuit passes such tests. Remove duplicates before encoding.
- Equivalent locations. A gate and a buffer chain or a gate with one fanout in front of it give the same corrections. The reported sets are candidates, not one true site.
- Per-test values may not be a gate. The new values may not be a function of the gate's own fanins, so a reported set does not mean that a change of gate type fixes the bug.
- A fix for the tests only. The reported sets pass the given tests. Check the repaired design against the full specification, for example with an equivalence check.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-design-debugging/. The authors are listed in prov/1D5R8Y.jsonl.
"""A small DPLL solver with two watched literals and chronological backtracking.
Literals are nonzero integers, -v is the negation of v. Clauses can be added
between calls of solve, which is enough for enumeration with blocking clauses.
"""
from __future__ import annotations
from typing import Iterable, Optional, Sequence
class Solver:
def __init__(self) -> None:
self.nvars = 0
self.clauses: list[list[int]] = []
self.units: list[int] = []
self.empty = False
self.order: list[int] = [] # decision order; others follow by index
def new_var(self) -> int:
self.nvars += 1
return self.nvars
def add_clause(self, lits: Iterable[int]) -> None:
c = list(dict.fromkeys(lits))
if any(-l in c for l in c):
return # a tautology
if not c:
self.empty = True
elif len(c) == 1:
self.units.append(c[0])
else:
self.clauses.append(c)
def solve(self, assumptions: Sequence[int] = ()) -> Optional[dict[int, bool]]:
if self.empty:
return None
n = self.nvars
val: list[Optional[bool]] = [None] * (n + 1)
watches: dict[int, list[int]] = {}
for ci, c in enumerate(self.clauses):
watches.setdefault(c[0], []).append(ci)
watches.setdefault(c[1], []).append(ci)
trail: list[int] = []
def value(lit: int) -> Optional[bool]:
v = val[abs(lit)]
return None if v is None else (v if lit > 0 else not v)
def enqueue(lit: int) -> bool:
v = value(lit)
if v is not None:
return v
val[abs(lit)] = lit > 0
trail.append(lit)
return True
def propagate(qhead: int) -> bool:
"""Unit propagation from trail[qhead:]; False on a conflict."""
while qhead < len(trail):
false_lit = -trail[qhead]
qhead += 1
ws = watches.get(false_lit, [])
keep: list[int] = []
ok = True
for i, ci in enumerate(ws):
if not ok:
keep.append(ci)
continue
c = self.clauses[ci]
if c[0] == false_lit:
c[0], c[1] = c[1], c[0]
if value(c[0]) is True:
keep.append(ci)
continue
for k in range(2, len(c)):
if value(c[k]) is not False:
c[1], c[k] = c[k], c[1]
watches.setdefault(c[1], []).append(ci)
break
else:
keep.append(ci)
if not enqueue(c[0]):
ok = False
watches[false_lit] = keep
if not ok:
return False
return True
for lit in list(self.units) + list(assumptions):
if not enqueue(lit):
return None
if not propagate(0):
return None
root = len(trail)
order = list(dict.fromkeys(self.order + list(range(1, n + 1))))
decisions: list[tuple[int, int, bool]] = [] # (trail length, literal, flipped)
qhead = root
while True:
if propagate(qhead):
qhead = len(trail)
var = next((v for v in order if val[v] is None), None)
if var is None:
return {v: bool(val[v]) for v in range(1, n + 1)}
decisions.append((len(trail), -var, False))
enqueue(-var)
continue
while decisions and decisions[-1][2]:
start, _, _ = decisions.pop()
for lit in trail[start:]:
val[abs(lit)] = None
del trail[start:]
if not decisions:
return None
start, lit, _ = decisions.pop()
for l in trail[start:]:
val[abs(l)] = None
del trail[start:]
decisions.append((start, -lit, True))
enqueue(-lit)
qhead = start
sat_based_design_debugging.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-design-debugging/. The authors are listed in prov/1D5R8Y.jsonl.
"""SAT-based design debugging with correction multiplexers.
A circuit is a list of gates in topological order. Each gate is
(name, op, fanins), with op in AND, OR, XOR, NAND, NOR, XNOR, NOT, BUF, and the
fanins are names of inputs or of earlier gates. A test is (inputs, expected),
two dicts from names to 0 or 1.
debug() returns every set of at most k_max suspect gates, of the least size
that works, such that new values at those gates make every test give its
expected outputs.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Sequence
from dpll import Solver
Gate = tuple[str, str, tuple[str, ...]]
Test = tuple[dict[str, int], dict[str, int]]
OPS = {
"AND": lambda xs: int(all(xs)),
"OR": lambda xs: int(any(xs)),
"XOR": lambda xs: sum(xs) & 1,
"NAND": lambda xs: 1 - int(all(xs)),
"NOR": lambda xs: 1 - int(any(xs)),
"XNOR": lambda xs: 1 - (sum(xs) & 1),
"NOT": lambda xs: 1 - xs[0],
"BUF": lambda xs: xs[0],
}
@dataclass
class Circuit:
inputs: list[str]
gates: list[Gate]
outputs: list[str]
def simulate(c: Circuit, inputs: dict[str, int], override: Optional[dict[str, int]] = None) -> dict[str, int]:
"""Values of all signals; override replaces the values of some gates."""
v = dict(inputs)
for name, op, fanins in c.gates:
if override and name in override:
v[name] = override[name]
else:
v[name] = OPS[op]([v[f] for f in fanins])
return v
def gate_clauses(s: Solver, op: str, out: int, ins: list[int]) -> None:
"""Tseitin clauses of out = op(ins)."""
if op in ("NOT", "BUF"):
a = ins[0] if op == "BUF" else -ins[0]
s.add_clause([-out, a])
s.add_clause([out, -a])
return
if op in ("XOR", "XNOR"):
acc = ins[0]
for x in ins[1:]:
t = s.new_var()
for a, b, r in ((1, 1, -1), (1, -1, 1), (-1, 1, 1), (-1, -1, -1)):
s.add_clause([-a * acc, -b * x, r * t])
acc = t
sign = 1 if op == "XOR" else -1
s.add_clause([-out, sign * acc])
s.add_clause([out, -sign * acc])
return
neg = op in ("NAND", "NOR")
o = -out if neg else out
if op in ("AND", "NAND"):
for x in ins:
s.add_clause([-o, x])
s.add_clause([o] + [-x for x in ins])
else:
for x in ins:
s.add_clause([o, -x])
s.add_clause([-o] + list(ins))
def at_most(s: Solver, xs: list[int], k: int) -> None:
"""Sinz's sequential counter for sum(xs) <= k."""
n = len(xs)
if k >= n:
return
if k == 0:
for x in xs:
s.add_clause([-x])
return
r = [[s.new_var() for _ in range(k)] for _ in range(n - 1)]
s.add_clause([-xs[0], r[0][0]])
for j in range(1, k):
s.add_clause([-r[0][j]])
for i in range(1, n - 1):
s.add_clause([-xs[i], r[i][0]])
s.add_clause([-r[i - 1][0], r[i][0]])
for j in range(1, k):
s.add_clause([-xs[i], -r[i - 1][j - 1], r[i][j]])
s.add_clause([-r[i - 1][j], r[i][j]])
s.add_clause([-xs[i], -r[i - 1][k - 1]])
s.add_clause([-xs[n - 1], -r[n - 2][k - 1]])
def debug_instance(c: Circuit, tests: Sequence[Test], suspects: Sequence[str]):
"""The CNF of lines L1 to L3. Returns the solver, the select variables, and
for each test the map from signal names to variables."""
s = Solver()
select = {g: s.new_var() for g in suspects}
s.order = list(select.values())
copies = []
for inputs, expected in tests: # @line L1
var = {x: s.new_var() for x in c.inputs}
for x in c.inputs:
s.add_clause([var[x] if inputs[x] else -var[x]])
for name, op, fanins in c.gates:
out = s.new_var()
if name in select: # @line L2
orig, w, sel = s.new_var(), s.new_var(), select[name]
gate_clauses(s, op, orig, [var[f] for f in fanins])
s.add_clause([-sel, -w, out])
s.add_clause([-sel, w, -out])
s.add_clause([sel, -orig, out])
s.add_clause([sel, orig, -out])
else:
gate_clauses(s, op, out, [var[f] for f in fanins]) # @line L3
var[name] = out
for y in c.outputs:
s.add_clause([var[y] if expected[y] else -var[y]])
copies.append(var)
return s, select, copies
def debug(c: Circuit, tests: Sequence[Test], k_max: int,
suspects: Optional[Sequence[str]] = None) -> tuple[int, list[frozenset[str]]]:
"""(k, all correction sets of size k) for the least k <= k_max that has one,
or (-1, []) if there is none."""
suspects = list(suspects) if suspects is not None else [g[0] for g in c.gates]
base, select, _ = debug_instance(c, tests, suspects)
for k in range(k_max + 1): # @line L4
s = Solver()
s.nvars, s.clauses, s.units, s.order = base.nvars, [list(x) for x in base.clauses], list(base.units), base.order
at_most(s, list(select.values()), k) # @line L5
found = []
while (model := s.solve()) is not None: # @line L6
sol = frozenset(g for g, v in select.items() if model[v]) # @line L7
found.append(sol)
s.add_clause([-select[g] for g in sol]) # @line L8
if found: # @line L9
return k, found
return -1, [] # @line L10
def correction_values(c: Circuit, tests: Sequence[Test], fix: frozenset[str]) -> Optional[list[dict[str, int]]]:
"""Values at the gates of fix, one dict per test, that make all tests pass."""
s, select, copies = debug_instance(c, tests, sorted(fix))
model = s.solve([select[g] for g in fix])
if model is None:
return None
return [{g: int(model[var[g]]) for g in fix} for var in copies]
test_sat_based_design_debugging.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-design-debugging/. The authors are listed in prov/1D5R8Y.jsonl.
import random
from itertools import combinations, product
from dpll import Solver
from sat_based_design_debugging import OPS, Circuit, at_most, correction_values, debug, simulate
BINARY = ("AND", "OR", "XOR", "NAND", "NOR", "XNOR")
# ------------------------------------------------------------------ references
def passes(c, tests, override_per_test=None):
for j, (inputs, expected) in enumerate(tests):
v = simulate(c, inputs, override_per_test[j] if override_per_test else None)
if any(v[y] != expected[y] for y in c.outputs):
return False
return True
def brute_force_fixes(c, tests, size):
"""All gate sets of the given size where some values per test fix every test."""
names = [g[0] for g in c.gates]
out = []
for fix in combinations(names, size):
for bits in product((0, 1), repeat=size * len(tests)):
over = [dict(zip(fix, bits[j * size:(j + 1) * size])) for j in range(len(tests))]
if passes(c, tests, over):
out.append(frozenset(fix))
break
return out
def random_circuit(rng, n_in, n_gates, n_out):
inputs = [f"i{j}" for j in range(n_in)]
gates = []
for j in range(n_gates):
pool = inputs + [g[0] for g in gates]
if rng.random() < 0.15:
gates.append((f"g{j}", "NOT", (rng.choice(pool),)))
else:
a, b = rng.sample(pool, 2)
gates.append((f"g{j}", rng.choice(BINARY), (a, b)))
return Circuit(inputs, gates, [g[0] for g in gates[-n_out:]])
def all_vectors(c):
return [dict(zip(c.inputs, bits)) for bits in product((0, 1), repeat=len(c.inputs))]
def make_tests(golden, vectors):
return [(v, {y: simulate(golden, v)[y] for y in golden.outputs}) for v in vectors]
def mutate(rng, c, count):
"""A copy of c with the type of count random two-input gates changed."""
gates = list(c.gates)
sites = rng.sample([j for j, g in enumerate(gates) if g[1] != "NOT"], count)
for j in sites:
name, op, fanins = gates[j]
gates[j] = (name, rng.choice([o for o in BINARY if o != op]), fanins)
return Circuit(c.inputs, gates, c.outputs), {gates[j][0] for j in sites}
# ----------------------------------------------------------------------- tests
EXAMPLE_GOLDEN = Circuit(["a", "b", "c"],
[("g1", "OR", ("a", "b")), ("g2", "AND", ("b", "c")),
("g3", "XOR", ("g1", "c")), ("g4", "OR", ("g1", "g2"))],
["g3", "g4"])
EXAMPLE_BUGGY = Circuit(["a", "b", "c"],
[("g1", "AND", ("a", "b")), ("g2", "AND", ("b", "c")),
("g3", "XOR", ("g1", "c")), ("g4", "OR", ("g1", "g2"))],
["g3", "g4"])
def test_example_of_the_page():
failing = [v for v in all_vectors(EXAMPLE_BUGGY)
if any(simulate(EXAMPLE_BUGGY, v)[y] != simulate(EXAMPLE_GOLDEN, v)[y] for y in ("g3", "g4"))]
assert [(v["a"], v["b"], v["c"]) for v in failing] == [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
tests = make_tests(EXAMPLE_GOLDEN, failing[:2])
k, fixes = debug(EXAMPLE_BUGGY, tests, 2)
assert k == 1 and set(fixes) == {frozenset({"g1"})}
assert correction_values(EXAMPLE_BUGGY, tests, frozenset({"g1"})) == [{"g1": 1}, {"g1": 1}]
# With one test only, the two outputs can also be fixed at g3 and g4 together, but not by one other gate.
k, fixes = debug(EXAMPLE_BUGGY, tests[:1], 2)
assert k == 1 and set(fixes) == {frozenset({"g1"})}
def test_tseitin_gates_and_counter():
for op in OPS:
arity = 1 if op in ("NOT", "BUF") else 3
for bits in product((0, 1), repeat=arity):
s = Solver()
ins = [s.new_var() for _ in bits]
out = s.new_var()
from sat_based_design_debugging import gate_clauses
gate_clauses(s, op, out, ins)
want = OPS[op](list(bits))
units = [x if b else -x for x, b in zip(ins, bits)]
assert s.solve(units + [out if want else -out]) is not None
assert s.solve(units + [-out if want else out]) is None
for n, k in product(range(1, 6), range(0, 6)):
for bits in product((0, 1), repeat=n):
s = Solver()
xs = [s.new_var() for _ in range(n)]
at_most(s, xs, k)
ok = s.solve([x if b else -x for x, b in zip(xs, bits)]) is not None
assert ok == (sum(bits) <= k)
def test_single_gate_debug_matches_brute_force():
rng = random.Random(1606)
checked = 0
while checked < 120:
golden = random_circuit(rng, 4, 10, 3)
buggy, sites = mutate(rng, golden, 1)
failing = [v for v in all_vectors(golden) if simulate(golden, v) != simulate(buggy, v)
and any(simulate(golden, v)[y] != simulate(buggy, v)[y] for y in golden.outputs)]
if not failing:
continue
rng.shuffle(failing)
tests = make_tests(golden, failing[:3])
k, fixes = debug(buggy, tests, 1)
assert k == 1
assert set(fixes) == set(brute_force_fixes(buggy, tests, 1))
assert sites <= set().union(*fixes) # the real error site is found
for fix in fixes: # each reported set really fixes the tests
over = correction_values(buggy, tests, fix)
assert passes(buggy, tests, over)
checked += 1
def test_two_errors_against_brute_force():
rng = random.Random(2005)
checked = 0
while checked < 40:
golden = random_circuit(rng, 3, 8, 2)
buggy, sites = mutate(rng, golden, 2)
failing = [v for v in all_vectors(golden)
if any(simulate(golden, v)[y] != simulate(buggy, v)[y] for y in golden.outputs)]
if not failing:
continue
tests = make_tests(golden, failing[:3])
k, fixes = debug(buggy, tests, 2)
assert k in (1, 2)
assert brute_force_fixes(buggy, tests, k - 1) == []
assert set(fixes) == set(brute_force_fixes(buggy, tests, k))
if k == 2:
assert all(len(f) == 2 for f in fixes)
checked += 1
def test_passing_circuit_needs_no_fix_and_impossible_tests_have_none():
rng = random.Random(3)
golden = random_circuit(rng, 4, 10, 2)
tests = make_tests(golden, all_vectors(golden))
assert debug(golden, tests, 2) == (0, [frozenset()])
# Two tests with the same inputs and different expected outputs: no circuit
# can pass both, but the instance gives each test its own correction values,
# so it is satisfiable. The theorem needs distinct input vectors.
v, e = tests[0]
flipped = {y: 1 - b for y, b in e.items()}
k, fixes = debug(golden, [(v, e), (v, flipped)], 3)
assert k >= 1 and set(fixes) == set(brute_force_fixes(golden, [(v, e), (v, flipped)], k))
# With a bound below the number of outputs that must change, there is no answer.
assert debug(golden, [(v, e), (v, flipped)], k - 1) == (-1, [])
def test_suspect_list_restricts_the_answer():
tests = make_tests(EXAMPLE_GOLDEN, [{"a": 0, "b": 1, "c": 0}, {"a": 1, "b": 0, "c": 1}])
k, fixes = debug(EXAMPLE_BUGGY, tests, 2, suspects=["g2", "g3", "g4"])
assert k == 2 and frozenset({"g3", "g4"}) in fixes
assert set(fixes) == set(f for f in brute_force_fixes(EXAMPLE_BUGGY, tests, 2) if "g1" not in f)
History
Smith, Veneris, Ali and Viglas presented the SAT formulation of logic debugging and fault diagnosis with correction multiplexers and published the journal version in 2005. Ali and coauthors extended it to sequential circuits at ICCAD 2004. Safarpour, Chen, Marques-Silva and Veneris then recast it as maximum satisfiability, with the journal paper in 2010. Later work added abstraction and refinement, hierarchical debugging, and unsatisfiable cores to handle large designs.
References
- A. Smith, A. Veneris, M. F. Ali and A. Viglas, Fault diagnosis and logic debugging using Boolean satisfiability, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 24(10), 1606 to 1621, 2005, the copies of the circuit per test vector, the multiplexer with a select line and a free value at each suspect, the bound on the number of active selects, and the enumeration of all solutions with blocking clauses
- M. F. Ali, A. Veneris, A. Smith, S. Safarpour, R. Drechsler and M. Abadir, Debugging sequential circuits using Boolean satisfiability, IEEE/ACM International Conference on Computer-Aided Design (ICCAD 2004), 204 to 209, 2004, the extension to sequential circuits by unrolling the circuit over the clock cycles of each failing trace, with one select per suspect shared by all cycles
- Y. Chen, S. Safarpour, J. Marques-Silva and A. Veneris, Automated design debugging with maximum satisfiability, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 29(11), 1804 to 1817, 2010, debugging as maximum satisfiability, in which the correction sets are the minimal correction subsets of soft constraints on the suspects
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 1D5R8Y Edit this page History Report an error Markdown