Algorithm Search⌘K

Algorithmadvanced

Lagrangian relaxation gate sizing

Also called Chen-Chu-Wong sizing, LR gate sizing.

Chen, Chu and Wong's sizing that moves the timing constraints into the objective with multipliers that obey flow conservation, and solves each subproblem by local resizing.

Time
O(S (n + m)) per_round
Space
O(n + m) extra
Where
S = the number of local resizing sweeps in a round; m = the number of connections; n = the number of gates
Properties
deterministicexactiterative
Origin
Chung Ping Chen, Chris C. N. Chu, D. F. Wong, 1998

Lagrangian relaxation gate sizing is an exact method for the continuous form of gate sizing under the Elmore delay. It puts a multiplier on every edge of the timing graph and moves the timing constraints into the objective. The optimality conditions force the multipliers to obey flow conservation, which removes the arrival times from the problem. What remains, for fixed multipliers, is a weighted sum of area and gate delays that one pass of closed-form updates, gate by gate, minimizes. An outer loop adjusts the multipliers until the target is met with least area. Chen, Chu and Wong gave the method in 1998 for gates and wires together.

In plain words

Each connection in the circuit gets a price, which says how much a delay on that connection costs. The prices follow a rule like water in pipes: the total price that flows into a gate also flows out of it, and the total reaching the outputs says how hard the target is.

With prices fixed, the problem is easy: make the sum of the area and the priced delays small. A gate that sits on expensive connections becomes larger, and a gate that loads expensive gates stays small. A short formula gives the best size of one gate when the others are fixed, and a few passes over the gates settle all sizes.

Then the circuit is timed. Prices go up where the circuit is late and down on connections with spare time. The loop repeats until the prices stop changing.

The problem

The circuit and the delay model are those of TILOS: gate ii has delay Di(x)=pi+(ri/xi)(fi+∑j∈out(i)cjxj)D_i(x) = p_i + (r_i / x_i)(f_i + \sum_{j \in \mathrm{out}(i)} c_j x_j) and area aixia_i x_i, but its size xix_i is now continuous in an interval [ℓi,hi][\ell_i, h_i]. The timing graph has a source ss before the gates without fanins and a sink tt after the gates without fanouts, and EE is its edge set. With arrival times AiA_i as variables, the problem is

min⁡∑iaixisubject toAu+Dv(x)≤Av for each edge (u,v) with v≠t,Au≤T for each edge (u,t),\min \sum_i a_i x_i \quad \text{subject to} \quad A_u + D_v(x) \le A_v \text{ for each edge } (u, v) \text{ with } v \ne t, \qquad A_u \le T \text{ for each edge } (u, t),

with As=0A_s = 0 and ℓ≤x≤h\ell \le x \le h. Each DvD_v is a posynomial, so this is a geometric program.

With a multiplier μe≥0\mu_e \ge 0 on each edge, the Lagrangian relaxation has a finite minimum over the arrival times only if, at every gate, the flow of multipliers in equals the flow out (flow conservation). Then it becomes

∑iaixi+∑iλiDi(x)−T∑(u,t)∈Eμut,λi=∑e into iμe.\sum_i a_i x_i + \sum_i \lambda_i D_i(x) - T \sum_{(u, t) \in E} \mu_{ut}, \qquad \lambda_i = \sum_{e \text{ into } i} \mu_e .

Minimizing the first two terms over the sizes is the local resizing subproblem.

The algorithm

  1. LR-SIZING(circuit, target T, rounds R)
  2. 1μ ← 1 on the edges into t, then make μ conserve flow at every gate
  3. 2repeat R times
  4. 3λ_i ← the sum of μ over the edges into gate i, for every gate i
  5. 4repeat until no size moves: for each gate i, x_i ← clamp of √(λ_i r_i (f_i + Σ_{j∈out(i)} c_j x_j) / (a_i + c_i Σ_{k∈in(i)} λ_k r_k / x_k)) into [ℓ_i, h_i]
  6. 5A ← the arrival times for x, by static timing analysis
  7. 6for each edge e = (u, v): μ_e ← μ_e · (A_u + D_v) / A_v, or μ_e ← μ_e · A_u / T if v = t
  8. 7from the outputs back to the inputs, scale the multipliers into each gate so that they sum to the flow out of it
  9. 8return x

