Algorithm Search⌘K

Algorithmresearch

HeAP FPGA placement

Also called heterogeneous analytical placement, analytical placement for heterogeneous FPGAs.

Gort and Anderson's analytical FPGA placer that solves a quadratic wirelength model and spreads LUTs, RAMs and DSP blocks into their own columns by partitioning.

Solves
Placement
Time
O(k (t (n + Q) + S log^2 S)) totalO(t (n + Q) + S log^2 S) per_iteration
Space
O(n + Q + S) total
Where
Q = the number of terminal pairs of the clique model; S = the number of sites; k = the number of iterations; n = the number of blocks; t = the number of conjugate gradient steps per solve
Properties
deterministicnot exactrecursive
Origin
Marcel Gort, Jason H. Anderson, 2012

HeAP is an analytical placer for heterogeneous FPGAs, a topic of FPGA CAD: it places the packed logic blocks, block RAMs and DSP blocks of a netlist on an island-style FPGA whose columns each hold one type of block. It follows SimPL: it minimizes a quadratic model of the wirelength by a sparse linear solve, spreads the crowded result over the legal sites, and pulls the next solve toward the spread positions with anchors of growing weight. The FPGA part is the spreading, which Gort and Anderson do separately for each block type, inside the columns of that type.

In plain words

An FPGA chip is a grid of seats, and each column of seats takes only one kind of part: logic, memory or multiplier. The placer must give every part a seat of its kind and keep connected parts close.

HeAP first pretends that wires are springs and finds where the parts settle. That is fast, but the parts bunch up, and a memory may settle on a logic column.

So HeAP then spreads each kind of part over the seats of that kind. It cuts the seats into halves, again and again, and sends the parts to the halves in the order of where they settled. Every part now has its own seat of the right kind.

Then it ties each part to its seat with a weak spring and lets the springs settle again. The ties get stronger each round, and HeAP keeps the best spread it has seen.

The problem

Input. A grid of nxn_x columns and nyn_y rows of sites, a type for each column (such as logic, memory or DSP), nn blocks with a type each, fixed pads with real positions, and a list of nets, each a set of blocks and pads.

Output. A legal placement: an injective map from the blocks to the sites that puts every block on a site of its own type.

Goal. Small total half-perimeter wirelength (HPWL), the sum over the nets of the width plus the height of the bounding box of their terminals. This is the wirelength version of the placement problem, with the column types as an extra constraint. HeAP does not minimize it exactly.

The algorithm

The quadratic model replaces each net of pp terminals by a clique whose p(p−1)/2p (p - 1) / 2 edges each weigh 1/(p−1)1 / (p - 1) (the clique net model), and minimizes the weighted sum of squared edge lengths, separately in xx and in yy. With anchors aia_i of weight β\beta, it adds β∑i∥pi−ai∥2\beta \sum_i \lVert p_i - a_i \rVert^2. The minimum solves a sparse symmetric positive definite system, which the conjugate gradient method solves.

  1. HEAP(grid, blocks, nets, iters, α)
  2. 1pos ← the minimum of the quadratic model with no anchors
  3. 2best ← none
  4. 3for k ← 1 to iters:
  5. 4for each block type t: SPREAD(the blocks of type t, the sites of type t, pos)
  6. 5if the HPWL of the spread placement is less than that of best: best ← the spread placement
  7. 6β ← α k
  8. 7pos ← the minimum of the quadratic model with each block anchored to its spread site with weight β
  9. 8return best

SPREAD(B,S)(B, S) is a recursive bisection. With one site, it puts the one block there. Otherwise it cuts the sites SS into a low and a high part along the axis on which they spread more, keeping sites with the same coordinate together where it can. It sorts the blocks BB by their position along the same axis and sends to the low part a share of the blocks equal to its share of the sites, rounded, but never more blocks than sites to either part. Then it recurses on both parts. Since a column has one type, the call for type tt only sees the columns of type tt; for a memory type with one column, the cuts run along that column.

The implementation makes three simplifications, and says so. It uses the clique model throughout; it adds a tiny pull of weight 10−310^{-3} toward the center of the grid so that the system stays positive definite when a group of blocks has no path to a pad; and its spreading cuts sites, not area, so that the leaves of the recursion are single sites and the spread placement is already legal. SimPL spreads by area into regions and then legalizes. The net model and the exact spreading and legalization steps of HeAP are in the paper and are not repeated here.

Example

