Algorithm Search⌘K

Algorithmcore

T-VPack

Also called VPack, timing-driven packing.

Marquardt, Betz and Rose's greedy packer that grows each cluster by adding the block with the most shared nets and most timing criticality until the cluster is full.

Time
O(n K) criticalityO(n^2 N K) packing
Space
O(n K) total
Where
K = the LUT size; N = the cluster size; n = the number of BLEs
Properties
deterministicnot exactiterative
Origin
Alexander Marquardt, Vaughn Betz, Jonathan Rose, 1999

T-VPack is a greedy algorithm for FPGA packing: it puts the basic logic elements (BLEs) of a mapped netlist into logic clusters of at most NN BLEs and II external inputs. It fills one cluster at a time, starting from the most timing-critical BLE that is left and adding, at each step, the BLE that fits and has the highest attraction, a mix of its criticality to the cluster and the number of nets it shares with it. The algorithm belongs to the FPGA CAD topic of this sub-area and is the packer of the VPR flow of Marquardt, Betz and Rose.

In plain words

After LUT mapping, a design is a list of small logic pieces, each a lookup table with an optional flip-flop. The chip groups these pieces into clusters, and a wire inside a cluster is much faster and cheaper than a wire between clusters.

T-VPack fills the clusters one by one. It starts a new cluster with the piece that sits on the slowest path of the design. Then it keeps adding the piece that is most attracted to the cluster: a piece that talks to the cluster over a slow path, or that shares many signals with it. It adds a piece only if the cluster still has room and enough input pins.

When the cluster is full, or no remaining piece fits, it closes the cluster and starts the next one.

The problem

Input. A list of nn BLEs. Each BLE has at most KK input nets, one output net, and a flag that says whether its flip-flop is used. Cluster parameters NN and II with K≤IK \le I, and a weight λ∈[0,1]\lambda \in [0, 1].

Output. A partition of the BLEs into clusters CC, each legal: ∣C∣≤N|C| \le N and ∣ext(C)∣≤I|\mathrm{ext}(C)| \le I, where ext(C)\mathrm{ext}(C) is the set of nets that a member reads and no member drives. This is the legality rule of a cluster with a full crossbar.

Goal. Few clusters, and few critical connections between clusters. T-VPack does not minimize either one exactly.

The algorithm

Before line L1, a static timing analysis with unit delays gives each connection (u,v)(u, v) from a BLE uu to a reader vv a criticality crit(u,v)=1−slack(u,v)/D\mathrm{crit}(u, v) = 1 - \mathrm{slack}(u, v) / D, where DD is the delay of the longest timing path. Each LUT has delay 1, connections have delay 0, and a flip-flop starts a new path. A BLE's criticality is the largest criticality of its connections. For a BLE bb and a cluster CC:

  • Crit(b,C)\mathrm{Crit}(b, C) is the largest criticality of a connection between bb and a member of CC, or 0;
  • Nets(b)\mathrm{Nets}(b) is the set of nets that bb reads or drives, and Nets(C)\mathrm{Nets}(C) the union over its members;
  • attraction(b,C)=λ Crit(b,C)+(1−λ) ∣Nets(b)∩Nets(C)∣/G\mathrm{attraction}(b, C) = \lambda \, \mathrm{Crit}(b, C) + (1 - \lambda) \, |\mathrm{Nets}(b) \cap \mathrm{Nets}(C)| / G, with G=K+1G = K + 1, the most nets that one BLE can touch.
  1. T-VPACK(B, N, I, K, λ)
  2. 1while some BLE is unclustered:
  3. 2seed ← the unclustered BLE of highest criticality (ties: more inputs, then lower index); C ← {seed}
  4. 3while |C| < N:
  5. 4for each unclustered BLE b:
  6. 5if |ext(C ∪ {b})| > I then skip b
  7. 6compute attraction(b, C)
  8. 7if every b was skipped then leave this loop
  9. 8add the kept b of highest attraction to C (ties: more inputs, then lower index)
  10. 9output C

A BLE that shares no net with the cluster has attraction 0, so line L8 then adds the BLE with the most inputs that fits. The paper fills a cluster in the same way when no connected BLE fits.

