Algorithm Search⌘K

Algorithmcore

Timing-driven annealing placement for FPGAs

Also called VPR placement, T-VPlace.

Betz, Marquardt and Rose's FPGA placer that swaps blocks by simulated annealing with an adaptive move range and a cost mixing wirelength and timing criticality.

Time
O(k (n^(4/3) F + P)) totalO(F) per_moveO(n^(4/3) F + P) per_temperature
Space
O(n + P) total
Where
F = the number of pins on the nets of the moved blocks; P = the number of pins on all nets; k = the number of temperatures; n = the number of blocks
Properties
randomizednot exactiterative
Origin
Alexander Marquardt, Vaughn Betz, Jonathan Rose, 2000

Timing-driven annealing placement is the placer of VPR for an island-style FPGA: it puts the packed blocks on the sites of the grid by simulated annealing, with moves that swap two blocks or move one to an empty site. The cost of a move mixes the change of a bounding box wirelength estimate and the change of a timing cost, in which each connection's delay is weighted by its criticality, each normalized by its value at the start of the temperature. An adaptive schedule sets the temperature, the number of moves and the range of a move from the fraction of moves that are accepted. The algorithm belongs to the FPGA CAD topic of this sub-area.

In plain words

After packing, the design is a few thousand blocks that must go onto a grid of sites. Blocks that are joined by nets should be close, so that the router needs short wires, and blocks on the slowest paths should be closest of all.

The placer starts from a random layout and then tries many small changes: move a block to a nearby site, or swap two blocks. A change that makes the layout better is kept. A change that makes it worse is sometimes kept too, more often early on, so the layout can get out of a bad corner. Over time the placer accepts fewer bad changes and makes its moves shorter, until the layout settles.

The score of a layout counts both the wire needed and the delay of the slow paths, so the placer trades a little wire for speed where it matters.

The problem

Input. A grid of nx×nyn_x \times n_y sites, nn blocks, and nets, each a driver block and one or more sink blocks. A weight λ∈[0,1]\lambda \in [0, 1].

Output. A legal placement: each block on its own site.

Goal. Low wirelength and low critical path delay, in the sense of the timing-driven placement problem. The algorithm minimizes a cost that stands for both; it does not find the minimum.

The model of this page has one block type, and a connection between sites aa and bb has delay 1+∣xa−xb∣+∣ya−yb∣1 + |x_a - x_b| + |y_a - y_b|. VPR uses a table of routed delays by distance and has I/O pads on the border and other block types in columns.

The algorithm

The costs:

  • Bounding box cost. BB=∑eq(∣e∣) (Δx(e)+1+Δy(e)+1)BB = \sum_e q(|e|) \, (\Delta x(e) + 1 + \Delta y(e) + 1), where Δx(e)\Delta x(e) and Δy(e)\Delta y(e) are the spans of the bounding box of net ee. This is the half-perimeter wirelength counted in channels crossed. The factor qq from Cheng is 1 for up to three terminals and grows with more, to about 2.79 at 50, because the half-perimeter underestimates the wire of a net with many terminals.
  • Timing cost. T=∑cd(c) crit(c)CET = \sum_c d(c) \, \mathrm{crit}(c)^{CE} over all connections cc from a driver to a sink, where crit(c)=1−slack(c)/Dmax\mathrm{crit}(c) = 1 - \mathrm{slack}(c) / D_{max} comes from a static timing analysis and CECE is the criticality exponent.
  • Move cost. ΔC=λ ΔT/Tprev+(1−λ) ΔBB/BBprev\Delta C = \lambda \, \Delta T / T_{prev} + (1 - \lambda) \, \Delta BB / BB_{prev}, with TprevT_{prev} and BBprevBB_{prev} the costs at the start of the temperature.
  1. PLACE(blocks, nets, n_x, n_y, λ, inner)
  2. 1random legal placement; T ← 20 × the standard deviation of the cost over n random moves; R ← R_max = max(n_x, n_y) − 1
  3. 2while T ≥ 0.005 / (number of nets):
  4. 3timing analysis: weights crit(c)^CE; set BB_prev and T_prev to the current costs
  5. 4repeat inner × n^(4/3) times:
  6. 5pick a random block a and a random site s with |Δx|, |Δy| ≤ R; the move swaps a with the block at s, if any
  7. 6ΔC ← λ ΔT / T_prev + (1 − λ) ΔBB / BB_prev, from the nets and connections of the moved blocks only
  8. 7if ΔC ≤ 0, or a random number in [0, 1) is below exp(−ΔC / T), make the move
  9. 8R_acc ← accepted / tried; T ← α(R_acc) × T, with α = 0.5, 0.9, 0.95, 0.8 for R_acc > 0.96, > 0.8, > 0.15, otherwise
  10. 9R ← R × (1 − 0.44 + R_acc), kept in [1, R_max]; CE ← 1 + 7 (1 − (R − 1) / (R_max − 1))
  11. 10one more round of moves at T = 0, which accepts only moves with ΔC ≤ 0
  12. 11return the placement