The grid has 3 columns and 2 rows; columns 0 and 2 are logic (L), column 1 is memory (M). Blocks 0, 1 and 2 are logic and block 3 is memory. Pad P0P_0 is at (−1,0.5)(-1, 0.5) and pad P1P_1 at (3,0.5)(3, 0.5). The five nets each have two terminals: {P0,0}\{P_0, 0\}, {0,3}\{0, 3\}, {3,1}\{3, 1\}, {1,P1}\{1, P_1\} and {2,3}\{2, 3\}.

Line L1. Every net has two terminals, so every edge weighs 1. In xx, block 0 sits between P0P_0 and block 3, block 3 between blocks 0, 1 and 2, block 1 between block 3 and P1P_1, and block 2 only on block 3. Setting each gradient to zero gives x0=0x_0 = 0, x3=1x_3 = 1, x1=2x_1 = 2 and x2=1x_2 = 1, and every yy is 0.50.5. So block 2 lands on top of block 3, in the memory column.

Line L4. The logic sites are (0,0),(0,1),(2,0),(2,1)(0, 0), (0, 1), (2, 0), (2, 1). They spread more in xx, so the cut puts column 0 low and column 2 high, two sites each. The logic blocks in xx order are 0, 2, 1, so the low part gets ⌊3⋅2/4+1/2⌋=2\lfloor 3 \cdot 2 / 4 + 1/2 \rfloor = 2 blocks, 0 and 2, and the high part gets block 1. In column 0 the cut is in yy; both blocks have y=0.5y = 0.5, and the tie goes to the smaller xx, so block 0 gets (0,0)(0, 0) and block 2 gets (0,1)(0, 1). Block 1 gets (2,0)(2, 0), and the memory block 3 gets (1,0)(1, 0).

Line L5. The HPWL is 1.5+1+1+1.5+2=71.5 + 1 + 1 + 1.5 + 2 = 7 for the nets in the order above. Trying every legal placement gives 7 as well, so on this instance the first spread is already optimal, and the later iterations keep it.

A larger toy run. On an 8 by 6 grid with columns L L M L L D L L, 30 logic blocks, 4 memory blocks, 3 DSP blocks, 6 pads and 43 random nets (seed 2), the HPWL of the spread placement was 189 after the first iteration and 177 after the ninth, and it stayed at 177 to iteration 20. Twenty random legal placements (seeds 100 to 119) had a mean HPWL of 282.7 and a best of 248. This is a toy run of the implementation, not a benchmark result.

Correctness

The full proof shows the following.

  • The solve is exact for its model. The matrix of the quadratic model is symmetric positive definite, so the model has one minimum, and conjugate gradients reach it in at most nn steps in exact arithmetic. In floating point the solve stops at a tolerance; the tests compare it with exact Gaussian elimination.
  • Spreading is legal. If a type has no more blocks than sites, SPREAD gives each block a distinct site of that type. The proof is an induction on the number of sites: both parts of a cut are nonempty, and the clamped share never sends more blocks to a part than it has sites.
  • The result is legal and its cost is a true upper bound. Every spread placement is legal, since columns of different types share no sites, and HEAP returns the one of least HPWL. So its HPWL is at least the optimum.

Nothing bounds the gap to the optimum, and nothing proves that the iterations converge or that the HPWL falls each round. On 60 seeded instances on a 3 by 2 grid (seed 1), the result was optimal on 20, and the mean ratio to the exhaustive optimum was about 1.10, with a worst case of about 1.44. These are measured on toy instances.

Proof: Every iterate of HeAP is a legal placement of each block type in its own columns, and the quadratic step finds the exact minimum of its modelfull

Setting

The grid has columns 0,…,nx−10, \ldots, n_x - 1 and rows 0,…,ny−10, \ldots, n_y - 1. Column xx has a type τ(x)\tau(x), and StS_t is the set of sites (x,y)(x, y) with τ(x)=t\tau(x) = t. Block ii has the type type(i)\mathrm{type}(i), and ntn_t is the number of blocks of type tt. A placement is legal when it maps the blocks injectively to sites and puts every block on a site of its own type. The algorithm is the one of the node page, as written in the implementation; it rejects the input when nt>∣St∣n_t > |S_t| for some tt, so below nt≤∣St∣n_t \le |S_t| for all tt.

The quadratic step

Fix one coordinate, say xx. For a net with p≥2p \ge 2 terminals, every pair of terminals gets the weight w=1/(p−1)w = 1 / (p - 1) (the clique net model). The model of the quadratic step is

Φ(x)=∑pairs {i,j} of blockswij(xi−xj)2+∑pairs {i,q}, q a padwiq(xi−Xq)2+β∑i(xi−ai)2+ε∑i(xi−c)2,\Phi(x) = \sum_{\text{pairs } \{i, j\} \text{ of blocks}} w_{ij} (x_i - x_j)^2 + \sum_{\text{pairs } \{i, q\},\ q \text{ a pad}} w_{iq} (x_i - X_q)^2 + \beta \sum_i (x_i - a_i)^2 + \varepsilon \sum_i (x_i - c)^2,