The implementation also has the step before packing that forms BLEs: a LUT and the flip-flop that its output feeds are merged into one BLE when the flip-flop is the only reader of that output. A flip-flop that cannot be merged gets a BLE of its own, whose LUT passes the data input through.

Example

Take K=2K = 2, N=2N = 2, I=3I = 3, λ=3/4\lambda = 3/4, and four BLEs: aa reads x,yx, y and drives AA; bb reads A,zA, z and drives BB; cc reads w,xw, x and drives CC; dd reads C,yC, y and drives DD. None is registered. The longest timing paths are a→ba \to b and c→dc \to d, with D=2D = 2, so both connections have criticality 1, and every BLE has criticality 1.

  1. All four BLEs tie on criticality and on inputs, so the seed is aa, and C={a}C = \{a\} with Nets(C)={x,y,A}\mathrm{Nets}(C) = \{x, y, A\}.
  2. Line L5: ext({a,b})={x,y,z}\mathrm{ext}(\{a, b\}) = \{x, y, z\}, ext({a,c})={w,x,y}\mathrm{ext}(\{a, c\}) = \{w, x, y\}, ext({a,d})={x,y,C}\mathrm{ext}(\{a, d\}) = \{x, y, C\}, so all three fit.
  3. Line L6: bb gets 34⋅1+14⋅13=56\tfrac34 \cdot 1 + \tfrac14 \cdot \tfrac13 = \tfrac56, since the connection a→ba \to b has criticality 1 and bb shares the net AA. cc shares only xx and gets 14⋅13=112\tfrac14 \cdot \tfrac13 = \tfrac1{12}, and dd shares only yy and gets 112\tfrac1{12}.
  4. Line L8 adds bb. The cluster {a,b}\{a, b\} is full.
  5. The next seed is cc. ext({c,d})={w,x,y}\mathrm{ext}(\{c, d\}) = \{w, x, y\} fits, and dd joins.

The result is {a,b}\{a, b\} and {c,d}\{c, d\}: two clusters, which is the least possible for four BLEs with N=2N = 2, and both critical connections are inside a cluster. The other pairing that keeps the critical connections apart, {a,c}\{a, c\} and {b,d}\{b, d\}, is not even legal, since ext({b,d})={A,z,C,y}\mathrm{ext}(\{b, d\}) = \{A, z, C, y\} has four nets.

Correctness

The full proof shows the following.

  • Legality. Each cluster that T-VPack outputs has at most NN BLEs and at most II external input nets, and every BLE is in exactly one cluster. The seed is legal because a BLE has at most K≤IK \le I inputs, and line L5 and line L3 keep both limits at each addition.
  • Termination. Each outer pass clusters at least its seed, and each inner pass adds a BLE or ends the cluster.
  • Maximality. A closed cluster is full, or no BLE that was unclustered at that moment fits into it.
  • Criticality. The unit-delay analysis returns crit(u,v)=ℓ(u,v)/D\mathrm{crit}(u, v) = \ell(u, v) / D, where ℓ(u,v)\ell(u, v) is the delay of the longest timing path through the connection.

What is not proved is the number of clusters. T-VPack is a heuristic, and it can use more clusters than needed.

Proof: T-VPack returns legal clusters that partition the netlist, each closed cluster is full or admits no further BLE, and the unit-delay criticalities are exactfull

We use the notation of the page. The netlist is a list of nn BLEs. BLE bb has a set of input nets of size at most KK, one output net, and a flag that says whether its flip-flop is used. For a set CC of BLEs, ext(C)\mathrm{ext}(C) is the set of nets that some member of CC reads and that no member of CC drives. A cluster CC is legal when ∣C∣≤N|C| \le N and ∣ext(C)∣≤I|\mathrm{ext}(C)| \le I, which is the legality rule of a logic cluster with a full crossbar. We assume K≤IK \le I, which the implementation checks.

Lemma 1 (a single BLE is legal). For every BLE bb, {b}\{b\} is legal.