The schedule aims at an acceptance rate of 0.44: the range limit grows when more moves are accepted and shrinks when fewer are, and the temperature falls slowly while the acceptance rate is in the middle band, where the cost improves most. As the range shrinks, the exponent CECE rises from 1 to 8, so late in the anneal only the most critical connections carry weight. The exit test of VPR is T<0.005 C/mT < 0.005 \, C / m for the cost CC and mm nets. With normalized costs, CC is about 1, which gives line L2.

Example

Take a 3×23 \times 2 grid, three blocks and two nets, e1=(0,1)e_1 = (0, 1) and e2=(1,2)e_2 = (1, 2), so the connections are 0→10 \to 1 and 1→21 \to 2. Place block 0 at (0,0)(0, 0), block 1 at (2,0)(2, 0) and block 2 at (0,1)(0, 1), with λ=0.5\lambda = 0.5 and CE=1CE = 1.

  • BBBB: net e1e_1 spans xx from 0 to 2 and one row, so 3+1=43 + 1 = 4; net e2e_2 spans xx from 0 to 2 and two rows, so 3+2=53 + 2 = 5; BB=9BB = 9.
  • Timing: d(0→1)=1+2=3d(0 \to 1) = 1 + 2 = 3 and d(1→2)=1+2+1=4d(1 \to 2) = 1 + 2 + 1 = 4. The only path has delay Dmax=7D_{max} = 7, so both connections have criticality 1 and T=7T = 7.

Move block 1 to the empty site (1,0)(1, 0). Net e1e_1 becomes 2+1=32 + 1 = 3 and net e2e_2 becomes 2+2=42 + 2 = 4, so ΔBB=−2\Delta BB = -2; the delays become 2 and 3, so ΔT=−2\Delta T = -2. Then

ΔC=0.5⋅−27+0.5⋅−29=−1663≈−0.254,\Delta C = 0.5 \cdot \frac{-2}{7} + 0.5 \cdot \frac{-2}{9} = -\frac{16}{63} \approx -0.254,

and the move is made. The move back has ΔC=+16/63\Delta C = +16/63 measured against the same normalizers; at T=0.1T = 0.1 it is accepted with probability e−2.54≈0.079e^{-2.54} \approx 0.079.

On a toy run, 25 blocks with 30 random nets on a 5×55 \times 5 grid (netlist seed 2, placer seed 3, inner =2= 2), a random placement has BB≈192.7BB \approx 192.7 and a critical path delay of 34. The placer, after 79 temperatures of 146 moves each, ends with BB≈135.3BB \approx 135.3 and delay 18 for λ=0.5\lambda = 0.5, and with BB≈132.3BB \approx 132.3 and delay 21 for λ=0\lambda = 0. This is a toy run, not a benchmark result, but it shows the trade: the timing term buys a shorter critical path for a little more wire.

Correctness

The full proof shows four things.

  • Legality. A move to an empty site or a swap keeps each block on its own site, so every placement the algorithm visits is legal.
  • Exact incremental cost. Only nets with a moved block and connections with a moved end change, so the costs of line L6, summed over the accepted moves, equal the costs recomputed from scratch. The tests run the placer with a recomputation after every move.
  • Criticalities. The timing analysis gives crit(c)=ℓ(c)/Dmax\mathrm{crit}(c) = \ell(c) / D_{max}, where ℓ(c)\ell(c) is the longest path through cc.
  • Termination. The temperature falls by a factor of at most 0.95 per round, so the number of temperatures is O(log⁡(T0⋅m))O(\log(T_0 \cdot m)) for mm nets.

What is not proved is the quality of the result. Simulated annealing reaches an optimum with probability tending to 1 only under cooling schedules far slower than this one, so the placer is a heuristic. On 40 random netlists of 3 to 5 blocks on a 3×23 \times 2 grid with λ=0\lambda = 0 (seed 1), the placer matched the exhaustive optimum of BBBB on all 40; this is a measurement on tiny instances, not a guarantee.

