Algorithm Search⌘K

Algorithmadvanced

AAPack

Also called architecture-aware packing.

Luu, Anderson and Rose's packer for logic blocks with hierarchy, modes and complex local interconnect, which checks each candidate by placing it and routing inside the block.

Time
O(n^2 N R) packing
Space
O(n K + N K (I + N)) total
Where
I = the number of input pins; K = the LUT size; N = the number of slots of a block; R = the time of one route inside a block; n = the number of BLEs
Properties
deterministicnot exactiterative
Origin
Jason Luu, Jason H. Anderson, Jonathan Rose, 2011

AAPack is a greedy algorithm for FPGA packing into logic blocks whose local routing is not a full crossbar, whose parts have modes, or that hold memories and multipliers. Like T-VPack, it fills one block at a time from a seed and adds the most attracted BLE that fits, but it decides that a BLE fits by placing it in a free slot of the block and routing all nets inside the block. The algorithm belongs to the FPGA CAD topic of this sub-area and is the packer of the VTR flow.

In plain words

T-VPack decides that a group of logic pieces fits in a block by counting: enough seats, and few enough input wires. That is right only when every input wire of the block can reach every seat.

Real blocks are not built that way. Each seat can only be reached from some of the input wires, some seats have a flip-flop and some do not, and some parts of a block can be set up in more than one way. Counting is then too optimistic: a group can pass the count and still not be wired up.

AAPack therefore tries for real. To add a piece, it picks a free seat that suits the piece and then searches for a wiring of the whole block. If the wiring works, the piece stays; if not, it tries another seat or another piece.

The problem

Input. A netlist of nn BLEs, each with at most KK input nets, one output net and a flag for its flip-flop. A logic block with NN slots, II input pins, a flag per slot for a flip-flop, and a local routing conn(s,j)\mathrm{conn}(s, j): the set of sources (input pins and slot outputs) that can drive LUT input jj of slot ss.

Output. A partition of the BLEs into blocks, and for each block a slot for each member, a pin for each external net and a LUT input for each input net of each member, such that every LUT input is driven by a source that carries its net. This is a legal configuration; the proof page states it in full.

Goal. Few blocks and, with a timing weight, few critical connections between blocks. AAPack minimizes neither exactly.

In the model of this page, each external net enters the block on one pin, and the LUT inputs of one LUT can be permuted, since a LUT can compute any function of its inputs in any order. The real tool reads a hierarchical description with modes, and its slots are the primitives of that description.

The algorithm

The attraction of a BLE bb to the open block CC is the one of T-VPack: λ Crit(b,C)+(1−λ) ∣Nets(b)∩Nets(C)∣/(K+1)\lambda \, \mathrm{Crit}(b, C) + (1 - \lambda) \, |\mathrm{Nets}(b) \cap \mathrm{Nets}(C)| / (K + 1). LEGAL checks the slot limit, the flip-flops and the count of external nets, and then, in detailed mode, routes the block. In speculative mode, LEGAL is the counting part only.

  1. AAPACK(B, block, λ, speculative)
  2. 1while some BLE is unclustered:
  3. 2seed ← the unclustered BLE of highest criticality (ties: more inputs, then lower index)
  4. 3place seed in the first slot s for which LEGAL({seed ↦ s}) holds
  5. 4while the block has a free slot:
  6. 5order the unclustered BLEs by attraction to the block, highest first
  7. 6for each BLE b in that order, and each free slot s:
  8. 7if LEGAL(block + {b ↦ s}) then place b at s and go back to line L4
  9. 8no BLE fits in any free slot: leave the loop
  10. 9route the block
  11. 10if the route fails (speculative mode only): redo lines L3 to L8 from the same seed in detailed mode
  12. 11output the block with its slots and its route

AAPack routes inside the block with a negotiated congestion router on a graph of the block's pins, multiplexers and LUT inputs, which is a routing resource graph of the block. That router is a heuristic: it can fail on a block that could be routed. The implementation instead routes exactly, which suits the tiny blocks of the tests. It tries every injective map from the external nets to the pins by backtracking, and for each map it gives the input nets of each member distinct LUT inputs by a bipartite matching, one per slot. The members of different slots never compete for a LUT input, so the matchings are independent.

Example