Proof. ∣{b}∣=1≤N|\{b\}| = 1 \le N, and ext({b})\mathrm{ext}(\{b\}) is a subset of the inputs of bb, so ∣ext({b})∣≤K≤I|\mathrm{ext}(\{b\})| \le K \le I. □\square

Theorem 2 (legality and partition). T-VPack stops, and its output is a list of legal clusters in which every BLE is in exactly one cluster.

Proof. Let UU be the set of unclustered BLEs and CC the open cluster. We show that the following invariant holds at line L3 each time it is tested: CC is legal, C∩U=∅C \cap U = \emptyset, and UU, CC and the clusters already output are pairwise disjoint with union the whole netlist.

At line L2 the seed is removed from UU and becomes CC, so the sets stay disjoint with the same union, and CC is legal by Lemma 1. In the loop, line L5 keeps only BLEs b∈Ub \in U with ∣ext(C∪{b})∣≤I|\mathrm{ext}(C \cup \{b\})| \le I. Line L8 runs only when line L3 has found ∣C∣<N|C| < N, so after it ∣C∪{b}∣≤N|C \cup \{b\}| \le N. So C∪{b}C \cup \{b\} is legal, and moving bb from UU to CC keeps the sets disjoint with the same union. Line L9 outputs CC, which is legal, and the next cluster starts with a new seed from UU.

Each pass of the inner loop either adds a BLE (line L8) or leaves it (line L7), and ∣C∣|C| grows by one per addition, so the inner loop ends after at most N−1N - 1 additions. Each pass of the outer loop removes at least the seed from UU, so the outer loop ends after at most nn passes. When it ends, U=∅U = \emptyset, so by the invariant the output clusters are disjoint and cover all BLEs. □\square

Theorem 3 (closed clusters are maximal). When line L9 outputs CC, either ∣C∣=N|C| = N, or for every BLE bb that is still unclustered at that time, ∣ext(C∪{b})∣>I|\mathrm{ext}(C \cup \{b\})| > I.

Proof. The inner loop ends in one of two ways. Line L3 fails, which means ∣C∣=N|C| = N. Or line L7 finds no kept BLE, which means that line L5 skipped every b∈Ub \in U, that is, ∣ext(C∪{b})∣>I|\mathrm{ext}(C \cup \{b\})| > I for each of them. □\square

The set of BLEs that are unclustered when CC is closed is exactly the set of BLEs that later clusters hold, so Theorem 3 says that no BLE of a later cluster could have joined CC. It does not say that the number of clusters is least: the page gives a netlist on which T-VPack uses 3 clusters and 2 suffice.

Unit-delay criticality. Call BLE uu combinational if its flip-flop is not used. A connection is a pair (u,v)(u, v) where vv reads the output net of uu. A timing path is a sequence v1,…,vrv_1, \ldots, v_r of BLEs with r≥1r \ge 1 in which each (vj,vj+1)(v_j, v_{j+1}) is a connection and v1,…,vr−1v_1, \ldots, v_{r-1} are combinational. It starts at a primary input or at a flip-flop and passes through the LUTs of v1,…,vrv_1, \ldots, v_r. Its delay is rr, one unit per LUT. We assume that the combinational connections form a directed acyclic graph HH, which is the usual condition that every cycle passes through a flip-flop. Let DD be the largest delay of a timing path. For a connection (u,v)(u, v), let ℓ(u,v)\ell(u, v) be the largest delay of a timing path that uses it.

Define to(v)\mathrm{to}(v) as the largest rr of a timing path that ends at vv, and from(v)\mathrm{from}(v) as the largest number of BLEs of a timing path that starts with the LUT of vv; so from(v)=1\mathrm{from}(v) = 1 if vv is registered, and otherwise 11 plus the largest from(w)\mathrm{from}(w) over connections (v,w)(v, w), or 11 if there is none.

Lemma 4. The arrays of the implementation satisfy arrival[v]=to(v)\mathrm{arrival}[v] = \mathrm{to}(v), D=max⁡varrival[v]D = \max_v \mathrm{arrival}[v], and required[v]=D−from(v)+1\mathrm{required}[v] = D - \mathrm{from}(v) + 1.

