Algorithm Search⌘K

Algorithmadvanced

Cutpoint-based equivalence checking

Also called Kuehlmann-Krohm equivalence checking, internal equivalence checking.

Kuehlmann and Krohm's method that finds equivalent internal nodes of two circuits, proves them and uses them as cut points so that hard outputs split into easy parts.

Time
O((N + P C) 4^(n + C)) worst
Space
O((N + P C) 4^(n + C)) extra
Where
C = the number of cut variables; N = the number of gates and gate inputs of both circuits; P = the number of compared node pairs; n = the number of primary inputs
Properties
completedeterministicexactrecursive
Origin
Andreas Kuehlmann, Florian Krohm, 1997

Cutpoint-based equivalence checking decides Boolean equivalence of two combinational circuits that have much structure in common, as after logic synthesis. It finds internal nodes of the two circuits that compute the same function, proves each such pair with a BDD, and then puts a fresh variable, the cut variable, in place of the pair. Later BDDs are built over the cut variables, so they stay small. A cut can hide the relation between the cut node and the other inputs, and then a difference of two nodes can look real while it is not. This is a false negative. The method resolves it by moving the cut back toward the primary inputs, through composition, until the difference is 0 or is a real counterexample.

In plain words

Two circuits that should do the same work are often almost the same inside. So the checker proves equality in small steps, from the inputs to the outputs. Quick random simulation shows which inside wires probably carry the same signal. The checker proves one such pair at a time. When a pair is proved, it gets a new name, and the rest of the work treats that name as if it were a new input. Each later check then only looks at the logic between the named wires, which is small.

The new names forget one thing: how the named wire depends on the real inputs. So a check can show a difference that no real input can cause. When that happens, the checker puts back what a name stands for, one name at a time, until the difference goes away or is real.

The problem

The input is two combinational circuits AA and BB on the same primary inputs x=(x1,…,xn)x = (x_1, \ldots, x_n), with outputs paired as (o1,o1′),…,(ok,ok′)(o_1, o_1'), \ldots, (o_k, o_k'). The output is "equivalent" if oj(x)=oj′(x)o_j(x) = o_j'(x) for every jj and every x∈{0,1}nx \in \{0, 1\}^n, and otherwise an input vector on which some pair differs. This is the Boolean equivalence checking problem, the check that the miter of AA and BB is 0 for every input. It is coNP-complete, so no method is fast on every input unless P = NP. This method is fast when the circuits share many internal equivalent nodes.

A cut is a set of nodes whose values are given names, the cut variables. Each cut variable vv stores its definition def(v)\mathrm{def}(v), the BDD of its node over the variables that existed before it. The cut miter of two nodes is the XOR of their BDDs over the current cut variables.

