Algorithmadvanced
BDD-based switching activity estimation
Also called Ghosh-Devadas-Keutzer-White estimation, symbolic switching activity.
Ghosh, Devadas, Keutzer and White's exact estimate of average switching under zero or gate delays, built from BDDs of each node's transitions over two input vectors.
- Time
- O(P B^2) worstO(P + n) best
- Space
- O(P B^2) extra
- Where
- B = the largest number of nodes of a BDD built during the run; G = the number of gates; P = the number of gate input pins; n = the number of primary inputs
- Model
- Word RAM
- Properties
- deterministicexactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Abhijit Ghosh, Srinivas Devadas, Kurt Keutzer, Jacob White, 1992
BDD-based switching activity estimation computes the exact expected number of transitions of every node of a combinational circuit in one clock cycle, given the joint law of each input's values in two consecutive cycles. It builds, with reduced ordered BDDs, the Boolean function of the event "the node changes" over two copies of the inputs, one for the old vector and one for the new, and then sums the probabilities of the paths of that BDD, as in the weighted form of BDD satisfy-count. Ghosh, Devadas, Keutzer and White (1992) did this for zero delay and, by symbolic simulation over time steps, for general gate delays, so that glitches are counted too. The result is exact for any circuit, reconvergent fanout included, as long as the inputs are independent of each other. The price is the size of the BDDs, which can grow exponentially with the number of inputs.
In plain words
To know how often a wire switches, ask a yes or no question about two clock cycles: is its value now different from its value before? That question is itself a logic function, of the old inputs and the new inputs.
A BDD stores a logic function as a decision graph and makes the chance that the function is true easy to compute: walk the graph once, weighting each branch by the chance of the input value it tests.
So the method builds, for each wire, the graph of the old value, the graph of the new value, and their XOR. The chance that the XOR is true is the switching activity. Nothing is guessed about how wires depend on each other, because the graphs keep the full logic.
The problem
The input is a combinational circuit with primary inputs and gates in topological order, and for each input a joint law for , where is the value in one cycle and the value in the next. The pairs of different inputs are independent; the two values of one input can be correlated, which is how the model expresses that an input changes rarely or often. Each node computes a Boolean function , so its value is in the first cycle and in the second.
Under the zero-delay model a node changes at most once per cycle, and the output is the switching activity
for every node . Under a delay model with gate delays, the output is the expected number of transitions of in the cycle, glitches included.
The algorithm
The BDDs use the variable order , so the two copies of an input are next to each other. PAIR-PROB is a memoized traversal; a node of the BDD of that tests stands for a function of only.
BDD-SWITCHING-ACTIVITY(C, J)- 1
for each primary input x_i do - 2
F[x_i] ← the BDD of the variable x_i; F'[x_i] ← the BDD of the variable x_i' - 3
for each gate y = kind(z_1, …, z_k) in topological order do - 4
F[y] ← kind(F[z_1], …, F[z_k]) and F'[y] ← kind(F'[z_1], …, F'[z_k]) by APPLY - 5
A ← F[y] XOR F'[y] - 6
α[y] ← PAIR-PROB(A, J) - 7
return α PAIR-PROB(u, J)- 8
if u is a terminal then return its value (0 or 1) - 9
if u tests x_i then return Σ_{v, v'} J_i(v, v') · PAIR-PROB(u with x_i = v and x_i' = v', J) - 10
if u tests x_i' then return Σ_{v'} (J_i(0, v') + J_i(1, v')) · PAIR-PROB(u with x_i' = v', J)
At line L9 the cofactor "u with and " is found by taking the child of and then, if that child tests , its child; if it does not test , the function does not depend on and the child itself is used. Line L10 handles a node whose function does not depend on , with the marginal law of . Each BDD node is visited once, thanks to the memo.
For a delay model with integer gate delays, the same idea runs over time. The inputs change from to at time 0, and the value of a gate with delay at time is the gate function of its fanins at time . This symbolic simulation builds a BDD for each node and each time step up to the latest arrival time. The expected number of transitions of is then .
Example
Take , and , so , the reconvergent circuit of signal probability propagation.
Fresh random vectors. Let every input be a fresh fair coin in each cycle, so for all four pairs. Then and are independent with , and the algorithm returns . Propagating numbers by independence would give and , which is wrong because of the reconvergence at .
Slowly changing inputs. Let every input keep its value with probability and have , so and . Each input switches in of the cycles, and the algorithm returns and , compared with for fresh vectors. By hand: , so , and is twice that. The BDD of in the order has 13 internal nodes.
Unequal delays. With unit delay on every gate, both paths to have the same length and the symbolic simulation gives transitions per cycle for fresh vectors, the same as zero delay. If has delay 2, a change of can reach through one step before it arrives through , and the result is transition per cycle: more, which is the expected number of glitch transitions.
Correctness
Under the zero-delay model, a node changes in the cycle exactly when , so is the probability that is 1. Lines L2 to L5 build the BDD of by APPLY, which is exact by induction over the gates.
PAIR-PROB returns for every BDD node , by induction on the BDD from the terminals. For a node that tests , the Shannon expansion on and then on writes as a sum over the four values of the indicator of times a cofactor. Because of the variable order, each cofactor depends only on the pairs with , which are independent of the pair . So the probability of each term is times the probability of the cofactor, and line L9 adds them. Line L10 is the same with only present. For the delay model, the number of transitions of is , and the expectation of a sum is the sum of the probabilities, each computed exactly. The full proof gives the details.
Proof: BDD-based switching activity is exact under the zero-delay and the transport delay modelsfull
Setting. The pairs are independent, and . All BDDs are reduced and ordered by . For a BDD node write for its function of . If is not a terminal and tests a variable of input , then depends only on the variables of inputs , because every path below tests only later variables.
Lemma 1 (PAIR-PROB). For every node , PAIR-PROB returns .
Proof. By induction on the BDD in the order of the variables from the bottom. For a terminal, line L8 returns the constant value of .
Suppose tests . Shannon expansion on and then on gives
where the four terms are disjoint. The cofactor is the function of the child of . If tests , then is the function of its child. If does not test , then is a terminal or tests a later variable, so does not depend on and . So the node that line L9 uses has , and it is a terminal or tests a variable of an input . Hence is a function of the pairs with and is independent of . Taking probabilities,
by the induction hypothesis, which is line L9.
Suppose tests . Then does not depend on , Shannon expansion on gives for the children , each child depends only on the inputs , and . This is line L10.
The memo returns, for a node already seen, the value computed the first time, which by the above is the same.
Theorem 1 (zero delay). Under the zero-delay model, BDD-SWITCHING-ACTIVITY returns, for every node , the expected number of transitions of in the cycle.
Proof. By induction in topological order, and are the BDDs of and : for a primary input this is line L2, and for a gate, APPLY computes the BDD of the gate function of its arguments, which by the induction hypothesis are the fanin functions. Under zero delay each node takes the value before the change and after it, with no intermediate values, so it makes one transition if and none otherwise. The expected number of transitions is , which Lemma 1 computes from the BDD of line L5.
Theorem 2 (transport delay). Let every gate have an integer delay , let the inputs change from to at time 0, and let the value of at time be its gate function applied to the values of its fanins at time , every node having its value under before time 0. If is the BDD of the value of at time as a function of , built by the same recurrence with APPLY, then the expected number of transitions of is , where is the latest arrival time.
Proof. By induction on and the topological order, is the BDD of the value of at time , since every value is a Boolean function of given by the recurrence. After time no node changes. The number of transitions of is . Its expectation is the sum of the probabilities by linearity of expectation, and Lemma 1 gives each of them.
Remarks. Neither theorem needs the absence of reconvergent fanout or the independence of and ; only the independence of different pairs is used, in Lemma 1. Theorem 2 is exact for the transport delay model with integer delays; it is not a statement about inertial delays or real circuits.
Complexity
Let be the largest number of nodes of a BDD built during the run. APPLY on two BDDs of sizes and costs , a gate with inputs needs APPLY calls for each copy and one XOR, and PAIR-PROB costs with the memo. So the run costs time, and the unique table can hold that many nodes. When all BDDs stay small, as for a chain of gates in a good order, the cost is . In the worst case is exponential in : a BDD over variables can have about nodes, and multipliers need exponential BDDs in every order. Exact signal probability reduces to this problem: keep every input constant over the cycle, with , add one input with , and the activity of is . Exact signal probability is #P-hard, so no exact method avoids such a cost in general unless every #P function is easy. The delay version multiplies the cost by the number of time steps.
Properties
- Exact. For any circuit and any laws , the result is the exact expected number of transitions under the stated delay model. Reconvergent fanout and the correlation between the two cycles of each input are handled.
- Independence between inputs is still assumed. Pairs of different inputs are independent. Correlated inputs need a joint model, for example a BDD or a Markov chain over the input vectors.
- Temporal correlation of inputs. With fresh independent vectors, , so the activity follows from the signal probability. With correlated it does not, and the full pair model is needed.
- Glitches need the delay model. The zero-delay result counts at most one transition per node per cycle. The symbolic simulation counts every transition that transport delay passes; it does not filter short pulses as inertial delay would.
- Order matters. The size of the BDDs, and so the cost, depends on the variable order. Keeping and adjacent keeps the XOR of the two copies small; putting all old variables before all new ones can make it large.
Variants and improvements
- Sequential circuits. In a finite state machine, the present-state lines are not independent inputs. The paper of Ghosh et al. (1992) also treats sequential circuits. There the state lines need the probabilities of the states, which are the stationary distribution of the state Markov chain, and the next-state logic gives the pairs of consecutive states.
- Partitioning. For a circuit too large for global BDDs, build BDDs over cut points, use independence across the cuts, and accept an approximation at the cuts.
- Probabilistic simulation. Track at each node the probabilities of the four transition types 0 to 0, 0 to 1, 1 to 0 and 1 to 1 under independence, gate by gate. This is fast and approximate, like transition density.
- Inertial filtering. Remove pulses shorter than the gate delay from the symbolic waveforms, to model inertial delay.
- Sampling. When the BDDs are too large, estimate by Monte Carlo power estimation, which has no size limit but gives only an interval.
When to use it
Use it when an exact activity is needed for a circuit or a cone whose BDDs fit in memory: to check faster estimators, for control logic with few inputs, or for the parts of a design whose input statistics are known and strongly correlated in time. For large datapaths such as multipliers the BDDs explode, and simulation is the practical choice.
Pitfalls
- Wrong order. An order with all before all often blows up the XOR of the two copies. Interleave them.
- Mismatched marginals. In steady state the law of and the law of should be the same. A whose marginals differ describes a single cycle, not an average over many cycles.
- Zero delay is not real power. The zero-delay activity misses glitches, which can be a large part of the power in arithmetic circuits, see glitch power.
- Exact under the model only. The result is exact for the stated input laws and delay model. If the inputs are correlated with each other, or the delays are not the integer delays of the model, the error of the model remains.
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 pr1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small reduced ordered BDD package.
Nodes are integers. 0 and 1 are the terminals. An internal node u has a
variable index var(u) (smaller indices are nearer the root), a low child
(the variable is 0) and a high child (the variable is 1). A unique table keeps
the diagram reduced, so two equal functions have the same node.
This module holds node creation, the apply operation with a computed table,
negation, evaluation and size. It holds no estimation algorithm.
"""
from __future__ import annotations
from typing import Callable, Mapping
TERMINAL_VAR = 1 << 30
class BDD:
def __init__(self) -> None:
self.var_of = [TERMINAL_VAR, TERMINAL_VAR]
self.lo = [0, 1]
self.hi = [0, 1]
self.unique: dict[tuple[int, int, int], int] = {}
def mk(self, v: int, lo: int, hi: int) -> int:
"""The node (v, lo, hi), reduced and shared."""
if lo == hi:
return lo
key = (v, lo, hi)
u = self.unique.get(key)
if u is None:
u = len(self.var_of)
self.var_of.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 variable v."""
return self.mk(v, 0, 1)
def is_terminal(self, u: int) -> bool:
return u < 2
def apply(self, op: Callable[[int, int], int], u: int, w: int) -> int:
"""The BDD of op(f_u, f_w) for a binary Boolean operator op."""
memo: dict[tuple[int, int], int] = {}
def rec(a: int, b: int) -> int:
if a < 2 and b < 2:
return op(a, b)
key = (a, b)
r = memo.get(key)
if r is not None:
return r
v = min(self.var_of[a], self.var_of[b])
a0, a1 = (self.lo[a], self.hi[a]) if self.var_of[a] == v else (a, a)
b0, b1 = (self.lo[b], self.hi[b]) if self.var_of[b] == v else (b, b)
r = self.mk(v, rec(a0, b0), rec(a1, b1))
memo[key] = r
return r
return rec(u, w)
def AND(self, u: int, w: int) -> int:
return self.apply(lambda a, b: a & b, u, w)
def OR(self, u: int, w: int) -> int:
return self.apply(lambda a, b: a | b, u, w)
def XOR(self, u: int, w: int) -> int:
return self.apply(lambda a, b: a ^ b, u, w)
def NOT(self, u: int) -> int:
return self.apply(lambda a, b: a ^ b, u, 1)
def evaluate(self, u: int, value: Mapping[int, int]) -> int:
"""The value of f_u when variable v has value value[v]."""
while u >= 2:
u = self.hi[u] if value[self.var_of[u]] else self.lo[u]
return u
def size(self, u: int) -> int:
"""The number of nodes reachable from u, terminals included."""
seen = set()
stack = [u]
while stack:
a = stack.pop()
if a in seen:
continue
seen.add(a)
if a >= 2:
stack.append(self.lo[a])
stack.append(self.hi[a])
return len(seen)
bdd_switching_activity_estimation.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bdd-switching-activity-estimation/. The authors are listed in prov/D7CR16.jsonl.
"""BDD-based switching activity estimation (Ghosh, Devadas, Keutzer and White 1992).
A clock cycle takes the inputs from x to x'. For each input i the pair
(x_i, x'_i) has the joint law J[i][(v, v')], and the pairs of different inputs
are independent. Input i has BDD variable 2i for x_i and 2i + 1 for x'_i, so
the two copies of an input are next to each other in the order.
switching_activity(c, J) returns, for every node y, the exact probability that
y changes in the cycle under the zero-delay model, P(y(x) XOR y(x')).
transport_activity(c, J) returns the exact expected number of transitions of
every node in the cycle under the transport delay model of netlist.waveforms,
glitches included, from the BDDs of the node values at each time step.
"""
from __future__ import annotations
from fractions import Fraction
from typing import Mapping, Sequence
from bdd import BDD
Joint = Mapping[tuple[int, int], Fraction]
def gate_bdd(m: BDD, kind: str, fs: Sequence[int]) -> int:
"""The BDD of a gate applied to the BDDs fs of its fanins."""
r = fs[0]
for f in fs[1:]:
if kind in ("AND", "NAND"):
r = m.AND(r, f)
elif kind in ("OR", "NOR"):
r = m.OR(r, f)
elif kind in ("XOR", "XNOR"):
r = m.XOR(r, f)
else:
raise ValueError(kind)
return m.NOT(r) if kind in ("NOT", "NAND", "NOR", "XNOR") else r
def pair_probability(m: BDD, u: int, J: Sequence[Joint], memo: dict[int, Fraction]) -> Fraction:
"""P(f_u = 1) when the pairs (x_i, x'_i) are independent with laws J[i]."""
def child(a: int, v: int, b: int) -> int:
"""The cofactor of a at variable v = b (a itself if a does not test v)."""
if m.var_of[a] != v:
return a
return m.hi[a] if b else m.lo[a]
def rec(a: int) -> Fraction:
if m.is_terminal(a):
return Fraction(a) # @line L8
r = memo.get(a)
if r is not None:
return r
v = m.var_of[a]
i = v // 2
r = Fraction(0)
if v % 2 == 0: # @line L9
for (b, b2), w in J[i].items():
if w:
r += w * rec(child(child(a, v, b), v + 1, b2))
else: # @line L10
for (b, b2), w in J[i].items():
if w:
r += w * rec(child(a, v, b2))
memo[a] = r
return r
return rec(u)
def switching_activity(c, J: Sequence[Joint]) -> dict[str, Fraction]:
"""Zero-delay switching activity of every node of the netlist.Circuit c."""
m = BDD()
F: dict[str, int] = {}
F2: dict[str, int] = {}
alpha: dict[str, Fraction] = {}
memo: dict[int, Fraction] = {}
for i, x in enumerate(c.inputs): # @line L1
F[x], F2[x] = m.var(2 * i), m.var(2 * i + 1) # @line L2
alpha[x] = pair_probability(m, m.XOR(F[x], F2[x]), J, memo)
for y, kind, fins in c.gates: # @line L3
F[y] = gate_bdd(m, kind, [F[z] for z in fins]) # @line L4
F2[y] = gate_bdd(m, kind, [F2[z] for z in fins])
A = m.XOR(F[y], F2[y]) # @line L5
alpha[y] = pair_probability(m, A, J, memo) # @line L6
return alpha # @line L7
def transport_activity(c, J: Sequence[Joint]) -> dict[str, Fraction]:
"""Expected transitions per cycle under transport delay, by symbolic simulation."""
m = BDD()
old: dict[str, int] = {}
for i, x in enumerate(c.inputs):
old[x] = m.var(2 * i)
for y, kind, fins in c.gates:
old[y] = gate_bdd(m, kind, [old[z] for z in fins])
horizon = max(c.arrival().values())
wave: dict[str, list[int]] = {}
for i, x in enumerate(c.inputs):
wave[x] = [old[x]] + [m.var(2 * i + 1)] * (horizon + 1) # index 0 is time -1
for y, kind, fins in c.gates:
d = c.delay[y]
w = [old[y]]
for t in range(horizon + 1):
s = t - d
w.append(gate_bdd(m, kind, [wave[z][s + 1] if s >= -1 else old[z] for z in fins]))
wave[y] = w
memo: dict[int, Fraction] = {}
out = {}
for v, w in wave.items():
out[v] = sum((pair_probability(m, m.XOR(w[t], w[t - 1]), J, memo) for t in range(1, len(w))), Fraction(0))
return out
def independent_pairs(p: Mapping[str, Fraction], inputs: Sequence[str]) -> list[Joint]:
"""Laws J[i] for inputs that are fresh and independent in each cycle."""
J = []
for x in inputs:
q = Fraction(p[x])
J.append({(a, b): (q if a else 1 - q) * (q if b else 1 - q) for a in (0, 1) for b in (0, 1)})
return J
netlist.py 187 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pr1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate-level combinational netlists for the power estimation pages.
A circuit has named primary inputs and gates in topological order. Each gate
has a kind (BUF, NOT, AND, OR, NAND, NOR, XOR, XNOR), a list of fanin names
and an integer delay (1 by default). A node is a primary input or a gate.
This module holds the circuit model, plain evaluation of one input vector,
structural queries (fanout, support, reconvergence) and a step simulation of
the transport delay model. It holds no estimation algorithm.
"""
from __future__ import annotations
import random
from typing import Iterable, Optional, Sequence
KINDS = ("BUF", "NOT", "AND", "OR", "NAND", "NOR", "XOR", "XNOR")
def gate_value(kind: str, bits: Sequence[int]) -> int:
"""Value of one gate on 0-1 inputs."""
if kind == "BUF":
return bits[0]
if kind == "NOT":
return 1 - bits[0]
if kind in ("AND", "NAND"):
v = int(all(bits))
elif kind in ("OR", "NOR"):
v = int(any(bits))
elif kind in ("XOR", "XNOR"):
v = sum(bits) % 2
else:
raise ValueError(f"unknown gate kind {kind}")
return 1 - v if kind in ("NAND", "NOR", "XNOR") else v
class Circuit:
"""Inputs, then gates (name, kind, fanins) in topological order."""
def __init__(
self,
inputs: Sequence[str],
gates: Sequence[tuple[str, str, Sequence[str]]],
delay: Optional[dict[str, int]] = None,
) -> None:
self.inputs = list(inputs)
self.gates = [(g, k, list(f)) for g, k, f in gates]
seen = set(self.inputs)
if len(seen) != len(self.inputs):
raise ValueError("repeated input name")
for g, k, fins in self.gates:
if k not in KINDS:
raise ValueError(f"unknown gate kind {k}")
if g in seen:
raise ValueError(f"repeated node name {g}")
if not fins or (k in ("BUF", "NOT") and len(fins) != 1):
raise ValueError(f"bad fanin count at {g}")
for f in fins:
if f not in seen:
raise ValueError(f"{g} reads {f} before it is defined")
seen.add(g)
self.nodes = self.inputs + [g for g, _, _ in self.gates]
self.delay = {g: 1 for g, _, _ in self.gates}
if delay:
self.delay.update(delay)
def evaluate(self, x: Sequence[int]) -> dict[str, int]:
"""Values of all nodes for the input vector x (in the order of self.inputs)."""
val = dict(zip(self.inputs, x))
for g, k, fins in self.gates:
val[g] = gate_value(k, [val[f] for f in fins])
return val
def fanout(self) -> dict[str, int]:
"""Number of gate input pins that each node drives."""
cnt = {v: 0 for v in self.nodes}
for _, _, fins in self.gates:
for f in fins:
cnt[f] += 1
return cnt
def is_fanout_free(self) -> bool:
return all(c <= 1 for c in self.fanout().values())
def support(self) -> dict[str, frozenset[str]]:
"""The primary inputs in the transitive fanin of each node."""
sup: dict[str, frozenset[str]] = {x: frozenset([x]) for x in self.inputs}
for g, _, fins in self.gates:
sup[g] = frozenset().union(*(sup[f] for f in fins))
return sup
def has_reconvergence(self) -> bool:
"""True when some gate has two fanin pins whose supports meet."""
sup = self.support()
for _, _, fins in self.gates:
for i in range(len(fins)):
for j in range(i + 1, len(fins)):
if sup[fins[i]] & sup[fins[j]]:
return True
return False
def arrival(self) -> dict[str, int]:
"""Latest time at which each node can change after the inputs change at time 0."""
t = {x: 0 for x in self.inputs}
for g, _, fins in self.gates:
t[g] = self.delay[g] + max(t[f] for f in fins)
return t
def waveforms(c: Circuit, x: Sequence[int], y: Sequence[int]) -> dict[str, list[int]]:
"""Transport delay simulation: the inputs change from x to y at time 0.
Returns, for each node, its values at times -1, 0, 1, ..., T, where T is the
largest arrival time. A gate with delay d has at time t the value of its
function on the values of its fanins at time t - d. Before time 0 every
node holds its value under x.
"""
old = c.evaluate(x)
horizon = max(c.arrival().values())
wave = {v: [old[v]] for v in c.nodes} # index 0 is time -1
for xi, a, b in zip(c.inputs, x, y):
wave[xi] = [a] + [b] * (horizon + 1)
for g, k, fins in c.gates:
d = c.delay[g]
w = [old[g]]
for t in range(horizon + 1):
s = t - d
w.append(gate_value(k, [wave[f][s + 1] if s >= -1 else old[f] for f in fins]))
wave[g] = w
return wave
def transitions(c: Circuit, x: Sequence[int], y: Sequence[int], delay_model: str = "zero") -> dict[str, int]:
"""Number of value changes of each node when the inputs change from x to y.
delay_model "zero": a node changes at most once, when its value under x and y differ.
delay_model "transport": the step simulation of waveforms(), which counts glitches.
"""
if delay_model == "zero":
a, b = c.evaluate(x), c.evaluate(y)
return {v: int(a[v] != b[v]) for v in c.nodes}
if delay_model == "transport":
w = waveforms(c, x, y)
return {v: sum(1 for t in range(1, len(s)) if s[t] != s[t - 1]) for v, s in w.items()}
raise ValueError(delay_model)
def random_circuit(
rng: random.Random,
n_inputs: int,
n_gates: int,
kinds: Iterable[str] = KINDS,
max_fanin: int = 3,
fanout_free: bool = False,
max_delay: int = 1,
) -> Circuit:
"""A random circuit. With fanout_free, every node drives at most one gate pin."""
kinds = list(kinds)
inputs = [f"x{i}" for i in range(n_inputs)]
free = list(inputs)
names = list(inputs)
gates = []
delay = {}
for j in range(n_gates):
pool = free if fanout_free else names
if not pool:
break
k = rng.choice(kinds)
if k in ("BUF", "NOT"):
m = 1
else:
m = min(len(pool), rng.randint(2, max_fanin))
if m < 2:
k = rng.choice(["BUF", "NOT"])
m = 1
fins = rng.sample(pool, m)
g = f"g{j}"
gates.append((g, k, fins))
delay[g] = rng.randint(1, max_delay)
if fanout_free:
for f in fins:
free.remove(f)
free.append(g)
names.append(g)
return Circuit(inputs, gates, delay)
test_bdd_switching_activity_estimation.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bdd-switching-activity-estimation/. The authors are listed in prov/D7CR16.jsonl.
import itertools
import random
from fractions import Fraction
from bdd import BDD
from bdd_switching_activity_estimation import (
gate_bdd,
independent_pairs,
switching_activity,
transport_activity,
)
from netlist import KINDS, Circuit, gate_value, random_circuit, transitions
HALF = Fraction(1, 2)
# y = ab + ac, the reconvergent example of the page.
RECONV = Circuit(["a", "b", "c"], [("u", "AND", ["a", "b"]), ("v", "AND", ["a", "c"]), ("y", "OR", ["u", "v"])])
def brute_force(c, J, delay_model):
"""Expected transitions of every node per cycle, by enumeration of all 4^n vector pairs, in Fraction."""
n = len(c.inputs)
out = {v: Fraction(0) for v in c.nodes}
for x in itertools.product((0, 1), repeat=n):
for y in itertools.product((0, 1), repeat=n):
w = Fraction(1)
for i in range(n):
w *= J[i][(x[i], y[i])]
if w == 0:
continue
for v, k in transitions(c, x, y, delay_model).items():
if k:
out[v] += w * k
return out
def random_joint(rng):
"""A random law of (x_i, x'_i), sometimes with equal marginals and sometimes not."""
ws = [rng.randint(0, 4) for _ in range(4)]
if sum(ws) == 0:
ws[0] = 1
s = sum(ws)
return {(a, b): Fraction(ws[2 * a + b], s) for a in (0, 1) for b in (0, 1)}
def test_bdd_package_against_truth_tables():
for kind in KINDS:
for k in ([1] if kind in ("BUF", "NOT") else [2, 3]):
m = BDD()
u = gate_bdd(m, kind, [m.var(j) for j in range(k)])
for bits in itertools.product((0, 1), repeat=k):
assert m.evaluate(u, dict(enumerate(bits))) == gate_value(kind, bits)
# Canonicity: the same function built two ways gives the same node.
m = BDD()
a, b, c = m.var(0), m.var(1), m.var(2)
f = m.AND(a, m.OR(b, c))
g = m.OR(m.AND(a, b), m.AND(a, c))
assert f == g and m.size(f) == 5
def test_page_example_temporally_independent():
J = independent_pairs({"a": HALF, "b": HALF, "c": HALF}, ["a", "b", "c"])
alpha = switching_activity(RECONV, J)
assert alpha["y"] == 2 * Fraction(3, 8) * Fraction(5, 8) == Fraction(15, 32)
assert alpha["u"] == alpha["v"] == Fraction(3, 8)
assert alpha == brute_force(RECONV, J, "zero")
def test_page_example_with_temporal_correlation():
# Each input keeps its value with probability 3/4 and has P = 1/2.
keep = {(0, 0): Fraction(3, 8), (1, 1): Fraction(3, 8), (0, 1): Fraction(1, 8), (1, 0): Fraction(1, 8)}
J = [keep] * 3
alpha = switching_activity(RECONV, J)
assert alpha["y"] == Fraction(69, 256)
assert alpha == brute_force(RECONV, J, "zero")
tr = transport_activity(RECONV, J)
assert tr == brute_force(RECONV, J, "transport")
def test_zero_delay_equals_enumeration_on_random_circuits():
rng = random.Random(2)
for _ in range(60):
c = random_circuit(rng, rng.randint(1, 5), rng.randint(1, 10))
J = [random_joint(rng) for _ in c.inputs]
assert switching_activity(c, J) == brute_force(c, J, "zero")
def test_transport_delay_equals_enumeration_on_random_circuits():
rng = random.Random(3)
for _ in range(40):
c = random_circuit(rng, rng.randint(1, 4), rng.randint(1, 8), max_delay=3)
J = [random_joint(rng) for _ in c.inputs]
assert transport_activity(c, J) == brute_force(c, J, "transport")
def test_page_example_with_skew():
skew = Circuit(RECONV.inputs, RECONV.gates, {"v": 2})
J = independent_pairs({"a": HALF, "b": HALF, "c": HALF}, ["a", "b", "c"])
assert transport_activity(RECONV, J)["y"] == Fraction(15, 32)
assert transport_activity(skew, J)["y"] == HALF
assert transport_activity(skew, J) == brute_force(skew, J, "transport")
def test_transport_counts_glitches():
c = Circuit(["a"], [("n", "NOT", ["a"]), ("y", "AND", ["a", "n"])])
J = independent_pairs({"a": HALF}, ["a"])
assert switching_activity(c, J)["y"] == 0
assert transport_activity(c, J)["y"] == HALF
def test_independent_vectors_give_2p_1_minus_p():
rng = random.Random(4)
for _ in range(30):
c = random_circuit(rng, rng.randint(1, 5), rng.randint(1, 8))
p = {x: Fraction(rng.randint(0, 4), 4) for x in c.inputs}
J = independent_pairs(p, c.inputs)
alpha = switching_activity(c, J)
prob = {v: Fraction(0) for v in c.nodes}
for x in itertools.product((0, 1), repeat=len(c.inputs)):
w = Fraction(1)
for name, b in zip(c.inputs, x):
w *= p[name] if b else 1 - p[name]
val = c.evaluate(x)
for v in c.nodes:
prob[v] += w * val[v]
for v in c.nodes:
assert alpha[v] == 2 * prob[v] * (1 - prob[v])
History
Ghosh, Devadas, Keutzer and White presented the method at the 1992 Design Automation Conference. They wrote, for each gate, the Boolean conditions under which it switches between two input vectors, under zero delay and under a general delay model by symbolic simulation, and evaluated the probabilities of these conditions with BDDs. This handled the reconvergent fanout that broke earlier propagation methods, and it covered sequential circuits through state probabilities. The method was one of the probabilistic techniques compared in Najm's 1994 survey, where its strength (exact results) and its weakness (BDD size) were already clear.
References
- Abhijit Ghosh, Srinivas Devadas, Kurt Keutzer and Jacob White, Estimation of average switching activity in combinational and sequential circuits, Proceedings of the 29th ACM/IEEE Design Automation Conference, 253 to 259, 1992, the symbolic simulation of the circuit over two input vectors under zero and general delay models, and the BDD computation of the probabilities of the resulting transition functions
- Farid N. Najm, A survey of power estimation techniques in VLSI circuits, IEEE Transactions on VLSI Systems 2(4), 446 to 455, December 1994, the section on probabilistic techniques, which compares BDD-based methods with signal probability and transition density
- Randal E. Bryant, Graph-based algorithms for Boolean function manipulation, IEEE Transactions on Computers C-35(8), 677 to 691, August 1986, reduced ordered BDDs and the apply operation that the method uses
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 D7CR16 Edit this page History Report an error Markdown