Line L4 is the local resizing. The formula of a gate follows from the terms of the subproblem that contain xix_i: its area, its own priced delay, which falls as 1/xi1/x_i, and the priced delays of its fanins, which grow with its input capacitance. Line L6 lowers the multiplier of every edge that is not critical, since there Au+Dv<AvA_u + D_v < A_v, and raises or lowers the flow into the sink by how late or early each output is. Chen, Chu and Wong update the multipliers by a subgradient step with step sizes that go to zero; the implementation uses the multiplicative rule of line L6, which keeps every multiplier positive. Line L7 is the projection back onto flow conservation.

Example

Take a fixed driver of size 1 and a chain of two gates with sizes in [1,16][1, 16], all pi=ri=ci=ai=1p_i = r_i = c_i = a_i = 1, a load f2=16f_2 = 16 at the output and the target T=12T = 12. The delay is (1+x1)+(1+x2/x1)+(1+16/x2)(1 + x_1) + (1 + x_2 / x_1) + (1 + 16 / x_2), which is 21 at the smallest sizes. On a chain, flow conservation makes every multiplier equal to one number μ\mu, and the local resizing is

x1=μ x21+μ,x2=16μ1+μ/x1.x_1 = \sqrt{\frac{\mu\, x_2}{1 + \mu}}, \qquad x_2 = \sqrt{\frac{16 \mu}{1 + \mu / x_1}} .
round μ\mu used x1x_1 x2x_2 delay area
1 1 1.2173 2.9638 12.0505 5.1811
2 1.0042 1.2196 2.9684 12.0436 5.1880
10 1.0241 1.2294 2.9889 12.0137 5.2183
50 1.0317 1.2339 2.9984 12.0000 5.2324

In round 1 the circuit is 0.05 late, so the multiplier grows by the factor 12.0505/1212.0505 / 12, and each round moves the sizes toward the target. The method settles at μ≈1.0318\mu \approx 1.0318, x1≈1.234x_1 \approx 1.234 and x2≈2.998x_2 \approx 2.998, with area 5.2324 and delay 12. A search over a refined grid of both sizes gives the same least area to four digits. The stage ratios are x1/1≈1.23x_1 / 1 \approx 1.23, x2/x1≈2.43x_2 / x_1 \approx 2.43 and 16/x2≈5.3416 / x_2 \approx 5.34. The fastest sizing of logical effort would make all three equal to 161/3≈2.5216^{1/3} \approx 2.52; here the early gates stay small because area costs and the target leaves room.

Correctness

The proof is in proofs/correctness.md. The coefficient of each arrival time in the Lagrangian is the flow out of its gate minus the flow in, so the dual function is finite only on flow-conserving multipliers, and there the arrival times drop out. For every such μ\mu, the dual value is at most the least area (weak duality). For fixed multipliers, the subproblem as a function of one size is αxi+β/xi\alpha x_i + \beta / x_i, minimized at β/α\sqrt{\beta/\alpha} clamped to the interval. After the change of variables xi=eyix_i = e^{y_i} the subproblem is strictly convex, so a point where no single size can improve is its unique minimum. The whole problem is convex in (y,A)(y, A), so when the target can be beaten strictly there is no duality gap: the best multipliers exist, conserve flow, and their subproblem solution is the optimal sizing. This is what makes the method exact. The convergence of the multiplier update of line L6 is not proved here; the tests measure it.

Proof: The Lagrangian relaxation of gate sizing reduces to flow-conserving multipliers, its local resizing is optimal, and there is no duality gapfull

Model. The circuit is a DAG of gates 0,…,n−10, \dots, n - 1 with mm edges. Gate ii has a size xi∈[ℓi,hi]x_i \in [\ell_i, h_i] with 0<ℓi≤hi0 < \ell_i \le h_i and constants pi≥0p_i \ge 0, ri,ci,ai>0r_i, c_i, a_i > 0 and fi≥0f_i \ge 0, and its delay is

Di(x)=pi+rixi(fi+∑j∈out(i)cjxj).D_i(x) = p_i + \frac{r_i}{x_i} \Big( f_i + \sum_{j \in \mathrm{out}(i)} c_j x_j \Big).

The timing graph adds a source ss with an edge to each gate without fanins and a sink tt with an edge from each gate without fanouts; let EE be all its edges. With arrival variables AiA_i and As=0A_s = 0, the problem (P) is