where XqX_q is the fixed position of pad qq, aia_i is the anchor of block ii (the term is absent in the first solve, β=0\beta = 0), cc is the center of the grid and ε>0\varepsilon > 0 is a small constant (10−310^{-3} in the implementation).

Lemma 1. Φ(x)=x⊤Ax−2b⊤x+const\Phi(x) = x^\top A x - 2 b^\top x + \mathrm{const}, where AA and bb are the matrix and vector that build_system returns (with εc\varepsilon c added to bb). AA is symmetric positive definite, so Φ\Phi has exactly one minimum, x∗=A−1bx^* = A^{-1} b.

Proof. Expand each term. w(xi−xj)2=wxi2+wxj2−2wxixjw (x_i - x_j)^2 = w x_i^2 + w x_j^2 - 2 w x_i x_j adds ww to AiiA_{ii} and AjjA_{jj} and −w-w to AijA_{ij} and AjiA_{ji}. w(xi−Xq)2=wxi2−2wXqxi+constw (x_i - X_q)^2 = w x_i^2 - 2 w X_q x_i + \mathrm{const} adds ww to AiiA_{ii} and wXqw X_q to bib_i. The anchor and center terms add β\beta and ε\varepsilon to AiiA_{ii} and βai\beta a_i and εc\varepsilon c to bib_i. These are the updates of build_system. For any z≠0z \ne 0,

z⊤Az=∑wij(zi−zj)2+∑wiqzi2+β∑zi2+ε∑zi2≥ε∥z∥2>0,z^\top A z = \sum w_{ij} (z_i - z_j)^2 + \sum w_{iq} z_i^2 + \beta \sum z_i^2 + \varepsilon \sum z_i^2 \ge \varepsilon \lVert z \rVert^2 > 0,

since every weight is nonnegative. So AA is positive definite. The gradient of Φ\Phi is 2(Ax−b)2 (A x - b), and a strictly convex quadratic has its one minimum where the gradient is zero. □\square

Lemma 2. In exact arithmetic, the conjugate gradient method on Ax=bA x = b reaches x∗x^* in at most nn steps.

Proof. This is the finite termination theorem of Hestenes and Stiefel (1952) for symmetric positive definite matrices, which this page cites and does not prove again: the search directions are AA-conjugate, so after mm steps the iterate minimizes Φ\Phi over an mm-dimensional affine subspace, and these subspaces grow until they are the whole space. Lemma 1 gives the hypothesis. □\square

In floating point the implementation stops when the residual is below a tolerance, so it returns an approximation of x∗x^*. The tests compare it with exact Gaussian elimination over the rationals. This is a measurement, not a proof. The legality below does not depend on how good the approximation is: SPREAD accepts any real positions.

The spreading step

SPREAD(B,S)(B, S) takes a list of blocks BB with m=∣B∣m = |B|, a list of distinct sites SS, and the current positions. If BB is empty it returns. If ∣S∣=1|S| = 1 it puts the first block of BB on the one site. Otherwise it picks the axis along which the sites spread more, sorts the sites by that axis, and cuts them into a low part of c1c_1 sites and a high part of c2c_2 sites. The cut is at ⌊∣S∣/2⌋\lfloor |S| / 2 \rfloor, moved down to the first site with the same coordinate when that leaves the low part nonempty. It sorts the blocks by their position along the axis, sends the first kk blocks to the low part and the others to the high part, where

k=max⁡(m−c2, min⁡(c1, ⌊mc1c1+c2+12⌋)),k = \max\left(m - c_2,\ \min\left(c_1,\ \left\lfloor \frac{m c_1}{c_1 + c_2} + \frac{1}{2} \right\rfloor\right)\right),

and recurses on both parts.

Lemma 3. If m≤∣S∣m \le |S|, then SPREAD(B,S)(B, S) ends and puts the blocks of BB on distinct sites of SS.

Proof. By induction on ∣S∣|S|. If BB is empty there is nothing to show. If ∣S∣=1|S| = 1, then m≤1m \le 1, so m=1m = 1 and the one block gets the one site.

Let ∣S∣≥2|S| \ge 2. First, 1≤c1≤∣S∣−11 \le c_1 \le |S| - 1. The default cut ⌊∣S∣/2⌋\lfloor |S| / 2 \rfloor is in that range. The moved cut is the number of sites whose coordinate is strictly below that of the site at the default cut; that site is not counted, so the number is at most the default cut, and the code uses it only when it is at least 1. So both parts are nonempty, and c1+c2=∣S∣c_1 + c_2 = |S|.

