Algorithmadvanced
Symbolic trajectory evaluation
Also called STE, Seger-Bryant trajectory evaluation.
Seger and Bryant's model checking of bounded properties over a lattice of ternary states by symbolic simulation, used on large memories and datapaths.
- Time
- O(d P B^2) worst
- Space
- O(d P B^2) extra
- Where
- B = the number of nodes of the largest rail BDD of the run (at most 2^(v + 1), v the number of symbolic variables of the assertion); P = the number of gate inputs of the circuit; d = the largest time in the assertion
- Model
- Word RAM
- Properties
- not completedeterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Carl Johan H. Seger, Randal E. Bryant, 1995
Symbolic trajectory evaluation (STE) checks an assertion on a gate-level circuit. Here and are trajectory formulas, which say which nodes hold which values at which of the first few clock cycles, under guards over symbolic variables. The method runs ternary simulation with BDD values, so each node holds 0, 1 or X under each assignment of the variables. Nodes that does not mention stay X and cost nothing. One run of this simulation builds the defining trajectory of , the least information that every run satisfying must contain. Then a single comparison in the information order tests whether that trajectory already contains what asks for. If the comparison holds for all assignments, every binary run of the circuit that satisfies satisfies . The method checks bounded properties: the depth of the check is the largest time in the formulas. Assertion graphs for unbounded time are the subject of generalized STE.
In plain words
You want to prove: "if the inputs and hold and now, and holds in the next cycle, then two cycles from now the register holds ". Here , and are names for any bits.
STE simulates the circuit once. It puts , and where the assertion says, and X (unknown) on every other input and register. A node gets a formula only when its inputs force one, so a node that does not matter stays X. At the end, STE asks if holds the wanted formula at cycle 2. If yes, the property holds for all values of , , and of the X nodes. If no, the failing cases form a formula. X only hides information, so it can make a true property fail but never makes a false property pass.
The problem
The lattice. A node value is one of X, 0, 1 and , ordered by information: X 0, X 1, 0 and 1 , with 0 and 1 not comparable. X means "no information", and means "conflicting information", which no real run has. The join is the least upper bound, so . A binary value is above exactly when is X or . This page puts X at the bottom. The ternary simulation page uses the order of definedness with 0 and 1 below X, so the two orders are opposite. The meaning is the same.
The circuit. A synchronous circuit has primary inputs, latches with a next-state node , and gates in topological order. In the binary model a run gives every node a value at each time . The inputs and the initial latch values are free. Each gate has the value of its function on its fanins at the same time, and . Seger and Bryant allow any monotone next-state function on the lattice of states. This page uses the zero-delay gate model, which is one instance.
Ternary gates. Each gate operator is extended to on the lattice. On X, 0 and 1 the result is binary when all ways of replacing the X arguments by 0 or 1 give the same binary result, and X otherwise. So and . The extension agrees with on binary arguments and is monotone: for all gives .
Trajectory formulas. Let be a set of symbolic variables and an assignment of them. The formulas here are conjunctions of constraints , read "if then node is at time ", where and are Boolean expressions over . In Seger and Bryant's syntax this is , built from the atoms " is 0" and " is 1", conjunction, a Boolean guard and the next-time operator . A run satisfies a formula at when every constraint with has . The assertion holds when, for every , every run that satisfies at satisfies at .
Defining sequence and trajectory. The defining sequence of a formula gives each node at each time the least lattice value that the formula asks for: the join, over the constraints on whose guard holds, of the value of . A run satisfies at exactly when at every node and time. The defining trajectory is the least sequence above that is closed under the circuit: each gate holds at least of its fanins, and each latch at time holds at least the value of its next-state node at time . The task is to compute, as a BDD, the set of assignments where fails.
The algorithm
Each lattice value under all assignments is a pair of BDDs (one, zero): at the value is X when neither holds, 1 when only one holds, 0 when only zero holds, and when both hold. The join is the OR of the rails, and is . A constraint adds to .
STE(C, A, Cons)- 1
d ← the largest time in A and Cons - 2
for t ← 0 to d do - 3
for each node u do τ_t(u) ← δ_A,t(u) - 4
if t > 0 then for each latch s do τ_t(s) ← τ_t(s) ⊔ τ_(t−1)(next(s)) - 5
for each gate u in topological order do τ_t(u) ← τ_t(u) ⊔ op̂(u)(τ_t of the fanins of u) - 6
AF ← the OR over all t and u of [τ_t(u) = ⊤] - 7
OK ← the AND over all t and u of [δ_Cons,t(u) ⊑ τ_t(u)] - 8
return the residual ¬(OK ∨ AF), and AF
Lines L2 to L5 are one pass of ternary symbolic simulation. Line L3 puts in the antecedent. Line L4 is the clock edge. Line L5 evaluates each gate on dual rails: for AND, the one-rail is the AND of the one-rails of the fanins and the zero-rail is the OR of their zero-rails, and NOT swaps the rails. The join at L5 keeps a value that the antecedent puts on an internal node. Line L6 collects the assignments where the antecedent contradicts itself or the circuit. At those no run satisfies , so the assertion holds there without content. This is an antecedent failure, and a tool reports it, since it often means a wrong antecedent. Line L7 is the one-step check. The assertion holds where the residual is 0, and any assignment in the residual is a counterexample to inspect.
Example
The circuit has inputs , , , latches with and with , and an unrelated latch with . The assertion is
: is at time 0, is at time 0, is at time 1, and : is at time 2.
The defining trajectory, with each node shown by its value as a function of , , :
| time | ||||||||
|---|---|---|---|---|---|---|---|---|
| 0 | X | X | X | X | X | |||
| 1 | X | X | X | X | X | |||
| 2 | X | X | X | X | X | X | X |
At time 0, , and is binary under every . At time 1, takes from time 0 at line L4. At time 2 the consequent asks for , and is that value, so OK is the constant 1. No node is , so AF is 0, and the residual is 0. The assertion holds.
The run used three variables. Symbolic simulation of the same three cycles needs a variable for each input in each cycle and for each latch, which is 12 variables, and would carry them through every cycle. Here stays X.
Now replace by . Then . The two values differ exactly when and are both 1, where the circuit gives 1 and asks for 0. So has one-rail 1 and has zero-rail 1 there, and the residual is . The counterexample is . The tests build both runs and compare them with all binary runs of the circuit.
Correctness
Claim (soundness). For every assignment where the residual is 0 and every binary run that satisfies at , satisfies at . Where AF holds, no run satisfies .
The proof rests on one lemma: if satisfies at , then at every node and time. It goes by induction on and, inside a time, on the order inputs, latches, gates. Each line that writes joins values that are all below . The antecedent part is below because satisfies . The latch part is below by induction at time , because . The gate part is below because is monotone and agrees with on binary values: . A join of values below a binary value is below it, since the join is the least upper bound. Monotonicity is the reason X is safe. Replacing a binary argument by X can only move the result down, to X, and never to the other binary value.
With the lemma, take where OK holds. Then , so satisfies . If AF holds at , some , and no binary value lies above , so no run satisfies at . A residual of 0 means that one of the two cases holds at each . The full proof, with the dual-rail encoding, is in the correctness proof.
The converse fails for binary runs. Seger and Bryant prove that the check is exact for the ternary model: the assertion holds in every trajectory of the ternary circuit exactly when . But a ternary trajectory need not be the image of a binary run. With and left at X, , so the check " is 1" fails, though is 1 in every binary run. When the antecedent fixes every input and every initial latch value to an expression, the trajectory is binary at each , and the check is then exact for binary runs too.
Proof: The one-step lattice check of STE is sound for binary runsfull
Setting. The lattice is with and . The circuit has inputs, latches with next-state nodes , and gates with operators in topological order. A binary run gives each node and time a value , with for each gate and for each latch. Inputs and initial latch values are free. An assignment gives 0 or 1 to each symbolic variable. A constraint holds in at when or . A formula is a finite set of constraints, and satisfies it at when all its constraints hold.
Encoding. A value under all assignments is a pair of BDDs . At it denotes X if , 1 if only , 0 if only , and if both are 1. In this encoding, at is at , and the join is . Both are checked on the 16 pairs of . The value of is the join over the constraints of of . All statements below are about one fixed , and we write for the lattice value that the pair denotes at .
Claim. Let be the residual of line L8. For every with and every run that satisfies at , satisfies at . Moreover, if , no run satisfies at .
Fact 1 (satisfaction is being above). For a binary value and , exactly when or . A constraint contributes X when and the binary value when . So satisfies at exactly when each contribution is below . A set of values is below exactly when its join is, because the join is the least upper bound. Hence satisfies at if and only if for all and .
Fact 2 (monotone gates). The dual-rail gate of line L5 is monotone and agrees with on binary arguments. For NOT the rails swap, which keeps . For AND the one-rail is and the zero-rail is . Both are positive in the rails, so raising any rail of an argument from 0 to 1 can only raise the rails of the result, and is the rail-wise order. OR is the dual. For XOR the rails are built by the recurrence , from , which is again positive in all rails. NAND, NOR and XNOR swap the rails at the end. On binary arguments the rails of each argument are , and each formula then gives . The tests check monotonicity on all argument tuples of . On arguments in they also check that the result is the exact ternary extension: binary exactly when all completions of the X arguments agree.
Lemma (the defining trajectory is below every run). If satisfies at , then for every and every node .
Proof. By induction on , and inside a time on the order of lines L3, L4, L5: inputs, then latches, then gates in topological order. Each line that writes sets it to a join. It is enough to show that each joined term is below , since the join of values below a binary value is below .
- Line L3: the term is , which is below by Fact 1, since satisfies . For inputs and for latches at time 0 this is the only term.
- Line L4, : the new term is . By induction at time it is below .
- Line L5: the new term is of the fanin values . Each fanin is an input, a latch or an earlier gate, so its value is final and by induction. By Fact 2, .
No later line changes .
Proof of the claim. First let . Line L6 gives some and with . If a run satisfied at , the Lemma would give , but no binary value is above . So no run satisfies at , and the assertion holds at without content.
Now let and , so . Line L7 gives for all and , where bounds the times of by line L1. Let satisfy at . By the Lemma and transitivity, for all and , and by Fact 1 satisfies at . If and , the first case applies.
What is not claimed. The check is not complete for binary runs. With and no constraint on , line L5 gives , so the consequent " is 1" fails although every run has . Seger and Bryant (1995) prove that the check is exact for the ternary circuit model: it passes exactly when every ternary trajectory above is above . This page relies on that result only for the remark and does not prove it. One case of completeness for binary runs follows from the Lemma. If sets every input at every time and every latch at time 0 to an expression with guard 1, then at there is exactly one run that satisfies . Each is then binary or . When it is binary it equals , by the Lemma and induction. So OK is false at exactly when breaks . The tests check this case against all runs.
Complexity
The model is the word RAM with hashing in expected constant time. Let be the largest time, the number of gate inputs, the number of symbolic variables and the largest rail BDD.
- Lines L3 and L4 cost one OR of rails per node and latch per time, and line L5 costs BDD operations per gate input. Each operation costs by Apply. Over times this is .
- Lines L6 and L7 cost operations per node and time, which stays within the same bound.
- The BDDs are over variables, so . The variables come from the assertion only, not from the circuit.
The last point is the gain. A circuit with a million latches costs a million X values, not a million variables. For a memory, an antecedent that writes one symbolic word to one address and reads it back leaves all other cells at X. The exponent cannot be removed in general: with empty except for the inputs set to variables, and asking one output to be 1, the residual is 0 exactly when the output function is a tautology, which is coNP-hard to decide.
Properties
- Sound for binary runs: a passing check proves the assertion for all binary runs and all values of the variables. A failing check gives a set of assignments to inspect, which may be false failures caused by X.
- Exact for the ternary model of the circuit (Seger and Bryant 1995).
- Bounded: the check covers times to , and every run of the circuit from any state, since the latches start at X unless sets them.
- The cost depends on the variables in the assertion and the depth, not on the number of latches.
- Deterministic. The result is the same BDD for every gate order that is topological.
Variants and improvements
- Generalized STE. GSTE replaces the linear sequence of times by an assertion graph and computes a fixed point, so a property can talk about unbounded time.
- Theorem proving on top. Hazelhurst and Seger (1995) give inference rules that join STE results, for example two assertions checked apart whose conjunction or sequential composition is then known to hold. This splits a check that is too large for one run.
- Refinement by variables. When a check fails because of X, the user replaces the X on a node by a fresh variable, as in the case. This is a manual form of abstraction refinement. Too many fresh variables bring back the cost of symbolic simulation.
- Abstract interpretation. The ternary lattice is an abstract domain for sets of binary values, with a Galois connection between sets of bits and lattice values. STE is a forward abstract run with one step per clock cycle.
- Other value encodings. The dual-rail pair of BDDs can be replaced by a pair of SAT formulas, so the check becomes a SAT call. This is close to bounded model checking with an X abstraction of the unconstrained nodes.
When to use it
Use STE for properties of bounded length on large circuits where most of the state does not matter for the property: a read after a write in a memory array, one pass of a datapath pipeline, the result of one instruction from any state. It was built for these cases, and the X abstraction keeps the cost to the part of the circuit that the property reads. For properties over unbounded time use GSTE or a symbolic model checker. For small control circuits where much of the state matters, plain symbolic simulation or bounded model checking has no false failures to deal with.
Pitfalls
- False failures from X. A node that the property needs but that the antecedent leaves at X gives a failing check with no real bug, as in . Before you report a bug, replay the counterexample in a binary simulator with values for the X nodes. If the failure goes away, add a variable to the antecedent.
- Vacuous passes. Where AF holds, the assertion passes because no run satisfies . An antecedent with " is 1" and " is 0" at the same time passes every consequent. Check that AF is 0, or at least that it is the expected set.
- The order of the lattice. Code that copies the convention of ternary simulation with 0 below X computes the join as a meet. Fix one order for the whole tool.
- Values on internal nodes. An antecedent may set an internal node, and line L5 joins it with the gate output. If the circuit drives the other value, the result is and the assertion passes without content there. Use this on purpose only, for example to cut a part of the circuit, and look at AF.
- Depth one too short. A latch takes its value at the next time. A consequent at time 1 on a register that is written from a value at time 1 sees only X.
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 hv2 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 ITE cache.
A node is an integer. The terminals are 0 (false) and 1 (true). A variable is a
non-negative integer, and a smaller integer is nearer the root. Every inner node
is a triple (var, lo, hi) with lo != hi, and the unique table keeps one node per
triple, so two BDDs of the same manager are equal functions exactly when they
are the same integer.
"""
from __future__ import annotations
from typing import Iterable, Optional
FALSE = 0
TRUE = 1
_TERMINAL_VAR = 1 << 30
class BDD:
"""One manager. All BDDs that are combined must come from the same manager."""
def __init__(self) -> None:
self._var: list[int] = [_TERMINAL_VAR, _TERMINAL_VAR]
self._lo: list[int] = [0, 1]
self._hi: list[int] = [0, 1]
self._unique: dict[tuple[int, int, int], int] = {}
self._ite_cache: dict[tuple[int, int, int], int] = {}
# -- construction -------------------------------------------------------
def mk(self, v: int, lo: int, hi: int) -> int:
"""The node (v, lo, hi), reduced: equal children give the child."""
if lo == hi:
return lo
key = (v, lo, hi)
n = self._unique.get(key)
if n is None:
n = len(self._var)
self._var.append(v)
self._lo.append(lo)
self._hi.append(hi)
self._unique[key] = n
return n
def var(self, v: int) -> int:
"""The BDD of the single variable v."""
return self.mk(v, FALSE, TRUE)
def top(self, f: int) -> int:
return self._var[f]
def low(self, f: int) -> int:
return self._lo[f]
def high(self, f: int) -> int:
return self._hi[f]
def _cof(self, f: int, v: int, b: int) -> int:
if self._var[f] != v:
return f
return self._hi[f] if b else self._lo[f]
def ite(self, f: int, g: int, h: int) -> int:
"""If f then g else h, by Shannon expansion on the top variable."""
if f == TRUE:
return g
if f == FALSE:
return h
if g == h:
return g
if g == TRUE and h == FALSE:
return f
key = (f, g, h)
r = self._ite_cache.get(key)
if r is not None:
return r
v = min(self._var[f], self._var[g], self._var[h])
lo = self.ite(self._cof(f, v, 0), self._cof(g, v, 0), self._cof(h, v, 0))
hi = self.ite(self._cof(f, v, 1), self._cof(g, v, 1), self._cof(h, v, 1))
r = self.mk(v, lo, hi)
self._ite_cache[key] = r
return r
def neg(self, f: int) -> int:
return self.ite(f, FALSE, TRUE)
def conj(self, f: int, g: int) -> int:
return self.ite(f, g, FALSE)
def disj(self, f: int, g: int) -> int:
return self.ite(f, TRUE, g)
def xor(self, f: int, g: int) -> int:
return self.ite(f, self.neg(g), g)
def xnor(self, f: int, g: int) -> int:
return self.ite(f, g, self.neg(g))
def restrict(self, f: int, v: int, b: int) -> int:
"""f with the variable v set to the constant b."""
memo: dict[int, int] = {}
def go(n: int) -> int:
if n <= 1 or self._var[n] > v:
return n
if n in memo:
return memo[n]
if self._var[n] == v:
r = self._hi[n] if b else self._lo[n]
else:
r = self.mk(self._var[n], go(self._lo[n]), go(self._hi[n]))
memo[n] = r
return r
return go(f)
def exists(self, f: int, vs: Iterable[int]) -> int:
"""Existential quantification of the variables vs."""
for v in sorted(set(vs), reverse=True):
f = self.disj(self.restrict(f, v, 0), self.restrict(f, v, 1))
return f
# -- queries ------------------------------------------------------------
def evaluate(self, f: int, assignment: dict[int, int]) -> int:
"""The value of f at a point; a missing variable counts as 0."""
while f > 1:
f = self._hi[f] if assignment.get(self._var[f], 0) else self._lo[f]
return f
def size(self, f: int) -> int:
"""The number of nodes of f, terminals included."""
seen: set[int] = set()
stack = [f]
while stack:
n = stack.pop()
if n in seen:
continue
seen.add(n)
if n > 1:
stack.append(self._lo[n])
stack.append(self._hi[n])
return len(seen)
def support(self, f: int) -> set[int]:
out: set[int] = set()
seen: set[int] = set()
stack = [f]
while stack:
n = stack.pop()
if n <= 1 or n in seen:
continue
seen.add(n)
out.add(self._var[n])
stack.append(self._lo[n])
stack.append(self._hi[n])
return out
def sat_one(self, f: int) -> Optional[dict[int, int]]:
"""One point where f is 1 (variables not on the path are left out), or None."""
if f == FALSE:
return None
out: dict[int, int] = {}
while f > 1:
if self._lo[f] != FALSE:
out[self._var[f]] = 0
f = self._lo[f]
else:
out[self._var[f]] = 1
f = self._hi[f]
return out
symbolic_trajectory_evaluation.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symbolic-trajectory-evaluation/. The authors are listed in prov/NEAHJQ.jsonl.
"""Symbolic trajectory evaluation (Seger and Bryant 1995) on a gate-level circuit.
Values lie in the lattice X below 0 and 1, and 0 and 1 below TOP. A symbolic
value is a dual-rail pair (one, zero) of BDDs over the symbolic variables: for
an assignment phi of the variables the node is X when neither holds, 1 when only
one holds, 0 when only zero holds, and TOP when both hold. The join is the OR of
the rails, and a <= b is (a.one -> b.one) and (a.zero -> b.zero).
An assertion A ==> C is given by two lists of constraints (t, node, e, g), each
meaning "if g then node is e at time t", with e and g BDDs over the variables.
The check builds the defining trajectory of A by ternary simulation and tests
that the defining sequence of C lies below it, for each phi at once.
Precondition: gates in topological order, as in the Circuit of the page. Cost:
O(d P) dual-rail operations for depth d and P gate inputs, each a BDD operation
on BDDs over the variables of the assertion only.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
from bdd import BDD, FALSE, TRUE
Val = tuple[int, int] # (one, zero)
XV: Val = (FALSE, FALSE)
@dataclass(frozen=True)
class Circuit:
"""inputs; latches as (name, next_state_node); gates as (name, op, fanins) in topological order."""
inputs: tuple[str, ...]
latches: tuple[tuple[str, str], ...]
gates: tuple[tuple[str, str, tuple[str, ...]], ...]
Constraint = tuple[int, str, int, int] # (time, node, value BDD, guard BDD)
@dataclass
class Result:
passed: bool
residual: int # the assignments phi where the assertion fails
antecedent_failure: int # the assignments phi where the trajectory reaches TOP
trajectory: list[dict[str, Val]]
def join(m: BDD, a: Val, b: Val) -> Val:
return (m.disj(a[0], b[0]), m.disj(a[1], b[1]))
def leq(m: BDD, a: Val, b: Val) -> int:
"""The BDD of the assignments where a is below or equal to b."""
return m.conj(m.disj(m.neg(a[0]), b[0]), m.disj(m.neg(a[1]), b[1]))
def gate_value(m: BDD, op: str, args: list[Val]) -> Val:
"""The monotone ternary extension of a gate on dual-rail values."""
if op == "BUF":
return args[0]
if op == "NOT":
return (args[0][1], args[0][0])
if op in ("AND", "NAND", "OR", "NOR"):
conj_like = op in ("AND", "NAND")
one, zero = (TRUE, FALSE) if conj_like else (FALSE, TRUE)
for a1, a0 in args:
if conj_like: # 1 when all are 1, 0 when some is 0
one, zero = m.conj(one, a1), m.disj(zero, a0)
else: # 1 when some is 1, 0 when all are 0
one, zero = m.disj(one, a1), m.conj(zero, a0)
return (zero, one) if op in ("NAND", "NOR") else (one, zero)
if op in ("XOR", "XNOR"):
one, zero = FALSE, TRUE
for a1, a0 in args:
one, zero = (m.disj(m.conj(one, a0), m.conj(zero, a1)),
m.disj(m.conj(one, a1), m.conj(zero, a0)))
return (zero, one) if op == "XNOR" else (one, zero)
raise ValueError(f"unknown gate type {op}")
def defining_sequence(m: BDD, cs: list[Constraint], depth: int) -> list[dict[str, Val]]:
"""delta: for each time, the least values that the constraints ask for."""
seq: list[dict[str, Val]] = [dict() for _ in range(depth + 1)]
for t, u, e, g in cs:
v = (m.conj(g, e), m.conj(g, m.neg(e)))
seq[t][u] = join(m, seq[t].get(u, XV), v)
return seq
def ste(c: Circuit, m: BDD, antecedent: list[Constraint], consequent: list[Constraint]) -> Result:
"""Check the assertion antecedent ==> consequent on the circuit c."""
depth = max([t for t, *_ in antecedent + consequent], default=0) # @line L1
da = defining_sequence(m, antecedent, depth)
dc = defining_sequence(m, consequent, depth)
traj: list[dict[str, Val]] = []
for t in range(depth + 1): # @line L2
tau: dict[str, Val] = {}
for u in list(c.inputs) + [s for s, _ in c.latches] + [g for g, _, _ in c.gates]:
tau[u] = da[t].get(u, XV) # @line L3
if t > 0:
for s, nxt in c.latches: # @line L4
tau[s] = join(m, tau[s], traj[t - 1][nxt])
for g, op, fanins in c.gates: # @line L5
tau[g] = join(m, tau[g], gate_value(m, op, [tau[f] for f in fanins]))
traj.append(tau)
af = FALSE
for tau in traj: # @line L6
for one, zero in tau.values():
af = m.disj(af, m.conj(one, zero))
ok = TRUE
for t in range(depth + 1): # @line L7
for u, v in dc[t].items():
ok = m.conj(ok, leq(m, v, traj[t][u]))
residual = m.neg(m.disj(ok, af)) # @line L8
return Result(residual == FALSE, residual, af, traj)
def is_(t: int, node: str, e: int, guard: int = TRUE) -> Constraint:
"""The constraint "if guard then node is e at time t"."""
return (t, node, e, guard)
def counterexample(m: BDD, r: Result) -> Optional[dict[int, int]]:
"""One assignment of the symbolic variables where the assertion fails."""
return m.sat_one(r.residual)
test_symbolic_trajectory_evaluation.py 215 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symbolic-trajectory-evaluation/. The authors are listed in prov/NEAHJQ.jsonl.
import itertools
import random
from bdd import FALSE, TRUE, BDD
from symbolic_trajectory_evaluation import Circuit, counterexample, gate_value, is_, leq, ste
OPS = ("BUF", "NOT", "AND", "OR", "NAND", "NOR", "XOR", "XNOR")
X, ZERO, ONE, TOP = (FALSE, FALSE), (FALSE, TRUE), (TRUE, FALSE), (TRUE, TRUE)
LATTICE = (X, ZERO, ONE, TOP)
def boolean(op, xs):
if op == "BUF":
return xs[0]
if op == "NOT":
return 1 - xs[0]
if op in ("AND", "NAND"):
return int(all(xs)) ^ (op == "NAND")
if op in ("OR", "NOR"):
return int(any(xs)) ^ (op == "NOR")
return (sum(xs) % 2) ^ (op == "XNOR")
def below(a, b):
return (not a[0] or b[0]) and (not a[1] or b[1])
def pipeline(second="XOR"):
"""The circuit of the page: r1 <- a AND b, r2 <- r1 op c, and an unrelated toggle q."""
return Circuit(
inputs=("a", "b", "c"),
latches=(("r1", "g1"), ("r2", "g2"), ("q", "nq")),
gates=(("g1", "AND", ("a", "b")), ("g2", second, ("r1", "c")), ("nq", "NOT", ("q",))),
)
def page_assertion(m):
x, y, z = m.var(0), m.var(1), m.var(2)
a = [is_(0, "a", x), is_(0, "b", y), is_(1, "c", z)]
c = [is_(2, "r2", m.xor(m.conj(x, y), z))]
return a, c
def test_gate_tables_are_monotone_and_exact():
m = BDD()
for op in OPS:
n = 1 if op in ("BUF", "NOT") else 2
for args in itertools.product(LATTICE, repeat=n):
out = gate_value(m, op, list(args))
for bigger in itertools.product(LATTICE, repeat=n):
if all(below(a, b) for a, b in zip(args, bigger)):
assert below(out, gate_value(m, op, list(bigger)))
if TOP in args:
continue
# On 0, 1 and X the table is Kleene's: binary exactly when all completions agree.
comps = [[0, 1] if a == X else [int(a == ONE)] for a in args]
vals = {boolean(op, list(xs)) for xs in itertools.product(*comps)}
want = X if len(vals) == 2 else (ONE if vals == {1} else ZERO)
assert out == want
def test_page_example_passes():
m = BDD()
a, c = page_assertion(m)
r = ste(pipeline(), m, a, c)
assert r.passed and r.antecedent_failure == FALSE
x, y, z = m.var(0), m.var(1), m.var(2)
assert r.trajectory[1]["r1"] == (m.conj(x, y), m.neg(m.conj(x, y)))
assert r.trajectory[2]["c"] == X and r.trajectory[2]["q"] == X
want = m.xor(m.conj(x, y), z)
assert r.trajectory[1]["g2"] == (want, m.neg(want))
assert r.trajectory[2]["r2"] == (want, m.neg(want))
assert r.trajectory[0]["r1"] == X and r.trajectory[1]["g1"] == X
def test_page_example_bug_is_found():
m = BDD()
a, c = page_assertion(m)
r = ste(pipeline("OR"), m, a, c)
assert not r.passed
x, y, z = m.var(0), m.var(1), m.var(2)
assert r.residual == m.conj(m.conj(x, y), z)
assert counterexample(m, r) == {0: 1, 1: 1, 2: 1}
def test_x_is_too_weak_without_a_variable():
# z = a OR NOT a is 1 in every run, but with a left at X the check fails.
c = Circuit(("a",), (), (("na", "NOT", ("a",)), ("z", "OR", ("a", "na"))))
m = BDD()
assert not ste(c, m, [], [is_(0, "z", TRUE)]).passed
assert ste(c, m, [is_(0, "a", m.var(0))], [is_(0, "z", TRUE)]).passed
def test_antecedent_failure_is_vacuous():
c = Circuit(("a",), (), (("z", "BUF", ("a",)),))
m = BDD()
x, y = m.var(0), m.var(1)
r = ste(c, m, [is_(0, "a", x), is_(0, "a", y)], [is_(0, "z", FALSE)])
assert r.antecedent_failure == m.xor(x, y)
assert r.residual == m.conj(x, y)
# ---------------------------------------------------------------- brute force
def runs(c, depth):
"""Every binary run of length depth + 1: all initial latch values and all inputs."""
nl, ni = len(c.latches), len(c.inputs)
for bits in itertools.product((0, 1), repeat=nl + ni * (depth + 1)):
state = dict(zip([s for s, _ in c.latches], bits[:nl]))
out = []
for t in range(depth + 1):
val = dict(state)
val.update(zip(c.inputs, bits[nl + t * ni: nl + (t + 1) * ni]))
for g, op, fi in c.gates:
val[g] = boolean(op, [val[f] for f in fi])
out.append(val)
state = {s: val[n] for s, n in c.latches}
yield out
def satisfies(m, cs, run, phi):
return all(not m.evaluate(g, phi) or run[t][u] == m.evaluate(e, phi) for t, u, e, g in cs)
def random_expr(m, rng, nv):
k = rng.randrange(5)
if k == 0:
return rng.choice((FALSE, TRUE))
v = m.var(rng.randrange(nv))
if k == 1:
return v
if k == 2:
return m.neg(v)
w = m.var(rng.randrange(nv))
return m.xor(v, w) if k == 3 else m.conj(v, w)
def random_case(rng):
ni, nl = rng.randint(1, 2), rng.randint(0, 2)
inputs = tuple(f"i{j}" for j in range(ni))
lat = [f"s{j}" for j in range(nl)]
nodes = list(inputs) + lat
gates = []
for j in range(rng.randint(1, 5)):
op = rng.choice(OPS)
ar = 1 if op in ("BUF", "NOT") else 2
gates.append((f"g{j}", op, tuple(rng.choice(nodes) for _ in range(ar))))
nodes.append(f"g{j}")
c = Circuit(inputs, tuple((s, rng.choice(nodes)) for s in lat), tuple(gates))
depth = rng.randint(0, 2)
while nl + ni * (depth + 1) > 8:
depth -= 1
return c, nodes, depth
def test_random_soundness_against_all_runs():
rng = random.Random(5150)
nv = 2
checked = 0
for _ in range(500):
c, nodes, depth = random_case(rng)
m = BDD()
guard = lambda: TRUE if rng.random() < 0.6 else random_expr(m, rng, nv) # noqa: E731
ant = [is_(rng.randint(0, depth), rng.choice(nodes), random_expr(m, rng, nv), guard())
for _ in range(rng.randint(0, 4))]
con = [is_(rng.randint(0, depth), rng.choice(nodes), random_expr(m, rng, nv), guard())
for _ in range(rng.randint(1, 2))]
r = ste(c, m, ant, con)
all_runs = list(runs(c, depth))
for bits in itertools.product((0, 1), repeat=nv):
phi = dict(enumerate(bits))
good = [run for run in all_runs if satisfies(m, ant, run, phi)]
if m.evaluate(r.antecedent_failure, phi):
assert not good # TOP means that no run meets the antecedent
for run in good:
# The key lemma: the defining trajectory lies below every run that meets A.
for t, tau in enumerate(r.trajectory):
for u, (one, zero) in tau.items():
if m.evaluate(one, phi):
assert run[t][u] == 1
if m.evaluate(zero, phi):
assert run[t][u] == 0
if not m.evaluate(r.residual, phi):
assert satisfies(m, con, run, phi) # soundness
checked += 1
assert checked > 1000
def test_complete_when_antecedent_fixes_all_inputs_and_state():
# With every input and initial latch value fixed, the trajectory is binary,
# so a failure is a real counterexample.
rng = random.Random(77)
for _ in range(300):
c, nodes, depth = random_case(rng)
m = BDD()
ant = [is_(0, s, random_expr(m, rng, 2)) for s, _ in c.latches]
ant += [is_(t, i, random_expr(m, rng, 2)) for t in range(depth + 1) for i in c.inputs]
con = [is_(rng.randint(0, depth), rng.choice(nodes), random_expr(m, rng, 2))]
r = ste(c, m, ant, con)
assert r.antecedent_failure == FALSE
for bits in itertools.product((0, 1), repeat=2):
phi = dict(enumerate(bits))
good = [run for run in runs(c, depth) if satisfies(m, ant, run, phi)]
assert len(good) == 1
assert bool(m.evaluate(r.residual, phi)) == (not satisfies(m, con, good[0], phi))
def test_leq_on_constants():
m = BDD()
for a in LATTICE:
for b in LATTICE:
assert leq(m, a, b) == (TRUE if below(a, b) else FALSE)
History
Bryant (1991) showed that ternary simulation, with X for unknown values and a monotone circuit model, verifies circuits soundly, and he used it for switch-level designs. Seger and Bryant (1995) built symbolic trajectory evaluation on top of it. They defined the lattice of states, trajectory formulas with the next-time operator, and the defining sequence and trajectory, and they proved that the one-step check is exact for the ternary model. The method went into Seger's Voss system and then into Forte at Intel, where it was used on memory arrays and arithmetic datapaths. Hazelhurst and Seger (1995) added a small theorem prover to join STE runs. Yang and Seger extended the method to assertion graphs as generalized STE.
References
- C.-J. H. Seger and R. E. Bryant, Formal verification by symbolic evaluation of partially-ordered trajectories, Formal Methods in System Design 6(2), 147 to 189, 1995, the lattice of ternary states, the monotone excitation function, trajectory formulas, the defining sequence and the defining trajectory, and the theorem that an assertion holds exactly when the defining sequence of the consequent lies below the defining trajectory of the antecedent
- R. E. Bryant, A methodology for hardware verification based on logic simulation, Journal of the ACM 38(2), 299 to 328, 1991, ternary simulation with X as a sound abstraction of binary behavior, and the monotonicity of the ternary circuit model
- S. Hazelhurst and C.-J. H. Seger, A simple theorem prover based on symbolic trajectory evaluation and BDDs, IEEE Transactions on Computer-Aided Design 14(4), 413 to 422, 1995, inference rules that join STE results, such as conjunction and sequential composition of assertions
- R. E. Bryant, Graph-based algorithms for Boolean function manipulation, IEEE Transactions on Computers C-35(8), 677 to 691, 1986, the reduced ordered BDD and the cost O(|f| |g|) of Apply
Where this leads
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 NEAHJQ Edit this page History Report an error Markdown