min⁡∑iaixisubject toAu+Dv(x)≤Av  ((u,v)∈E, v≠t),Au≤T  ((u,t)∈E),ℓ≤x≤h.\min \sum_i a_i x_i \quad \text{subject to} \quad A_u + D_v(x) \le A_v \ \ ((u, v) \in E,\ v \ne t), \qquad A_u \le T \ \ ((u, t) \in E), \qquad \ell \le x \le h.

(P) is the same as asking that the latest arrival time be at most TT: given xx, the arrival times of static timing analysis are the least AA that meet the first constraints.

Lemma 1 (flow conservation). For multipliers μ≥0\mu \ge 0 on EE, let L(x,A,μ)\mathcal L(x, A, \mu) be the Lagrangian of the timing constraints. Its infimum over the free variables AA is −∞-\infty unless, at every gate ii, ∑e into iμe=∑e out of iμe\sum_{e \text{ into } i} \mu_e = \sum_{e \text{ out of } i} \mu_e. Under this condition

L(x,A,μ)=∑iaixi+∑iλiDi(x)−T∑(u,t)∈Eμut,λi=∑e into iμe.\mathcal L(x, A, \mu) = \sum_i a_i x_i + \sum_i \lambda_i D_i(x) - T \sum_{(u, t) \in E} \mu_{ut}, \qquad \lambda_i = \sum_{e \text{ into } i} \mu_e.

Proof. L=∑iaixi+∑(u,v),v≠tμuv(Au+Dv−Av)+∑(u,t)μut(Au−T)\mathcal L = \sum_i a_i x_i + \sum_{(u, v), v \ne t} \mu_{uv} (A_u + D_v - A_v) + \sum_{(u, t)} \mu_{ut} (A_u - T). The coefficient of AiA_i is the flow out of ii minus the flow into ii. A linear function of an unbounded variable has infimum −∞-\infty unless its coefficient is 0. With all coefficients 0 the AA terms vanish, and each DvD_v appears with the sum of the multipliers into vv. □\square

So the dual function is Q(μ)=min⁡ℓ≤x≤hΦλ(x)−T∑(u,t)μutQ(\mu) = \min_{\ell \le x \le h} \Phi_\lambda(x) - T \sum_{(u, t)} \mu_{ut} with Φλ(x)=∑iaixi+∑iλiDi(x)\Phi_\lambda(x) = \sum_i a_i x_i + \sum_i \lambda_i D_i(x), on the set Ω\Omega of nonnegative flow-conserving μ\mu. The inner problem is the local resizing subproblem.

Lemma 2 (weak duality). For every μ∈Ω\mu \in \Omega, Q(μ)≤OPT(P)Q(\mu) \le \mathrm{OPT}(P).

Proof. For a feasible (x,A)(x, A), every multiplier term is μe\mu_e times a number at most 0, so L(x,A,μ)≤∑iaixi\mathcal L(x, A, \mu) \le \sum_i a_i x_i. Take the minimum over xx on the left and over feasible points on the right. □\square

Lemma 3 (one gate in closed form). Fix λ≥0\lambda \ge 0 and all sizes except xix_i. Then Φλ\Phi_\lambda as a function of xix_i is αxi+β/xi+const\alpha x_i + \beta / x_i + \text{const} with

α=ai+ci∑k∈in(i)λkrkxk>0,β=λiri(fi+∑j∈out(i)cjxj)≥0,\alpha = a_i + c_i \sum_{k \in \mathrm{in}(i)} \frac{\lambda_k r_k}{x_k} > 0, \qquad \beta = \lambda_i r_i \Big( f_i + \sum_{j \in \mathrm{out}(i)} c_j x_j \Big) \ge 0,

and its minimum over [ℓi,hi][\ell_i, h_i] is at xi=min⁡(hi,max⁡(ℓi,β/α))x_i = \min(h_i, \max(\ell_i, \sqrt{\beta / \alpha})).

Proof. xix_i appears in aixia_i x_i, in λiDi\lambda_i D_i as λiri(⋯ )/xi\lambda_i r_i (\cdots) / x_i, and in λkDk\lambda_k D_k for each fanin kk through the load cixic_i x_i, which gives λkrkcixi/xk\lambda_k r_k c_i x_i / x_k. The function αz+β/z\alpha z + \beta / z is convex on z>0z > 0 with its unconstrained minimum at β/α\sqrt{\beta / \alpha} (at z→0z \to 0 if β=0\beta = 0), so its minimum over an interval is that point clamped into the interval. □\square