Next, the value kk satisfies 0≤k≤m0 \le k \le m, k≤c1k \le c_1 and m−k≤c2m - k \le c_2. Let r=min⁡(c1,⌊mc1/(c1+c2)+1/2⌋)r = \min(c_1, \lfloor m c_1 / (c_1 + c_2) + 1/2 \rfloor). Since 0≤mc1/(c1+c2)≤m0 \le m c_1 / (c_1 + c_2) \le m, the rounded value is in [0,m][0, m], so 0≤r≤min⁡(c1,m)0 \le r \le \min(c_1, m). If r≥m−c2r \ge m - c_2, then k=rk = r, and k≤c1k \le c_1, k≤mk \le m, m−k≤c2m - k \le c_2 all hold. Otherwise k=m−c2>r≥0k = m - c_2 > r \ge 0; then m−k=c2m - k = c_2, k≤mk \le m, and k=m−c2≤c1k = m - c_2 \le c_1 because m≤∣S∣=c1+c2m \le |S| = c_1 + c_2.

So the low call gets k≤c1k \le c_1 blocks on c1<∣S∣c_1 < |S| sites, and the high call gets m−k≤c2m - k \le c_2 blocks on c2<∣S∣c_2 < |S| sites. By the induction hypothesis both end and place their blocks on distinct sites of their own part. The two parts are disjoint and the two block lists are disjoint, so all blocks of BB get distinct sites of SS. □\square

The rounded value in kk is the share of the blocks that matches the share of the sites. The clamp only changes it when a part would get more blocks than sites, and then it sends the excess to the other part.

The whole algorithm

Theorem 4 (legality). Every placement that line L4 builds is legal, and so is the placement that HEAP returns.

Proof. Line L4 calls SPREAD once per type tt, with the blocks of type tt and the sites StS_t. Since nt≤∣St∣n_t \le |S_t|, Lemma 3 puts every block of type tt on a distinct site of StS_t. The sets StS_t for different types are disjoint, because each column has one type. So the whole map is injective and every block is on a site of its type. HEAP returns one of these placements. □\square

Theorem 5 (the returned cost). HEAP ends after iters iterations. It returns the placement of least HPWL among the placements of line L4, and that HPWL is at least the least HPWL over all legal placements.

Proof. The loop of line L3 runs iters times, each solve ends (the conjugate gradient loop has a step cap), and each SPREAD ends by Lemma 3. Line L5 keeps the placement of least HPWL so far, so at the end best has the least HPWL in the history. It is legal by Theorem 4, so its HPWL is at least the minimum over all legal placements. □\square

What is not proved

Nothing here bounds the ratio of the returned HPWL to the optimum, and nothing proves that the anchored solves converge to a legal placement or that the HPWL decreases from one iteration to the next. HeAP, like SimPL, is a heuristic: the tests measure that on small seeded instances the returned HPWL is close to the exhaustive optimum, and they check the lower bound of Theorem 5 on every instance. ■\blacksquare

Complexity

Let QQ be the number of terminal pairs of the clique model, the sum of p(p−1)/2p (p - 1) / 2 over the nets. Building the system takes O(n+Q)O(n + Q) time, and each conjugate gradient step is one product with a matrix of O(n+Q)O(n + Q) nonzeros, so a solve with tt steps takes O(t(n+Q))O(t (n + Q)). SPREAD sorts the sites and the blocks at each level of the recursion; the levels have O(log⁡S)O(\log S) depth and each level sorts at most SS items in all, so a spread of all types takes O(Slog⁡2S)O(S \log^2 S). The HPWL takes O(∑p)O(\sum p), which is within O(n+Q)O(n + Q) for nets of at least two terminals. In total, kk iterations take O(k(t(n+Q)+Slog⁡2S))O(k (t (n + Q) + S \log^2 S)) time and O(n+Q+S)O(n + Q + S) space. The clique model makes QQ quadratic in the size of a net, which is why large placers use sparser net models.

Properties

  • Legal at every iteration. Each spread placement is legal, so the algorithm can stop at any iteration with a usable result.
  • Deterministic. There is no randomness; ties are broken by position and then by block index.
  • Types are separate. Each type is spread only over its own columns, so a memory block never takes a logic site, and the logic blocks are spread around the memory and DSP columns, not over them.
  • Not exact. The quadratic model is not HPWL, and the spreading follows the order of the solve, so the result can be worse than the optimum, as the toy runs show.