Proof: The annealing placer keeps a legal placement, its incremental cost change equals the change of the cost recomputed from scratch, the criticalities are exact, and it stopsfull

We use the notation of the page. A placement is a map loc\mathrm{loc} from the nn blocks to the sites of an nx×nyn_x \times n_y grid. It is legal when it is injective. A net ee is a list of blocks, and its bounding box cost is bb(e)=q(∣e∣) (Δx(e)+1+Δy(e)+1)\mathrm{bb}(e) = q(|e|) \, (\Delta x(e) + 1 + \Delta y(e) + 1), where Δx(e)\Delta x(e) and Δy(e)\Delta y(e) are the spans of the coordinates of its blocks. BB=∑ebb(e)BB = \sum_e \mathrm{bb}(e). A connection c=(u,v)c = (u, v) joins the driver of a net to one of its sinks, with delay d(c)=1+∣xu−xv∣+∣yu−yv∣d(c) = 1 + |x_u - x_v| + |y_u - y_v|, and T=∑cwc d(c)T = \sum_c w_c \, d(c) with weights wc=crit(c)CEw_c = \mathrm{crit}(c)^{CE} that stay fixed during a temperature.

Lemma 1 (legality is kept). If the placement is legal before a move, it is legal after it.

Proof. A move picks a block aa and a site s≠loc(a)s \ne \mathrm{loc}(a). If ss is empty, aa moves to ss, and no other block is at ss. If block bb is at ss, then aa and bb exchange sites. In both cases the sites of all other blocks are unchanged, and the map stays injective. The initial placement gives the blocks the first nn sites of a shuffled list of distinct sites, so it is legal. □\square

Lemma 2 (locality of the cost change). Let MM be the set of moved blocks ({a}\{a\} or {a,b}\{a, b\}). Let EME_M be the nets that hold a block of MM, and CMC_M the connections with an end in MM. Then

BB′−BB=∑e∈EM(bb′(e)−bb(e)),T′−T=∑c∈CMwc (d′(c)−d(c)),BB' - BB = \sum_{e \in E_M} (\mathrm{bb}'(e) - \mathrm{bb}(e)), \qquad T' - T = \sum_{c \in C_M} w_c \, (d'(c) - d(c)),

where primes denote values after the move.

Proof. bb(e)\mathrm{bb}(e) depends only on the sites of the blocks of ee. A net outside EME_M has no block of MM, and the move changes only the sites of blocks of MM, so its term is the same before and after. The same holds for d(c)d(c) with c∉CMc \notin C_M, and the weights do not change within a temperature. Subtracting the two sums term by term leaves the terms of EME_M and CMC_M. □\square

The function that evaluates a move computes exactly these two sums: it applies the move, sums bb\mathrm{bb} and wc dw_c \, d over EME_M and CMC_M, undoes the move, and subtracts. So the running totals, updated by these differences after each accepted move, are equal to BBBB and TT recomputed from scratch, by induction over the accepted moves. At the start of each temperature the totals are set by a full recomputation, which starts the induction again with the new weights. (The implementation asserts this equality after every move when its check flag is set, up to rounding of floating point.) The move cost

ΔC=λ T′−TTprev+(1−λ) BB′−BBBBprev\Delta C = \lambda \, \frac{T' - T}{T_{\mathrm{prev}}} + (1 - \lambda) \, \frac{BB' - BB}{BB_{\mathrm{prev}}}

is therefore the change of the normalized cost λT/Tprev+(1−λ)BB/BBprev\lambda T / T_{\mathrm{prev}} + (1 - \lambda) BB / BB_{\mathrm{prev}}, whose normalizers are fixed during the temperature.

Lemma 3 (criticalities). Let the connections form a directed acyclic graph, and let ℓ(c)\ell(c) be the largest delay of a path through cc, where the delay of a path is the sum of the delays of its connections, and D=max⁡cℓ(c)>0D = \max_c \ell(c) > 0. Then the timing analysis returns crit(c)=ℓ(c)/D\mathrm{crit}(c) = \ell(c) / D.