Lemma 4 (a fixed point of local resizing solves the subproblem). With yi=log⁡xiy_i = \log x_i, Ψ(y)=Φλ(ey)\Psi(y) = \Phi_\lambda(e^y) is convex, differentiable and strictly convex, so the subproblem has a unique minimizer. A point at which every xix_i satisfies the formula of Lemma 3 is that minimizer.

Proof. Every term of Φλ\Phi_\lambda is a positive constant times a monomial ∏kxkαk\prod_k x_k^{\alpha_k}, which is exp⁡\exp of an affine function of yy, hence convex in yy. The terms aieyia_i e^{y_i} are strictly convex in yiy_i, and their sum is strictly convex in yy. The box ℓ≤x≤h\ell \le x \le h is a box in yy. At a point where each coordinate is optimal on its interval, each partial derivative ∂Ψ/∂yi\partial \Psi / \partial y_i is 0, or is ≥0\ge 0 at the lower end, or is ≤0\le 0 at the upper end. These are the KKT conditions of a differentiable convex function on a box, which are sufficient for a global minimum. □\square

Theorem 1 (no duality gap). If some sizes in the box have latest arrival time below TT, then max⁡μ∈ΩQ(μ)=OPT(P)\max_{\mu \in \Omega} Q(\mu) = \mathrm{OPT}(P), the maximum is attained at some μ∗\mu^*, and the unique minimizer x(μ∗)x(\mu^*) of the local resizing subproblem is the unique optimal sizing.

Proof. In the variables (y,A)(y, A), problem (P) has the convex objective ∑iaieyi\sum_i a_i e^{y_i}, the constraints Au+Dv(ey)−Av≤0A_u + D_v(e^y) - A_v \le 0, whose left sides are convex by the argument of Lemma 4, the affine constraints Au≤TA_u \le T and a box on yy. Sizes with latest arrival below TT, with AA slightly above the arrival times, meet all the timing constraints strictly, so Slater's condition holds. Hence the Lagrangian dual has the same value and a dual optimum μ∗\mu^* is attained; by Lemma 1, μ∗∈Ω\mu^* \in \Omega. For an optimal (y∗,A∗)(y^*, A^*) and μ∗\mu^*, the saddle point property says that y∗y^* minimizes L(⋅,A∗,μ∗)=Ψ(⋅)+const\mathcal L(\cdot, A^*, \mu^*) = \Psi(\cdot) + \text{const} over the box. By Lemma 4 this minimizer is unique, so it is x(μ∗)x(\mu^*). The primal optimum is unique because the objective is strictly convex in yy and the feasible set is convex. □\square

Corollary (certificate). For every μ∈Ω\mu \in \Omega and every sizing xx that meets the target, Q(μ)≤OPT(P)≤∑iaixiQ(\mu) \le \mathrm{OPT}(P) \le \sum_i a_i x_i. So a pair whose two values are close proves that xx is close to optimal. The tests check this bound for the computed pair.

Theorem 2 (cost of one round). One sweep of local resizing, one timing pass, the update of all multipliers and the projection each take O(n+m)O(n + m) time. A round with SS sweeps takes O(S(n+m))O(S (n + m)) time.

Proof. In a sweep, gate ii needs its load and the sum over its fanins, in O(1+∣in(i)∣+∣out(i)∣)O(1 + |\mathrm{in}(i)| + |\mathrm{out}(i)|), which sums to O(n+m)O(n + m). Static timing is one pass in topological order. The projection visits the gates in reverse topological order and touches each edge twice. □\square

What is not proved here. The multiplier update of the implementation, which scales each edge by the ratio of the arrival time through it to the arrival time at its head (or to TT for an edge into the sink) and then restores flow conservation by proportional scaling, is not proved to converge. The tests measure that it reaches the grid optimum and the dual bound within a relative 10−310^{-3} on small circuits.

Complexity