Variants and improvements

  • Net models. The clique model costs O(p2)O(p^2) per net. SimPL uses the bound-to-bound model of Kraftwerk2, with O(p)O(p) edges per net, whose weights make the quadratic cost of a net equal to its HPWL at the current positions; see analytical placement.
  • Area-based spreading and legalization. SimPL spreads by area into regions and then legalizes; this keeps fine detail of the solve that a site-by-site cut loses.
  • Detailed placement. A short detailed placement after the global placement, such as low-temperature annealing or pairwise swaps, recovers wirelength that the spreading lost.
  • Timing. Weights on critical nets, as in timing-driven annealing placement, pull critical connections shorter.

When to use it

Use an analytical placer like HeAP for large FPGA designs where an annealer is too slow, and where the device has columns of memory and DSP blocks among the logic. The quadratic solve scales well, and spreading per type handles the columns directly. For small designs, or when the last few percent of wirelength matter, anneal the result or use the annealing placer alone.

Pitfalls

  • Spreading all types together. A spreading step that ignores types puts memory blocks on logic sites. Spread each type over its own columns.
  • A singular system. If a group of blocks has no path to a pad and no anchor, the matrix is only positive semidefinite and the solve has no unique answer. Add anchors, a small diagonal term, or fix some blocks.
  • Anchors too strong too soon. A large first anchor weight freezes the first spread, which follows a crowded solve. Grow the weight slowly.
  • Reading the quadratic minimum as a bound. The wirelength of the unspread solve is not a proved lower bound on the optimal HPWL; it is the minimum of a different objective.

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.

heap_fpga_placement.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heap-fpga-placement/. The authors are listed in prov/5EREMJ.jsonl.

"""HeAP-style analytical placement for a heterogeneous FPGA.

The grid has nx columns and ny rows. Column x has the type col_type[x], such as
"L" for logic, "M" for memory or "D" for DSP, and every site in it has that
type. Movable block i has the type types[i]. Fixed pads have real positions.
A net is a list of terminals: ("b", i) for movable block i, ("p", j) for pad j.

Each iteration solves a quadratic wirelength model (clique net model, solved
by conjugate gradients), spreads the blocks of each type over the sites of
that type by recursive partitioning, and pulls the blocks toward their spread
sites with anchors of growing weight. The best legal placement is kept.
"""

import itertools
from typing import Optional

Pos = tuple[float, float]


def hpwl(nets, loc: list[Pos], pads: list[Pos]) -> float:
    total = 0.0
    for net in nets:
        pts = [loc[i] if k == "b" else pads[i] for k, i in net]
        xs = [p[0] for p in pts]
        ys = [p[1] for p in pts]
        total += (max(xs) - min(xs)) + (max(ys) - min(ys))
    return total


def build_system(n: int, nets, pads: list[Pos], anchors: Optional[list[Pos]], anchor_w: float, eps: float):
    """The matrix and the two right-hand sides of the clique model, as dicts of dicts."""
    a: list[dict[int, float]] = [dict() for _ in range(n)]
    bx = [0.0] * n
    by = [0.0] * n

    def add_diag(i: int, w: float) -> None:
        a[i][i] = a[i].get(i, 0.0) + w

    for net in nets:
        if len(net) < 2:
            continue
        w = 1.0 / (len(net) - 1)
        for (k1, i1), (k2, i2) in itertools.combinations(net, 2):
            if k1 == "b" and k2 == "b":
                if i1 == i2:
                    continue
                add_diag(i1, w)
                add_diag(i2, w)
                a[i1][i2] = a[i1].get(i2, 0.0) - w
                a[i2][i1] = a[i2].get(i1, 0.0) - w
            elif k1 == "b" or k2 == "b":
                i, j = (i1, i2) if k1 == "b" else (i2, i1)
                add_diag(i, w)
                bx[i] += w * pads[j][0]
                by[i] += w * pads[j][1]
    for i in range(n):
        target, w = (anchors[i], anchor_w) if anchors is not None else (None, 0.0)
        if eps > 0:
            add_diag(i, eps)
        if target is not None:
            add_diag(i, w)
            bx[i] += w * target[0]
            by[i] += w * target[1]
    return a, bx, by


def matvec(a: list[dict[int, float]], v: list[float]) -> list[float]:
    return [sum(w * v[j] for j, w in row.items()) for row in a]


def conjugate_gradient(a, b: list[float], x0: list[float], tol: float = 1e-12, max_iter: int = 1000) -> list[float]:
    x = list(x0)
    r = [bi - ai for bi, ai in zip(b, matvec(a, x))]
    p = list(r)
    rr = sum(v * v for v in r)
    for _ in range(max_iter):
        if rr <= tol * tol:
            break
        ap = matvec(a, p)
        step = rr / sum(pi * api for pi, api in zip(p, ap))
        x = [xi + step * pi for xi, pi in zip(x, p)]
        r = [ri - step * api for ri, api in zip(r, ap)]
        rr_new = sum(v * v for v in r)
        p = [ri + (rr_new / rr) * pi for ri, pi in zip(r, p)]
        rr = rr_new
    return x


