Algorithm Search⌘K

Algorithmcore

Monte Carlo power estimation

Also called Burch-Najm-Yang-Trick estimation, statistical power estimation.

Simulates random input samples until a confidence interval on the mean power is tight enough, a stopping rule by Burch, Najm, Yang and Trick.

Time
O(N T (G + P)) worst
Space
O(G + n) extra
Where
G = the number of gates; N = the number of samples drawn; P = the number of gate input pins; T = the number of clock cycles per sample; n = the number of primary inputs
Properties
randomizednot exactonlineiterative
Origin
Richard Burch, Farid N. Najm, Ping Yang, Timothy N. Trick, 1992

Monte Carlo power estimation finds the average power of a circuit by simulation with random inputs, and decides by itself when to stop. Each sample is the power of the circuit over a short period of simulated clock cycles with random input vectors, and the samples are independent. By the central limit theorem, the mean of NN samples is close to normal for large NN, so after each sample the method computes a confidence interval for the mean power. It stops when the half width of the interval is below a fraction ε\varepsilon of the sample mean, after a minimum number of samples. Burch, Najm, Yang and Trick (1992, 1993) proposed this method. It works with any simulator and any delay model, it handles reconvergent fanout, correlation and glitches as well as the simulator does, and the number of samples depends on the spread of the power, not on the size of the circuit. The result is a statistical statement: with probability about 1−α1 - \alpha the true mean is within the interval.

In plain words

To learn the average power of a chip, run it on random inputs for a short time, measure the power, and do this again and again. Each run gives a number, and the average of the numbers approaches the true average.

The question is when to stop. After each run, look at how much the numbers differ from each other. From that spread and the number of runs, statistics tells how far the current average can be from the true one, with a chosen confidence such as 95 percent.

Stop when that distance is small compared with the average itself, for example under 5 percent. Circuits whose power varies little stop after a few dozen runs.

The problem

The input is a circuit with a simulator, a random model of its inputs, a period of TT clock cycles, a relative error ε∈(0,1)\varepsilon \in (0, 1) and a confidence level 1−α1 - \alpha. A sample is the power over one period: the simulator starts from a random state of the inputs, applies TT random input vectors, adds 12CyVDD2\frac{1}{2} C_y V_{DD}^2 for every transition of every node yy with load CyC_y, and divides by the period. The samples E1,E2,…E_1, E_2, \ldots are independent and have the same law, with an unknown mean μ>0\mu > 0, the average power, and a finite variance σ2\sigma^2. The output is an estimate η\eta of μ\mu with a half width hh such that h<εηh < \varepsilon \eta and the interval [η−h,η+h][\eta - h, \eta + h] contains μ\mu with probability about 1−α1 - \alpha.

The algorithm

  1. MONTE-CARLO-POWER(sample, ε, α, N_min, N_max)
  2. 1z ← the 1 − α/2 quantile of the standard normal law
  3. 2N ← 0; mean ← 0; M2 ← 0; h ← ∞
  4. 3repeat
  5. 4E ← sample() ▷ simulate one period of T cycles with random inputs
  6. 5N ← N + 1; δ ← E − mean; mean ← mean + δ / N; M2 ← M2 + δ · (E − mean)
  7. 6if N ≥ 2 then s ← sqrt(M2 / (N − 1)); h ← z · s / sqrt(N)
  8. 7until N ≥ N_max or (N ≥ N_min and h < ε · mean)
  9. 8return mean, h, N

Line L5 is Welford's update, which keeps the mean and the sum of squared deviations in one pass without loss of precision. Line L7 is the stopping rule. Nmin⁡N_{\min}, often 30, keeps the rule from stopping on a few samples that happen to agree, and Nmax⁡N_{\max} stops the loop when the mean is 0 or the samples vary too much.

Example

Take a two-bit ripple-carry adder built from two full adders (10 gates: per bit two XOR, two AND and one OR), with unit load on each gate output, VDD=1V_{DD} = 1, and energies in units of CVDD2C V_{DD}^2 per cycle. Each of the five inputs is a two-state Markov chain from cycle to cycle with its own switching probabilities. Enumerating all 454^5 pairs of consecutive vectors in exact arithmetic gives the true mean: 233/120≈1.942233/120 \approx 1.942 per cycle with zero delay, and 5519/2160≈2.5555519/2160 \approx 2.555 per cycle with unit transport delay, where glitches are 24 percent of the total, 32 percent more than with zero delay.