Proof. The depth-first search follows only edges from combinational BLEs, which are the edges of HH, and appends a node after all its predecessors in HH, so the order is a topological order of HH. A timing path that ends at vv is either vv alone or a timing path that ends at a combinational predecessor uu followed by vv. So to(v)=1+max⁡to(u)\mathrm{to}(v) = 1 + \max \mathrm{to}(u) over the combinational uu with (u,v)(u, v) a connection, or 11 if there is none. The code computes exactly this recurrence in topological order, so arrival[v]=to(v)\mathrm{arrival}[v] = \mathrm{to}(v) by induction along the order. Every timing path has its delay as the to\mathrm{to} of its last BLE, so D=max⁡vto(v)D = \max_v \mathrm{to}(v).

For the required times, the code sets required[u]=D\mathrm{required}[u] = D and lowers it to required[v]−1\mathrm{required}[v] - 1 for each combinational connection (u,v)(u, v), in reverse topological order. When uu is combinational, its readers vv come after it in the order, so by induction required[u]=min⁡(D,min⁡v(D−from(v)))\mathrm{required}[u] = \min(D, \min_v (D - \mathrm{from}(v))) over the connections (u,v)(u, v). This is D−max⁡vfrom(v)D - \max_v \mathrm{from}(v) if uu has a reader and DD if not, which in both cases is D−(from(u)−1)D - (\mathrm{from}(u) - 1). A registered uu has no outgoing edge in HH, so required[u]=D=D−from(u)+1\mathrm{required}[u] = D = D - \mathrm{from}(u) + 1. □\square

Theorem 5 (criticality). For every connection (u,v)(u, v), the implementation returns crit(u,v)=ℓ(u,v)/D\mathrm{crit}(u, v) = \ell(u, v) / D. So 0<crit(u,v)≤10 < \mathrm{crit}(u, v) \le 1, with crit(u,v)=1\mathrm{crit}(u, v) = 1 if and only if the connection is on a timing path of delay DD.

Proof. A timing path through (u,v)(u, v) is a part that ends at uu and a part that starts with vv. If uu is combinational, the first part is a timing path that ends at uu, so ℓ(u,v)=to(u)+from(v)\ell(u, v) = \mathrm{to}(u) + \mathrm{from}(v). If uu is registered, the path through (u,v)(u, v) starts at the flip-flop of uu, so ℓ(u,v)=from(v)\ell(u, v) = \mathrm{from}(v). The code sets start=arrival[u]\mathrm{start} = \mathrm{arrival}[u] in the first case and 00 in the second, and

slack=required[v]−1−start=D−from(v)−start=D−ℓ(u,v)\mathrm{slack} = \mathrm{required}[v] - 1 - \mathrm{start} = D - \mathrm{from}(v) - \mathrm{start} = D - \ell(u, v)

by Lemma 4. So 1−slack/D=ℓ(u,v)/D1 - \mathrm{slack} / D = \ell(u, v) / D. Since 1≤ℓ(u,v)≤D1 \le \ell(u, v) \le D, the value lies in (0,1](0, 1]. ■\blacksquare

Complexity

The timing analysis is two passes over the connections, O(nK)O(n K). In the implementation, each addition at line L8 scans all unclustered BLEs, and each candidate costs O(NK)O(N K) for the external inputs and O(N)O(N) for Crit\mathrm{Crit}. There are at most nn additions and nn closed clusters, so packing takes O(n2NK)O(n^2 N K) time. The space is O(nK)O(n K) for the netlist and the criticalities.

VPR keeps, for the open cluster, only the BLEs that share a net with it, with their attraction updated when a BLE joins, so a step does not look at the whole netlist. Its running time is close to linear in practice; this is a measured property of the tool, not a bound proved here.