Proof. The procedure orders the blocks topologically by repeatedly taking blocks with no unprocessed fanin (topological sort). In that order, arrival(v)\mathrm{arrival}(v) is the maximum of arrival(u)+d(u,v)\mathrm{arrival}(u) + d(u, v) over fanin connections, which by induction is the largest delay of a path that ends at vv. In reverse order, required(u)=min⁡(D,min⁡v(required(v)−d(u,v)))\mathrm{required}(u) = \min(D, \min_v (\mathrm{required}(v) - d(u, v))), which by induction is DD minus the largest delay of a path that starts at uu. A path through c=(u,v)c = (u, v) is a path that ends at uu, then cc, then a path that starts at vv, so ℓ(c)=arrival(u)+d(c)+(D−required(v))\ell(c) = \mathrm{arrival}(u) + d(c) + (D - \mathrm{required}(v)). The returned value is 1−(required(v)−arrival(u)−d(c))/D=ℓ(c)/D1 - (\mathrm{required}(v) - \mathrm{arrival}(u) - d(c)) / D = \ell(c) / D. □\square

Lemma 4 (termination). The number of temperatures is at most 1+log⁡(T0 m/0.005)/log⁡(1/0.95)1 + \log(T_0 \, m / 0.005) / \log(1 / 0.95) for mm nets and initial temperature T0>0T_0 > 0, and the placer stops.

Proof. Each temperature multiplies TT by α∈{0.5,0.8,0.9,0.95}\alpha \in \{0.5, 0.8, 0.9, 0.95\}, so after kk temperatures T≤0.95kT0T \le 0.95^k T_0. The loop runs while T≥0.005/mT \ge 0.005 / m, so 0.95kT0≥0.005/m0.95^{k} T_0 \ge 0.005 / m for every kk for which a temperature starts after the first, which bounds kk as stated. Each temperature and the final quench make a fixed number of moves, each of finite work. If T0=0T_0 = 0, the loop does not run. □\square

None of this is about the quality of the result. With a finite schedule, simulated annealing gives no guarantee of an optimal placement; the convergence results for simulated annealing need a cooling schedule far slower than this one. How far from the optimum the placer ends on small instances is a measurement, reported on the page.

Theorem 5. The placer returns a legal placement, its accepted moves change BBBB and TT by exactly the values it computes, and it stops.

Proof. Lemmas 1, 2 and 4. ■\blacksquare

Complexity

A move touches the nets and connections of at most two blocks, so with FF the number of pins on those nets it costs O(F)O(F). A temperature makes inner⋅n4/3\mathrm{inner} \cdot n^{4/3} moves and one timing analysis in O(P)O(P) time, where PP is the number of pins of all nets, so it costs O(n4/3F+P)O(n^{4/3} F + P). The number kk of temperatures depends on the acceptance rates; Lemma 4 of the proof bounds it by O(log⁡(T0m))O(\log(T_0 m)), and the toy run above used 79. The space is O(n+P)O(n + P).

VPR updates the bounding box of a net in O(1)O(1) in most cases by keeping the number of terminals on each edge of the box, and recomputes it only when a terminal leaves an edge that it alone held. The implementation recomputes the boxes of the affected nets, which costs O(F)O(F).

Properties

  • Randomized. The result depends on the seed of the random generator.
  • Adaptive. The schedule needs no tuning per design: the starting temperature, the cooling rate and the range limit all follow the measured acceptance rate.
  • Trade-off by one weight. λ=0\lambda = 0 gives the wirelength-only placer, and λ\lambda near 1 places for delay only. Marquardt, Betz and Rose used λ=0.5\lambda = 0.5 and report a large cut in critical path delay for a small growth in wirelength over the placer without timing; that is a measured result on their benchmarks.
  • Stale timing. Criticalities are fixed during a temperature, so a move that changes the critical path is judged with old weights until the next analysis.
  • Effort knob. The factor inner scales the number of moves, trading run time for quality.

Variants and improvements

  • Path-based timing cost. Instead of weighting connections, add the delay of the critical paths. This is more exact and slower.
  • Directed moves. Move a block toward the center of its nets, or toward a critical neighbor, instead of to a random site in range.
  • Heterogeneous arrays. Restrict moves of a memory or DSP block to sites of its own type in its columns, as VPR does for each block type.
  • Analytical start. Start the anneal at a low temperature from a placement found by an analytical method, such as HeAP, and use annealing only to refine it.
  • Parallel annealing. Split the grid into regions and anneal them in parallel, at the cost of moves that cross regions.

When to use it