A sweep of line L4 costs O(n+m)O(n + m), since each gate needs its load and the priced resistance of its fanins. Timing, the update and the projection also cost O(n+m)O(n + m) each. A round with SS sweeps costs O(S(n+m))O(S (n + m)), and the space is O(n+m)O(n + m) for the multipliers. The number of rounds depends on the step rule and the accuracy and has no closed-form bound. On the small circuits of the tests, 3000 rounds reach a relative error below 10−310^{-3}; this is measured, not proved.

Properties

  • Exact for continuous sizes under the Elmore delay: the optimal multipliers give the optimal sizing, with no duality gap (proved).
  • Every flow-conserving set of multipliers gives a lower bound on the least area, so the gap between the bound and a feasible sizing certifies how close it is (proved).
  • The local resizing works on one gate at a time, so it scales to large circuits without a general convex solver.
  • At the optimum, the multiplier of an edge whose timing constraint is not tight is zero (complementary slackness), and the flow into a gate is the price of its delay.
  • Discrete library sizes are not handled. The continuous answer must be rounded, which can break the target or add area.

Variants and improvements

  • Wire sizing. The original method sizes gates and wire segments together. Each wire segment is a node of the RC interconnect tree with its own width, and its local formula has the same form.
  • Multiplier updates. The subgradient step of Chen, Chu and Wong, μe←max⁡(0,μe+ρk(Au+Dv−Av))\mu_e \leftarrow \max(0, \mu_e + \rho_k (A_u + D_v - A_v)) with ρk→0\rho_k \to 0, and multiplicative rules like line L6 are both used; they differ in speed and in how they handle multipliers near zero.
  • General convex solvers. The same geometric program can be solved by interior point methods, as Boyd, Kim, Patil and Horowitz describe for digital circuits. These are robust but slower on very large circuits.
  • Discrete sizes and other delay models. With library cells and table delays, the relaxed problem is no longer convex. The relaxation with multipliers is then used as a heuristic: the local resizing picks the best library cell for each gate under the current prices.

When to use it

Use it to size gates, or gates and wires, of a large circuit to a delay target with least area or power, when the Elmore delay or another posynomial model is acceptable and a provable lower bound is wanted. It is much faster than a general geometric programming solver on large circuits. For a quick sizing with discrete cells, TILOS is simpler. For sizing with buffers on long wires, combine it with van Ginneken buffer insertion.

Pitfalls

  • The multipliers must conserve flow before the subproblem is solved. Without it the arrival times do not drop out and the subproblem is not the dual.
  • With an additive step, the multiplier of an edge can reach zero early. The proportional projection of line L7 keeps it at zero while another edge into the same gate carries flow, and a critical edge gets a step of zero, so the edge cannot regain its price if it becomes critical later. The multiplicative rule of line L6 keeps every multiplier positive.
  • The step sizes decide the speed. With steps ρk=ρ0/k\rho_k = \rho_0 / k, a poor ρ0\rho_0 can leave the sizing far from the target after many rounds.
  • A gate with λi=0\lambda_i = 0 goes to its smallest size. That is right only if none of its paths is critical.
  • The sizing at a given round can miss the target slightly. Check the timing of the final sizing, and use the dual bound to judge how far it is from optimal.
  • Optimality holds for the continuous problem. After rounding to library sizes, the result is no longer optimal, and the discrete problem is strongly NP-hard.

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.

lagrangian_relaxation_gate_sizing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lagrangian-relaxation-gate-sizing/. The authors are listed in prov/AB69M9.jsonl.
"""Gate sizing by Lagrangian relaxation (Chen, Chu and Wong, 1999).

The circuit is a DAG of gates 0..n-1 in topological order. Gate i has an
intrinsic delay p[i], a drive resistance r[i] / x for size x, an input
capacitance c[i] * x, an area a[i] * x, a fixed load f[i] and a size range
lo[i] <= x <= hi[i]. Its delay is

    D_i = p[i] + r[i] / x_i * (f[i] + sum of c[j] * x_j over fanouts j).

The timing graph has a source s with an edge to each gate without fanins,
the circuit edges, and an edge from each gate without fanouts to a sink t.
A multiplier mu[e] >= 0 sits on every edge. The problem is: least area such
that every arrival time is at most the target T. Arithmetic is in floating
point, since the local resizing uses square roots.
"""

import math