def solve_quadratic(n, nets, pads, anchors, anchor_w, center: Pos, x0: list[Pos], eps: float = 1e-3) -> list[Pos]:
    """Minimize the clique-model quadratic wirelength plus anchor terms, in x and in y."""
    a, bx, by = build_system(n, nets, pads, anchors, anchor_w, eps)
    bx = [v + eps * center[0] for v in bx]
    by = [v + eps * center[1] for v in by]
    xs = conjugate_gradient(a, bx, [p[0] for p in x0])
    ys = conjugate_gradient(a, by, [p[1] for p in x0])
    return list(zip(xs, ys))


def spread(blocks: list[int], sites: list[tuple[int, int]], pos: list[Pos], out: dict[int, tuple[int, int]]) -> None:
    """Recursive partitioning: split the sites in two along the longer side, and the blocks in order with them."""
    if not blocks:
        return
    if len(sites) == 1:
        out[blocks[0]] = sites[0]
        return
    xs = {s[0] for s in sites}
    ys = {s[1] for s in sites}
    axis = 0 if max(xs) - min(xs) >= max(ys) - min(ys) else 1
    sites = sorted(sites, key=lambda s: (s[axis], s[1 - axis]))
    cut = len(sites) // 2
    # keep sites with the same coordinate on one side when that leaves both sides nonempty
    lo = [s for s in sites if s[axis] < sites[cut][axis]]
    if lo:
        cut = len(lo)
    c1, c2 = cut, len(sites) - cut
    order = sorted(blocks, key=lambda b: (pos[b][axis], pos[b][1 - axis], b))
    m = len(order)
    k = (2 * m * c1 + c1 + c2) // (2 * (c1 + c2))  # m * c1 / (c1 + c2), rounded half up
    k = max(m - c2, min(c1, k))
    spread(order[:k], sites[:cut], pos, out)
    spread(order[k:], sites[cut:], pos, out)


def heap_place(nx: int, ny: int, col_type: list[str], types: list[str], pads: list[Pos], nets, iters: int = 20, alpha: float = 0.05):
    """Returns (best legal placement, its HPWL, the HPWL of each iteration)."""
    n = len(types)
    sites_of: dict[str, list[tuple[int, int]]] = {}
    for x in range(nx):
        for y in range(ny):
            sites_of.setdefault(col_type[x], []).append((x, y))
    for t in set(types):
        if types.count(t) > len(sites_of.get(t, [])):
            raise ValueError(f"more blocks of type {t} than sites")
    center = ((nx - 1) / 2, (ny - 1) / 2)
    pos = solve_quadratic(n, nets, pads, None, 0.0, center, [center] * n)  # @line L1
    best: Optional[list[Pos]] = None  # @line L2
    best_cost = float("inf")
    history = []
    for k in range(1, iters + 1):  # @line L3
        out: dict[int, tuple[int, int]] = {}
        for t, sites in sites_of.items():  # @line L4
            spread([i for i in range(n) if types[i] == t], sites, pos, out)
        legal = [(float(out[i][0]), float(out[i][1])) for i in range(n)]
        cost = hpwl(nets, legal, pads)  # @line L5
        history.append(cost)
        if cost < best_cost:
            best, best_cost = legal, cost
        weight = alpha * k  # @line L6
        pos = solve_quadratic(n, nets, pads, legal, weight, center, pos)  # @line L7
    assert best is not None
    return best, best_cost, history  # @line L8


def exhaustive_min_hpwl(nx, ny, col_type, types, pads, nets) -> float:
    """Least HPWL over all legal placements: each type permuted over its own sites."""
    sites_of: dict[str, list[tuple[int, int]]] = {}
    for x in range(nx):
        for y in range(ny):
            sites_of.setdefault(col_type[x], []).append((x, y))
    groups = {t: [i for i in range(len(types)) if types[i] == t] for t in set(types)}
    keys = sorted(groups)
    best = float("inf")
    for choice in itertools.product(*(itertools.permutations(sites_of[t], len(groups[t])) for t in keys)):
        loc: list[Pos] = [(0.0, 0.0)] * len(types)
        for t, sites in zip(keys, choice):
            for i, s in zip(groups[t], sites):
                loc[i] = (float(s[0]), float(s[1]))
        best = min(best, hpwl(nets, loc, pads))
    return best