One run with T=4T = 4, ε=0.1\varepsilon = 0.1 and α=0.05\alpha = 0.05 (z=1.96z = 1.96):

delay model samples NN estimate η\eta half width hh h/ηh / \eta true mean covered
zero 33 1.955 0.190 0.097 1.942 yes
transport 64 2.314 0.231 0.100 2.555 no

The second run misses: its interval ends at 2.545. A 95 percent interval misses about one run in 20, and this is one of them. Over 300 runs with different seeds and zero delay, the interval contained the true mean in 94.7 percent of the runs, with 30 to 63 samples per run; over 150 runs with transport delay, in 96.0 percent, with 30 to 77 samples. With T=1T = 1, single-cycle samples, the runs needed about 149 samples and the coverage fell to 92.0 percent, because one-cycle energies take few values and are far from normal. These are measured frequencies, not proved values.

Correctness

Three facts hold, with the details in the full proof.

When the interval covers, the relative error is bounded. At the stop, h<εηh < \varepsilon \eta. If also ∣η−μ∣≤h|\eta - \mu| \le h, then ∣η−μ∣<εη|\eta - \mu| < \varepsilon \eta, and since then η<μ/(1−ε)\eta < \mu / (1 - \varepsilon), the error relative to the true mean is below ε/(1−ε)\varepsilon / (1 - \varepsilon). For ε=0.05\varepsilon = 0.05 this is 5.3 percent.

For a fixed number of samples, the interval has the stated confidence. If NN is fixed and the samples are normal, (η−μ)/(s/N)(\eta - \mu) / (s / \sqrt{N}) has the Student tt law with N−1N - 1 degrees of freedom, so the interval with the tt quantile in place of zz has coverage exactly 1−α1 - \alpha; with zz the coverage is slightly lower, about 94 percent in place of 95 at N=30N = 30 for α=0.05\alpha = 0.05. If the samples are not normal but have finite variance, the coverage tends to 1−α1 - \alpha as NN grows, by the central limit theorem and the convergence of ss to σ\sigma.

With the stopping rule, the confidence is only asymptotic. Here NN depends on the data, and the coverage is not exactly 1−α1 - \alpha even for normal samples. Chow and Robbins (1965) proved that for the analogous rule with a fixed width the coverage tends to 1−α1 - \alpha as the width tends to 0; the relative rule behaves the same way when μ>0\mu > 0. This is cited, not proved here. In practice the coverage is measured, as in the example.

Proof: The stopping rule of Monte Carlo power estimation from the normal confidence intervalfull

Setting. The samples E1,E2,…E_1, E_2, \ldots are independent with the same law, mean μ>0\mu > 0 and variance σ2∈(0,∞)\sigma^2 \in (0, \infty). After NN samples, ηN\eta_N is the sample mean, sNs_N the sample standard deviation, zz the 1−α/21 - \alpha/2 quantile of the standard normal law and hN=zsN/Nh_N = z s_N / \sqrt{N}.

Lemma 1 (Welford). After line L5 has run NN times, mean =ηN= \eta_N and M2=∑k=1N(Ek−ηN)2M2 = \sum_{k=1}^N (E_k - \eta_N)^2, so line L6 sets s=sNs = s_N and h=hNh = h_N.

Proof. By induction on NN. For N=1N = 1, mean =E1= E_1 and M2=0M2 = 0. Suppose the claim holds for N−1N - 1. With δ=EN−ηN−1\delta = E_N - \eta_{N-1}, line L5 sets mean =ηN−1+δ/N=ηN= \eta_{N-1} + \delta / N = \eta_N. Also EN−ηN=δ(N−1)/NE_N - \eta_N = \delta (N - 1)/N, and

∑k=1N(Ek−ηN)2=∑k=1N−1(Ek−ηN−1)2+(N−1)(ηN−1−ηN)2+(EN−ηN)2,\sum_{k=1}^{N} (E_k - \eta_N)^2 = \sum_{k=1}^{N-1} (E_k - \eta_{N-1})^2 + (N - 1)(\eta_{N-1} - \eta_N)^2 + (E_N - \eta_N)^2,

