Algorithmadvanced
Signal correspondence
Also called van Eijk's method, induction-based register correspondence.
Van Eijk's method that guesses classes of equal signals by simulation and refines them by induction until they are an inductive invariant that proves sequential equivalence.
- Time
- O(V^2 4^(L + 2I)) worst
- Space
- O(V^2 4^(L + 2I)) extra
- Where
- I = the number of primary inputs; L = the number of latches of the product machine; V = the number of nodes and gate inputs of the product machine
- Model
- Word RAM
- Properties
- not completedeterministicnot exactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Cornelis A. J. van Eijk, 1998
Signal correspondence proves that two sequential circuits are equivalent without exploring their states. It works on the product machine of the two circuits. Random simulation from the initial state groups the latches and gates into classes of signals that seem equal at every step. The method then splits the classes until the equalities hold in the initial state and are kept by one step of the machine. Such a set of equalities is an inductive invariant, so it holds in every reachable state. If each pair of outputs ends in one class, the circuits are equivalent. The method is sound but not complete: an equivalence that needs a fact about unreachable states is missed.
In plain words
Two versions of the same design usually still have many wires and registers that carry the same value at every clock tick. Simulate both versions together for a few hundred ticks from reset. Wires that always showed the same value go into one group.
Now test the guess. Assume that every group is right at some tick. Is every group still right one tick later, for every input? If yes, the groups are right forever, because they are right at reset. If not, the test gives a state that breaks some group. Split the groups by the values in that state and test again.
When nothing breaks, look at the outputs. Two outputs in one group are equal forever. Two outputs in different groups may still be equal, so the answer is only "unknown".
The problem
The input is a product machine with latches , inputs , initial state , next-state function , and output pairs . Each node (a latch, a gate, or a constant) has a value . The task is the sequential equivalence question: is for every reachable state and every ? Signal correspondence answers "equivalent" or "unknown".
A partition of the nodes gives the formula : all members of each class have equal values at . is inductive when holds for every , and implies for all . The method returns the coarsest inductive partition that refines the simulation classes.
The algorithm
SIGNAL-CORRESPONDENCE(P, pairs)- 1
simulate P from s₀ on random inputs; classes ← groups of nodes with equal values (the constants 0 and 1 are nodes) - 2
while some class K has a node u with u(s₀, x) ≠ rep(K)(s₀, x) for some x do - 3
split every class by the values of its nodes at (s₀, x) - 4
repeat - 5
C(s, x₀) ← ∧ over classes K and u ∈ K of [u(s, x₀) = rep(K)(s, x₀)] - 6
if some (s, x₀, x₁) with C(s, x₀) = 1 has a node u of a class K with u(δ(s, x₀), x₁) ≠ rep(K)(δ(s, x₀), x₁) then - 7
split every class by the values of its nodes at (δ(s, x₀), x₁) - 8
until line L6 found no such point - 9
if every pair (o, o') lies in one class then return "equivalent" - 10
return "unknown"
Line L1 is cheap. It only guesses, but every class it makes holds on the simulated runs. Lines L2 and L3 make the guess hold in the initial state for every input, not only for the random ones. This is the base case of the induction.
Lines L4 to L8 are the induction step. Line L5 builds the hypothesis , the conjunction of all equalities in frame 0. Line L6 asks whether some state and inputs satisfy but break an equality in frame 1, one step later. The code does this with BDDs over , and ; a SAT solver works as well. A point found there is a real counterexample to the induction, though its state may not be reachable. Line L7 splits by the frame-1 values at that point, which separates at least the node and its representative. The loop ends when the hypothesis is inductive.
The difference from k-induction is the invariant. K-induction tries to prove the output equality itself, with a longer hypothesis. Signal correspondence makes the invariant stronger instead, with the equalities of all internal signals, and keeps the induction one step long. The difference from cutpoint equivalence checking is time: there the equal nodes are equal as functions of the inputs, here they are equal only in reachable states.
Example
Circuit is a one-hot ring of three latches with initial state and next state . Its output is . Circuit has the output . The reachable states of are , and , so is always 0, and the circuits are equivalent. There are no primary inputs.
Simulation for 8 cycles gives , , , and 0 for and .
| step | classes | hypothesis | check | outcome |
|---|---|---|---|---|
| L1 | ||||
| L2 | same | at : , | no split | |
| L5, L6 | same | , that is | frame 1: ; | point |
| L7 | at : , | 1 split | ||
| L5, L6 | same | true | everywhere | no point; stop |
| L9 | and in different classes | "unknown" |
The state is not reachable, but the one-step hypothesis "" does not exclude it. This is the miss. No inductive partition at all keeps and together, as the proof shows, so a different simulation cannot help.
Add two gates and to , outside its outputs. Then line L1 gives the class , whose hypothesis says that at most one latch is 1. One step of the ring keeps that, so line L6 finds no point, there are 0 splits, and the answer is "equivalent". The extra signals made the invariant strong enough.
Correctness
Two facts are proved in the correctness proof. Soundness: if the final partition is inductive and puts each output pair in one class, then by induction over reachable states the equalities hold in every reachable state, so the circuits give the same outputs on every input sequence. Optimality: the result is the coarsest inductive partition below the simulation classes, the greatest fixed point of the refinement. The key invariant is that every inductive partition that refines the simulation classes also refines the current one; each split is forced, because a point found at line L6 satisfies the hypothesis of every finer partition. The proof also shows that the method is incomplete, with the example above.
Proof: Signal correspondence returns the coarsest inductive refinement of the simulation classes, which is sound and not completefull
Setting. The product machine has latches , primary inputs , initial state and next-state function . Each node (a latch, a gate, or one of the constants 0 and 1) has a value in state under input ; for a latch, is its bit of . A state is reachable if it is or for a reachable and some .
A partition of the nodes into classes, each with a first member , defines
holds exactly when all members of each class have equal values at , so it does not depend on the choice of representatives. The partition is inductive when
- (B) for every , and
- (S) for all .
refines , written , when every class of lies inside a class of . If , then , since asks for a subset of the equalities, and (B) for gives (B) for .
Theorem 1 (soundness). If is inductive, then holds for every reachable and every . So if each output pair lies in one class of , the two circuits give the same output sequence for every input sequence from the initial state.
Proof. Induction on the reachability of . For , (B) gives the claim. If with reachable, the hypothesis gives , and (S) gives for every . For an input sequence , the states , are reachable, so at every step .
Lemma 2 (each split is forced). Let be the current partition and any inductive partition with . Let be the result of a split at line L3 or L7. Then .
Proof. A split at line L3 uses a point and puts two nodes of a class of in the same class of exactly when their values at the point are equal. Take a class of . It lies in one class of , and by (B) for all its members have equal values at . So lies in one class of .
A split at line L7 uses a point with , and splits by the values at . Since , gives , and (S) for gives . So again all members of a class of have equal values at the point, and the class lies in one class of .
Lemma 3 (termination). Lines L2 to L3 and L4 to L8 run at most splits in total, for nodes and the partition of line L1.
Proof. A split happens only at a point where some node and the representative of its class differ. They go to different classes, so the number of classes grows by at least 1. It never exceeds . Each pass of lines L5 and L6 does a finite number of BDD checks.
Theorem 4 (greatest fixed point). The partition at line L9 is inductive, refines , and is refined by every inductive partition that refines . So it is the unique coarsest inductive partition below .
Proof. Splits only refine, so . The loop of lines L2 and L3 stops when no class has a member that differs from its representative at for any , which is (B). Later splits keep (B), because (B) passes to finer partitions. The loop of lines L4 to L8 stops when no has and a member that differs from its representative at , which is (S). So is inductive. Every inductive satisfies : it holds for , and Lemma 2 keeps it through every split. Two partitions that each refine the other are equal, so the coarsest one is unique.
In terms of fixed points: let be split by the values at every point and at every point with . Then is monotone in the refinement order, its fixed points below are the inductive partitions below , and Theorem 4 says the algorithm returns the greatest of them. It reaches it one counterexample at a time, not by computing at once.
Theorem 5 (incompleteness). There are sequentially equivalent circuits that the algorithm does not prove, for every choice of random simulation.
Proof. Let have three latches with initial state and next state , and the output . Let have no latches and the output constant 0. The reachable states of are , and , and in each, so and are sequentially equivalent. The nodes of the product are the constants 0 and 1, , and the output of (there are no inputs). We show that no inductive partition at all has and in one class. Since the algorithm returns an inductive partition (Theorem 4), it does not prove the pair, whatever is.
Let be inductive. By Theorem 1, the members of each class agree in the three reachable states. In the node is 1 and and the constant 0 are 0. In the node is 0 and the constant 1 is 1. So is alone in its class. In the same way and are alone, and the constant 1 is alone (it differs from , and the constant 0 everywhere). Suppose and share a class. That class is or , and all other classes have one member. Take , which is not reachable. There , so holds. But , where and , so fails, and (S) fails. This contradicts the choice of .
The induction fails only because of the unreachable state . A stronger hypothesis removes it: with the extra gates and in , the class says that at most one latch is 1, which is inductive.
Complexity
Let count the nodes and gate inputs of the product machine. Each split adds at least one class, so lines L3 and L7 run at most times in total. Each pass of lines L5 and L6 makes BDD applies: one equality per class member for , and one check per member. The BDDs are over variables (, , ), so each has at most nodes and each apply costs with the cache. Building the frame-0, frame-1 and initial-state BDDs once costs applies. The total is time in the worst case on the word RAM with expected constant-time hashing, and the tables hold at most one entry per step of work, which gives the same space bound.
The exponential factor is the worst case of BDDs, not the usual case. The point of the method is that the hypothesis relates two similar circuits, so its BDD, or the SAT instance in a SAT-based version, stays near the size of the circuits. No step enumerates states. With SAT in place of BDDs, each check is one call on two copies of the combinational logic, with at most calls per pass and at most passes.
Properties
- Sound: "equivalent" is always right.
- Incomplete: "unknown" does not mean different. The example above is equivalent and not proved.
- The result does not depend on the order of the checks or on which counterexample is found, because the coarsest inductive partition below the start is unique. It does depend on the simulation, but only through the start partition.
- Deterministic for a fixed seed.
Variants and improvements
- SAT-based induction. Bjesse and Claessen (FMCAD 2000) did line L6 with SAT on two time frames. Each counterexample splits the classes, as here.
- Longer induction. Assume the equalities in consecutive frames and prove them in the next. In the ring example, 3-step induction proves and 2-step induction does not: the unreachable state has and then again at , but one step later. See k-induction.
- Complemented equalities. Classes can hold nodes equal up to complement, so a latch and its inverted copy also match.
- Other invariants. Implications between signals, or the constraints found by IC3, give a stronger hypothesis when equalities are not enough.
- Synthesis. The same fixed point finds sequentially equivalent signals in one circuit, which can then be merged. This is the sequential form of SAT sweeping.
When to use it
Use it when the two circuits keep most of their state encoding, as after combinational optimization, small sequential changes, or a pipeline with the same registers. Then the latches correspond, many internal signals match, and the induction succeeds. It is much cheaper than a full reachability analysis of the product machine and needs no latch mapping step: corresponding latches are found as a side effect. When the state encoding changed, after state reencoding or deep retiming, few signals match, the hypothesis is too weak, and the answer is often "unknown". Then use reachability, bounded model checking to find a difference, or IC3.
Pitfalls
- Skipping the base case. Simulation checks the initial state only for the random inputs. A version that goes from line L1 to line L4 can accept classes that fail in the initial state for some other input, and then line L9 is unsound. Lines L2 and L3 must check every input at .
- Checking frame 1 under the wrong hypothesis. The hypothesis at line L5 must be rebuilt from the current classes after every split. Using the hypothesis of the first pass keeps equalities that were already refuted and makes the induction step unsound.
- Reading "unknown" as "different". A missed equivalence such as the ring example is not a bug in the design. Only a reachable counterexample, for example from bounded model checking, shows a real difference.
- No reset state. The base case needs one initial state. Circuits without reset need a different notion, such as safe replaceability.
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
# Shared helper of the hv1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small reduced ordered BDD package with a unique table and an operation cache.
A node is an integer. The terminals are 0 and 1. A variable is a non-negative
integer; a smaller variable is nearer to the root. Every Boolean function has
exactly one node for a fixed order, so two functions are equal if and only if
their nodes are equal. The recursion depth of every operation is at most the
number of variables plus one.
"""
from __future__ import annotations
from typing import Mapping, Optional
TERMINAL_LEVEL = 1 << 30
class BDD:
"""A manager that owns all nodes. Functions of different managers must not be mixed."""
def __init__(self) -> None:
self._level: list[int] = [TERMINAL_LEVEL, TERMINAL_LEVEL]
self._lo: list[int] = [0, 1]
self._hi: list[int] = [0, 1]
self._unique: dict[tuple[int, int, int], int] = {}
self._cache: dict[tuple, int] = {}
# Structure.
def level(self, u: int) -> int:
"""The variable of the root of u, or TERMINAL_LEVEL for a terminal."""
return self._level[u]
def low(self, u: int) -> int:
"""The child of u for the value 0 of its root variable."""
return self._lo[u]
def high(self, u: int) -> int:
"""The child of u for the value 1 of its root variable."""
return self._hi[u]
def mk(self, v: int, lo: int, hi: int) -> int:
"""The unique node (v, lo, hi), with the reduction rule lo = hi."""
if lo == hi:
return lo
key = (v, lo, hi)
u = self._unique.get(key)
if u is None:
u = len(self._level)
self._level.append(v)
self._lo.append(lo)
self._hi.append(hi)
self._unique[key] = u
return u
def var(self, v: int) -> int:
"""The function that is the variable v."""
return self.mk(v, 0, 1)
def cofactors(self, u: int, v: int) -> tuple[int, int]:
"""The two cofactors of u by v, when v is at or above the root of u."""
if self._level[u] == v:
return self._lo[u], self._hi[u]
return u, u
# Boolean operations.
def apply(self, op: str, u: int, w: int) -> int:
"""op(u, w) for op in and, or, xor. Cost O(|u| |w|) with the cache."""
if op == "and":
if u == 0 or w == 0:
return 0
if u == 1 or u == w:
return w
if w == 1:
return u
elif op == "or":
if u == 1 or w == 1:
return 1
if u == 0 or u == w:
return w
if w == 0:
return u
elif op == "xor":
if u == w:
return 0
if u == 0:
return w
if w == 0:
return u
else:
raise ValueError(op)
if u > w:
u, w = w, u
key = (op, u, w)
r = self._cache.get(key)
if r is None:
v = min(self._level[u], self._level[w])
u0, u1 = self.cofactors(u, v)
w0, w1 = self.cofactors(w, v)
r = self.mk(v, self.apply(op, u0, w0), self.apply(op, u1, w1))
self._cache[key] = r
return r
def conj(self, u: int, w: int) -> int:
return self.apply("and", u, w)
def disj(self, u: int, w: int) -> int:
return self.apply("or", u, w)
def xor(self, u: int, w: int) -> int:
return self.apply("xor", u, w)
def neg(self, u: int) -> int:
return self.apply("xor", u, 1)
def xnor(self, u: int, w: int) -> int:
return self.neg(self.xor(u, w))
def ite(self, f: int, g: int, h: int) -> int:
"""If f then g else h."""
return self.disj(self.conj(f, g), self.conj(self.neg(f), h))
# Substitution and quantification.
def restrict(self, u: int, v: int, b: int) -> int:
"""The cofactor of u with variable v fixed to b."""
if self._level[u] > v:
return u
if self._level[u] == v:
return self._hi[u] if b else self._lo[u]
key = ("restrict", u, v, b)
r = self._cache.get(key)
if r is None:
r = self.mk(self._level[u], self.restrict(self._lo[u], v, b), self.restrict(self._hi[u], v, b))
self._cache[key] = r
return r
def compose(self, u: int, v: int, g: int) -> int:
"""u with variable v replaced by the function g."""
return self.ite(g, self.restrict(u, v, 1), self.restrict(u, v, 0))
def exists(self, u: int, vs: frozenset[int]) -> int:
"""The existential quantification of u over the variables vs."""
if u <= 1 or not vs:
return u
key = ("exists", u, vs)
r = self._cache.get(key)
if r is None:
v = self._level[u]
lo = self.exists(self._lo[u], vs)
hi = self.exists(self._hi[u], vs)
r = self.disj(lo, hi) if v in vs else self.mk(v, lo, hi)
self._cache[key] = r
return r
# Queries.
def support(self, u: int) -> set[int]:
"""The variables that u depends on."""
seen: set[int] = set()
out: set[int] = set()
stack = [u]
while stack:
w = stack.pop()
if w <= 1 or w in seen:
continue
seen.add(w)
out.add(self._level[w])
stack.append(self._lo[w])
stack.append(self._hi[w])
return out
def size(self, u: int) -> int:
"""The number of nodes of u, terminals included."""
seen: set[int] = set()
stack = [u]
while stack:
w = stack.pop()
if w in seen:
continue
seen.add(w)
if w > 1:
stack.append(self._lo[w])
stack.append(self._hi[w])
return len(seen)
def sat_one(self, u: int) -> Optional[dict[int, int]]:
"""One assignment to some variables that makes u true, or None if u is 0."""
if u == 0:
return None
point: dict[int, int] = {}
while u != 1:
if self._lo[u] != 0:
point[self._level[u]] = 0
u = self._lo[u]
else:
point[self._level[u]] = 1
u = self._hi[u]
return point
def evaluate(self, u: int, point: Mapping[int, int]) -> int:
"""The value of u at the point; a variable not in the point has the value 0."""
while u > 1:
u = self._hi[u] if point.get(self._level[u], 0) else self._lo[u]
return u
netlist.py 180 lines
# SPDX-License-Identifier: MIT
# Shared helper of the hv1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate netlists with optional latches: bit-parallel simulation, BDDs of nodes, and two-circuit products.
A gate is (name, op, fanins). The gates are in topological order. A latch is
(name, next-state node, initial value). Fanins and next-state nodes name
primary inputs, latches or gates.
"""
from __future__ import annotations
import random
from dataclasses import dataclass
from bdd import BDD
OPS = ("AND", "OR", "NAND", "NOR", "XOR", "XNOR", "NOT", "BUF", "CONST0", "CONST1")
BINARY_OPS = ("AND", "OR", "NAND", "NOR", "XOR", "XNOR")
@dataclass(frozen=True)
class Netlist:
inputs: tuple[str, ...]
gates: tuple[tuple[str, str, tuple[str, ...]], ...]
outputs: tuple[str, ...]
latches: tuple[tuple[str, str, int], ...] = ()
def eval_op(op: str, vals: list[int], mask: int) -> int:
"""The value of one gate on bit-parallel words; mask has a 1 in every used bit."""
if op == "CONST0":
return 0
if op == "CONST1":
return mask
if op in ("BUF", "NOT"):
r = vals[0]
elif op in ("AND", "NAND"):
r = mask
for v in vals:
r &= v
elif op in ("OR", "NOR"):
r = 0
for v in vals:
r |= v
elif op in ("XOR", "XNOR"):
r = 0
for v in vals:
r ^= v
else:
raise ValueError(op)
if op in ("NOT", "NAND", "NOR", "XNOR"):
r ^= mask
return r & mask
def simulate(net: Netlist, values: dict[str, int], mask: int) -> dict[str, int]:
"""Values of all nodes, given words for the primary inputs and the latches. Cost O(gates + pins)."""
val = dict(values)
for name, op, fanins in net.gates:
val[name] = eval_op(op, [val[f] for f in fanins], mask)
return val
def next_state(net: Netlist, val: dict[str, int]) -> dict[str, int]:
"""The next value of every latch, from the node values of simulate."""
return {name: val[nxt] for name, nxt, _ in net.latches}
def initial_state(net: Netlist, mask: int) -> dict[str, int]:
"""The initial value of every latch, copied into every used bit."""
return {name: (mask if init else 0) for name, _, init in net.latches}
def bdd_op(bdd: BDD, op: str, args: list[int]) -> int:
"""The BDD of one gate applied to the BDDs of its fanins."""
if op == "CONST0":
return 0
if op == "CONST1":
return 1
if op in ("BUF", "NOT"):
r = args[0]
elif op in ("AND", "NAND"):
r = 1
for a in args:
r = bdd.conj(r, a)
elif op in ("OR", "NOR"):
r = 0
for a in args:
r = bdd.disj(r, a)
elif op in ("XOR", "XNOR"):
r = 0
for a in args:
r = bdd.xor(r, a)
else:
raise ValueError(op)
if op in ("NOT", "NAND", "NOR", "XNOR"):
r = bdd.neg(r)
return r
def build_bdds(net: Netlist, bdd: BDD, leaves: dict[str, int]) -> dict[str, int]:
"""BDDs of all nodes, given the BDDs of the primary inputs and the latches."""
f = dict(leaves)
for name, op, fanins in net.gates:
f[name] = bdd_op(bdd, op, [f[x] for x in fanins])
return f
def product(a: Netlist, b: Netlist) -> tuple[Netlist, list[tuple[str, str]]]:
"""The product of a and b on shared primary inputs, and the pairs of matching outputs.
The latches and gates of a get the prefix "a." and those of b the prefix "b.".
"""
if a.inputs != b.inputs or len(a.outputs) != len(b.outputs):
raise ValueError("the circuits must have the same inputs and the same number of outputs")
ins = set(a.inputs)
def ren(p: str, n: str) -> str:
return n if n in ins else p + n
gates = [(ren("a.", n), op, tuple(ren("a.", x) for x in fs)) for n, op, fs in a.gates]
gates += [(ren("b.", n), op, tuple(ren("b.", x) for x in fs)) for n, op, fs in b.gates]
latches = [(ren("a.", n), ren("a.", nx), i) for n, nx, i in a.latches]
latches += [(ren("b.", n), ren("b.", nx), i) for n, nx, i in b.latches]
oa = [ren("a.", o) for o in a.outputs]
ob = [ren("b.", o) for o in b.outputs]
return Netlist(a.inputs, tuple(gates), tuple(oa + ob), tuple(latches)), list(zip(oa, ob))
def random_netlist(rng: random.Random, n_inputs: int, n_latches: int, n_gates: int, n_outputs: int) -> Netlist:
"""A random netlist; every latch reads a random node and has a random initial value."""
inputs = tuple(f"x{i}" for i in range(n_inputs))
latches = [f"q{i}" for i in range(n_latches)]
pool = list(inputs) + latches
gates = []
for k in range(n_gates):
op = rng.choice(BINARY_OPS + ("NOT",))
if op == "NOT":
fanins: tuple[str, ...] = (rng.choice(pool),)
else:
fanins = (rng.choice(pool), rng.choice(pool))
name = f"g{k}"
gates.append((name, op, fanins))
pool.append(name)
nodes = pool[n_inputs:] or pool
outputs = tuple(rng.choice(nodes) for _ in range(n_outputs))
lat = tuple((q, rng.choice(nodes), rng.randrange(2)) for q in latches)
return Netlist(inputs, tuple(gates), outputs, lat)
def rewrite(net: Netlist, rng: random.Random) -> Netlist:
"""An equivalent netlist: some gates are rewritten by De Morgan's laws, with new NOT gates."""
gates = []
for name, op, fanins in net.gates:
if len(fanins) == 2 and op in ("AND", "OR", "NAND", "NOR") and rng.random() < 0.6:
na, nb = name + "_n0", name + "_n1"
gates.append((na, "NOT", (fanins[0],)))
gates.append((nb, "NOT", (fanins[1],)))
dual = {"AND": "NOR", "OR": "NAND", "NAND": "OR", "NOR": "AND"}[op]
gates.append((name, dual, (na, nb)))
elif op == "XOR" and rng.random() < 0.6:
na = name + "_n0"
gates.append((na, "NOT", (fanins[0],)))
gates.append((name, "XNOR", (na, fanins[1])))
else:
gates.append((name, op, fanins))
return Netlist(net.inputs, tuple(gates), net.outputs, net.latches)
def mutate(net: Netlist, rng: random.Random) -> Netlist:
"""A netlist with the operator of one random two-input gate changed; it may or may not be equivalent."""
idx = [k for k, (_, _, fs) in enumerate(net.gates) if len(fs) == 2]
if not idx:
return net
k = rng.choice(idx)
name, op, fanins = net.gates[k]
new_op = rng.choice([o for o in BINARY_OPS if o != op])
gates = list(net.gates)
gates[k] = (name, new_op, fanins)
return Netlist(net.inputs, tuple(gates), net.outputs, net.latches)
signal_correspondence.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/signal-correspondence/. The authors are listed in prov/EMBMJW.jsonl.
"""Signal correspondence (van Eijk 2000): the greatest inductive set of signal equalities, with BDDs.
Random simulation from the initial state groups the latches and gates of a
product machine into candidate classes of equal signals. The classes are then
split until they hold in the initial state for every input and are preserved
by one step of the machine. Pairs of outputs in one class are then equal in
every reachable state, so the two circuits are sequentially equivalent.
"""
from __future__ import annotations
import random
from dataclasses import dataclass
from typing import Optional
from bdd import BDD
from netlist import Netlist, build_bdds, initial_state, next_state, simulate
ZERO, ONE = "#0", "#1"
@dataclass
class Result:
proved: bool
classes: list[list[str]]
splits: int
def signal_nodes(p: Netlist) -> list[str]:
"""The nodes that take part: the two constants, the latches and the gates."""
return [ZERO, ONE] + [name for name, _, _ in p.latches] + [name for name, _, _ in p.gates]
def simulation_classes(p: Netlist, cycles: int = 8, width: int = 32, seed: int = 1) -> list[list[str]]:
"""Classes of nodes with equal values on `width` random runs of `cycles` cycles from the initial state."""
rng = random.Random(seed)
mask = (1 << width) - 1
state = initial_state(p, mask)
nodes = signal_nodes(p)
sig: dict[str, list[int]] = {n: [] for n in nodes}
for _ in range(cycles):
val = simulate(p, {**{x: rng.getrandbits(width) for x in p.inputs}, **state}, mask)
val[ZERO], val[ONE] = 0, mask
for n in nodes:
sig[n].append(val[n])
state = next_state(p, val)
groups: dict[tuple[int, ...], list[str]] = {}
for n in nodes:
groups.setdefault(tuple(sig[n]), []).append(n)
return list(groups.values())
def split(classes: list[list[str]], value: dict[str, int]) -> list[list[str]]:
"""Split every class by the value of its nodes at one point; the order inside a class is kept."""
out: list[list[str]] = []
for k in classes:
parts: dict[int, list[str]] = {}
for n in k:
parts.setdefault(value[n], []).append(n)
out.extend(parts.values())
return out
def first_difference(bdd: BDD, classes: list[list[str]], f: dict[str, int], care: int) -> Optional[dict[int, int]]:
"""A point where care holds and some node differs from the representative of its class, or None."""
for k in classes:
for n in k[1:]:
d = bdd.conj(care, bdd.xor(f[n], f[k[0]]))
if d != 0:
return bdd.sat_one(d)
return None
def signal_correspondence(
p: Netlist,
pairs: list[tuple[str, str]],
cycles: int = 8,
width: int = 32,
seed: int = 1,
classes: Optional[list[list[str]]] = None,
) -> Result:
"""Try to prove that each pair of outputs of the product machine p is equal in every reachable state.
Precondition: p is a netlist with latches (for example netlist.product(a, b)) and the
pairs name its nodes. If classes is given, it replaces the simulation classes.
Returns proved (True means equivalent; False means unknown), the final classes and
the number of splits. Cost: at most V - 1 splits for V nodes, each after at most V
BDD checks; a BDD can be exponential in the latches and inputs.
"""
if classes is None:
classes = simulation_classes(p, cycles, width, seed) # @line L1
classes = [list(k) for k in classes]
n_lat, n_in = len(p.latches), len(p.inputs)
bdd = BDD()
s = {name: bdd.var(j) for j, (name, _, _) in enumerate(p.latches)}
x0 = {x: bdd.var(n_lat + i) for i, x in enumerate(p.inputs)}
x1 = {x: bdd.var(n_lat + n_in + i) for i, x in enumerate(p.inputs)}
f0 = build_bdds(p, bdd, {**s, **x0})
delta = {name: f0[nxt] for name, nxt, _ in p.latches}
f1 = build_bdds(p, bdd, {**delta, **x1})
b0 = build_bdds(p, bdd, {**{name: init for name, _, init in p.latches}, **x0})
for f in (f0, f1, b0):
f[ZERO], f[ONE] = 0, 1
splits = 0
while True:
point = first_difference(bdd, classes, b0, 1) # @line L2
if point is None:
break
classes = split(classes, {n: bdd.evaluate(b0[n], point) for n in signal_nodes(p)}) # @line L3
splits += 1
while True: # @line L4
care = 1
for k in classes: # @line L5
for n in k[1:]:
care = bdd.conj(care, bdd.xnor(f0[n], f0[k[0]]))
point = first_difference(bdd, classes, f1, care) # @line L6
if point is None: # @line L8
break
classes = split(classes, {n: bdd.evaluate(f1[n], point) for n in signal_nodes(p)}) # @line L7
splits += 1
where = {n: i for i, k in enumerate(classes) for n in k}
proved = all(where.get(o, o) == where.get(o2, o2) for o, o2 in pairs) # @line L9
return Result(proved, classes, splits) # @line L10
test_signal_correspondence.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/signal-correspondence/. The authors are listed in prov/EMBMJW.jsonl.
import itertools
import random
from netlist import Netlist, initial_state, mutate, next_state, product, random_netlist, rewrite, simulate
from signal_correspondence import ONE, ZERO, signal_correspondence, simulation_classes
# The page example: a one-hot ring of three latches; the output h0 AND h1 is always 0.
RING = Netlist(
(),
(("o", "AND", ("h0", "h1")),),
("o",),
(("h0", "h2", 1), ("h1", "h0", 0), ("h2", "h1", 0)),
)
ZERO_CIRCUIT = Netlist((), (("z", "CONST0", ()),), ("z",))
# The same ring with the other two pairwise ANDs as extra gates.
RING3 = Netlist(
(),
(("o", "AND", ("h0", "h1")), ("u", "AND", ("h1", "h2")), ("w", "AND", ("h0", "h2"))),
("o",),
RING.latches,
)
def explicit_equivalent(p: Netlist, pairs) -> bool:
"""Oracle: explicit-state reachability of the product machine; every output pair agrees in every reachable state."""
names = [n for n, _, _ in p.latches]
start = tuple(initial_state(p, 1)[n] for n in names)
seen = {start}
todo = [start]
while todo:
st = todo.pop()
for xs in itertools.product((0, 1), repeat=len(p.inputs)):
val = simulate(p, {**dict(zip(p.inputs, xs)), **dict(zip(names, st))}, 1)
if any(val[o] != val[o2] for o, o2 in pairs):
return False
nxt = next_state(p, val)
t = tuple(nxt[n] for n in names)
if t not in seen:
seen.add(t)
todo.append(t)
return True
def explicit_gfp(p: Netlist, classes):
"""Oracle: the greatest inductive refinement of classes, by enumeration of all (s, x0, x1) at once."""
names = [n for n, _, _ in p.latches]
nl, ni = len(names), len(p.inputs)
npts = 1 << (nl + 2 * ni)
mask = (1 << npts) - 1
def bit_word(b: int) -> int:
return sum(1 << i for i in range(npts) if (i >> b) & 1)
s = {n: bit_word(j) for j, n in enumerate(names)}
x0 = {x: bit_word(nl + i) for i, x in enumerate(p.inputs)}
x1 = {x: bit_word(nl + ni + i) for i, x in enumerate(p.inputs)}
v0 = simulate(p, {**s, **x0}, mask)
v1 = simulate(p, {**next_state(p, v0), **x1}, mask)
vb = simulate(p, {**initial_state(p, mask), **x0}, mask)
for v in (v0, v1, vb):
v[ZERO], v[ONE] = 0, mask
def refine(cls, key):
out = []
for k in cls:
parts = {}
for n in k:
parts.setdefault(key(n), []).append(n)
out.extend(parts.values())
return out
cls = refine(classes, lambda n: vb[n])
while True:
q = mask
for k in cls:
for n in k[1:]:
q &= ~(v0[n] ^ v0[k[0]])
new = refine(cls, lambda n: v1[n] & q)
if len(new) == len(cls):
return cls
cls = new
def as_sets(classes):
return {frozenset(k) for k in classes}
def test_page_example_is_a_miss():
p, pairs = product(RING, ZERO_CIRCUIT)
init = simulation_classes(p)
assert ["a.o", "b.z"] == [n for k in init if ZERO in k for n in k if n != ZERO]
res = signal_correspondence(p, pairs)
assert not res.proved
assert res.splits == 1
assert explicit_equivalent(p, pairs)
assert as_sets(res.classes) == as_sets(explicit_gfp(p, init))
def test_extra_signals_make_the_page_example_provable():
p, pairs = product(RING3, ZERO_CIRCUIT)
res = signal_correspondence(p, pairs)
assert res.proved and res.splits == 0
assert explicit_equivalent(p, pairs)
def test_a_real_difference_is_never_proved():
# The ring against a circuit whose output is h0 (not always 0).
other = Netlist((), (("o", "BUF", ("h0",)),), ("o",), RING.latches)
p, pairs = product(RING, other)
assert not explicit_equivalent(p, pairs)
assert not signal_correspondence(p, pairs).proved
def test_given_classes_and_trivial_classes():
p, pairs = product(RING, RING)
res = signal_correspondence(p, pairs)
assert res.proved
alone = [[n] for k in simulation_classes(p) for n in k]
res2 = signal_correspondence(p, pairs, classes=alone)
assert not res2.proved and res2.splits == 0
def test_random_sound_and_greatest_fixed_point():
rng = random.Random(4242)
proved_rewrites = 0
for case in range(500):
a = random_netlist(rng, rng.randint(0, 2), rng.randint(1, 2), rng.randint(2, 6), rng.randint(1, 2))
b = rewrite(a, rng)
kind = case % 3
if kind == 1:
b = mutate(b, rng)
p, pairs = product(a, b)
init = simulation_classes(p, cycles=rng.randint(1, 6), width=rng.choice([1, 8, 32]), seed=case)
res = signal_correspondence(p, pairs, classes=init)
if res.proved:
assert explicit_equivalent(p, pairs)
assert as_sets(res.classes) == as_sets(explicit_gfp(p, init))
if kind != 1:
# A pure rewrite keeps every signal of a, so the correspondence by name is inductive.
full = signal_correspondence(p, pairs, cycles=8, width=64, seed=case)
assert full.proved
proved_rewrites += 1
assert proved_rewrites > 300
History
Van Eijk gave the method at DATE 1998, under the title "Sequential equivalence checking without state space traversal", and in the journal version in IEEE TCAD 19(7), 2000. He used BDDs for the induction step. Bjesse and Claessen (2000) did the step with SAT. The fixed point over equivalence classes has the same shape as partition refinement for automata, but the splitting test is an induction check, not a transition count.
References
- C. A. J. van Eijk, Sequential equivalence checking based on structural similarities, IEEE TCAD 19(7), 814 to 819, July 2000, the candidate classes from simulation, the inductive check with BDDs, and the refinement to a fixed point
- C. A. J. van Eijk, Sequential equivalence checking without state space traversal, DATE 1998, 618 to 623, the first version of the method
- P. Bjesse and K. Claessen, SAT-based verification without state space traversal, FMCAD 2000, the induction step of van Eijk's method done with SAT, and its use with stronger induction
- A. Kuehlmann and C. A. J. van Eijk, Combinational and sequential equivalence checking, in S. Hassoun and T. Sasao (editors), Logic Synthesis and Verification, Kluwer, 2002, 343 to 372, the section on sequential equivalence checking by signal correspondence
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 EMBMJW Edit this page History Report an error Markdown