test_heap_fpga_placement.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heap-fpga-placement/. The authors are listed in prov/5EREMJ.jsonl.

import math
import random
from fractions import Fraction

from heap_fpga_placement import (
    build_system,
    conjugate_gradient,
    exhaustive_min_hpwl,
    heap_place,
    hpwl,
    solve_quadratic,
    spread,
)

PAGE_COLS = ["L", "M", "L"]
PAGE_TYPES = ["L", "L", "L", "M"]
PAGE_PADS = [(-1, 0.5), (3, 0.5)]
PAGE_NETS = [
    [("p", 0), ("b", 0)],
    [("b", 0), ("b", 3)],
    [("b", 3), ("b", 1)],
    [("b", 1), ("p", 1)],
    [("b", 2), ("b", 3)],
]


def random_instance(rng, nx, ny, col_type, counts, n_pads, n_nets):
    types = [t for t, c in counts.items() for _ in range(c)]
    n = len(types)
    pads = [(rng.choice([-1, nx]), rng.uniform(0, ny - 1)) for _ in range(n_pads)]
    nets = []
    for _ in range(n_nets):
        terms = [("b", i) for i in rng.sample(range(n), min(rng.randint(2, 4), n))]
        if n_pads and rng.random() < 0.4:
            terms.append(("p", rng.randrange(n_pads)))
        nets.append(terms)
    return types, pads, nets


def gauss_solve(a, b):
    """Exact dense Gaussian elimination over the rationals, the reference for conjugate gradients."""
    n = len(b)
    m = [[Fraction(a[i].get(j, 0.0)) for j in range(n)] + [Fraction(b[i])] for i in range(n)]
    for c in range(n):
        p = next(r for r in range(c, n) if m[r][c] != 0)
        m[c], m[p] = m[p], m[c]
        for r in range(n):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                m[r] = [x - f * y for x, y in zip(m[r], m[c])]
    return [float(m[i][n] / m[i][i]) for i in range(n)]


def test_hpwl_by_hand():
    loc = [(0.0, 0.0), (2.0, 0.0), (0.0, 1.0), (1.0, 0.0)]
    assert hpwl(PAGE_NETS, loc, PAGE_PADS) == 1.5 + 1 + 1 + 1.5 + 2


def test_page_example():
    c = (1.0, 0.5)
    pos = solve_quadratic(4, PAGE_NETS, PAGE_PADS, None, 0.0, c, [c] * 4, eps=0.0)
    want = [(0.0, 0.5), (2.0, 0.5), (1.0, 0.5), (1.0, 0.5)]
    assert all(math.isclose(p[0], w[0], abs_tol=1e-9) and math.isclose(p[1], w[1], abs_tol=1e-9) for p, w in zip(pos, want))
    out = {}
    spread([0, 1, 2], [(0, 0), (0, 1), (2, 0), (2, 1)], pos, out)
    assert out == {0: (0, 0), 2: (0, 1), 1: (2, 0)}
    best, cost, history = heap_place(3, 2, PAGE_COLS, PAGE_TYPES, PAGE_PADS, PAGE_NETS, iters=5)
    assert cost == 7.0 == exhaustive_min_hpwl(3, 2, PAGE_COLS, PAGE_TYPES, PAGE_PADS, PAGE_NETS)
    assert best[3] == (1.0, 0.0)


def test_conjugate_gradient_matches_gaussian_elimination():
    rng = random.Random(3)
    for _ in range(30):
        n = rng.randint(2, 7)
        types, pads, nets = random_instance(rng, 4, 3, ["L"] * 4, {"L": n}, 2, rng.randint(1, 6))
        anchors = [(rng.uniform(0, 3), rng.uniform(0, 2)) for _ in range(n)] if rng.random() < 0.5 else None
        a, bx, by = build_system(n, nets, pads, anchors, 0.3, 1e-3)
        for b in (bx, by):
            got = conjugate_gradient(a, b, [0.0] * n)
            want = gauss_solve(a, b)
            assert all(math.isclose(g, w, rel_tol=1e-7, abs_tol=1e-7) for g, w in zip(got, want))