Properties

  • Not optimal. Take K=2K = 2, N=2N = 2, I=2I = 2 and four BLEs: o0o_0 reads i0i_0; o1o_1 reads o0o_0; o2o_2 reads i0i_0 and o0o_0; o3o_3 reads o1o_1 (each BLE is named after its output). The connections o0→o1o_0 \to o_1 and o1→o3o_1 \to o_3 have criticality 1 and o0→o2o_0 \to o_2 has 2/32/3. T-VPack seeds with o0o_0 and adds o1o_1 (attraction 5/65/6 against 2/32/3 for o2o_2). Then o3o_3 seeds the next cluster, and {o3,o2}\{o_3, o_2\} needs the three inputs o1,i0,o0o_1, i_0, o_0, so o2o_2 ends alone: 3 clusters. The partition {o0,o2}\{o_0, o_2\}, {o1,o3}\{o_1, o_3\} is legal with 2. With λ=0\lambda = 0 the packer finds that partition, so the timing term costs a cluster here.
  • Deterministic. All ties are broken by fixed rules, so the same input gives the same clusters.
  • Greedy and final. A BLE never leaves its cluster. The method makes one pass and has no local search.
  • The weight. λ=1\lambda = 1 packs for delay only and λ=0\lambda = 0 for shared nets only. Marquardt, Betz and Rose report that a large weight on timing gives faster circuits at almost the same cluster count; that is a measured result on their benchmarks.

Variants and improvements

  • Without timing. The earlier packer of Betz and Rose (1997) is the case λ=0\lambda = 0, with the seed chosen by the most used inputs instead of by criticality.
  • Ties by timing. The paper breaks ties among equally critical BLEs with more timing measures. This page breaks them by inputs and index.
  • Clock limits. A real cluster has a few clock pins, so the check of line L5 also counts the distinct clocks.
  • Hill climbing. A BLE that drives a net that the cluster reads removes that net from ext(C)\mathrm{ext}(C). So a packer can let the input count go above II for a while, in the hope that a later BLE absorbs nets, and undo the steps if it does not.
  • Complex blocks. AAPack keeps the greedy growth and the attraction, but checks each candidate by placing it in a slot and routing it inside the cluster, which handles sparse local routing, modes and hard blocks.
  • Placement-aware packing. Later packers use the placement, or a quick estimate of it, to choose the BLEs of a cluster.

When to use it

Use T-VPack, or its successor in VTR, to pack a LUT netlist into homogeneous clusters with a full crossbar, where the two counting conditions are the whole legality rule. It is fast and simple, and the timing term keeps critical paths inside clusters. For clusters whose local routing is sparse, or for blocks with modes, use AAPack, because the input count no longer tells whether a cluster can be routed. When the cluster count matters more than speed, lower λ\lambda.

Pitfalls

  • Counting inputs per BLE. The limit is on distinct external nets of the cluster. A net that two members read takes one pin, and a net that a member drives takes none.
  • Forgetting nets that leave. An output that is read outside the cluster leaves on its own output pin. It does not count against II but it does go into Nets(C)\mathrm{Nets}(C).
  • Stale criticality. The criticalities are computed once, before packing, with a delay model that does not know which connections end up inside clusters. A packer that updates them as it goes pays for more timing analyses.
  • A BLE wider than the cluster. If K>IK > I, a BLE with KK distinct inputs fits nowhere. The implementation raises an error.
  • Combinational loops. The timing analysis needs every cycle to pass through a flip-flop.

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.

t_vpack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t-vpack/. The authors are listed in prov/R2R827.jsonl.

"""T-VPack: greedy timing-driven packing of BLEs into clusters.

A BLE is a K-input LUT, an optional flip-flop and an output multiplexer. A netlist of BLEs is a list of Ble records. Nets are
strings. A cluster holds at most N BLEs and at most I distinct nets that
come from outside it. All arithmetic is in Fraction, so a run is exact.
"""

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


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


def form_bles(luts: list[tuple[tuple[str, ...], str]], ffs: list[tuple[str, str]]) -> list[Ble]:
    """Step 1: put each LUT together with the flip-flop that it alone feeds.

    luts: (input nets, output net). ffs: (D net, Q net). A flip-flop whose D net
    is not the output of a LUT with that flip-flop as its only reader gets a
    BLE of its own, whose LUT passes D through.
    """
    readers: dict[str, int] = {}
    for ins, _ in luts:
        for n in ins:
            readers[n] = readers.get(n, 0) + 1
    for d, _ in ffs:
        readers[d] = readers.get(d, 0) + 1
    by_out = {out: (ins, out) for ins, out in luts}
    merged: set[str] = set()
    bles = []
    for d, q in ffs:
        if d in by_out and readers[d] == 1 and d not in merged:
            merged.add(d)
            bles.append(Ble(by_out[d][0], q, True))
        else:
            bles.append(Ble((d,), q, True))
    for ins, out in luts:
        if out not in merged:
            bles.append(Ble(ins, out, False))
    return bles