class Circuit:
    def __init__(self, fanin, p, r, c, a, f, lo, hi):
        self.n = len(fanin)
        self.fanin = [list(v) for v in fanin]
        self.fanout = [[] for _ in range(self.n)]
        for j, ins in enumerate(self.fanin):
            for i in ins:
                assert i < j
                self.fanout[i].append(j)
        self.p, self.r, self.c, self.a, self.f = p, r, c, a, f
        self.lo, self.hi = lo, hi
        # edges as (tail, head); tail -1 is the source, head n is the sink
        self.edges = [(-1, j) for j in range(self.n) if not self.fanin[j]]
        self.edges += [(i, j) for j in range(self.n) for i in self.fanin[j]]
        self.edges += [(i, self.n) for i in range(self.n) if not self.fanout[i]]


def gate_delay(ckt, x, i):
    load = ckt.f[i] + sum(ckt.c[j] * x[j] for j in ckt.fanout[i])
    return ckt.p[i] + ckt.r[i] / x[i] * load


def arrivals(ckt, x):
    arr = []
    for i in range(ckt.n):
        arr.append(max([arr[k] for k in ckt.fanin[i]], default=0.0) + gate_delay(ckt, x, i))
    return arr


def delay(ckt, x):
    return max(arrivals(ckt, x))


def area(ckt, x):
    return sum(ckt.a[i] * x[i] for i in range(ckt.n))


def flow_through(ckt, mu):
    """lambda_i: the sum of the multipliers on the edges into gate i."""
    lam = [0.0] * ckt.n
    for e, (u, v) in enumerate(ckt.edges):
        if v < ckt.n:
            lam[v] += mu[e]
    return lam


def project(ckt, mu):
    """Restore flow conservation: scale the edges into each gate, from the
    outputs back to the inputs, so that they carry what leaves the gate."""
    mu = list(mu)
    into = [[] for _ in range(ckt.n)]
    out_of = [[] for _ in range(ckt.n)]
    for e, (u, v) in enumerate(ckt.edges):
        if v < ckt.n:
            into[v].append(e)
        if u >= 0:
            out_of[u].append(e)
    for i in reversed(range(ckt.n)):
        need = sum(mu[e] for e in out_of[i])
        have = sum(mu[e] for e in into[i])
        for e in into[i]:
            mu[e] = need * mu[e] / have if have > 0 else need / len(into[i])
    return mu


def local_resize(ckt, lam, x, sweeps=200, tol=1e-12):
    """Solve min sum a_i x_i + sum lam_i D_i(x) over the box, one gate at a
    time in closed form, until no size moves."""
    x = list(x)
    for _ in range(sweeps):
        moved = 0.0
        for i in range(ckt.n):
            load = ckt.f[i] + sum(ckt.c[j] * x[j] for j in ckt.fanout[i])
            up = sum(lam[k] * ckt.r[k] / x[k] for k in ckt.fanin[i])
            den = ckt.a[i] + ckt.c[i] * up
            best = math.sqrt(lam[i] * ckt.r[i] * load / den) if lam[i] * load > 0 else ckt.lo[i]
            best = min(max(best, ckt.lo[i]), ckt.hi[i])  # @line L4
            moved = max(moved, abs(best - x[i]) / x[i])
            x[i] = best
        if moved < tol:
            break
    return x


def lr_sizing(ckt, target, rounds=3000, power=1.0):
    """Return (sizes, multipliers) after the given number of rounds.

    The multipliers are updated by the multiplicative rule: an edge into a
    gate is scaled by (arrival through the edge) / (arrival at the gate),
    which is 1 on a critical edge and below 1 otherwise, and an edge into the
    sink is scaled by (arrival) / target. Multipliers stay positive, so the
    projection can always move flow back to an edge that becomes critical."""
    mu = [1.0 if v == ckt.n else 0.0 for (u, v) in ckt.edges]  # @line L1
    mu = project(ckt, mu)
    x = list(ckt.lo)
    for _ in range(rounds):  # @line L2
        lam = flow_through(ckt, mu)  # @line L3
        x = local_resize(ckt, lam, x)
        arr = arrivals(ckt, x)  # @line L5
        new = []
        for e, (u, v) in enumerate(ckt.edges):  # @line L6
            if v == ckt.n:
                ratio = arr[u] / target
            else:
                start = 0.0 if u < 0 else arr[u]
                ratio = (start + gate_delay(ckt, x, v)) / arr[v]
            new.append(mu[e] * ratio ** power)
        mu = project(ckt, new)  # @line L7
    return x, mu  # @line L8