The algorithm

  1. CUTPOINT-EC(A, B, pairs)
  2. 1give each primary input a BDD variable, which is its own cut variable
  3. 2simulate A and B on W random input vectors; sig(u) ← the W values of node u
  4. 3for each gate u of A, then of B, in topological order do
  5. 4R(u) ← the gate of u applied to F of its fanins
  6. 5F(u) ← R(u)
  7. 6if an earlier node r has sig(r) = sig(u) then (r is the first such node)
  8. 7if RESOLVE(R(u) ⊕ R(r)) = 0 then
  9. 8if r has no cut variable then make a fresh variable v_r; def(v_r) ← R(r); F(r) ← v_r
  10. 9F(u) ← v_r
  11. 10for each pair (o, o') do
  12. 11G ← RESOLVE(F(o) ⊕ F(o'))
  13. 12if G ≠ 0 then return "different", a satisfying assignment of G
  14. 13return "equivalent"
  15. RESOLVE(G)
  16. 14while G ≠ 0 and the support of G has a cut variable do
  17. 15v ← the cut variable in the support of G with the largest index
  18. 16G ← G with v replaced by def(v)
  19. 17return G

Line L2 is cheap bit-parallel simulation. It only proposes pairs, the candidates; it proves nothing. Lines L4 and L5 build the BDD of the node over the current cut. Line L6 looks up the first node with the same simulation values, so each group of candidates has one representative.

Line L7 checks the pair. The difference R(u)⊕R(r)R(u) \oplus R(r) is a cut miter. If it is 0 at once, the pair is equal. If it is not 0 but depends on cut variables, it may be a false negative, so RESOLVE moves the cut back. Line L16 substitutes for the newest cut variable in the difference the function that it names. The definition of a cut variable uses only older variables, so the newest cut variable in the support goes down at each step, and the loop ends. When only primary inputs remain, a nonzero difference is real.

Lines L8 and L9 make the cut. The representative gets a cut variable if it has none, and both nodes use that variable from now on. A primary input is its own cut variable, so a node equal to an input becomes that input. Lines L10 to L12 do the same check on the output pairs. A nonzero result there has primary inputs only, so any satisfying assignment is a real counterexample.

Example

Take inputs a,ba, b. Circuit AA has the gate g=a∧bg = a \wedge b and the outputs (g,a)(g, a). Circuit BB has p=¬ap = \neg a, q=¬bq = \neg b, r=p∨qr = p \vee q, z=¬rz = \neg r, w=z∨aw = z \vee a and the outputs (z,w)(z, w). So z=a∧bz = a \wedge b and w=(a∧b)∨a=aw = (a \wedge b) \vee a = a, and the circuits are equivalent. The signature of a node is its value on the four vectors ab=00,01,10,11ab = 00, 01, 10, 11.

step node function sig R(u)R(u) over the current cut first node with this sig RESOLVE F(u)F(u)
L1 aa, bb inputs 0011, 0101 aa, bb themselves none aa, bb
1 gg a∧ba \wedge b 0001 a∧ba \wedge b gg none a∧ba \wedge b
2 pp ¬a\neg a 1100 ¬a\neg a pp none ¬a\neg a
3 qq ¬b\neg b 1010 ¬b\neg b qq none ¬b\neg b
4 rr ¬a∨¬b\neg a \vee \neg b 1110 ¬a∨¬b\neg a \vee \neg b rr none ¬a∨¬b\neg a \vee \neg b
5 zz a∧ba \wedge b 0001 a∧ba \wedge b gg 00 at once vv, a new cut variable with def(v)=a∧b\mathrm{def}(v) = a \wedge b; also F(g)=vF(g) = v
6 ww aa 0011 v∨av \vee a aa (v∨a)⊕a=v∧¬a(v \vee a) \oplus a = v \wedge \neg a, then v:=a∧bv := a \wedge b gives 00 aa

At step 6 the cut miter v∧¬av \wedge \neg a is satisfied by v=1,a=0v = 1, a = 0. No input vector gives that point: v=1v = 1 means a=b=1a = b = 1. This is the false negative. The cut at zz hid the fact that z=1z = 1 forces a=1a = 1, a don't care of ww seen from the cut. Composing def(v)=a∧b\mathrm{def}(v) = a \wedge b into the cut miter gives ((a∧b)∨a)⊕a=0((a \wedge b) \vee a) \oplus a = 0, so the pair is equal and ww becomes the variable aa.

At lines L10 to L12, the pair (g,z)(g, z) has F(g)⊕F(z)=v⊕v=0F(g) \oplus F(z) = v \oplus v = 0 and the pair (a,w)(a, w) has a⊕a=0a \oplus a = 0. The answer is "equivalent", with 2 merges and 1 false negative. If ww were z∨bz \vee b instead, then w=bw = b. Step 6 would merge ww with the input bb after the same kind of false negative, v∧¬bv \wedge \neg b. The output pair (a,w)(a, w) would then give a⊕ba \oplus b, a BDD over primary inputs only, and line L12 would return the real counterexample a=0,b=1a = 0, b = 1.

Correctness

The answer is exact: "equivalent" if and only if every output pair computes the same function, and a returned vector always separates a pair. The key fact is that substitution keeps meaning. Read each cut variable as the function of primary inputs that its definition gives. Then every BDD R(u)R(u) and F(u)F(u) means the true function of uu, and RESOLVE never changes the meaning of its argument. RESOLVE stops only at 0 or at a BDD with primary inputs only, and such a BDD means itself. So a 0 result proves equality, and a nonzero result is a real difference. A satisfying point of a cut miter that still has cut variables may assign a cut variable a value that its definition cannot take at the same inputs, which is the false negative. Moving the cut back to the primary inputs gives the exact miter of the two nodes. The full proof is in the correctness proof.

Proof: Cutpoint equivalence checking answers exactly, and its cut differences are false negatives only until the cut moves backfull

Setting. The two circuits are combined into one product netlist with primary inputs x1,…,xnx_1, \ldots, x_n and the gates of both circuits in topological order. The BDD variable of xix_i has index i−1i - 1. Every node uu computes a function [ ⁣[u] ⁣]:{0,1}n→{0,1}[\![u]\!] : \{0, 1\}^n \to \{0, 1\}. Line L8 creates cut variables with indices n,n+1,…n, n + 1, \ldots in the order of creation and gives each cut variable vv a BDD def(v)\mathrm{def}(v).

Lemma 1 (definitions point down). For every cut variable vv, every variable in the support of def(v)\mathrm{def}(v) is smaller than vv.

Proof. Line L8 sets def(v)=R(r)\mathrm{def}(v) = R(r) for the next free index vv. R(r)R(r) was built at line L4 from BDDs that existed before, and every variable that existed before has a smaller index than the new one. □\square

Meaning of a BDD. By Lemma 1 we can define, by induction on the variable index, the value of each variable at an input vector a∈{0,1}na \in \{0, 1\}^n: the variable of xix_i has the value aia_i, and a cut variable vv has the value μ(def(v))(a)\mu(\mathrm{def}(v))(a). For a BDD GG, μ(G)(a)\mu(G)(a) is the value of GG when every variable in it has this value. So μ\mu is evaluation at one point per input vector, and therefore μ(G∘H)=μ(G)∘μ(H)\mu(G \circ H) = \mu(G) \circ \mu(H) for every gate operator ∘\circ, and μ(G[v:=def(v)])=μ(G)\mu(G[v := \mathrm{def}(v)]) = \mu(G), because the substituted function has the same value at the point as vv itself.

Lemma 2 (RESOLVE). RESOLVE(GG) terminates. Its result G′G' satisfies μ(G′)=μ(G)\mu(G') = \mu(G), and if G′≠0G' \ne 0, then the support of G′G' has primary input variables only. Hence RESOLVE(GG) =0= 0 if and only if μ(G)=0\mu(G) = 0.

Proof. Each pass of lines L14 to L16 replaces the largest cut variable vv in the support by def(v)\mathrm{def}(v). The other cut variables in the support are smaller than vv, and so is every variable of def(v)\mathrm{def}(v) by Lemma 1. So the largest cut variable in the support decreases strictly at each pass, and the loop stops after at most CC passes for CC cut variables. Each pass keeps μ\mu, as shown above. The loop stops only when G′=0G' = 0 or the support has no cut variable. In the second case G′G' is a BDD over the primary inputs, so μ(G′)=G′\mu(G') = G'. Then μ(G)=G′≠0\mu(G) = G' \ne 0. In the first case μ(G)=μ(0)=0\mu(G) = \mu(0) = 0. □\square

Lemma 3 (invariant). After line L3 has processed a node uu, and until the end of the run, μ(R(u))=[ ⁣[u] ⁣]\mu(R(u)) = [\![u]\!] and μ(F(u))=[ ⁣[u] ⁣]\mu(F(u)) = [\![u]\!].

Proof. Induction over the nodes in topological order. For a primary input, FF and RR are its variable, and μ\mu gives aia_i. For a gate uu, line L4 applies the gate to FF of the fanins, which were processed before, so μ(R(u))=[ ⁣[u] ⁣]\mu(R(u)) = [\![u]\!] by the induction hypothesis and the first property of μ\mu. Line L5 copies it to F(u)F(u). Line L9 sets F(u)=vrF(u) = v_r only when RESOLVE(R(u)⊕R(r)R(u) \oplus R(r)) =0= 0, so μ(R(u))=μ(R(r))\mu(R(u)) = \mu(R(r)) by Lemma 2. When vrv_r is made at line L8, def(vr)=R(r)\mathrm{def}(v_r) = R(r), so μ(vr)=μ(R(r))=[ ⁣[r] ⁣]=[ ⁣[u] ⁣]\mu(v_r) = \mu(R(r)) = [\![r]\!] = [\![u]\!]. Line L8 also changes F(r)F(r) to vrv_r, and μ(vr)=[ ⁣[r] ⁣]\mu(v_r) = [\![r]\!], so the claim for rr stays true. Nothing else changes RR or FF. □\square

Theorem (correctness). The algorithm returns "equivalent" if and only if [ ⁣[o] ⁣]=[ ⁣[o′] ⁣][\![o]\!] = [\![o']\!] for every output pair (o,o′)(o, o'). When it returns "different", the input vector it returns gives different values on some pair.

Proof. At line L11, μ(F(o)⊕F(o′))=[ ⁣[o] ⁣]⊕[ ⁣[o′] ⁣]\mu(F(o) \oplus F(o')) = [\![o]\!] \oplus [\![o']\!] by Lemma 3. By Lemma 2, the result GG of RESOLVE is 0 exactly when this function is 0, that is, when the outputs agree on every input vector. If every pair gives 0, line L13 returns "equivalent". If some pair gives G≠0G \ne 0, then GG is a BDD over the primary inputs and G=[ ⁣[o] ⁣]⊕[ ⁣[o′] ⁣]G = [\![o]\!] \oplus [\![o']\!]. A satisfying path of GG fixes some inputs; every completion of it satisfies GG, so the vector of line L12 (with 0 for the free inputs) separates oo and o′o'. ■\blacksquare

Remark (false negatives). The cut miter GG at line L11 or L7, read as a function of free variables, may be satisfiable while μ(G)=0\mu(G) = 0. A satisfying point of GG that gives a cut variable vv a value that def(v)\mathrm{def}(v) cannot take at the same inputs is not a point of any real input vector. This is the false negative. Lemma 2 shows that moving the cut back, one cut variable at a time, removes every such point and never removes a real one.

Remark (simulation). The signatures of line L2 only choose which pairs to compare. A wrong guess costs one RESOLVE and changes nothing in Lemmas 1 to 3, so the answer does not depend on the random vectors.

Complexity

The model is the word RAM with hashing in expected constant time. Let NN count the gates and gate inputs of both circuits, CC the cut variables and PP the node pairs that reach line L7 or L11. Every BDD in the run is over at most n+Cn + C variables, so it has at most 2n+C+12^{n + C} + 1 nodes: at most 2i2^i nodes test the variable at depth ii, plus the two sinks.

  • Simulation at line L2 costs O(N)O(N) word operations for WW up to the word size.
  • Line L4 makes one apply per gate input. An apply of BDDs with ss and tt nodes costs O(st)O(st) with the operation cache, so each costs O(4n+C)O(4^{n + C}).
  • RESOLVE makes at most CC compositions (Lemma 2 of the proof), each two restrictions and an if-then-else, that is, a constant number of applies of O(4n+C)O(4^{n + C}) each, plus a support scan of linear cost.

The total is O((N+PC) 4n+C)O((N + PC)\, 4^{n + C}) time, and the unique table and cache hold at most one entry per step, which gives the same space bound. This bound is far from what happens on circuits that share structure: there each cut miter has a few nodes, CC is close to the number of merged pairs, and the run time is close to linear in NN. No bound that is polynomial on every input is expected, since the problem is coNP-complete.

Properties

  • Exact and complete: it always ends with "equivalent" or a real counterexample. The random simulation affects only the speed.
  • Deterministic for a fixed seed.
  • When RESOLVE must go all the way back to the primary inputs, it builds the full BDDs of the two nodes, so a hard pair costs what a monolithic BDD check of that pair costs.
  • The result does not depend on the variable order, but the cost does.

Variants and improvements

  • SAT in place of BDDs. The check at line L7 can be a SAT call on the cut miter. A satisfying point then has to be checked against the real inputs, or the cut is moved back as here. SAT sweeping is this idea on one and-inverter graph for synthesis, with no cut variables; its counterexamples refine the simulation classes.
  • Many cut frontiers. Kuehlmann and Krohm keep several cut frontiers and control how far a false negative moves the cut back. Line L15, one variable at a time from the newest, is the simplest such rule.
  • Structural hashing. Merging gates with the same operator and the same fanins before line L3 finds many equal pairs for free, see hash-consing.
  • Complemented pairs. A node can be equal to the complement of another node. Signatures that are equal up to complement find such pairs; the code here uses plain equality.
  • Sequential circuits. With the latches matched by latch mapping, each pair of next-state functions is a combinational check. Without a match, signal correspondence proves equalities across time by induction.

When to use it

Use it when the two circuits are related by synthesis steps that keep many internal signals: technology mapping, buffering, local rewrites. Then most internal nodes have a partner, and the BDDs between cuts stay small. When the circuits share little inside, as for a multiplier against a different multiplier architecture, few pairs merge, the cuts help little, and a monolithic BDD or a plain SAT check of the miter costs the same or less. Arithmetic with no common structure needs other methods altogether.

Pitfalls

  • Returning the cut miter's point as a counterexample. A version that returns "different" as soon as R(u)⊕R(r)R(u) \oplus R(r) or F(o)⊕F(o′)F(o) \oplus F(o') is nonzero reports false negatives as bugs. In the example it would report v=1,a=0v = 1, a = 0, which is not an input vector. Lines L7 and L11 must call RESOLVE first, and line L12 must return only a point of a BDD over primary inputs.
  • Merging on simulation alone. Equal signatures at line L6 do not prove anything. Merging there without line L7 makes the method unsound: two different nodes that the WW vectors did not separate become one variable.
  • Losing the definition order. RESOLVE ends because each definition uses only older variables (line L15 takes the newest). If a cut variable were defined from a newer one, composition could loop.
  • Cutting at a primary input twice. A node equal to a primary input must reuse the input's own variable, as line L8 does. A second variable for the same input loses the link between them and makes more false negatives.

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
cutpoint_equivalence_checking.py 95 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cutpoint-equivalence-checking/. The authors are listed in prov/MX8Z1M.jsonl.
"""Cutpoint-based combinational equivalence checking (Kuehlmann and Krohm 1997), with BDDs.

Internal nodes of the two circuits that have the same simulation values are
candidates. When a candidate pair is proved equal, the pair gets a fresh cut
variable, and later BDDs use that variable in place of the function of the pair.
A difference that still depends on a cut variable may be a false negative, so
the cut variables in it are composed back (the cut moves toward the inputs)
until the difference is 0 or depends on primary inputs only.
"""

from __future__ import annotations

import random
from dataclasses import dataclass
from typing import Optional

from bdd import BDD
from netlist import Netlist, bdd_op, product, simulate


@dataclass
class Result:
    equivalent: bool
    counterexample: Optional[dict[str, int]]
    merges: int
    false_negatives: int


def resolve(bdd: BDD, g: int, definition: dict[int, int]) -> tuple[int, bool]:
    """Compose cut variables back into g until g is 0 or has no cut variable.

    definition maps each cut variable to its function over smaller variables.
    Returns the final g and True if g was nonzero over a cut variable and became 0.
    """
    start_nonzero = g != 0
    while g != 0:  # @line L14
        cuts = [v for v in bdd.support(g) if v in definition]
        if not cuts:
            break
        v = max(cuts)  # @line L15
        g = bdd.compose(g, v, definition[v])  # @line L16
    return g, start_nonzero and g == 0  # @line L17


def cutpoint_equivalence(a: Netlist, b: Netlist, width: int = 64, seed: int = 1) -> Result:
    """Decide whether the combinational circuits a and b compute the same outputs.

    Precondition: a and b have the same primary inputs, the same number of outputs and no latches.
    Returns equivalent, a distinguishing input vector when they differ, the number of
    proved merges and the number of differences that were false negatives of a cut.
    Cost: O(N + P C) BDD operations for N gates, P compared pairs and C cut variables;
    each operation is polynomial in the BDD sizes, which can be exponential in the inputs.
    """
    p, pairs = product(a, b)
    bdd = BDD()
    cut_var = {x: i for i, x in enumerate(p.inputs)}  # @line L1
    f = {x: bdd.var(i) for x, i in cut_var.items()}
    raw = dict(f)
    definition: dict[int, int] = {}
    next_var = len(p.inputs)
    rng = random.Random(seed)
    mask = (1 << width) - 1
    sig = simulate(p, {x: rng.getrandbits(width) for x in p.inputs}, mask)  # @line L2
    first: dict[int, str] = {}
    for x in p.inputs:
        first.setdefault(sig[x], x)
    merges = 0
    false_negatives = 0
    for name, op, fanins in p.gates:  # @line L3
        raw[name] = bdd_op(bdd, op, [f[x] for x in fanins])  # @line L4
        f[name] = raw[name]  # @line L5
        r = first.setdefault(sig[name], name)
        if r == name:  # @line L6
            continue
        g, was_false = resolve(bdd, bdd.xor(raw[name], raw[r]), definition)  # @line L7
        false_negatives += was_false
        if g != 0:
            continue
        if r not in cut_var:  # @line L8
            cut_var[r] = next_var
            definition[next_var] = raw[r]
            f[r] = bdd.var(next_var)
            next_var += 1
        f[name] = bdd.var(cut_var[r])  # @line L9
        merges += 1
    for o, o2 in pairs:  # @line L10
        g, was_false = resolve(bdd, bdd.xor(f[o], f[o2]), definition)  # @line L11
        false_negatives += was_false
        if g != 0:  # @line L12
            point = bdd.sat_one(g) or {}
            cex = {x: point.get(i, 0) for i, x in enumerate(p.inputs)}
            return Result(False, cex, merges, false_negatives)
    return Result(True, None, merges, false_negatives)  # @line L13
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)
test_cutpoint_equivalence_checking.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cutpoint-equivalence-checking/. The authors are listed in prov/MX8Z1M.jsonl.

import random

from bdd import BDD
from cutpoint_equivalence_checking import cutpoint_equivalence
from netlist import Netlist, mutate, random_netlist, rewrite, simulate

# The circuits of the page. A: o1 = a AND b, o2 = a.
# B: z = NOT(NOT a OR NOT b), w = z OR a, outputs (z, w).
A = Netlist(("a", "b"), (("g", "AND", ("a", "b")),), ("g", "a"))
B = Netlist(
    ("a", "b"),
    (
        ("p", "NOT", ("a",)),
        ("q", "NOT", ("b",)),
        ("r", "OR", ("p", "q")),
        ("z", "NOT", ("r",)),
        ("w", "OR", ("z", "a")),
    ),
    ("z", "w"),
)


def truth_tables(net: Netlist) -> list[int]:
    """Oracle: the truth table of every output, by simulation of all 2^n input vectors at once."""
    n = len(net.inputs)
    rows = 1 << n
    mask = (1 << rows) - 1
    words = {}
    for i, x in enumerate(net.inputs):
        w = 0
        for r in range(rows):
            if (r >> i) & 1:
                w |= 1 << r
        words[x] = w
    val = simulate(net, words, mask)
    return [val[o] for o in net.outputs]


def outputs_at(net: Netlist, point: dict[str, int]) -> list[int]:
    val = simulate(net, dict(point), 1)
    return [val[o] for o in net.outputs]


def test_page_example_is_equivalent_after_one_false_negative():
    res = cutpoint_equivalence(A, B)
    assert res.equivalent and res.counterexample is None
    assert res.merges == 2
    assert res.false_negatives == 1
    assert truth_tables(A) == truth_tables(B)


def test_the_cut_miter_of_the_page_has_a_false_counterexample():
    bdd = BDD()
    a, v = bdd.var(0), bdd.var(2)
    cut_miter = bdd.xor(bdd.disj(v, a), a)
    assert cut_miter == bdd.conj(v, bdd.neg(a))
    assert bdd.sat_one(cut_miter) == {0: 0, 2: 1}
    # No real input vector gives z = 1 and a = 0, and no input vector separates the circuits.
    for av in (0, 1):
        for bv in (0, 1):
            assert outputs_at(A, {"a": av, "b": bv}) == outputs_at(B, {"a": av, "b": bv})
    # Moving the cut back to the inputs: v := a AND b gives the exact miter, which is 0.
    assert bdd.compose(cut_miter, 2, bdd.conj(a, bdd.var(1))) == 0


def test_real_difference_gives_a_true_counterexample():
    b2 = Netlist(B.inputs, B.gates[:-1] + (("w", "OR", ("z", "b")),), B.outputs)
    res = cutpoint_equivalence(A, b2)
    assert not res.equivalent
    assert outputs_at(A, res.counterexample) != outputs_at(b2, res.counterexample)


def test_identical_and_constant_circuits():
    c = Netlist(("x",), (("k", "CONST1", ()), ("y", "AND", ("x", "k"))), ("y",))
    d = Netlist(("x",), (), ("x",))
    assert cutpoint_equivalence(c, c).equivalent
    assert cutpoint_equivalence(c, d).equivalent
    e = Netlist(("x",), (("k", "CONST0", ()),), ("k",))
    res = cutpoint_equivalence(c, e)
    assert not res.equivalent and res.counterexample == {"x": 1}


def test_random_against_exhaustive_simulation():
    rng = random.Random(20260)
    seen_false_negative = 0
    seen_different = 0
    for case in range(600):
        n = rng.randint(1, 5)
        a = random_netlist(rng, n, 0, rng.randint(1, 9), rng.randint(1, 3))
        b = rewrite(a, rng)
        if case % 2:
            b = mutate(b, rng)
        res = cutpoint_equivalence(a, b, width=rng.choice([1, 4, 64]), seed=case)
        same = truth_tables(a) == truth_tables(b)
        assert res.equivalent == same
        if not same:
            seen_different += 1
            assert outputs_at(a, res.counterexample) != outputs_at(b, res.counterexample)
        seen_false_negative += res.false_negatives
    assert seen_different > 50
    assert seen_false_negative > 0

History

Berman and Trevillyan (ICCAD 1989) compared two designs by finding internal points that are equivalent and treating them as new inputs of the parts beyond them. Brand (ICCAD 1993) found internal equivalences with test generation on a miter and replaced proved points. Kuehlmann and Krohm (DAC 1997) built BDDs over cut variables with structural hashing, kept many cut frontiers, and removed false negatives by composing back. Kuehlmann, Paruthi, Krohm and Ganai (2002) folded these steps, with SAT, into one engine on an and-inverter graph.

References

  1. A. Kuehlmann and F. Krohm, Equivalence checking using cuts and heaps, DAC 1997, 263 to 268, the cut frontiers, the BDDs over cut variables, and the elimination of false negatives by composition
  2. C. L. Berman and L. H. Trevillyan, Functional comparison of logic designs for VLSI circuits, ICCAD 1989, 456 to 459, equivalent internal points used as cut points that split the two circuits
  3. D. Brand, Verification of large synthesized designs, ICCAD 1993, 534 to 537, internal equivalences found by test generation on a miter, and the replacement of proved points
  4. A. Kuehlmann, V. Paruthi, F. Krohm and M. K. Ganai, Robust Boolean reasoning for equivalence checking and functional property verification, IEEE Transactions on Computer-Aided Design 21(12), 1377 to 1394, 2002, the later engine that interleaves structural hashing, simulation, SAT and BDD sweeping
  5. 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 combinational equivalence checking with cut points and false negatives

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