def external_inputs(bles: list[Ble], members: set[int]) -> set[str]:
    """Nets used by some member and driven by no member."""
    driven = {bles[i].output for i in members}
    return {n for i in members for n in bles[i].inputs if n not in driven}


def criticalities(bles: list[Ble]) -> dict[tuple[int, int], Fraction]:
    """Criticality 1 - slack / Dmax of each connection (driver BLE, reader BLE).

    Unit delay model: each BLE has delay 1, connections have delay 0, and a
    registered BLE starts a new path at its output. The netlist must have no
    combinational cycle.
    """
    driver = {b.output: i for i, b in enumerate(bles)}
    n = len(bles)
    fanin = [[driver[x] for x in b.inputs if x in driver] for b in bles]
    order: list[int] = []
    state = [0] * n

    def visit(v: int) -> None:
        state[v] = 1
        for u in fanin[v]:
            if not bles[u].registered and state[u] == 0:
                visit(u)
        state[v] = 2
        order.append(v)

    for v in range(n):
        if state[v] == 0:
            visit(v)
    # arrival[v]: time at the output of v's LUT (before its flip-flop).
    arrival = [0] * n
    for v in order:
        a = 0
        for u in fanin[v]:
            if not bles[u].registered:
                a = max(a, arrival[u])
        arrival[v] = a + 1
    dmax = max(arrival) if arrival else 1
    required = [dmax] * n
    for v in reversed(order):
        for u in fanin[v]:
            if not bles[u].registered:
                required[u] = min(required[u], required[v] - 1)
    crit = {}
    for v in range(n):
        for u in fanin[v]:
            start = 0 if bles[u].registered else arrival[u]  # a flip-flop output starts a path
            slack = required[v] - 1 - start
            crit[(u, v)] = 1 - Fraction(slack, dmax)
    return crit


def t_vpack(
    bles: list[Ble],
    n_max: int,
    i_max: int,
    lam: Fraction = Fraction(3, 4),
    k: Optional[int] = None,
) -> list[list[int]]:
    """Pack the BLEs into clusters of at most n_max BLEs and i_max inputs.

    Returns the clusters as lists of BLE indices, in the order filled.
    """
    if k is None:
        k = max((len(b.inputs) for b in bles), default=1)
    if k > i_max:
        raise ValueError("a BLE with more inputs than the cluster cannot be packed")
    g = k + 1  # the most nets a BLE can touch: K inputs and one output
    crit = criticalities(bles)
    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]  # pair_crit[a][b]: most critical connection between a and b
    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)
    unclustered = set(range(len(bles)))
    clusters = []
    while unclustered:  # @line L1
        seed = max(unclustered, key=lambda i: (ble_crit[i], len(bles[i].inputs), -i))  # @line L2
        members = {seed}
        unclustered.discard(seed)
        while len(members) < n_max:  # @line L3
            cluster_nets = set().union(*(nets_of[i] for i in members))
            best = None
            best_key = None
            for b in sorted(unclustered):  # @line L4
                if len(external_inputs(bles, members | {b})) > i_max:  # @line L5
                    continue
                shared = len(nets_of[b] & cluster_nets)
                c = max((pair_crit[b].get(m, Fraction(0)) for m in members), default=Fraction(0))
                attraction = lam * c + (1 - lam) * Fraction(shared, g)  # @line L6
                key = (attraction, len(bles[b].inputs), -b)
                if best_key is None or key > best_key:
                    best, best_key = b, key
            if best is None:  # @line L7
                break
            members.add(best)  # @line L8
            unclustered.discard(best)
        clusters.append(sorted(members))  # @line L9
    return clusters