The block has N=2N = 2 slots, K=2K = 2, I=3I = 3 pins, and a flip-flop only in slot 0. Each LUT input has a multiplexer with two sources:

LUT input sources
slot 0, input 0 pin 0, output of slot 1
slot 0, input 1 pin 1, output of slot 0
slot 1, input 0 pin 2, output of slot 0
slot 1, input 1 pin 1, output of slot 1

Counting is not enough. Two BLEs both read xx and yy. Together they have 2 external nets, fewer than 3, and 2 BLEs, so the counting checks pass. But slot 0 can read external nets only from pins 0 and 1, and slot 1 only from pins 2 and 1. So xx and yy would have to be on pins 0 and 1 for slot 0 and on pins 2 and 1 for slot 1, which needs both nets on pin 1. No configuration exists. AAPack in detailed mode puts the two BLEs in two blocks. In speculative mode it first puts both in one block by counting, then line L9 fails, and line L10 repacks the block, again with one BLE.

The slot choice matters. BLE aa reads x,yx, y; BLE bb reads w,xw, x and is registered. The seed is aa, since both have two inputs and aa comes first, and line L3 puts it in slot 0, which routes. Then bb needs the flip-flop of slot 0, which is taken, so the block closes with aa alone and bb gets a second block. Yet one block suffices: bb in slot 0 and aa in slot 1, with ww on pin 0, xx on pin 1 and yy on pin 2. Slot 0 reads ww on input 0 and xx on input 1; slot 1 reads yy on input 0 and xx on input 1, both from pin 1. AAPack never moves a member that it has placed, so it does not find this.

Correctness

The full proof shows the following, assuming that every BLE fits alone in some slot of an empty block.

  • The route is exact. With the slots fixed, the route of the implementation finds a legal configuration if and only if one exists. The proof combines the search over all pin maps with Kuhn's algorithm, which finds a covering matching whenever one exists by Berge's lemma.
  • Legality. Every block that AAPack outputs comes with a configuration, in both modes, and so has at most NN BLEs and at most II external nets. In speculative mode this rests on the final route of line L9 and the repack of line L10.
  • Partition and termination. Every BLE is in exactly one block, and the loops end.
  • Maximality for fixed slots. In detailed mode, a closed block admits no remaining BLE in any free slot, as long as its members keep their slots.

With PathFinder in place of the exact route, a block that AAPack outputs is still legal, because PathFinder's success is a real routing; only its failures can be wrong, and they cost blocks, not legality. Nothing here bounds the number of blocks, and the second example shows a loss.

Proof: The exact intra-block route succeeds if and only if a legal configuration exists, so every block that AAPack outputs is legal, and the blocks partition the netlistfull

We use the block model of the page. The block has slots 0,…,N−10, \ldots, N - 1; slot ss has a LUT with inputs 0,…,K−10, \ldots, K - 1 and a flip-flop if ff(s)\mathrm{ff}(s) holds. It has input pins 0,…,I−10, \ldots, I - 1. LUT input jj of slot ss can be driven by the sources in conn(s,j)\mathrm{conn}(s, j), where a source is an input pin or the output of a slot. A set CC of BLEs and an injective map σ\sigma from CC to the slots are given. Let ext(C)\mathrm{ext}(C) be the set of nets that a member reads and no member drives.

A configuration for (C,σ)(C, \sigma) is a pair (π,μ)(\pi, \mu) where

  1. π\pi maps ext(C)\mathrm{ext}(C) injectively to the input pins;
  2. for each b∈Cb \in C, μb\mu_b maps the distinct input nets of bb injectively to the LUT inputs of slot σ(b)\sigma(b);
  3. for each b∈Cb \in C and each input net xx of bb, the source of xx is in conn(σ(b),μb(x))\mathrm{conn}(\sigma(b), \mu_b(x)), where the source of xx is the output of slot σ(d)\sigma(d) if a member dd drives xx, and the pin π(x)\pi(x) otherwise;
  4. every registered member is in a slot with a flip-flop.

(C,σ)(C, \sigma) is legal if a configuration exists. This is the model's statement that the block, with its members in these slots, can be routed: each external net enters on one pin, each LUT input carries one net, and each net reaches every LUT input that needs it through a switch that exists.