test_lagrangian_relaxation_gate_sizing.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lagrangian-relaxation-gate-sizing/. The authors are listed in prov/AB69M9.jsonl.

import itertools
import math
import random

from lagrangian_relaxation_gate_sizing import (Circuit, area, delay, flow_through, gate_delay,
                                               local_resize, lr_sizing, project)

TOL = 1e-3


def grid_search(ckt, target, pts, rounds=6):
    """Least area over a grid of sizes in log scale that meet the target,
    refined around the best point a few times."""
    free = [i for i in range(ckt.n) if ckt.lo[i] < ckt.hi[i]]
    box = [(math.log(ckt.lo[i]), math.log(ckt.hi[i])) for i in free]
    best = None
    for _ in range(rounds):
        axes = [[l + (h - l) * t / (pts - 1) for t in range(pts)] for (l, h) in box]
        for ys in itertools.product(*axes):
            x = list(ckt.lo)
            for i, y in zip(free, ys):
                x[i] = math.exp(y)
            if delay(ckt, x) <= target:
                ar = area(ckt, x)
                if best is None or ar < best[0]:
                    best = (ar, x)
        if best is None:
            return None
        box = [(max(math.log(ckt.lo[i]), math.log(best[1][i]) - 2 * (h - l) / (pts - 1)),
                min(math.log(ckt.hi[i]), math.log(best[1][i]) + 2 * (h - l) / (pts - 1)))
               for i, (l, h) in zip(free, box)]
    return best[0]


def dual_value(ckt, mu, target):
    """Q(mu) = min over x of area + sum lam_i D_i(x) - T * (flow into the sink).
    By weak duality it is a lower bound on the least area."""
    lam = flow_through(ckt, mu)
    x = local_resize(ckt, lam, list(ckt.lo), sweeps=5000, tol=1e-14)
    total = sum(m for m, (u, v) in zip(mu, ckt.edges) if v == ckt.n)
    return area(ckt, x) + sum(lam[i] * gate_delay(ckt, x, i) for i in range(ckt.n)) - target * total


def random_case(rng, shape):
    if shape == "chain":
        m = rng.randint(2, 3)
        fanin = [[]] + [[i - 1] for i in range(1, m + 1)]
    else:  # a driver, two gates in parallel, and a gate that joins them
        fanin = [[], [0], [0], [1, 2]]
    n = len(fanin)
    r = [rng.uniform(1, 3) for _ in range(n)]
    a = [rng.uniform(1, 3) for _ in range(n)]
    f = [0.0] * (n - 1) + [rng.uniform(5, 20)]
    if shape == "dag":
        f[1] = rng.uniform(0, 4)  # gate 1 also drives some wire
    ckt = Circuit(fanin, [1.0] * n, r, [1.0] * n, a, f, [1.0] * n, [1.0] + [8.0] * (n - 1))
    target = delay(ckt, [1.0] * n) * rng.uniform(0.6, 0.95)
    return ckt, target


def test_against_grid_search(rng=random.Random(1999)):
    checked = 0
    for k in range(24):
        ckt, target = random_case(rng, "chain" if k % 3 else "dag")
        free = sum(1 for i in range(ckt.n) if ckt.lo[i] < ckt.hi[i])
        best = grid_search(ckt, target, pts=40 if free == 2 else 14)
        if best is None:
            continue  # no sizing in the box meets the target
        x, mu = lr_sizing(ckt, target)
        assert all(ckt.lo[i] - 1e-12 <= x[i] <= ckt.hi[i] + 1e-12 for i in range(ckt.n))
        assert delay(ckt, x) <= target * (1 + TOL)
        assert abs(area(ckt, x) - best) <= TOL * best
        # the multipliers certify the answer: the dual bound is close to it
        q = dual_value(ckt, mu, target)
        assert q <= best * (1 + TOL) and q >= best * (1 - TOL)
        checked += 1
    assert checked >= 15


def test_zero_multiplier_stays_zero_under_projection(rng=random.Random(3)):
    # proportional scaling keeps a zero edge at zero while another edge into
    # the same gate is positive; only a positive update can bring it back
    ckt, _ = random_case(rng, "dag")
    edges = ckt.edges
    join = edges.index((2, 3))
    for _ in range(20):
        mu = [rng.uniform(0.5, 2) for _ in edges]
        mu[join] = 0.0
        assert project(ckt, mu)[join] == 0.0


