Algorithm Search⌘K

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
Properties
deterministicexactofflinerecursive
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 CC with primary inputs x1,…,xnx_1, \ldots, x_n and gates in topological order, and for each input ii a joint law Ji(v,v′)=P(xi=v,xi′=v′)J_i(v, v') = P(x_i = v, x_i' = v') for v,v′∈{0,1}v, v' \in \{0, 1\}, where xix_i is the value in one cycle and xi′x_i' the value in the next. The pairs (xi,xi′)(x_i, x_i') 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 yy computes a Boolean function fyf_y, so its value is fy(x)f_y(x) in the first cycle and fy(x′)f_y(x') in the second.

Under the zero-delay model a node changes at most once per cycle, and the output is the switching activity

α(y)  =  P(fy(x)≠fy(x′))  =  P(fy(x)⊕fy(x′)=1)\alpha(y) \;=\; P\big(f_y(x) \ne f_y(x')\big) \;=\; P\big(f_y(x) \oplus f_y(x') = 1\big)

for every node yy. Under a delay model with gate delays, the output is the expected number of transitions of yy in the cycle, glitches included.

The algorithm

The BDDs use the variable order x1,x1′,x2,x2′,…,xn,xn′x_1, x_1', x_2, x_2', \ldots, x_n, x_n', so the two copies of an input are next to each other. PAIR-PROB is a memoized traversal; a node of the BDD of ff that tests xix_i stands for a function of xi,xi′,…,xn,xn′x_i, x_i', \ldots, x_n, x_n' only.

  1. BDD-SWITCHING-ACTIVITY(C, J)
  2. 1for each primary input x_i do
  3. 2F[x_i] ← the BDD of the variable x_i; F'[x_i] ← the BDD of the variable x_i'
  4. 3for each gate y = kind(z_1, …, z_k) in topological order do
  5. 4F[y] ← kind(F[z_1], …, F[z_k]) and F'[y] ← kind(F'[z_1], …, F'[z_k]) by APPLY
  6. 5A ← F[y] XOR F'[y]
  7. 6α[y] ← PAIR-PROB(A, J)
  8. 7return α
  9. PAIR-PROB(u, J)
  10. 8if u is a terminal then return its value (0 or 1)
  11. 9if u tests x_i then return Σ_{v, v'} J_i(v, v') · PAIR-PROB(u with x_i = v and x_i' = v', J)
  12. 10if 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 xi=vx_i = v and xi′=v′x_i' = v'" is found by taking the vv child of uu and then, if that child tests xi′x_i', its v′v' child; if it does not test xi′x_i', the function does not depend on xi′x_i' and the child itself is used. Line L10 handles a node whose function does not depend on xix_i, with the marginal law of xi′x_i'. 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 xx to x′x' at time 0, and the value of a gate with delay dd at time tt is the gate function of its fanins at time t−dt - d. This symbolic simulation builds a BDD Ft[y]F_t[y] for each node and each time step tt up to the latest arrival time. The expected number of transitions of yy is then ∑tPAIR-PROB(Ft[y]⊕Ft−1[y],J)\sum_t \text{PAIR-PROB}(F_t[y] \oplus F_{t-1}[y], J).

Example

Take u=AND(a,b)u = \mathrm{AND}(a, b), v=AND(a,c)v = \mathrm{AND}(a, c) and y=OR(u,v)y = \mathrm{OR}(u, v), so y=a(b∨c)y = a(b \lor c), the reconvergent circuit of signal probability propagation.

Fresh random vectors. Let every input be a fresh fair coin in each cycle, so Ji(v,v′)=1/4J_i(v, v') = 1/4 for all four pairs. Then fy(x)f_y(x) and fy(x′)f_y(x') are independent with P(y=1)=3/8P(y = 1) = 3/8, and the algorithm returns α(y)=2⋅38⋅58=15/32\alpha(y) = 2 \cdot \frac{3}{8} \cdot \frac{5}{8} = 15/32. Propagating numbers by independence would give P(y=1)=7/16P(y = 1) = 7/16 and α(y)=2⋅716⋅916=63/128\alpha(y) = 2 \cdot \frac{7}{16} \cdot \frac{9}{16} = 63/128, which is wrong because of the reconvergence at yy.

Slowly changing inputs. Let every input keep its value with probability 3/43/4 and have P=1/2P = 1/2, so Ji(0,0)=Ji(1,1)=3/8J_i(0, 0) = J_i(1, 1) = 3/8 and Ji(0,1)=Ji(1,0)=1/8J_i(0, 1) = J_i(1, 0) = 1/8. Each input switches in 1/41/4 of the cycles, and the algorithm returns α(u)=α(v)=7/32\alpha(u) = \alpha(v) = 7/32 and α(y)=69/256≈0.27\alpha(y) = 69/256 \approx 0.27, compared with 15/32≈0.4715/32 \approx 0.47 for fresh vectors. By hand: P(y=y′=1)=P(a=a′=1)⋅P(b∨c=1,b′∨c′=1)=38⋅4164P(y = y' = 1) = P(a = a' = 1) \cdot P(b \lor c = 1, b' \lor c' = 1) = \frac{3}{8} \cdot \frac{41}{64}, so P(y=1,y′=0)=38−123512=69512P(y = 1, y' = 0) = \frac{3}{8} - \frac{123}{512} = \frac{69}{512}, and α(y)\alpha(y) is twice that. The BDD of F[y]⊕F′[y]F[y] \oplus F'[y] in the order a,a′,b,b′,c,c′a, a', b, b', c, c' has 13 internal nodes.

Unequal delays. With unit delay on every gate, both paths to yy have the same length and the symbolic simulation gives 15/3215/32 transitions per cycle for fresh vectors, the same as zero delay. If vv has delay 2, a change of aa can reach yy through uu one step before it arrives through vv, and the result is 1/21/2 transition per cycle: 1/321/32 more, which is the expected number of glitch transitions.

Correctness

Under the zero-delay model, a node changes in the cycle exactly when fy(x)≠fy(x′)f_y(x) \ne f_y(x'), so α(y)\alpha(y) is the probability that A=F[y]⊕F′[y]A = F[y] \oplus F'[y] is 1. Lines L2 to L5 build the BDD of AA by APPLY, which is exact by induction over the gates.

PAIR-PROB returns P(fu=1)P(f_u = 1) for every BDD node uu, by induction on the BDD from the terminals. For a node that tests xix_i, the Shannon expansion on xix_i and then on xi′x_i' writes fuf_u as a sum over the four values (v,v′)(v, v') of the indicator of (xi,xi′)=(v,v′)(x_i, x_i') = (v, v') times a cofactor. Because of the variable order, each cofactor depends only on the pairs (xj,xj′)(x_j, x_j') with j>ij > i, which are independent of the pair (xi,xi′)(x_i, x_i'). So the probability of each term is Ji(v,v′)J_i(v, v') times the probability of the cofactor, and line L9 adds them. Line L10 is the same with only xi′x_i' present. For the delay model, the number of transitions of yy is ∑t[Ft[y]≠Ft−1[y]]\sum_t [F_t[y] \ne F_{t-1}[y]], 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 (X1,X1′),…,(Xn,Xn′)(X_1, X_1'), \ldots, (X_n, X_n') are independent, and P(Xi=v,Xi′=v′)=Ji(v,v′)P(X_i = v, X_i' = v') = J_i(v, v'). All BDDs are reduced and ordered by x1<x1′<x2<x2′<⋯<xn<xn′x_1 < x_1' < x_2 < x_2' < \cdots < x_n < x_n'. For a BDD node uu write fuf_u for its function of (x,x′)(x, x'). If uu is not a terminal and tests a variable of input ii, then fuf_u depends only on the variables of inputs i,i+1,…,ni, i + 1, \ldots, n, because every path below uu tests only later variables.

Lemma 1 (PAIR-PROB). For every node uu, PAIR-PROB(u,J)(u, J) returns P(fu(X,X′)=1)P(f_u(X, X') = 1).

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 fuf_u.

Suppose uu tests xix_i. Shannon expansion on xix_i and then on xi′x_i' gives

fu  =  ∑v,v′∈{0,1}[xi=v] [xi′=v′]  fu∣xi=v, xi′=v′,f_u \;=\; \sum_{v, v' \in \{0,1\}} [x_i = v]\,[x_i' = v']\; f_u|_{x_i = v,\, x_i' = v'},

where the four terms are disjoint. The cofactor fu∣xi=vf_u|_{x_i = v} is the function of the vv child cc of uu. If cc tests xi′x_i', then fc∣xi′=v′f_c|_{x_i' = v'} is the function of its v′v' child. If cc does not test xi′x_i', then cc is a terminal or tests a later variable, so fcf_c does not depend on xi′x_i' and fc∣xi′=v′=fcf_c|_{x_i' = v'} = f_c. So the node wvv′w_{v v'} that line L9 uses has fwvv′=fu∣xi=v,xi′=v′f_{w_{v v'}} = f_u|_{x_i = v, x_i' = v'}, and it is a terminal or tests a variable of an input j>ij > i. Hence fwvv′(X,X′)f_{w_{v v'}}(X, X') is a function of the pairs (Xj,Xj′)(X_j, X_j') with j>ij > i and is independent of (Xi,Xi′)(X_i, X_i'). Taking probabilities,

P(fu=1)  =  ∑v,v′P(Xi=v,Xi′=v′)  P(fwvv′=1)  =  ∑v,v′Ji(v,v′) PAIR-PROB(wvv′,J)P(f_u = 1) \;=\; \sum_{v, v'} P(X_i = v, X_i' = v')\; P(f_{w_{v v'}} = 1) \;=\; \sum_{v, v'} J_i(v, v')\, \text{PAIR-PROB}(w_{v v'}, J)

by the induction hypothesis, which is line L9.

Suppose uu tests xi′x_i'. Then fuf_u does not depend on xix_i, Shannon expansion on xi′x_i' gives fu=∑v′[xi′=v′]fcv′f_u = \sum_{v'} [x_i' = v'] f_{c_{v'}} for the children cv′c_{v'}, each child depends only on the inputs j>ij > i, and P(Xi′=v′)=Ji(0,v′)+Ji(1,v′)P(X_i' = v') = J_i(0, v') + J_i(1, v'). 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. □\square

Theorem 1 (zero delay). Under the zero-delay model, BDD-SWITCHING-ACTIVITY returns, for every node yy, the expected number of transitions of yy in the cycle.

Proof. By induction in topological order, F[y]F[y] and F′[y]F'[y] are the BDDs of fy(x)f_y(x) and fy(x′)f_y(x'): 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 fy(x)f_y(x) before the change and fy(x′)f_y(x') after it, with no intermediate values, so it makes one transition if fy(x)≠fy(x′)f_y(x) \ne f_y(x') and none otherwise. The expected number of transitions is P(fy(X)⊕fy(X′)=1)P(f_y(X) \oplus f_y(X') = 1), which Lemma 1 computes from the BDD AA of line L5. □\square

Theorem 2 (transport delay). Let every gate yy have an integer delay dy≥1d_y \ge 1, let the inputs change from xx to x′x' at time 0, and let the value of yy at time t≥0t \ge 0 be its gate function applied to the values of its fanins at time t−dyt - d_y, every node having its value under xx before time 0. If Ft[y]F_t[y] is the BDD of the value of yy at time tt as a function of (x,x′)(x, x'), built by the same recurrence with APPLY, then the expected number of transitions of yy is ∑t=0TPAIR-PROB(Ft[y]⊕Ft−1[y],J)\sum_{t = 0}^{T} \text{PAIR-PROB}(F_t[y] \oplus F_{t-1}[y], J), where TT is the latest arrival time.

Proof. By induction on tt and the topological order, Ft[y]F_t[y] is the BDD of the value of yy at time tt, since every value is a Boolean function of (x,x′)(x, x') given by the recurrence. After time TT no node changes. The number of transitions of yy is ∑t=0T[y(t)≠y(t−1)]\sum_{t=0}^{T} [y(t) \ne y(t - 1)]. Its expectation is the sum of the probabilities P(Ft[y]⊕Ft−1[y]=1)P(F_t[y] \oplus F_{t-1}[y] = 1) by linearity of expectation, and Lemma 1 gives each of them. □\square

Remarks. Neither theorem needs the absence of reconvergent fanout or the independence of XiX_i and Xi′X_i'; 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 BB be the largest number of nodes of a BDD built during the run. APPLY on two BDDs of sizes b1b_1 and b2b_2 costs O(b1b2)O(b_1 b_2), a gate with kk inputs needs k−1k - 1 APPLY calls for each copy and one XOR, and PAIR-PROB costs O(B)O(B) with the memo. So the run costs O(PB2)O(P B^2) 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 O(P+n)O(P + n). In the worst case BB is exponential in nn: a BDD over 2n2n variables can have about 22n/n2^{2n} / n nodes, and multipliers need exponential BDDs in every order. Exact signal probability reduces to this problem: keep every input constant over the cycle, with Ji(v,v)=P(xi=v)J_i(v, v) = P(x_i = v), add one input tt with Jt(0,1)=1J_t(0, 1) = 1, and the activity of AND(y,t)\mathrm{AND}(y, t) is P(y=1)P(y = 1). 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 JiJ_i, 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, α(y)=2P(y)(1−P(y))\alpha(y) = 2 P(y)(1 - P(y)), so the activity follows from the signal probability. With correlated JiJ_i 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 xix_i and xi′x_i' 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 xx before all x′x' often blows up the XOR of the two copies. Interleave them.
  • Mismatched marginals. In steady state the law of xix_i and the law of xi′x_i' should be the same. A JiJ_i 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.

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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • 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