Lemma 1 (one slot). Fix π\pi, and so the source of every net. For a member bb, a map μb\mu_b that meets conditions 2 and 3 exists if and only if the bipartite graph HbH_b, with the input nets of bb on one side, the LUT inputs of σ(b)\sigma(b) on the other, and an edge (x,j)(x, j) when the source of xx is in conn(σ(b),j)\mathrm{conn}(\sigma(b), j), has a matching that covers every net. The procedure of the implementation finds such a matching whenever one exists.

Proof. A map μb\mu_b with conditions 2 and 3 is exactly an injective choice of an edge of HbH_b at each net, which is a matching that covers the nets. The procedure is Kuhn's algorithm: it tries an augmenting path from each net in turn. Kuhn's algorithm returns a maximum matching of a bipartite graph, by Berge's lemma: a matching is maximum if and only if no augmenting path exists. If some net finds no augmenting path, the maximum matching leaves a net uncovered, so no covering matching exists, and returning failure is right. Otherwise the result covers every net. □\square

Lemma 2 (the route is exact). For fixed (C,σ)(C, \sigma) that meet condition 4, ROUTE-CLUSTER returns a configuration if and only if (C,σ)(C, \sigma) is legal, and what it returns is a configuration.

Proof. Soundness. The search gives each net of ext(C)\mathrm{ext}(C) a pin that no earlier net holds, so π\pi is injective (condition 1). Each μb\mu_b comes from a covering matching of HbH_b, which gives conditions 2 and 3 by Lemma 1. Condition 4 is assumed.

Completeness. Let (π∗,μ∗)(\pi^*, \mu^*) be a configuration. The search tries every injective map from ext(C)\mathrm{ext}(C) to the pins, in a fixed order, so it reaches π∗\pi^* unless it returns earlier with another configuration. With π=π∗\pi = \pi^*, the maps μb∗\mu^*_b are covering matchings of the graphs HbH_b. The graphs of different members use the LUT inputs of different slots, so the members do not compete for LUT inputs, and the choices for different members are independent. By Lemma 1 the procedure finds a covering matching for every member, so the search returns a configuration. □\square

Theorem 3 (legality and partition). Assume that every BLE is legal alone in some slot of an empty block. Then AAPack stops, every block that it outputs comes with a configuration, every block has at most NN BLEs and at most II external nets, and every BLE is in exactly one block. This holds in both modes.

Proof. In detailed mode, the predicate LEGAL is the counting check of conditions 4, the slot limit and ∣ext∣≤I|\mathrm{ext}| \le I, followed by ROUTE-CLUSTER. By Lemma 2 it is true exactly for legal (C,σ)(C, \sigma). Line L3 places the seed in a slot where LEGAL holds; one exists by the assumption. Line L7 adds a BLE only where LEGAL holds for the new block. So, at every step, the current block with its slots is legal. When the loop ends, line L9 routes that block, and by Lemma 2 the route succeeds.

In speculative mode, line L7 tests only the counting checks. If line L9 then finds a route, the block is legal by Lemma 2. If not, line L10 grows the block again from the same seed in detailed mode, which ends with a legal block as above, and its route succeeds. So every output block has a configuration, and a configuration uses distinct slots and distinct pins, so the block has at most NN BLEs and at most II external nets.

Each pass of the outer loop removes the BLEs of its block from the unclustered set, at least the seed, so there are at most nn passes. Each pass of the inner loop places a BLE in a free slot or ends the block, so it ends after at most N−1N - 1 additions. The BLEs of a block are taken from the unclustered set and then removed from it, so the blocks are disjoint, and the outer loop ends only when every BLE is in a block. □\square

Theorem 4 (maximality for fixed slots). In detailed mode, when line L8 ends a block (C,σ)(C, \sigma), then for every BLE bb that is still unclustered and every free slot ss, (C∪{b},σ∪{b↦s})(C \cup \{b\}, \sigma \cup \{b \mapsto s\}) is not legal.

Proof. Line L8 is reached only after line L7 has tested every pair of an unclustered BLE and a free slot and found LEGAL false for each. By Lemma 2, LEGAL is false exactly when the block is not legal. ■\blacksquare