Use timing-driven annealing to place packed blocks on an FPGA when quality matters more than run time, and the design has up to some hundred thousand blocks. It handles any cost that can be evaluated per move, including timing, congestion and heterogeneous sites. For very large designs, an analytical placer is much faster, and annealing then serves as the refinement step. Run the placer with λ=0\lambda = 0 if only the minimum channel width matters.

Pitfalls

  • Costs on different scales. ΔT\Delta T and ΔBB\Delta BB have different units. Without the normalization by TprevT_{prev} and BBprevBB_{prev}, one term swamps the other, and the weight λ\lambda means nothing.
  • Drift of the incremental cost. Floating point totals drift after millions of moves. Recompute both costs from scratch at the start of each temperature.
  • Range limit below 1. A range limit below 1 allows no move. Keep it at least 1.
  • Criticality without exponent. With CE=1CE = 1, near-critical and non-critical connections weigh almost the same. The exponent sharpens the focus on the critical paths.
  • Too few moves. Fewer moves per temperature save run time but lower the quality. Change the factor inner, not the exponent 4/34/3, to trade the two.

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.

fpga_timing_driven_annealing_placement.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fpga-timing-driven-annealing-placement/. The authors are listed in prov/ZDNXW1.jsonl.

"""Timing-driven simulated annealing placement for an island-style FPGA, after VPR.

Blocks are placed on the sites (x, y) of an nx by ny grid, one block per site.
A net is a list of blocks, the driver first. The cost of a move is

    dC = lam * dT / prev_T + (1 - lam) * dBB / prev_BB,

where BB is the bounding box cost and T the timing cost, and prev_T, prev_BB
are their values at the start of the temperature.
"""

import itertools
import math
import random
from dataclasses import dataclass, field

# Cheng's crossing-count correction q(n) for a net with n terminals. The values for n <= 10 and
# the growth above 50 follow the table of VPR; between 10 and 50 this file interpolates linearly.
Q_TABLE = [1.0, 1.0, 1.0, 1.0, 1.0828, 1.1536, 1.2206, 1.2823, 1.3385, 1.3991, 1.4493]


def q(n: int) -> float:
    if n < len(Q_TABLE):
        return Q_TABLE[n]
    if n <= 50:
        return 1.4493 + (n - 10) * (2.7933 - 1.4493) / 40
    return 2.7933 + 0.02616 * (n - 50)


def delay(a: tuple[int, int], b: tuple[int, int]) -> int:
    """Delay of a connection between sites a and b: 1 plus the Manhattan distance."""
    return 1 + abs(a[0] - b[0]) + abs(a[1] - b[1])


def net_bb(net: list[int], loc: list[tuple[int, int]]) -> float:
    xs = [loc[b][0] for b in net]
    ys = [loc[b][1] for b in net]
    return q(len(net)) * ((max(xs) - min(xs) + 1) + (max(ys) - min(ys) + 1))


def bb_cost(nets: list[list[int]], loc: list[tuple[int, int]]) -> float:
    return sum(net_bb(net, loc) for net in nets)


def connections(nets: list[list[int]]) -> list[tuple[int, int]]:
    return [(net[0], s) for net in nets for s in net[1:]]


def criticalities(n_blocks: int, conns: list[tuple[int, int]], loc: list[tuple[int, int]]) -> list[float]:
    """Static timing analysis: crit(c) = 1 - slack(c) / Dmax for each connection c.

    The connections must form a directed acyclic graph; blocks have delay 0.
    """
    fanin: list[list[int]] = [[] for _ in range(n_blocks)]
    fanout: list[list[int]] = [[] for _ in range(n_blocks)]
    for i, (u, v) in enumerate(conns):
        fanin[v].append(i)
        fanout[u].append(i)
    indeg = [len(fanin[v]) for v in range(n_blocks)]
    order = [v for v in range(n_blocks) if indeg[v] == 0]
    for v in order:
        for i in fanout[v]:
            w = conns[i][1]
            indeg[w] -= 1
            if indeg[w] == 0:
                order.append(w)
    d = [delay(loc[u], loc[v]) for u, v in conns]
    arrival = [0] * n_blocks
    for v in order:
        for i in fanout[v]:
            arrival[conns[i][1]] = max(arrival[conns[i][1]], arrival[v] + d[i])
    dmax = max(arrival, default=0)
    if dmax == 0:
        return [0.0] * len(conns)
    required = [dmax] * n_blocks
    for v in reversed(order):
        for i in fanout[v]:
            required[v] = min(required[v], required[conns[i][1]] - d[i])
    return [1 - (required[v] - arrival[u] - d[i]) / dmax for i, (u, v) in enumerate(conns)]