def is_legal(bles: list[Ble], clusters: list[list[int]], n_max: int, i_max: int) -> bool:
    """Every BLE in exactly one cluster, and every cluster within N and I."""
    seen = sorted(i for c in clusters for i in c)
    if seen != list(range(len(bles))):
        return False
    return all(1 <= len(c) <= n_max and len(external_inputs(bles, set(c))) <= i_max for c in clusters)


def min_clusters(bles: list[Ble], n_max: int, i_max: int) -> int:
    """Exact least number of legal clusters, by dynamic programming over subsets."""
    n = len(bles)
    full = (1 << n) - 1
    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) <= n_max and len(external_inputs(bles, members)) <= i_max
    best = [0] + [n + 1] * full
    for mask in range(1, full + 1):
        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[full]
test_t_vpack.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t-vpack/. The authors are listed in prov/R2R827.jsonl.

import random
from fractions import Fraction

from t_vpack import Ble, criticalities, external_inputs, form_bles, is_legal, min_clusters, t_vpack


def random_netlist(rng: random.Random, n: int, k: int, primaries: int) -> list[Ble]:
    """BLE i reads primary inputs, outputs of earlier BLEs, and outputs of later registered BLEs."""
    registered = [rng.random() < 0.3 for _ in range(n)]
    bles = []
    for i in range(n):
        pool = [f"i{p}" for p in range(primaries)]
        pool += [f"o{j}" for j in range(i)]
        pool += [f"o{j}" for j in range(i + 1, n) if registered[j]]
        size = rng.randint(1, min(k, len(pool)))
        bles.append(Ble(tuple(sorted(rng.sample(pool, size))), f"o{i}", registered[i]))
    return bles


def brute_criticalities(bles: list[Ble]) -> dict[tuple[int, int], Fraction]:
    """Longest paths by enumerating every combinational path from scratch."""
    driver = {b.output: i for i, b in enumerate(bles)}
    edges = [(driver[x], v) for v, b in enumerate(bles) for x in b.inputs if x in driver]
    comb = [(u, v) for u, v in edges if not bles[u].registered]

    def longest_to(v: int) -> int:  # BLEs on the longest path that ends at v, v included
        return 1 + max((longest_to(u) for u, w in comb if w == v), default=0)

    def longest_from(v: int) -> int:  # BLEs on the longest path that starts at v, v included
        if bles[v].registered:
            return 1
        return 1 + max((longest_from(w) for u, w in comb if u == v), default=0)

    dmax = max(longest_to(v) for v in range(len(bles)))
    out = {}
    for u, v in edges:
        before = 0 if bles[u].registered else longest_to(u)
        through = before + longest_from(v)
        out[(u, v)] = 1 - Fraction(dmax - through, dmax)
    return out


def test_hand_example():
    # a(x, y) -> A, b(A, z) -> B, c(x, w) -> C, d(C, y) -> D with N = 2, I = 3
    bles = [
        Ble(("x", "y"), "A"),
        Ble(("A", "z"), "B"),
        Ble(("w", "x"), "C"),
        Ble(("C", "y"), "D"),
    ]
    clusters = t_vpack(bles, 2, 3)
    assert is_legal(bles, clusters, 2, 3)
    assert clusters == [[0, 1], [2, 3]]
    assert min_clusters(bles, 2, 3) == 2
    assert len(external_inputs(bles, {0, 2})) == 3
    assert len(external_inputs(bles, {1, 3})) == 4  # A, z, C, y: the other pairing is illegal


def test_suboptimal_example():
    bles = [Ble(("i0",), "o0"), Ble(("o0",), "o1"), Ble(("i0", "o0"), "o2"), Ble(("o1",), "o3")]
    crit = criticalities(bles)
    assert crit == {(0, 1): 1, (0, 2): Fraction(2, 3), (1, 3): 1}
    clusters = t_vpack(bles, 2, 2, k=2)
    assert clusters == [[0, 1], [3], [2]]
    assert is_legal(bles, clusters, 2, 2)
    assert min_clusters(bles, 2, 2) == 2
    assert t_vpack(bles, 2, 2, lam=Fraction(0), k=2) == [[0, 2], [1, 3]]