since the cross term ∑k<N(Ek−ηN−1)\sum_{k < N} (E_k - \eta_{N-1}) is 0. With ηN−1−ηN=−δ/N\eta_{N-1} - \eta_N = -\delta / N the last two terms are δ2(N−1)/N2+δ2(N−1)2/N2=δ2(N−1)/N=δ(EN−ηN)\delta^2 (N - 1)/N^2 + \delta^2 (N-1)^2/N^2 = \delta^2 (N - 1)/N = \delta (E_N - \eta_N), which is the increment of line L5. □\square

Theorem 1 (relative error on the covering event). Let ε∈(0,1)\varepsilon \in (0, 1). If the run stops by the rule hN<εηNh_N < \varepsilon \eta_N and ∣ηN−μ∣≤hN|\eta_N - \mu| \le h_N, then

∣ηN−μ∣<ε ηNand∣ηN−μ∣μ<ε1−ε.|\eta_N - \mu| < \varepsilon\, \eta_N \qquad\text{and}\qquad \frac{|\eta_N - \mu|}{\mu} < \frac{\varepsilon}{1 - \varepsilon}.

Proof. The first inequality is ∣ηN−μ∣≤hN<εηN|\eta_N - \mu| \le h_N < \varepsilon \eta_N. It gives ηN−μ<εηN\eta_N - \mu < \varepsilon \eta_N, so ηN(1−ε)<μ\eta_N (1 - \varepsilon) < \mu and ηN<μ/(1−ε)\eta_N < \mu / (1 - \varepsilon). Then ∣ηN−μ∣<εηN<εμ/(1−ε)|\eta_N - \mu| < \varepsilon \eta_N < \varepsilon \mu / (1 - \varepsilon). □\square

So the probability that the returned estimate has relative error below ε/(1−ε)\varepsilon / (1 - \varepsilon) is at least the probability that the interval [ηN−hN,ηN+hN][\eta_N - h_N, \eta_N + h_N] at the stopping time contains μ\mu. The rest of the argument is about that probability.

Theorem 2 (fixed NN). Let N≥2N \ge 2 be fixed.

  1. If the EkE_k are normal, then P(∣ηN−μ∣≤t sN/N)=1−αP(|\eta_N - \mu| \le t\, s_N / \sqrt{N}) = 1 - \alpha for the 1−α/21 - \alpha/2 quantile tt of the Student law with N−1N - 1 degrees of freedom.
  2. For any law with finite variance, P(∣ηN−μ∣≤hN)→1−αP(|\eta_N - \mu| \le h_N) \to 1 - \alpha as N→∞N \to \infty.

Proof. (1) For normal samples, ηN\eta_N and sN2s_N^2 are independent, N(ηN−μ)/σ\sqrt{N}(\eta_N - \mu)/\sigma is standard normal and (N−1)sN2/σ2(N - 1) s_N^2 / \sigma^2 is chi-square with N−1N - 1 degrees of freedom, so N(ηN−μ)/sN\sqrt{N} (\eta_N - \mu) / s_N has the Student law with N−1N - 1 degrees of freedom. (2) By the central limit theorem N(ηN−μ)/σ\sqrt{N}(\eta_N - \mu)/\sigma tends in law to the standard normal law, and sN→σs_N \to \sigma almost surely by the law of large numbers, so by Slutsky's lemma N(ηN−μ)/sN\sqrt{N} (\eta_N - \mu) / s_N tends in law to the standard normal law, whose probability of [−z,z][-z, z] is 1−α1 - \alpha. □\square

The stopping time. At line L7 the number of samples is a random time τ\tau that depends on sNs_N and ηN\eta_N, so Theorem 2 does not apply directly at N=τN = \tau. As ε→0\varepsilon \to 0, τ→∞\tau \to \infty and τ ε2μ2/(z2σ2)→1\tau\, \varepsilon^2 \mu^2 / (z^2 \sigma^2) \to 1 almost surely, because sN/ηN→σ/μs_N / \eta_N \to \sigma / \mu almost surely. Chow and Robbins (1965) proved, for the fixed-width rule that stops when hNh_N is below a given width dd, that the coverage at the stopping time tends to 1−α1 - \alpha as d→0d \to 0; the proof uses Anscombe's theorem, which keeps the central limit theorem valid at a random index τ\tau with τ/nε→1\tau / n_\varepsilon \to 1 in probability for constants nε→∞n_\varepsilon \to \infty. The same argument applies to the relative rule with nε=z2σ2/(ε2μ2)n_\varepsilon = z^2 \sigma^2 / (\varepsilon^2 \mu^2). This step is cited, not proved here. For fixed ε\varepsilon the coverage is not exactly 1−α1 - \alpha, and the example of the page measures it.