def alpha(r_acc: float) -> float:
    if r_acc > 0.96:
        return 0.5
    if r_acc > 0.8:
        return 0.9
    if r_acc > 0.15:
        return 0.95
    return 0.8


@dataclass
class Placer:
    nx: int
    ny: int
    n_blocks: int
    nets: list[list[int]]
    lam: float = 0.5
    inner: float = 1.0
    check_every_move: bool = False
    loc: list[tuple[int, int]] = field(default_factory=list)
    stats: dict = field(default_factory=dict)

    def __post_init__(self) -> None:
        self.conns = connections(self.nets)
        self.nets_of: list[list[int]] = [[] for _ in range(self.n_blocks)]
        for i, net in enumerate(self.nets):
            for b in set(net):
                self.nets_of[b].append(i)
        self.conns_of: list[list[int]] = [[] for _ in range(self.n_blocks)]
        for i, (u, v) in enumerate(self.conns):
            self.conns_of[u].append(i)
            if v != u:
                self.conns_of[v].append(i)
        self.weight = [0.0] * len(self.conns)  # crit ** CE, fixed during a temperature

    def timing_cost(self) -> float:
        return sum(w * delay(self.loc[u], self.loc[v]) for w, (u, v) in zip(self.weight, self.conns))

    def _move_delta(self, a: int, b, target: tuple[int, int]) -> tuple[float, float]:
        """dBB and dT of moving a to target and b (or nothing) to a's site, from the affected nets only."""
        moved = [a] if b is None else [a, b]
        net_ids = sorted({i for m in moved for i in self.nets_of[m]})
        conn_ids = sorted({i for m in moved for i in self.conns_of[m]})
        old_bb = sum(net_bb(self.nets[i], self.loc) for i in net_ids)
        old_t = sum(self.weight[i] * delay(self.loc[self.conns[i][0]], self.loc[self.conns[i][1]]) for i in conn_ids)
        src = self.loc[a]
        self.loc[a] = target
        if b is not None:
            self.loc[b] = src
        new_bb = sum(net_bb(self.nets[i], self.loc) for i in net_ids)
        new_t = sum(self.weight[i] * delay(self.loc[self.conns[i][0]], self.loc[self.conns[i][1]]) for i in conn_ids)
        self.loc[a] = src
        if b is not None:
            self.loc[b] = target
        return new_bb - old_bb, new_t - old_t

    def place(self, rng: random.Random) -> list[tuple[int, int]]:
        sites = [(x, y) for x in range(self.nx) for y in range(self.ny)]
        if self.n_blocks > len(sites):
            raise ValueError("more blocks than sites")
        n = self.n_blocks
        rng.shuffle(sites)
        self.loc = sites[:n]  # @line L1
        at = {self.loc[i]: i for i in range(n)}
        r_max = max(self.nx, self.ny) - 1
        rlimit = float(max(r_max, 1))
        ce = 1.0

        def set_weights() -> None:
            crit = criticalities(n, self.conns, self.loc)
            self.weight = [c ** ce for c in crit]

        def try_move(t: float, prev_bb: float, prev_t: float, totals: list[float]) -> bool:
            a = rng.randrange(n)  # @line L5
            r = max(1, int(rlimit))
            ax, ay = self.loc[a]
            target = (
                rng.randint(max(0, ax - r), min(self.nx - 1, ax + r)),
                rng.randint(max(0, ay - r), min(self.ny - 1, ay + r)),
            )
            if target == self.loc[a]:
                return False
            b = at.get(target)
            d_bb, d_t = self._move_delta(a, b, target)
            d_c = (1 - self.lam) * d_bb / prev_bb + (self.lam * d_t / prev_t if prev_t > 0 else 0.0)  # @line L6
            if d_c <= 0 or (t > 0 and rng.random() < math.exp(-d_c / t)):  # @line L7
                src = self.loc[a]
                self.loc[a] = target
                at[target] = a
                if b is None:
                    del at[src]
                else:
                    self.loc[b] = src
                    at[src] = b
                totals[0] += d_bb
                totals[1] += d_t
                if self.check_every_move:
                    assert math.isclose(totals[0], bb_cost(self.nets, self.loc), rel_tol=1e-9, abs_tol=1e-9)
                    assert math.isclose(totals[1], self.timing_cost(), rel_tol=1e-9, abs_tol=1e-9)
                return True
            return False

        # Initial temperature: 20 times the standard deviation of the cost over n random moves.
        set_weights()
        prev_bb, prev_t = bb_cost(self.nets, self.loc), self.timing_cost()
        if prev_bb == 0:
            return self.loc
        samples = []
        totals = [prev_bb, prev_t]
        for _ in range(n):
            try_move(math.inf, prev_bb, prev_t, totals)
            samples.append((1 - self.lam) * totals[0] / prev_bb + (self.lam * totals[1] / prev_t if prev_t > 0 else 0.0))
        mean = sum(samples) / len(samples)
        t = 20 * math.sqrt(sum((s - mean) ** 2 for s in samples) / len(samples))
        moves = max(1, int(self.inner * n ** (4 / 3)))
        temps = 0
        while t >= 0.005 / len(self.nets):  # @line L2
            set_weights()  # @line L3
            prev_bb, prev_t = bb_cost(self.nets, self.loc), self.timing_cost()
            totals = [prev_bb, prev_t]
            accepted = sum(try_move(t, prev_bb, prev_t, totals) for _ in range(moves))  # @line L4
            r_acc = accepted / moves
            t *= alpha(r_acc)  # @line L8
            rlimit = min(max(rlimit * (1 - 0.44 + r_acc), 1.0), max(r_max, 1))  # @line L9
            ce = 1 + 7 * (1 - (rlimit - 1) / (r_max - 1)) if r_max > 1 else 8.0
            temps += 1
        set_weights()  # @line L10
        prev_bb, prev_t = bb_cost(self.nets, self.loc), self.timing_cost()
        totals = [prev_bb, prev_t]
        for _ in range(moves):
            try_move(0.0, prev_bb, prev_t, totals)
        self.stats = {"temperatures": temps, "moves_per_temperature": moves}
        return self.loc  # @line L11