def test_form_bles():
    luts = [(("a", "b"), "x"), (("x", "c"), "y"), (("y",), "z")]
    ffs = [("x", "qx"), ("z", "qz"), ("c", "qc")]
    bles = form_bles(luts, ffs)
    # x has two readers, so its flip-flop gets a BLE of its own; z feeds only its flip-flop.
    assert Ble(("x",), "qx", True) in bles
    assert Ble(("y",), "qz", True) in bles
    assert Ble(("c",), "qc", True) in bles
    assert Ble(("a", "b"), "x", False) in bles
    assert Ble(("x", "c"), "y", False) in bles
    assert len(bles) == 5


def test_criticalities_match_path_enumeration():
    rng = random.Random(11)
    for _ in range(300):
        bles = random_netlist(rng, rng.randint(1, 7), 3, 3)
        assert criticalities(bles) == brute_criticalities(bles)


def test_legal_and_never_below_optimum():
    rng = random.Random(1)
    worse = 0
    for _ in range(600):
        k = rng.randint(1, 3)
        bles = random_netlist(rng, rng.randint(1, 8), k, rng.randint(1, 4))
        n_max = rng.randint(1, 4)
        i_max = rng.randint(k, k + 3)
        for lam in (Fraction(0), Fraction(3, 4), Fraction(1)):
            clusters = t_vpack(bles, n_max, i_max, lam=lam, k=k)
            assert is_legal(bles, clusters, n_max, i_max)
            best = min_clusters(bles, n_max, i_max)
            assert len(clusters) >= best
            assert len(clusters) >= -(-len(bles) // n_max)
            worse += len(clusters) > best
    assert worse > 0  # the greedy is a heuristic: some instances need more clusters than the optimum


def test_cluster_is_full_when_a_ble_fits():
    """A closed cluster is full, or no unclustered BLE of that moment fits in it."""
    rng = random.Random(3)
    for _ in range(300):
        k = rng.randint(1, 3)
        bles = random_netlist(rng, rng.randint(1, 8), k, 3)
        n_max, i_max = rng.randint(1, 4), rng.randint(k, k + 2)
        clusters = t_vpack(bles, n_max, i_max, k=k)
        later: set[int] = set(range(len(bles)))
        for c in clusters:
            later -= set(c)
            if len(c) < n_max:
                assert all(len(external_inputs(bles, set(c) | {b})) > i_max for b in later)


def test_rejects_too_wide_ble():
    bles = [Ble(("a", "b", "c"), "o")]
    try:
        t_vpack(bles, 2, 2)
    except ValueError:
        return
    raise AssertionError("expected ValueError")

History

Betz and Rose (1997) built a greedy packer that seeds a cluster with the BLE of the most used inputs and grows it by shared nets, and used it to study the cluster size and the number of inputs. Marquardt, Betz and Rose (1999) added the timing-driven seed and the attraction that mixes criticality with shared nets, and reported faster circuits at about the same area. Their packer was the packing step of VPR for many years, and its greedy structure carried over to AAPack in the VTR flow.

References

  1. Alexander Marquardt, Vaughn Betz and Jonathan Rose, Using cluster-based logic blocks and timing-driven packing to improve FPGA speed and density, Proceedings of the ACM/SIGDA International Symposium on Field Programmable Gate Arrays (FPGA '99), 37 to 46, 1999, the section on the timing-driven packing algorithm (the seed choice, the attraction function with its weight on criticality and the normalized count of shared nets, and the legality checks) and the experimental results against the packer without timing
  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 3, Section 3.1 Logic Block Packing (forming BLEs from LUTs and flip-flops, and the greedy growth of clusters)
  3. Vaughn Betz and Jonathan Rose, Cluster-based logic blocks for FPGAs, area-efficiency vs. input sharing and size, Proceedings of the IEEE Custom Integrated Circuits Conference (CICC), 1997, the earlier packer that grows clusters by the number of shared nets (general locator)

Where this leads

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.criticality
  • 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