What is proved and what is measured. Proved: lines L5 and L6 compute the sample mean and the half width exactly (Lemma 1); on the event that the interval covers μ\mu, the relative error is below ε/(1−ε)\varepsilon / (1 - \varepsilon) (Theorem 1); for fixed NN the coverage is exact with the tt quantile and normal samples, and asymptotic otherwise (Theorem 2). Cited: the asymptotic coverage under the stopping rule. Measured: the coverage of the rule for a given circuit, input model and ε\varepsilon.

Complexity

Each sample simulates TT cycles, and one zero-delay simulation of a cycle costs O(G+P)O(G + P), so the run costs O(NT(G+P))O(N T (G + P)) time and O(G+n)O(G + n) space beyond the circuit. With an event-driven simulator the cost per cycle is proportional to the number of events, which is smaller when activity is low. The number of samples is set by the stopping rule: the rule stops near

N  ≈  (z σε μ)2,N \;\approx\; \left(\frac{z\, \sigma}{\varepsilon\, \mu}\right)^2,

the usual sample size for a relative error. It grows as 1/ε21 / \varepsilon^2 and with the square of the coefficient of variation σ/μ\sigma / \mu of the samples, and it does not depend on the number of gates. Longer periods TT lower σ/μ\sigma / \mu and so lower NN, at a higher cost per sample.

Properties

  • Unbiased samples, approximate stop. Each EkE_k has mean μ\mu exactly when the inputs start from their stationary law; the estimate at the stop has a small bias because the stop depends on the data.
  • Any delay model. The method uses the simulator as a black box. Glitches, real gate delays, and correlated or sequential inputs are handled as well as the simulator handles them.
  • Online. Samples can be added one at a time, and the run can be paused and resumed, since Welford's update keeps all the state in three numbers.
  • Parallel. Samples are independent, so they can be run on many machines and the means and variances merged.
  • Statistical guarantee only. No finite run proves a bound. A miss happens with probability about α\alpha, and with heavy-tailed or very skewed samples more often.

Variants and improvements

  • Student tt quantile. Use the tt quantile with N−1N - 1 degrees of freedom in place of zz at line L6, as in a t confidence interval. For N≥30N \ge 30 the two differ by a few percent.
  • Absolute error for small values. For the activity of single nodes, a node that rarely switches would need a huge NN for a relative error. Najm and his students certified such nodes with an absolute error bound instead, and used the relative rule only above a threshold.
  • Nonparametric stopping. Methods based on order statistics drop the normal assumption on the samples.
  • Variance reduction. Stratified sampling of input patterns and importance sampling lower σ\sigma and so NN.
  • Anytime-valid intervals. A confidence sequence holds at every NN at once, so it allows any stopping rule with an exact guarantee, at the cost of a wider interval.
  • Exact methods. For small circuits, BDD-based switching activity estimation gives the exact mean under its delay model, and transition density gives a fast approximation without simulation.

When to use it

Use it for the average power of a large gate-level or transistor-level circuit when the input statistics are known and a stated accuracy is needed, especially when glitches, real delays or correlations make probabilistic methods unreliable. It is the reference method against which faster estimators are checked. Do not use it for the peak power or the worst case: it estimates a mean, and rare high-power vectors barely affect the mean.

Pitfalls

  • Non-stationary start. If each sample starts from a fixed state, for example all zeros, the first cycles have a different law and the mean is biased. Start from the stationary law, or discard a warm-up period.
  • Dependent samples. Consecutive periods of one long simulation are correlated. The interval then is too narrow. Use independent restarts, or batch means with batches long enough.
  • Too short periods. Samples of one or two cycles take few values and are skewed, so the normal interval covers less than its nominal level, as the example shows.
  • Mean near zero. The relative rule never stops when μ\mu is 0 or tiny. Use Nmax⁡N_{\max}, or an absolute error.
  • Stopping too early. With Nmin⁡N_{\min} too small, a few samples that happen to agree give a small ss and an early stop.
  • The input model is part of the answer. The interval is about the mean under the chosen random inputs. If real workloads differ, the estimate is precise and wrong.

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.