def exhaustive_min_bb(nx: int, ny: int, n_blocks: int, nets: list[list[int]]) -> float:
    """Least bounding box cost over all placements, by trying every injective map of blocks to sites."""
    sites = [(x, y) for x in range(nx) for y in range(ny)]
    return min(bb_cost(nets, list(p)) for p in itertools.permutations(sites, n_blocks))
test_fpga_timing_driven_annealing_placement.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fpga-timing-driven-annealing-placement/. The authors are listed in prov/ZDNXW1.jsonl.

import math
import random

from fpga_timing_driven_annealing_placement import (
    Placer,
    alpha,
    bb_cost,
    connections,
    criticalities,
    delay,
    exhaustive_min_bb,
    net_bb,
    q,
)


def random_nets(rng: random.Random, n_blocks: int, n_nets: int, max_fanout: int) -> list[list[int]]:
    """Each net is driven by a block and read by later blocks, so the connections form a DAG."""
    nets = []
    for _ in range(n_nets):
        d = rng.randrange(n_blocks - 1)
        sinks = rng.sample(range(d + 1, n_blocks), rng.randint(1, min(max_fanout, n_blocks - 1 - d)))
        nets.append([d] + sinks)
    return nets


def brute_criticalities(n_blocks, conns, loc):
    d = [delay(loc[u], loc[v]) for u, v in conns]

    def longest_to(v):
        return max((longest_to(u) + d[i] for i, (u, w) in enumerate(conns) if w == v), default=0)

    def longest_from(v):
        return max((d[i] + longest_from(w) for i, (u, w) in enumerate(conns) if u == v), default=0)

    dmax = max(longest_to(v) for v in range(n_blocks))
    return [(longest_to(u) + d[i] + longest_from(v)) / dmax for i, (u, v) in enumerate(conns)]


def test_small_functions():
    assert [q(n) for n in (1, 2, 3)] == [1.0, 1.0, 1.0]
    assert q(4) > 1 and q(50) > q(10) > q(4)
    assert delay((0, 0), (2, 1)) == 4
    assert net_bb([0, 1, 2], [(0, 0), (2, 1), (1, 3)]) == (3 + 4)
    assert [alpha(r) for r in (0.99, 0.9, 0.5, 0.1)] == [0.5, 0.9, 0.95, 0.8]