def test_quadratic_solution_is_a_minimum():
    """No small step of one block lowers the clique-model objective."""
    rng = random.Random(4)
    for _ in range(20):
        n = rng.randint(2, 6)
        types, pads, nets = random_instance(rng, 4, 3, ["L"] * 4, {"L": n}, 2, rng.randint(2, 6))
        anchors = [(rng.uniform(0, 3), rng.uniform(0, 2)) for _ in range(n)]
        c = (1.5, 1.0)
        pos = solve_quadratic(n, nets, pads, anchors, 0.5, c, [c] * n)

        def objective(p):
            total = 0.0
            for net in nets:
                pts = [p[i] if k == "b" else pads[i] for k, i in net]
                w = 1.0 / (len(net) - 1)
                for s in range(len(pts)):
                    for t in range(s + 1, len(pts)):
                        total += w * ((pts[s][0] - pts[t][0]) ** 2 + (pts[s][1] - pts[t][1]) ** 2)
            for i in range(n):
                total += 0.5 * ((p[i][0] - anchors[i][0]) ** 2 + (p[i][1] - anchors[i][1]) ** 2)
                total += 1e-3 * ((p[i][0] - c[0]) ** 2 + (p[i][1] - c[1]) ** 2)
            return total

        base = objective(pos)
        for i in range(n):
            for dx, dy in ((0.01, 0), (-0.01, 0), (0, 0.01), (0, -0.01)):
                moved = list(pos)
                moved[i] = (pos[i][0] + dx, pos[i][1] + dy)
                assert objective(moved) >= base - 1e-9


def test_spread_is_legal_and_ordered():
    rng = random.Random(5)
    for _ in range(300):
        nx, ny = rng.randint(1, 5), rng.randint(1, 5)
        sites = [(x, y) for x in range(nx) for y in range(ny) if rng.random() < 0.8] or [(0, 0)]
        m = rng.randint(1, len(sites))
        pos = [(rng.uniform(-1, nx), rng.uniform(-1, ny)) for _ in range(m)]
        out = {}
        spread(list(range(m)), sites, pos, out)
        assert sorted(out) == list(range(m))
        assert len(set(out.values())) == m and set(out.values()) <= set(sites)


def test_heap_is_legal_and_reports_its_cost():
    rng = random.Random(6)
    cols = ["L", "L", "M", "L", "D", "L"]
    for _ in range(10):
        counts = {"L": rng.randint(5, 16), "M": rng.randint(1, 4), "D": rng.randint(0, 4)}
        types, pads, nets = random_instance(rng, 6, 4, cols, counts, 3, rng.randint(5, 25))
        best, cost, history = heap_place(6, 4, cols, types, pads, nets, iters=8)
        assert len(set(best)) == len(types)
        for i, (x, y) in enumerate(best):
            assert x == int(x) and y == int(y) and 0 <= y < 4 and cols[int(x)] == types[i]
        assert cost == hpwl(nets, best, pads) == min(history)


def test_never_below_exhaustive_optimum():
    rng = random.Random(1)
    equal = 0
    ratios = []
    for _ in range(60):
        cols = ["L", "M", "L"]
        counts = {"L": rng.randint(2, 4), "M": rng.randint(1, 2)}
        types, pads, nets = random_instance(rng, 3, 2, cols, counts, 2, rng.randint(3, 6))
        _, cost, _ = heap_place(3, 2, cols, types, pads, nets, iters=15)
        opt = exhaustive_min_hpwl(3, 2, cols, types, pads, nets)
        assert cost >= opt - 1e-9
        equal += math.isclose(cost, opt)
        ratios.append(cost / opt)
    # measured on these toy instances, not a bound: 20 of 60 optimal, mean ratio about 1.10
    assert equal >= 15 and sum(ratios) / len(ratios) < 1.2


def test_too_many_blocks_of_one_type():
    try:
        heap_place(3, 2, ["L", "M", "L"], ["M", "M", "M"], [], [[("b", 0), ("b", 1)]])
    except ValueError:
        return
    raise AssertionError("expected ValueError")

History

Kim, Lee and Markov (2010) showed with SimPL that a short loop of a quadratic solve, a spreading step and anchors could match far larger placers for standard cells. Gort and Anderson (2012) adapted that loop to heterogeneous FPGAs with LUT-based logic blocks, multiplier or DSP blocks and block RAMs, where each block type has its own columns, and named it HeAP. At the time, the standard academic FPGA placer was the annealing placer of VPR; analytical placers for FPGAs have since become common.

References

  1. Marcel Gort and Jason H. Anderson, Analytical placement for heterogeneous FPGAs, Proceedings of the International Conference on Field Programmable Logic and Applications (FPL), 143 to 150, 2012, the HeAP algorithm, which adapts SimPL to FPGAs with LUT-based logic blocks, multiplier or DSP blocks and block RAMs (general locator)
  2. Myung-Chul Kim, Dong-Jin Lee and Igor L. Markov, SimPL, an effective placement algorithm, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 31(1), 50 to 60, 2012, the lower-bound and upper-bound placements, the spreading by recursive bisection and the pseudo-nets to anchors that HeAP builds on

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_iteration
  • 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
  • at least three sources
  • a scene preset for the example