Theorem 4 keeps the slots of the members fixed. A BLE may still fit if the members moved to other slots; the page gives a two-BLE netlist where this happens, and AAPack then uses two blocks where one suffices. So nothing here bounds the number of blocks.

Complexity

Let RR be the time of one route inside a block. Each addition at line L7 tries at most nn BLEs in at most NN slots, so it makes O(nN)O(n N) calls of LEGAL, and so does each closing at line L8. There are at most nn additions and nn blocks, so packing makes O(n2N)O(n^2 N) calls and takes O(n2NR)O(n^2 N R) time. Speculative mode makes at most one route per block in the good case and repeats a block in detailed mode only when its final route fails.

The exact route of the implementation takes O(I!/(I−e)!⋅NK3)O(I! / (I - e)! \cdot N K^3) time for ee external nets, which is exponential and fine only for the small blocks of the tests. A PathFinder route takes time polynomial in the size of the block's graph per iteration, with a cap on the iterations. The space holds the netlist and the local routing of one block.

Properties

  • Legal by construction. A block is accepted only with a route, so placement and routing never meet a block that cannot be wired inside.
  • Not optimal. The second example uses 2 blocks where 1 suffices. On seeded random tests with blocks of at most 3 slots, AAPack used more blocks than the exhaustive optimum on some instances; these are toy instances, not benchmark results.
  • Members stay put. A placed member is never moved to another slot, which keeps the method simple and greedy.
  • Architecture-independent. The same code packs any block that the description language can express, since all of its structure is in the routing graph and the slot types.

Variants and improvements

  • Speculative packing. Luu, Rose and Anderson (2014) count pins while they add BLEs and route a block only once, when it is full; if that route fails, they repack the block with a route after each addition. When most blocks route at the first try, this saves most of the routes.
  • Interconnect-adaptive packing. The same 2014 work aims to adapt the packer to how sparse the interconnect of the block is.
  • Timing. With λ>0\lambda > 0 and criticalities from a static timing analysis, the packer keeps critical connections inside blocks, as in T-VPack.
  • Moving members. A packer can try to move placed members when a candidate does not fit, at the cost of more routes. The second example shows what this can gain.

When to use it

Use AAPack, or the VTR packer that grew from it, when the logic block has sparse local routing, modes, carry chains, memories or multipliers, so that counting cannot decide legality. For a homogeneous block with a full crossbar, the counting checks are already exact, and T-VPack gives the same blocks with no routes. When packing time matters, turn on speculative mode.

Pitfalls

  • Trusting the count. Passing ∣C∣≤N|C| \le N and ∣ext(C)∣≤I|\mathrm{ext}(C)| \le I does not mean a block can be routed when the crossbar is sparse; the first example fails with two nets on three pins.
  • Forgetting slot types. A registered BLE needs a slot with a flip-flop. A packer that places unregistered BLEs into those slots first can run out of them, as in the second example.
  • A heuristic failure is not a proof. When PathFinder fails inside a block, the block may still be routable. Treat the failure as a cost, not as a fact about the block.
  • Routing one net at a time. Nets inside a block compete for pins and multiplexer inputs, so they must be routed together, as a matching or with negotiation, not one by one.

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.

aapack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aapack/. The authors are listed in prov/11GQMP.jsonl.

"""AAPack: greedy packing with a placement and an intra-cluster route for each candidate.

The logic block has N slots. Slot s holds one LUT with K inputs and, if
has_ff[s], a flip-flop. The block has I input pins. The local routing is a
sparse crossbar: LUT input j of slot s can be driven by the sources in
conn[s][j], where ("pin", p) is input pin p and ("fb", t) is the output of
slot t. LUT inputs of one LUT can be permuted, so a net may use any LUT input
of its slot whose source carries it.

AAPack routes inside the block with PathFinder. This file routes inside the
block with an exact search (pin assignment by backtracking, then one
bipartite matching per slot), so a failed route is a real failure.
"""

from dataclasses import dataclass, field
from fractions import Fraction
from typing import Optional

Source = tuple[str, int]


@dataclass(frozen=True)
class Ble:
    inputs: tuple[str, ...]
    output: str
    registered: bool = False


@dataclass
class Block:
    has_ff: list[bool]
    i_pins: int
    k: int
    conn: list[list[frozenset[Source]]]  # conn[s][j]

    @property
    def n_slots(self) -> int:
        return len(self.has_ff)