def test_page_example():
    nets = [[0, 1], [1, 2]]
    p = Placer(3, 2, 3, nets)
    p.loc = [(0, 0), (2, 0), (0, 1)]
    p.weight = criticalities(3, p.conns, p.loc)
    assert p.weight == [1.0, 1.0]
    assert bb_cost(nets, p.loc) == 9 and p.timing_cost() == 7
    assert p._move_delta(1, None, (1, 0)) == (-2, -2)


def test_criticalities_match_path_enumeration():
    rng = random.Random(4)
    for _ in range(200):
        n = rng.randint(2, 7)
        nets = random_nets(rng, n, rng.randint(1, 5), 3)
        conns = connections(nets)
        loc = [(rng.randrange(4), rng.randrange(4)) for _ in range(n)]
        got = criticalities(n, conns, loc)
        want = brute_criticalities(n, conns, loc)
        assert all(math.isclose(a, b) for a, b in zip(got, want))
        assert max(got) == 1.0


def test_incremental_cost_equals_recomputation():
    rng = random.Random(7)
    for trial in range(6):
        n = rng.randint(8, 14)
        nets = random_nets(rng, n, n, 4)
        p = Placer(4, 4, n, nets, lam=0.5 if trial % 2 else 0.0, check_every_move=True)
        loc = p.place(random.Random(trial))
        assert len(set(loc)) == n
        assert all(0 <= x < 4 and 0 <= y < 4 for x, y in loc)


def test_never_below_exhaustive_optimum():
    rng = random.Random(1)
    equal = 0
    trials = 40
    for trial in range(trials):
        nx, ny = 3, 2
        n = rng.randint(3, 5)
        nets = random_nets(rng, n, rng.randint(2, 5), 3)
        best = exhaustive_min_bb(nx, ny, n, nets)
        p = Placer(nx, ny, n, nets, lam=0.0, inner=4.0)
        loc = p.place(random.Random(100 + trial))
        got = bb_cost(nets, loc)
        assert got >= best - 1e-9
        equal += math.isclose(got, best)
    assert equal >= trials * 3 // 4


def test_annealing_beats_random_placement():
    rng = random.Random(2)
    n = 25
    nets = random_nets(rng, n, 30, 3)
    sites = [(x, y) for x in range(5) for y in range(5)]
    rng.shuffle(sites)
    start = bb_cost(nets, sites[:n])
    p = Placer(5, 5, n, nets, lam=0.5, inner=2.0)
    loc = p.place(random.Random(3))
    assert bb_cost(nets, loc) < start

History

Annealing placement of standard cells goes back to TimberWolf by Sechen and Sangiovanni-Vincentelli in the 1980s, with its range limiter. Betz and Rose's VPR (1997) adapted it to FPGAs with a schedule driven by the acceptance rate: the starting temperature from the spread of the cost, the cooling factor from the acceptance rate, and a range limit that keeps that rate near 0.44, and with Cheng's factor qq in the bounding box cost. Marquardt, Betz and Rose (2000) added the timing cost with criticality weights and the normalized mix of the two costs; this placer, often called T-VPlace, became the default of VPR and of the VTR flow.

References

  1. Alexander Marquardt, Vaughn Betz and Jonathan Rose, Timing-driven placement for FPGAs, Proceedings of the ACM/SIGDA International Symposium on Field Programmable Gate Arrays (FPGA '00), 203 to 213, 2000, the timing cost with the criticality exponent, the normalized cost of a move with the weight lambda, and the update of the criticalities once per temperature
  2. Vaughn Betz, Jonathan Rose and Alexander Marquardt, Architecture and CAD for Deep-Submicron FPGAs, Kluwer, 1999 (doi 10.1007/978-1-4615-5145-4), Chapter 4, the VPR placer (the bounding box cost with the factor q, the initial temperature, the number of moves per temperature, the update of the temperature and of the range limit from the acceptance rate, and the exit test)
  3. Vaughn Betz and Jonathan Rose, VPR, a new packing, placement and routing tool for FPGA research, Field-Programmable Logic and Applications (FPL 1997), Lecture Notes in Computer Science 1304, Springer, 1997, the adaptive annealing schedule of VPR (general locator)
  4. Chih-Liang Eric Cheng, RISA, accurate and efficient placement routability modeling, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design (ICCAD), 1994, the factor q(n) that corrects the bounding box of a net with n terminals (general locator)

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.per_move
  • a full proof of time.per_temperature
  • a full proof of time.total
  • a full proof of space.total
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