monte_carlo_power_estimation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monte-carlo-power-estimation/. The authors are listed in prov/QFM309.jsonl.
"""Monte Carlo power estimation with a stopping rule (after Burch, Najm, Yang and Trick 1993).

monte_carlo_power(sample, eps, alpha) draws independent power samples until
the half width of the normal confidence interval at level 1 - alpha is below
eps times the sample mean, after at least n_min samples. It returns the mean,
the half width and the number of samples. The mean and the variance are kept
by Welford's update.

power_sampler(c, up, down, cap, T, rng) builds a sampler for a netlist.Circuit:
each input is a two-state Markov chain per clock cycle (0 -> 1 with
probability up, 1 -> 0 with probability down), independent of the other
inputs. One sample starts from the stationary law, simulates T cycles and
returns the mean energy per cycle, sum over transitions of cap[node] / 2, in
units of V_DD^2. Power is this value times the clock frequency.
"""

from __future__ import annotations

import math
import random
from statistics import NormalDist
from typing import Callable, Mapping, Sequence

from netlist import transitions


def monte_carlo_power(
    sample: Callable[[], float],
    eps: float,
    alpha: float = 0.05,
    n_min: int = 30,
    n_max: int = 10**6,
) -> tuple[float, float, int]:
    """Return (mean, half width, N) of the estimate of E[sample()]."""
    z = NormalDist().inv_cdf(1 - alpha / 2)  # @line L1
    n, mean, m2, half = 0, 0.0, 0.0, math.inf  # @line L2
    while True:  # @line L3
        e = sample()  # @line L4
        n += 1
        delta = e - mean
        mean += delta / n
        m2 += delta * (e - mean)  # @line L5
        if n >= 2:
            half = z * math.sqrt(m2 / (n - 1)) / math.sqrt(n)  # @line L6
        if n >= n_max or (n >= n_min and half < eps * mean):  # @line L7
            return mean, half, n  # @line L8


def power_sampler(
    c,
    up: Sequence[float],
    down: Sequence[float],
    cap: Mapping[str, float],
    T: int,
    rng: random.Random,
    delay_model: str = "zero",
) -> Callable[[], float]:
    """A sampler of the mean energy per cycle over T cycles, from a stationary start."""
    n = len(c.inputs)
    pi1 = [up[i] / (up[i] + down[i]) for i in range(n)]

    def sample() -> float:
        x = [1 if rng.random() < pi1[i] else 0 for i in range(n)]
        energy = 0.0
        for _ in range(T):
            y = [(1 - b) if rng.random() < (down[i] if b else up[i]) else b for i, b in enumerate(x)]
            for v, k in transitions(c, x, y, delay_model).items():
                if k:
                    energy += 0.5 * cap.get(v, 0.0) * k
            x = y
        return energy / T

    return sample
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_monte_carlo_power_estimation.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monte-carlo-power-estimation/. The authors are listed in prov/QFM309.jsonl.

import itertools
import math
import random
import statistics
from fractions import Fraction
from statistics import NormalDist

from monte_carlo_power_estimation import monte_carlo_power, power_sampler
from netlist import Circuit, transitions


def full_adder(p, a, b, c):
    return [
        (p + "t", "XOR", [a, b]),
        (p + "s", "XOR", [p + "t", c]),
        (p + "g", "AND", [a, b]),
        (p + "h", "AND", [p + "t", c]),
        (p + "co", "OR", [p + "g", p + "h"]),
    ]


# The two-bit ripple-carry adder of the page, unit load on every gate output.
ADD = Circuit(["a0", "b0", "a1", "b1", "ci"], full_adder("f0", "a0", "b0", "ci") + full_adder("f1", "a1", "b1", "f0co"))
CAP = {g: 1 for g, _, _ in ADD.gates}
UP = [Fraction(1, 2), Fraction(1, 4), Fraction(1, 2), Fraction(1, 3), Fraction(1, 5)]
DOWN = [Fraction(1, 2), Fraction(1, 2), Fraction(1, 4), Fraction(1, 3), Fraction(1, 5)]