@dataclass
class Config:
    slot_of: dict[int, int]  # BLE -> slot
    pin_of: dict[str, int] = field(default_factory=dict)  # external net -> input pin
    lut_in: dict[tuple[int, str], int] = field(default_factory=dict)  # (BLE, net) -> LUT input


def external_inputs(bles: list[Ble], members) -> list[str]:
    driven = {bles[i].output for i in members}
    return sorted({n for i in members for n in bles[i].inputs if n not in driven})


def _match_slot(block: Block, s: int, nets: list[str], source_of: dict[str, Source]) -> Optional[dict[str, int]]:
    """Kuhn's augmenting paths: give each net a distinct LUT input of slot s whose source carries it."""
    owner: dict[int, str] = {}

    def augment(x: str, seen: set[int]) -> bool:
        for j in range(block.k):
            if source_of[x] in block.conn[s][j] and j not in seen:
                seen.add(j)
                if j not in owner or augment(owner[j], seen):
                    owner[j] = x
                    return True
        return False

    for x in nets:
        if not augment(x, set()):
            return None
    return {x: j for j, x in owner.items()}


def route_cluster(bles: list[Ble], block: Block, slot_of: dict[int, int]) -> Optional[Config]:
    """An exact intra-cluster route for fixed slots, or None if none exists."""
    members = list(slot_of)
    driver_slot = {bles[i].output: slot_of[i] for i in members}
    ext = external_inputs(bles, members)
    if len(ext) > block.i_pins:
        return None
    pin_of: dict[str, int] = {}

    def finish() -> Optional[Config]:
        source_of: dict[str, Source] = {x: ("pin", p) for x, p in pin_of.items()}
        source_of.update({x: ("fb", t) for x, t in driver_slot.items()})
        cfg = Config(dict(slot_of), dict(pin_of))
        for i in members:
            m = _match_slot(block, slot_of[i], sorted(set(bles[i].inputs)), source_of)
            if m is None:
                return None
            cfg.lut_in.update({(i, x): j for x, j in m.items()})
        return cfg

    def assign(t: int) -> Optional[Config]:
        if t == len(ext):
            return finish()
        for p in range(block.i_pins):
            if p not in pin_of.values():
                pin_of[ext[t]] = p
                cfg = assign(t + 1)
                if cfg is not None:
                    return cfg
                del pin_of[ext[t]]
        return None

    return assign(0)


def fits_by_count(bles: list[Ble], block: Block, slot_of: dict[int, int]) -> bool:
    """The counting checks of speculative packing: slots, flip-flops, LUT inputs and pins."""
    return (
        len(set(slot_of.values())) == len(slot_of)
        and all(block.has_ff[s] or not bles[i].registered for i, s in slot_of.items())
        and all(len(set(bles[i].inputs)) <= block.k for i in slot_of)
        and len(external_inputs(bles, slot_of)) <= block.i_pins
    )


