Algorithm Search⌘K

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
Properties
not completedeterministicnot exactrecursive
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 PP with latches s∈{0,1}Ls \in \{0, 1\}^L, inputs x∈{0,1}Ix \in \{0, 1\}^I, initial state s0s_0, next-state function δ(s,x)\delta(s, x), and output pairs (oj,oj′)(o_j, o_j'). Each node uu (a latch, a gate, or a constant) has a value u(s,x)u(s, x). The task is the sequential equivalence question: is oj(s,x)=oj′(s,x)o_j(s, x) = o_j'(s, x) for every reachable state ss and every xx? Signal correspondence answers "equivalent" or "unknown".

A partition Π\Pi of the nodes gives the formula EΠ(s,x)E_\Pi(s, x): all members of each class have equal values at (s,x)(s, x). Π\Pi is inductive when EΠ(s0,x)E_\Pi(s_0, x) holds for every xx, and EΠ(s,x0)E_\Pi(s, x_0) implies EΠ(δ(s,x0),x1)E_\Pi(\delta(s, x_0), x_1) for all s,x0,x1s, x_0, x_1. The method returns the coarsest inductive partition that refines the simulation classes.

The algorithm

  1. SIGNAL-CORRESPONDENCE(P, pairs)
  2. 1simulate P from s₀ on random inputs; classes ← groups of nodes with equal values (the constants 0 and 1 are nodes)
  3. 2while some class K has a node u with u(s₀, x) ≠ rep(K)(s₀, x) for some x do
  4. 3split every class by the values of its nodes at (s₀, x)
  5. 4repeat
  6. 5C(s, x₀) ← ∧ over classes K and u ∈ K of [u(s, x₀) = rep(K)(s, x₀)]
  7. 6if 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
  8. 7split every class by the values of its nodes at (δ(s, x₀), x₁)
  9. 8until line L6 found no such point
  10. 9if every pair (o, o') lies in one class then return "equivalent"
  11. 10return "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 CC, the conjunction of all equalities in frame 0. Line L6 asks whether some state and inputs satisfy CC but break an equality in frame 1, one step later. The code does this with BDDs over ss, x0x_0 and x1x_1; 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 AA is a one-hot ring of three latches h0,h1,h2h_0, h_1, h_2 with initial state (1,0,0)(1, 0, 0) and next state (h2,h0,h1)(h_2, h_0, h_1). Its output is o=h0∧h1o = h_0 \wedge h_1. Circuit BB has the output z=0z = 0. The reachable states of AA are (1,0,0)(1, 0, 0), (0,1,0)(0, 1, 0) and (0,0,1)(0, 0, 1), so oo is always 0, and the circuits are equivalent. There are no primary inputs.

Simulation for 8 cycles gives h0=10010010h_0 = 10010010, h1=01001001h_1 = 01001001, h2=00100100h_2 = 00100100, and 0 for oo and zz.

step classes hypothesis C(s)C(s) check outcome
L1 {0,o,z},{1},{h0},{h1},{h2}\{0, o, z\}, \{1\}, \{h_0\}, \{h_1\}, \{h_2\}
L2 same at s0=(1,0,0)s_0 = (1, 0, 0): o=0o = 0, z=0z = 0 no split
L5, L6 same o=0o = 0, that is ¬(h0∧h1)\neg(h_0 \wedge h_1) frame 1: o′=h2∧h0o' = h_2 \wedge h_0; C∧o′=h0∧¬h1∧h2C \wedge o' = h_0 \wedge \neg h_1 \wedge h_2 point s=(1,0,1)s = (1, 0, 1)
L7 {0,z},{o},{1},{h0},{h1},{h2}\{0, z\}, \{o\}, \{1\}, \{h_0\}, \{h_1\}, \{h_2\} at δ(s)=(1,1,0)\delta(s) = (1, 1, 0): o=1o = 1, z=0z = 0 1 split
L5, L6 same true z′=0z' = 0 everywhere no point; stop
L9 oo and zz in different classes "unknown"

The state (1,0,1)(1, 0, 1) is not reachable, but the one-step hypothesis "o=0o = 0" does not exclude it. This is the miss. No inductive partition at all keeps oo and zz together, as the proof shows, so a different simulation cannot help.

Add two gates u=h1∧h2u = h_1 \wedge h_2 and w=h0∧h2w = h_0 \wedge h_2 to AA, outside its outputs. Then line L1 gives the class {0,o,u,w,z}\{0, o, u, w, z\}, 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 s∈{0,1}Ls \in \{0, 1\}^L, primary inputs x∈{0,1}Ix \in \{0, 1\}^I, initial state s0s_0 and next-state function δ(s,x)\delta(s, x). Each node uu (a latch, a gate, or one of the constants 0 and 1) has a value u(s,x)u(s, x) in state ss under input xx; for a latch, u(s,x)u(s, x) is its bit of ss. A state is reachable if it is s0s_0 or δ(t,x)\delta(t, x) for a reachable tt and some xx.

A partition Π\Pi of the nodes into classes, each with a first member rep(K)\mathrm{rep}(K), defines

EΠ(s,x)=⋀K∈Π⋀u∈K[u(s,x)=rep(K)(s,x)].E_\Pi(s, x) = \bigwedge_{K \in \Pi} \bigwedge_{u \in K} \big[u(s, x) = \mathrm{rep}(K)(s, x)\big].

EΠ(s,x)E_\Pi(s, x) holds exactly when all members of each class have equal values at (s,x)(s, x), so it does not depend on the choice of representatives. The partition Π\Pi is inductive when

  • (B) EΠ(s0,x)E_\Pi(s_0, x) for every xx, and
  • (S) EΠ(s,x0)⇒EΠ(δ(s,x0),x1)E_\Pi(s, x_0) \Rightarrow E_\Pi(\delta(s, x_0), x_1) for all s,x0,x1s, x_0, x_1.

Π\Pi refines Π′\Pi', written Π≤Π′\Pi \le \Pi', when every class of Π\Pi lies inside a class of Π′\Pi'. If Π≤Π′\Pi \le \Pi', then EΠ′(s,x)⇒EΠ(s,x)E_{\Pi'}(s, x) \Rightarrow E_\Pi(s, x), since EΠE_\Pi asks for a subset of the equalities, and (B) for Π′\Pi' gives (B) for Π\Pi.

Theorem 1 (soundness). If Π\Pi is inductive, then EΠ(s,x)E_\Pi(s, x) holds for every reachable ss and every xx. So if each output pair (o,o′)(o, o') lies in one class of Π\Pi, the two circuits give the same output sequence for every input sequence from the initial state.

Proof. Induction on the reachability of ss. For s=s0s = s_0, (B) gives the claim. If s=δ(t,x0)s = \delta(t, x_0) with tt reachable, the hypothesis gives EΠ(t,x0)E_\Pi(t, x_0), and (S) gives EΠ(s,x1)E_\Pi(s, x_1) for every x1x_1. For an input sequence x0,x1,…x^0, x^1, \ldots, the states s0=s0s^0 = s_0, st+1=δ(st,xt)s^{t+1} = \delta(s^t, x^t) are reachable, so o(st,xt)=o′(st,xt)o(s^t, x^t) = o'(s^t, x^t) at every step tt. □\square

Lemma 2 (each split is forced). Let Π\Pi be the current partition and Π∘\Pi^\circ any inductive partition with Π∘≤Π\Pi^\circ \le \Pi. Let Π′\Pi' be the result of a split at line L3 or L7. Then Π∘≤Π′\Pi^\circ \le \Pi'.

Proof. A split at line L3 uses a point (s0,x)(s_0, x) and puts two nodes of a class of Π\Pi in the same class of Π′\Pi' exactly when their values at the point are equal. Take a class K∘K^\circ of Π∘\Pi^\circ. It lies in one class KK of Π\Pi, and by (B) for Π∘\Pi^\circ all its members have equal values at (s0,x)(s_0, x). So K∘K^\circ lies in one class of Π′\Pi'.

A split at line L7 uses a point (s,x0,x1)(s, x_0, x_1) with C(s,x0)=EΠ(s,x0)=1C(s, x_0) = E_\Pi(s, x_0) = 1, and splits by the values at (δ(s,x0),x1)(\delta(s, x_0), x_1). Since Π∘≤Π\Pi^\circ \le \Pi, EΠ(s,x0)E_\Pi(s, x_0) gives EΠ∘(s,x0)E_{\Pi^\circ}(s, x_0), and (S) for Π∘\Pi^\circ gives EΠ∘(δ(s,x0),x1)E_{\Pi^\circ}(\delta(s, x_0), x_1). So again all members of a class of Π∘\Pi^\circ have equal values at the point, and the class lies in one class of Π′\Pi'. □\square

Lemma 3 (termination). Lines L2 to L3 and L4 to L8 run at most V−∣Π0∣V - |\Pi_0| splits in total, for VV nodes and the partition Π0\Pi_0 of line L1.

Proof. A split happens only at a point where some node uu 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 VV. Each pass of lines L5 and L6 does a finite number of BDD checks. □\square

Theorem 4 (greatest fixed point). The partition Π\Pi at line L9 is inductive, refines Π0\Pi_0, and is refined by every inductive partition that refines Π0\Pi_0. So it is the unique coarsest inductive partition below Π0\Pi_0.

Proof. Splits only refine, so Π≤Π0\Pi \le \Pi_0. The loop of lines L2 and L3 stops when no class has a member that differs from its representative at (s0,x)(s_0, x) for any xx, which is (B). Later splits keep (B), because (B) passes to finer partitions. The loop of lines L4 to L8 stops when no (s,x0,x1)(s, x_0, x_1) has EΠ(s,x0)E_\Pi(s, x_0) and a member that differs from its representative at (δ(s,x0),x1)(\delta(s, x_0), x_1), which is (S). So Π\Pi is inductive. Every inductive Π∘≤Π0\Pi^\circ \le \Pi_0 satisfies Π∘≤Π\Pi^\circ \le \Pi: it holds for Π0\Pi_0, and Lemma 2 keeps it through every split. Two partitions that each refine the other are equal, so the coarsest one is unique. ■\blacksquare

In terms of fixed points: let Φ(Π)\Phi(\Pi) be Π\Pi split by the values at every point (s0,x)(s_0, x) and at every point (δ(s,x0),x1)(\delta(s, x_0), x_1) with EΠ(s,x0)E_\Pi(s, x_0). Then Φ\Phi is monotone in the refinement order, its fixed points below Π0\Pi_0 are the inductive partitions below Π0\Pi_0, and Theorem 4 says the algorithm returns the greatest of them. It reaches it one counterexample at a time, not by computing Φ\Phi at once.

Theorem 5 (incompleteness). There are sequentially equivalent circuits that the algorithm does not prove, for every choice of random simulation.

Proof. Let AA have three latches h0,h1,h2h_0, h_1, h_2 with initial state (1,0,0)(1, 0, 0) and next state (h2,h0,h1)(h_2, h_0, h_1), and the output o=h0∧h1o = h_0 \wedge h_1. Let BB have no latches and the output constant 0. The reachable states of AA are (1,0,0)(1, 0, 0), (0,1,0)(0, 1, 0) and (0,0,1)(0, 0, 1), and o=0o = 0 in each, so AA and BB are sequentially equivalent. The nodes of the product are the constants 0 and 1, h0,h1,h2h_0, h_1, h_2, oo and the output zz of BB (there are no inputs). We show that no inductive partition at all has oo and zz in one class. Since the algorithm returns an inductive partition (Theorem 4), it does not prove the pair, whatever Π0\Pi_0 is.

Let Π\Pi be inductive. By Theorem 1, the members of each class agree in the three reachable states. In (1,0,0)(1, 0, 0) the node h0h_0 is 1 and h1,h2,o,zh_1, h_2, o, z and the constant 0 are 0. In (0,1,0)(0, 1, 0) the node h0h_0 is 0 and the constant 1 is 1. So h0h_0 is alone in its class. In the same way h1h_1 and h2h_2 are alone, and the constant 1 is alone (it differs from oo, zz and the constant 0 everywhere). Suppose oo and zz share a class. That class is {o,z}\{o, z\} or {o,z,0}\{o, z, 0\}, and all other classes have one member. Take s=(1,0,1)s = (1, 0, 1), which is not reachable. There o=1∧0=0o = 1 \wedge 0 = 0, so EΠ(s)E_\Pi(s) holds. But δ(s)=(1,1,0)\delta(s) = (1, 1, 0), where o=1o = 1 and z=0z = 0, so EΠ(δ(s))E_\Pi(\delta(s)) fails, and (S) fails. This contradicts the choice of Π\Pi. □\square

The induction fails only because of the unreachable state (1,0,1)(1, 0, 1). A stronger hypothesis removes it: with the extra gates h1∧h2h_1 \wedge h_2 and h0∧h2h_0 \wedge h_2 in AA, the class {0,o,h1∧h2,h0∧h2,z}\{0, o, h_1 \wedge h_2, h_0 \wedge h_2, z\} says that at most one latch is 1, which is inductive.

Complexity

Let VV 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 VV times in total. Each pass of lines L5 and L6 makes O(V)O(V) BDD applies: one equality per class member for CC, and one check per member. The BDDs are over L+2IL + 2I variables (ss, x0x_0, x1x_1), so each has at most 2L+2I+12^{L + 2I} + 1 nodes and each apply costs O(4L+2I)O(4^{L + 2I}) with the cache. Building the frame-0, frame-1 and initial-state BDDs once costs O(V)O(V) applies. The total is O(V2 4L+2I)O(V^2 \, 4^{L + 2I}) 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 CC 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 VV calls per pass and at most V+1V + 1 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 kk consecutive frames and prove them in the next. In the ring example, 3-step induction proves o=0o = 0 and 2-step induction does not: the unreachable state (0,1,1)(0, 1, 1) has o=0o = 0 and then o=0o = 0 again at (1,0,1)(1, 0, 1), but o=1o = 1 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 s0s_0.
  • Checking frame 1 under the wrong hypothesis. The hypothesis CC 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.

bdd.pyI0RawGitHub
# 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

  1. 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
  2. C. A. J. van Eijk, Sequential equivalence checking without state space traversal, DATE 1998, 618 to 623, the first version of the method
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example