def exact_mean(c, up, down, cap, model):
    """E[energy per cycle] in the stationary regime, by enumeration of all 4^n vector pairs, in Fraction."""
    n = len(c.inputs)
    tot = Fraction(0)
    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):
                pi1 = up[i] / (up[i] + down[i])
                w *= pi1 if x[i] else 1 - pi1
                f = down[i] if x[i] else up[i]
                w *= f if x[i] != y[i] else 1 - f
            if w == 0:
                continue
            for v, k in transitions(c, x, y, model).items():
                tot += w * Fraction(cap.get(v, 0)) * k / 2
    return tot


def run(model, T, eps, runs, seed):
    mu = float(exact_mean(ADD, UP, DOWN, CAP, model))
    covered = relative_ok = 0
    sizes = []
    for r in range(runs):
        rng = random.Random(seed + r)
        s = power_sampler(ADD, [float(u) for u in UP], [float(d) for d in DOWN], CAP, T, rng, model)
        m, h, n = monte_carlo_power(s, eps, 0.05)
        assert n >= 30 and h < eps * m
        covered += abs(m - mu) <= h
        relative_ok += abs(m - mu) <= eps / (1 - eps) * mu
        sizes.append(n)
    return covered / runs, relative_ok / runs, sizes


def test_exact_means_of_the_page():
    assert exact_mean(ADD, UP, DOWN, CAP, "zero") == Fraction(233, 120)
    assert exact_mean(ADD, UP, DOWN, CAP, "transport") == Fraction(5519, 2160)


def test_welford_matches_statistics():
    rng = random.Random(1)
    data = [rng.expovariate(1.0) for _ in range(200)]
    it = iter(data)
    m, h, n = monte_carlo_power(lambda: next(it), eps=0.0, alpha=0.05, n_max=200)
    assert n == 200
    assert math.isclose(m, statistics.fmean(data), rel_tol=1e-12)
    z = NormalDist().inv_cdf(0.975)
    assert math.isclose(h, z * statistics.stdev(data) / math.sqrt(200), rel_tol=1e-9)


def test_minimum_sample_count_and_cap():
    m, h, n = monte_carlo_power(lambda: 1.0, eps=0.01)
    assert (m, h, n) == (1.0, 0.0, 30)
    m, h, n = monte_carlo_power(lambda: 0.0, eps=0.01, n_max=50)
    assert n == 50


def test_coverage_zero_delay():
    cov, rel, sizes = run("zero", T=4, eps=0.1, runs=300, seed=1000)
    # Nominal level 0.95; the measured coverage must be close to it.
    assert cov >= 0.9
    assert rel >= cov


def test_coverage_transport_delay():
    cov, rel, sizes = run("transport", T=4, eps=0.1, runs=150, seed=5000)
    assert cov >= 0.88
    assert rel >= cov


def test_sample_count_grows_as_one_over_eps_squared():
    _, _, wide = run("zero", T=4, eps=0.2, runs=40, seed=7000)
    _, _, narrow = run("zero", T=4, eps=0.1, runs=40, seed=7000)
    assert statistics.fmean(narrow) > 1.3 * statistics.fmean(wide)

History

Burch, Najm, Yang and Trick presented McPOWER at ICCAD in 1992 and published the method in the first issue of IEEE Transactions on VLSI Systems in 1993. They argued that the power over a period with random inputs is close to normal, and applied a stopping rule from the normal interval with a minimum number of samples, so that the simulation length follows from the requested accuracy and not from a guess. Najm's 1994 survey set the statistical approach next to the probabilistic ones, and later work extended it to the activity of each node, to sequential circuits and to nonparametric stopping rules. The statistical background, sequential intervals whose sample size depends on the data, goes back to Chow and Robbins (1965).

References

  1. Richard Burch, Farid N. Najm, Ping Yang and Timothy N. Trick, A Monte Carlo approach for power estimation, IEEE Transactions on VLSI Systems 1(1), 63 to 71, March 1993, the sampling of the power over random input periods, the normality argument, and the stopping criterion with a minimum number of samples (the exact form of the criterion was not checked against the paper)
  2. Richard Burch, Farid N. Najm, Ping Yang and Timothy N. Trick, McPOWER, a Monte Carlo approach to power estimation, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design, 90 to 97, November 1992, the first presentation of the method
  3. 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 statistical techniques
  4. Y. S. Chow and Herbert Robbins, On the asymptotic theory of fixed-width sequential confidence intervals for the mean, Annals of Mathematical Statistics 36(2), 457 to 462, 1965, the asymptotic coverage of a confidence interval whose sample size is chosen by a stopping rule on the sample variance

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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