def aapack(
    bles: list[Ble],
    block: Block,
    lam: Fraction = Fraction(0),
    crit: Optional[dict[tuple[int, int], Fraction]] = None,
    speculative: bool = False,
) -> list[Config]:
    """Pack the BLEs into blocks. Returns one Config per block, with the route inside it."""
    crit = crit or {}
    g = block.k + 1
    nets_of = [set(b.inputs) | {b.output} for b in bles]
    ble_crit = [Fraction(0)] * len(bles)
    pair_crit: list[dict[int, Fraction]] = [{} for _ in bles]
    for (u, v), c in crit.items():
        ble_crit[u] = max(ble_crit[u], c)
        ble_crit[v] = max(ble_crit[v], c)
        pair_crit[u][v] = max(pair_crit[u].get(v, Fraction(0)), c)
        pair_crit[v][u] = max(pair_crit[v].get(u, Fraction(0)), c)

    def legal(slot_of: dict[int, int], counting_only: bool) -> bool:
        if not fits_by_count(bles, block, slot_of):
            return False
        return counting_only or route_cluster(bles, block, slot_of) is not None

    def grow(seed: int, unclustered: set[int], counting_only: bool) -> dict[int, int]:
        slot_of: dict[int, int] = {}
        for s in range(block.n_slots):  # @line L3
            if legal({seed: s}, counting_only):
                slot_of = {seed: s}
                break
        if not slot_of:
            raise ValueError(f"BLE {seed} fits in no slot of an empty block")
        while len(slot_of) < block.n_slots:  # @line L4
            cluster_nets = set().union(*(nets_of[i] for i in slot_of))

            def attraction(b: int) -> Fraction:
                c = max((pair_crit[b].get(m, Fraction(0)) for m in slot_of), default=Fraction(0))
                return lam * c + (1 - lam) * Fraction(len(nets_of[b] & cluster_nets), g)

            order = sorted(unclustered - set(slot_of), key=lambda b: (-attraction(b), -len(bles[b].inputs), b))  # @line L5
            added = False
            for b in order:  # @line L6
                for s in range(block.n_slots):
                    if s not in slot_of.values() and legal({**slot_of, b: s}, counting_only):  # @line L7
                        slot_of[b] = s
                        added = True
                        break
                if added:
                    break
            if not added:  # @line L8
                break
        return slot_of

    unclustered = set(range(len(bles)))
    out = []
    while unclustered:  # @line L1
        seed = max(unclustered, key=lambda i: (ble_crit[i], len(bles[i].inputs), -i))  # @line L2
        slot_of = grow(seed, unclustered, speculative)
        cfg = route_cluster(bles, block, slot_of)  # @line L9
        if cfg is None:  # @line L10
            slot_of = grow(seed, unclustered, False)
            cfg = route_cluster(bles, block, slot_of)
        assert cfg is not None
        out.append(cfg)  # @line L11
        unclustered -= set(slot_of)
    return out


def check_config(bles: list[Ble], block: Block, cfg: Config) -> bool:
    """Check a configuration directly against the block, with no search."""
    slot_of = cfg.slot_of
    members = set(slot_of)
    if len(set(slot_of.values())) != len(slot_of) or not all(0 <= s < block.n_slots for s in slot_of.values()):
        return False
    if any(bles[i].registered and not block.has_ff[s] for i, s in slot_of.items()):
        return False
    driver_slot = {bles[i].output: slot_of[i] for i in members}
    ext = set(external_inputs(bles, members))
    if set(cfg.pin_of) != ext or len(set(cfg.pin_of.values())) != len(ext):
        return False
    if not all(0 <= p < block.i_pins for p in cfg.pin_of.values()):
        return False
    for i in members:
        used = [cfg.lut_in.get((i, x)) for x in set(bles[i].inputs)]
        if None in used or len(set(used)) != len(used):
            return False
        for x in set(bles[i].inputs):
            j = cfg.lut_in[(i, x)]
            src = ("fb", driver_slot[x]) if x in driver_slot else ("pin", cfg.pin_of[x])
            if not 0 <= j < block.k or src not in block.conn[slot_of[i]][j]:
                return False
    return True
test_aapack.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aapack/. The authors are listed in prov/11GQMP.jsonl.

import itertools
import random
from fractions import Fraction

from aapack import Ble, Block, aapack, check_config, external_inputs, fits_by_count, route_cluster


def pins(*ps):
    return [("pin", p) for p in ps]


def fbs(*ts):
    return [("fb", t) for t in ts]


def sparse_block() -> Block:
    """The block of the page: N = 2, K = 2, I = 3, a flip-flop in slot 0 only, two sources per LUT input."""
    return Block(
        [True, False],
        3,
        2,
        [
            [frozenset(pins(0) + fbs(1)), frozenset(pins(1) + fbs(0))],
            [frozenset(pins(2) + fbs(0)), frozenset(pins(1) + fbs(1))],
        ],
    )


def full_block(n: int, k: int, i: int) -> Block:
    every = frozenset(pins(*range(i)) + fbs(*range(n)))
    return Block([True] * n, i, k, [[every] * k for _ in range(n)])


def random_block(rng: random.Random) -> Block:
    n, k = rng.randint(1, 3), rng.randint(1, 2)
    i = rng.randint(k, k + 2)
    sources = pins(*range(i)) + fbs(*range(n))
    conn = [[frozenset(rng.sample(sources, rng.randint(1, len(sources)))) for _ in range(k)] for _ in range(n)]
    return Block([rng.random() < 0.7 for _ in range(n)], i, k, conn)