def test_projection_conserves_flow(rng=random.Random(4)):
    ckt, _ = random_case(rng, "dag")
    for _ in range(50):
        mu = project(ckt, [rng.uniform(0, 3) for _ in ckt.edges])
        for i in range(ckt.n):
            into = sum(m for m, (u, v) in zip(mu, ckt.edges) if v == i)
            out = sum(m for m, (u, v) in zip(mu, ckt.edges) if u == i)
            assert abs(into - out) <= 1e-9 * (1 + out)


def test_local_resize_is_optimal(rng=random.Random(6)):
    # the relaxed problem for fixed multipliers is convex in log sizes; the
    # gate by gate closed form must reach the grid minimum
    for _ in range(10):
        ckt, _ = random_case(rng, "chain")
        lam = [rng.uniform(0.1, 2) for _ in range(ckt.n)]
        x = local_resize(ckt, lam, list(ckt.lo), sweeps=5000, tol=1e-14)

        def value(z):
            return area(ckt, z) + sum(lam[i] * gate_delay(ckt, z, i) for i in range(ckt.n))

        free = [i for i in range(ckt.n) if ckt.lo[i] < ckt.hi[i]]
        best = math.inf
        for ys in itertools.product(*[[math.exp(math.log(8) * t / 30) for t in range(31)]] * len(free)):
            z = list(ckt.lo)
            for i, y in zip(free, ys):
                z[i] = y
            best = min(best, value(z))
        assert value(x) <= best + 1e-9


def test_example_of_the_page():
    ckt = Circuit([[], [0], [1]], [1.0] * 3, [1.0, 1.0, 1.0], [1.0] * 3, [1.0] * 3,
                  [0.0, 0.0, 16.0], [1.0, 1.0, 1.0], [1.0, 16.0, 16.0])
    assert delay(ckt, [1.0] * 3) == 21
    x, mu = lr_sizing(ckt, 12.0)
    assert abs(x[1] - 1.2340) < 1e-3 and abs(x[2] - 2.9984) < 1e-3
    assert abs(delay(ckt, x) - 12) < 1e-3 and abs(area(ckt, x) - 5.2324) < 1e-3
    # on a chain, flow conservation makes all multipliers equal
    assert max(mu) - min(mu) < 1e-9 and abs(mu[0] - 1.0318) < 1e-3
    # the closed forms of the local resizing hold at the answer
    m = mu[0]
    assert abs(x[1] - math.sqrt(m * x[2] / (1 + m))) < 1e-6
    assert abs(x[2] - math.sqrt(m * 16 / (1 + m / x[1]))) < 1e-6
    assert abs(grid_search(ckt, 12.0, pts=40) - area(ckt, x)) < TOL * area(ckt, x)

History

Fishburn and Dunlop observed in 1985 that under the Elmore model the sizing problem is posynomial, and Sapatnekar, Rao, Vaidya and Kang solved transistor sizing exactly by convex optimization in 1993. Chung-Ping Chen, Chris Chu and D. F. Wong presented Lagrangian relaxation for simultaneous gate and wire sizing at ICCAD 1998 and in IEEE Transactions on Computer-Aided Design in 1999. Their observation that the optimal multipliers conserve flow made the relaxed problem simple enough for very large circuits. Later work on sizing with library cells kept the multipliers and the local resizing, and changed the update of the multipliers.

References

  1. Chung-Ping Chen, Chris C. N. Chu and D. F. Wong, Fast and exact simultaneous gate and wire sizing by Lagrangian relaxation, IEEE Transactions on Computer-Aided Design 18(7), 1014 to 1025, 1999, the flow conservation of the optimal multipliers, the local resizing subproblem and its greedy solution, and the optimality of the method under the Elmore delay
  2. Chung-Ping Chen, Chris C. N. Chu and D. F. Wong, Fast and exact simultaneous gate and wire sizing by Lagrangian relaxation, Proceedings of ICCAD 1998, 617 to 624, the conference version
  3. Stephen Boyd, Seung-Jean Kim, Dinesh D. Patil and Mark A. Horowitz, Digital circuit optimization via geometric programming, Operations Research 53(6), 2005, gate sizing as a geometric program and its solution by convex optimization

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 correctness
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