def random_netlist(rng: random.Random, n: int, k: int) -> list[Ble]:
    bles = []
    for v in range(n):
        pool = ["x", "y", "z", "w"][: rng.randint(1, 4)] + [f"o{j}" for j in range(v)]
        size = rng.randint(1, min(k, len(pool)))
        bles.append(Ble(tuple(sorted(rng.sample(pool, size))), f"o{v}", rng.random() < 0.25))
    return bles


def brute_routable(bles: list[Ble], block: Block, slot_of: dict[int, int]) -> bool:
    """Try every pin assignment and every order of LUT inputs: no matching, no pruning."""
    members = list(slot_of)
    if len(set(slot_of.values())) != len(members):
        return False
    if any(bles[i].registered and not block.has_ff[s] for i, s in slot_of.items()):
        return False
    driver = {bles[i].output: slot_of[i] for i in members}
    ext = external_inputs(bles, members)
    for perm in itertools.permutations(range(block.i_pins), len(ext)):
        pin_of = dict(zip(ext, perm))
        ok = True
        for i in members:
            nets = sorted(set(bles[i].inputs))
            src = [("fb", driver[x]) if x in driver else ("pin", pin_of[x]) for x in nets]
            if not any(
                all(src[t] in block.conn[slot_of[i]][js[t]] for t in range(len(nets)))
                for js in itertools.permutations(range(block.k), len(nets))
            ):
                ok = False
                break
        if ok:
            return True
    return False


def brute_legal(bles: list[Ble], block: Block, members: list[int]) -> bool:
    return any(
        brute_routable(bles, block, dict(zip(members, perm)))
        for perm in itertools.permutations(range(block.n_slots), len(members))
    )


def brute_min_blocks(bles: list[Ble], block: Block) -> int:
    n = len(bles)
    legal = [False] * (1 << n)
    for mask in range(1, 1 << n):
        members = [i for i in range(n) if mask >> i & 1]
        legal[mask] = len(members) <= block.n_slots and brute_legal(bles, block, members)
    best = [0] + [n + 1] * ((1 << n) - 1)
    for mask in range(1, 1 << n):
        low = mask & -mask
        sub = mask
        while sub:
            if sub & low and legal[sub]:
                best[mask] = min(best[mask], best[mask ^ sub] + 1)
            sub = (sub - 1) & mask
    return best[-1]


def assert_partition(bles, result):
    seen = sorted(i for cfg in result for i in cfg.slot_of)
    assert seen == list(range(len(bles)))


def test_counts_fit_but_route_fails():
    block = sparse_block()
    bles = [Ble(("x", "y"), "o0"), Ble(("x", "y"), "o1")]
    assert len(external_inputs(bles, [0, 1])) == 2
    assert fits_by_count(bles, block, {0: 0, 1: 1})
    assert route_cluster(bles, block, {0: 0, 1: 1}) is None
    assert route_cluster(bles, block, {0: 1, 1: 0}) is None
    assert not brute_legal(bles, block, [0, 1])
    result = aapack(bles, block)
    assert len(result) == 2
    # Speculative packing puts both in one block, the final route fails, and the block is redone.
    assert len(aapack(bles, block, speculative=True)) == 2


def test_slot_choice_example():
    block = sparse_block()
    bles = [Ble(("x", "y"), "o0"), Ble(("w", "x"), "o1", True)]
    result = aapack(bles, block)
    assert [cfg.slot_of for cfg in result] == [{0: 0}, {1: 0}]
    assert brute_min_blocks(bles, block) == 1
    cfg = route_cluster(bles, block, {0: 1, 1: 0})
    assert cfg is not None and check_config(bles, block, cfg)


def test_route_cluster_matches_brute_force():
    rng = random.Random(5)
    agree = [0, 0]
    for _ in range(400):
        block = random_block(rng)
        bles = random_netlist(rng, rng.randint(1, 3), block.k)
        m = rng.randint(1, min(len(bles), block.n_slots))
        members = rng.sample(range(len(bles)), m)
        slots = rng.sample(range(block.n_slots), m)
        slot_of = dict(zip(members, slots))
        cfg = route_cluster(bles, block, slot_of) if fits_by_count(bles, block, slot_of) else None
        want = brute_routable(bles, block, slot_of) and all(len(set(bles[i].inputs)) <= block.k for i in members)
        assert (cfg is not None) == want
        if cfg is not None:
            assert check_config(bles, block, cfg)
        agree[want] += 1
    assert min(agree) > 20  # both outcomes occur


def test_full_crossbar_route_iff_counts():
    rng = random.Random(8)
    for _ in range(300):
        n, k = rng.randint(1, 3), rng.randint(1, 3)
        i = rng.randint(k, k + 2)
        block = full_block(n, k, i)
        bles = [b for b in random_netlist(rng, rng.randint(1, n), k)]
        slot_of = {v: v for v in range(len(bles))}
        routed = route_cluster(bles, block, slot_of) is not None
        assert routed == (len(external_inputs(bles, slot_of)) <= i)


def test_legal_and_never_below_optimum():
    rng = random.Random(1)
    worse = 0
    for t in range(500):
        block = sparse_block() if t % 2 == 0 else random_block(rng)
        bles = random_netlist(rng, rng.randint(1, 5), block.k)
        if not all(brute_legal(bles, block, [v]) for v in range(len(bles))):
            continue  # some BLE fits in no slot of an empty block
        best = brute_min_blocks(bles, block)
        for speculative in (False, True):
            result = aapack(bles, block, speculative=speculative)
            assert_partition(bles, result)
            assert all(check_config(bles, block, cfg) for cfg in result)
            assert len(result) >= best
            worse += len(result) > best
    assert worse > 0


def test_closed_blocks_are_maximal():
    rng = random.Random(3)
    for _ in range(150):
        block = random_block(rng)
        bles = random_netlist(rng, rng.randint(1, 5), block.k)
        try:
            result = aapack(bles, block)
        except ValueError:
            continue
        later = set(range(len(bles)))
        for cfg in result:
            later -= set(cfg.slot_of)
            free = [s for s in range(block.n_slots) if s not in cfg.slot_of.values()]
            for b in later:
                for s in free:
                    assert not brute_routable(bles, block, {**cfg.slot_of, b: s})


def test_timing_weight_and_full_crossbar_speculation():
    rng = random.Random(12)
    for _ in range(100):
        block = full_block(3, 2, 4)
        bles = random_netlist(rng, rng.randint(1, 6), 2)
        crit = {(u, v): Fraction(rng.randint(1, 4), 4) for v, b in enumerate(bles) for u in range(v) if f"o{u}" in b.inputs}
        a = aapack(bles, block, lam=Fraction(3, 4), crit=crit)
        b = aapack(bles, block, lam=Fraction(3, 4), crit=crit, speculative=True)
        assert [c.slot_of for c in a] == [c.slot_of for c in b]
        assert all(check_config(bles, block, cfg) for cfg in a)

History

Luu, Anderson and Rose (2011) introduced AAPack with an architecture description language for logic blocks with hierarchy, modes and complex interconnect. They kept the greedy growth of T-VPack and checked each candidate by placing it in a primitive of the block and routing the block with a PathFinder-based router, which made the packer work for any block that the language describes. Luu, Rose and Anderson (2014) added speculative packing, which routes a block once instead of after every addition. The packer is part of VPR in the VTR flow.

References

  1. Jason Luu, Jason H. Anderson and Jonathan Rose, Architecture description and packing for logic blocks with hierarchy, modes and complex interconnect, Proceedings of the ACM/SIGDA International Symposium on Field Programmable Gate Arrays (FPGA '11), 227 to 236, 2011, the architecture description language and the packing algorithm (seed choice, candidate choice by attraction, placement of a candidate in a primitive and the intra-block route with a PathFinder-based router)
  2. Jason Luu, Jonathan Rose and Jason Anderson, Towards interconnect-adaptive packing for FPGAs, Proceedings of the ACM/SIGDA International Symposium on Field-Programmable Gate Arrays (FPGA '14), 2014, speculative packing, with a single route at the end of a block and a detailed repack on failure (general locator)
  3. Jason Luu and others, VTR 7.0, next generation architecture and CAD system for FPGAs, ACM Transactions on Reconfigurable Technology and Systems 7(2), 2014, the packer of the VTR flow (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.packing
  • 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