Algorithm Search⌘K

Algorithmcore

FlowMap

Also called Cong-Ding FlowMap.

Cong and Ding's depth-optimal k-LUT mapping that labels nodes in topological order, finding a k-feasible cut of least height by a max-flow test.

Time
O(K m n) worst
Space
O(m) extra
Where
K = the number of inputs of a LUT; m = the number of edges; n = the number of nodes
Properties
deterministicexactofflineiterative
Origin
Jason Cong, Yuzheng Ding, 1992

FlowMap maps a Boolean network into KK-input lookup tables (LUTs) so that the longest chain of LUTs from an input to an output is as short as possible. It is the depth version of LUT mapping. The network must be KK-bounded: every gate has at most KK fanins. FlowMap gives each node a label, the least depth of a LUT that computes the node, in topological order. The label of a gate tt is either pp or p+1p + 1, where pp is the largest label of a fanin. It is pp exactly when a KK-feasible cut of tt separates tt and all nodes of label pp from the inputs, and a max-flow computation on a network with unit node capacities tests this. Cong and Ding (1992, 1994) proved that the labels are the least possible depths, so the mapping is depth-optimal, in O(Kmn)O(K m n) time. Before FlowMap, depth-optimal mapping was known only for trees.

In plain words

An FPGA builds logic from small tables. Each table takes up to KK wires and can compute any function of them. You must cut a circuit of small gates into such tables. Each signal passes through a chain of tables, and you want the longest chain to be short, because each table adds delay.

Work from the inputs. For each gate, look at the gates that feed it and take the worst depth among them. The gate can reach that same depth only if one table can hold the gate together with every feeding gate at the worst depth, and that table needs at most KK wires in. A flow test on the graph answers this: it finds the fewest wires that separate the gate from the inputs. If the answer is too many, the gate gets one more level. At the end, build tables from the outputs back.

The problem

The input is a KK-bounded network NN with nn nodes and mm edges, a directed acyclic graph whose sources are the primary inputs (PIs), and a set of output nodes. A mapping gives each node vv that it needs a LUT whose inputs form a KK-feasible cut CvC_v of vv, with v∉Cvv \notin C_v. The LUT computes vv from CvC_v, which is possible because a node is a function of each of its cuts. The LUT inputs that are gates need LUTs too. A gate can be covered by several LUTs, so logic may be duplicated. Under the unit delay model, the depth of a mapping is the largest number of LUTs on a path from a PI to an output. The task is a mapping of least depth.

Let NtN_t be the cone of tt, the nodes from which tt can be reached. Let d(t)d(t) be the least depth of a LUT for tt:

d(t)=0 for a PI,d(t)=min⁡C(1+max⁡u∈Cd(u)),d(t) = 0 \text{ for a PI}, \qquad d(t) = \min_{C} \Big(1 + \max_{u \in C} d(u)\Big),

where CC ranges over the KK-feasible cuts of tt that do not contain tt. A mapping that uses at each node a cut that reaches this minimum has depth max⁡od(o)\max_o d(o) over the outputs oo, and no mapping has less, since the LUT inputs of tt in any mapping form such a cut. FlowMap computes dd without listing the cuts.

The algorithm

  1. FLOWMAP(N, K, outputs)
  2. 1ℓ(v) ← 0 for each primary input v
  3. 2for each gate t in topological order do
  4. 3p ← the largest label ℓ(u) of a fanin u of t
  5. 4if p = 0 then ℓ(t) ← 1; C_t ← the fanins of t; continue
  6. 5N' ← the cone N_t with t and every node of label p merged into one sink t'
  7. 6F ← N' with each other node w split into w_in → w_out of capacity 1, the other edges of capacity ∞, and a source s with an edge of capacity ∞ into each PI
  8. 7if the max flow from s to t' in F is at most K then
  9. 8ℓ(t) ← p; C_t ← the nodes w with w_in reachable from s in the residual graph and w_out not reachable
  10. 9else
  11. 10ℓ(t) ← p + 1; C_t ← the fanins of t
  12. 11L ← the outputs that are gates; S ← ∅
  13. 12while L holds a gate t ∉ S do
  14. 13add a LUT for t with the inputs C_t to S; add the gates of C_t to L
  15. 14return ℓ and S

Lines L1 to L10 are the labeling phase and lines L11 to L14 the mapping phase. At line L4 all fanins are PIs, so the fanins form a cut of depth 1. Line L7 does not need the whole max flow: the code of this page stops after K+1K + 1 augmenting paths of a breadth-first augmenting path search, as in Edmonds-Karp. The split of line L6 turns a node cut into an edge cut, as on the vertex capacities page. A merged node is not split, so it can never be in the cut.

Example

Take K=3K = 3, inputs a,b,c,d,ea, b, c, d, e and the gates f=(a,b)f = (a, b), g=(b,c)g = (b, c), h=(c,d)h = (c, d), i=(f,g)i = (f, g), j=(g,h)j = (g, h) and o=(i,j,e)o = (i, j, e), with oo the output. Node gg feeds both ii and jj.

gate pp merged into t′t' max flow label CtC_t
f,g,hf, g, h 0 1 the fanins
ii 1 i,f,gi, f, g 3: through aa, bb, cc 1 {a,b,c}\{a, b, c\}
jj 1 j,g,hj, g, h 3: through bb, cc, dd 1 {b,c,d}\{b, c, d\}
oo 1 o,f,g,h,i,jo, f, g, h, i, j 5: through aa, bb, cc, dd, ee 2 {i,j,e}\{i, j, e\}

At oo, each of the five inputs has its own edge into a merged node, so 5 node-disjoint paths reach t′t', and the code stops after the fourth. The mapping phase starts at oo and makes three LUTs: oo over {e,i,j}\{e, i, j\}, ii over {a,b,c}\{a, b, c\} and jj over {b,c,d}\{b, c, d\}. The depth is 2. Gate gg is inside the LUTs of both ii and jj, so it is duplicated. Without duplication, gg needs its own LUT, then ii or jj has depth 2 and oo has depth 3. The test file checks this example with a brute force over all KK-feasible cuts of each node.

Correctness

The full proof shows that ℓ(t)=d(t)\ell(t) = d(t) for every node, by induction in topological order. Three facts carry it. First, dd is monotone along the cone: if uu is in the cone of tt, then d(u)≤d(t)d(u) \le d(t). With the fanin cut, this gives p≤d(t)≤p+1p \le d(t) \le p + 1. Second, d(t)=pd(t) = p exactly when some cut of tt with at most KK nodes has only nodes of label below pp, and by monotonicity such a set is a cut of tt exactly when it meets every path from a PI to a node of N′N' that was merged into t′t'. Third, by the max-flow min-cut theorem with unit node capacities, that set exists exactly when the max flow at line L7 is at most KK, and the residual reachability of line L8 gives one. The mapping phase then builds, for each LUT root tt, a LUT of depth ℓ(t)\ell(t), so the depth is max⁡od(o)\max_o d(o), the least possible.

Proof: FlowMap labels are the least LUT depths, and the mapping reaches themfull

Let NN be a KK-bounded network: a directed acyclic graph whose sources are the primary inputs (PIs), in which every gate has between 1 and KK fanins. For a node tt, NtN_t is the cone of tt, the set of nodes from which tt can be reached, tt included. A cut of tt is a set of nodes that meets every path from a PI to tt. Let C(t)\mathcal{C}(t) be the set of cuts CC of tt with ∣C∣≤K|C| \le K and t∉Ct \notin C. Define

d(t)=0 for a PI,d(t)=min⁡C∈C(t)h(C),h(C)=1+max⁡u∈Cd(u),d(t) = 0 \text{ for a PI}, \qquad d(t) = \min_{C \in \mathcal{C}(t)} h(C), \quad h(C) = 1 + \max_{u \in C} d(u),

for a gate. The set of fanins of a gate is in C(t)\mathcal{C}(t), so the minimum exists.

Lemma 1 (d is the least depth). In every mapping, the LUT network has depth at least d(t)d(t) at each LUT root tt, and the mapping that uses at each needed gate a cut Ct∈C(t)C_t \in \mathcal{C}(t) with h(Ct)=d(t)h(C_t) = d(t) has depth exactly d(t)d(t) at tt.

Proof. The inputs of the LUT of tt are PIs or LUT roots, and the LUT computes tt from them for all inputs of the network, so they form a cut of tt; the cut does not contain tt and has at most KK nodes, so it is in C(t)\mathcal{C}(t). By induction on the topological order, each LUT input uu has depth at least d(u)d(u), so tt has depth at least h(Ct)≥d(t)h(C_t) \ge d(t). For the second claim, the same induction gives depth 1+max⁡u∈Ctd(u)=d(t)1 + \max_{u \in C_t} d(u) = d(t). □\square

Lemma 2 (d is monotone). If u∈Ntu \in N_t, then d(u)≤d(t)d(u) \le d(t).

Proof. Induction on the topological order of tt. For t=ut = u, or for a PI uu with d(u)=0d(u) = 0, it is clear. Let u≠tu \ne t be a gate, so tt is a gate too, and let C∈C(t)C \in \mathcal{C}(t) with h(C)=d(t)h(C) = d(t). There are two cases.

If some path QQ from uu to tt avoids CC, then CC is a cut of uu: a path PP from a PI to uu, followed by QQ, meets CC, and not on QQ, so PP meets CC. Also u∉Cu \notin C. So C∈C(u)C \in \mathcal{C}(u) and d(u)≤h(C)=d(t)d(u) \le h(C) = d(t).

Otherwise every path from uu to tt meets CC. Take one, and let ww be its first node in CC. Then u∈Nwu \in N_w, ww comes before tt, and by induction d(u)≤d(w)≤h(C)−1<d(t)d(u) \le d(w) \le h(C) - 1 < d(t). □\square

Lemma 3 (two values). Let tt be a gate and p=max⁡d(u)p = \max d(u) over its fanins uu. Then p≤d(t)≤p+1p \le d(t) \le p + 1. If p=0p = 0, then d(t)=1d(t) = 1.

Proof. Each fanin is in NtN_t, so p≤d(t)p \le d(t) by Lemma 2. The fanin set is in C(t)\mathcal{C}(t) and has h=p+1h = p + 1. If p=0p = 0, then d(t)≥1d(t) \ge 1 because h(C)≥1h(C) \ge 1 for every CC. □\square

So for p≥1p \ge 1, d(t)=pd(t) = p exactly when some C∈C(t)C \in \mathcal{C}(t) has d(u)≤p−1d(u) \le p - 1 for all u∈Cu \in C. Let H={t}∪{w∈Nt∖{t}:d(w)=p}H = \{t\} \cup \{w \in N_t \setminus \{t\} : d(w) = p\}, the set merged at line L5. By Lemma 2, every w∈Nt∖{t}w \in N_t \setminus \{t\} has d(w)≤pd(w) \le p, since ww is in the cone of some fanin of tt.

Lemma 4 (cuts of low label are the separators of H). Let p≥1p \ge 1 and let CC be a set of nodes of Nt∖HN_t \setminus H. Then CC is a cut of tt if and only if CC meets every path in NtN_t from a PI to a node of HH.

Proof. If CC meets every path to a node of HH, it meets every path to t∈Ht \in H. Conversely, let CC be a cut of tt and PP a path from a PI to w∈Hw \in H. Extend PP by a path from ww to tt. The extended path meets CC. Every node xx on the extension, after ww, has w∈Nxw \in N_x, so d(x)≥d(w)=pd(x) \ge d(w) = p by Lemma 2 (or x=tx = t), so x∈Hx \in H and x∉Cx \notin C. Hence PP meets CC. □\square

Lemma 5 (the flow test). Let p≥1p \ge 1 and let FF be the network of line L6. The max flow from ss to t′t' is the least size of a set C⊆Nt∖HC \subseteq N_t \setminus H that meets every path from a PI to HH. If the flow is at most KK, the set of line L8 is such a set of size equal to the flow.

Proof. A path from ss to t′t' in FF is s→win1→wout1→⋯→t′s \to w^1_{in} \to w^1_{out} \to \cdots \to t', where w1w^1 is a PI and w1,w2,…w^1, w^2, \ldots is a path of NtN_t to a node of HH, and conversely. An ss-t′t' edge cut of finite capacity uses only split edges win→woutw_{in} \to w_{out}, which have capacity 1, and a set of split edges is an ss-t′t' cut exactly when the set of their nodes meets every path from a PI to HH. So the least finite cut capacity is the least size of such a node set. A finite cut exists, for example the split edges of all PIs. By the max-flow min-cut theorem, the max flow equals this least size.

For the second claim, let RR be the set of nodes of FF reachable from ss in the residual graph of a max flow. Then t′∉Rt' \notin R, and the edges from RR to the rest are saturated, and they form a min cut. An edge of capacity ∞\infty cannot be saturated by a finite flow, so every edge leaving RR is a split edge win→woutw_{in} \to w_{out} with win∈Rw_{in} \in R and wout∉Rw_{out} \notin R. These ww are the nodes of line L8, and their number is the cut capacity, which equals the flow. The code stops after K+1K + 1 augmenting paths: if the search finds no path before that, the flow is maximum, and if it finds K+1K + 1, the max flow is more than KK. □\square

Theorem. FLOWMAP sets ℓ(t)=d(t)\ell(t) = d(t) for every node, and every CtC_t is in C(t)\mathcal{C}(t) with h(Ct)=d(t)h(C_t) = d(t). The returned mapping has depth max⁡od(o)\max_o d(o) over the outputs, the least depth of any mapping.

Proof. Induction on the topological order. For a PI, line L1 sets ℓ=0=d\ell = 0 = d. Let tt be a gate, and assume ℓ(u)=d(u)\ell(u) = d(u) for all nodes before tt. Then the value pp of line L3 is the pp of Lemma 3, and the merged set of line L5 is HH.

If p=0p = 0, line L4 sets ℓ(t)=1=d(t)\ell(t) = 1 = d(t) by Lemma 3, and the fanin set has h=1h = 1.

If p≥1p \ge 1 and the flow is at most KK, Lemma 5 gives a set Ct⊆Nt∖HC_t \subseteq N_t \setminus H of at most KK nodes that meets every path from a PI to HH. By Lemma 4 it is a cut of tt. It avoids HH, so each of its nodes has d≤p−1d \le p - 1, and t∉Ctt \notin C_t. So Ct∈C(t)C_t \in \mathcal{C}(t) and h(Ct)≤ph(C_t) \le p, and with Lemma 3, d(t)=p=ℓ(t)d(t) = p = \ell(t) and h(Ct)=ph(C_t) = p.

If p≥1p \ge 1 and the flow is more than KK, suppose d(t)=pd(t) = p. Then some C∈C(t)C \in \mathcal{C}(t) has only nodes of d≤p−1d \le p - 1. Remove from CC the nodes outside NtN_t; the rest is still a cut of tt, it lies in Nt∖HN_t \setminus H, and by Lemma 4 it meets every path from a PI to HH. By Lemma 5 the flow is at most ∣C∣≤K|C| \le K, a contradiction. So d(t)=p+1d(t) = p + 1 by Lemma 3, which is the value of line L10, and the fanin set has h=p+1h = p + 1.

For the mapping phase, line L13 makes a LUT for tt over CtC_t, which computes tt because a node is a function of each of its cuts. Every gate of CtC_t gets a LUT in turn, so the LUT network is complete, and by the second part of Lemma 1 the depth at each LUT root tt is h(Ct)=d(t)h(C_t) = d(t). By the first part of Lemma 1, no mapping has smaller depth at any output. ■\blacksquare

Running time. At one gate, FF has O(∣Nt∣)O(|N_t|) nodes and O(m)O(m) edges, and each breadth-first augmenting path costs O(m)O(m). Line L7 uses at most K+1K + 1 paths, so the labeling costs O(Km)O(K m) per gate and O(Kmn)O(K m n) in all.

Complexity

At a gate tt, the network FF has O(∣Nt∣)O(|N_t|) nodes and O(m)O(m) edges. One augmenting path costs O(m)O(m) time by breadth-first search, and line L7 needs at most K+1K + 1 of them, so a gate costs O(Km)O(K m) and the labeling phase O(Kmn)O(K m n). The mapping phase visits each LUT root once and costs O(Kn)O(K n). The flow network of one gate takes O(m)O(m) space. On circuits, the cones are much smaller than the whole network for most gates, so the run time is far below the bound.

Properties

What is proved. For a KK-bounded network under the unit delay model, with duplication allowed, the mapping has the least depth among all mappings into KK-input LUTs of the given network structure. Each label is the least depth of a LUT for its node, and the labels never decrease along paths. The algorithm runs in polynomial time.

What is not proved. The number of LUTs is not optimized. Finding a mapping with the fewest LUTs is NP-hard (Farrahi and Sarrafzadeh 1994), and FlowMap often duplicates logic to save depth. The optimum is only over mappings of the given structure: a different decomposition of the same functions into KK-bounded gates can allow a smaller depth. The result does not hold for a network that is not KK-bounded without first splitting its large gates, and the depth then depends on the split.

What is measured. The test file compares the labels with the brute-force dd on 500 random networks with up to 6 inputs, 14 gates and KK from 2 to 4 (seed 5), and compares the mapping depth with an exhaustive search over every choice of one cut per gate on 40 networks with K=3K = 3 (seed 9). These are checks of the code, not benchmark results. Cong and Ding report results on benchmark circuits in their paper.

Variants and improvements

  • Area recovery. After labeling, each node has a required time from the depth bound. A mapper can then choose, among the cuts that meet the required times, cuts that need fewer LUTs, for example cuts that do not duplicate logic. Later mappers do this with area flow and exact area, as in priority cuts.
  • Depth relaxation. Relax the depth bound on paths that are not critical and use the slack to save LUTs. Cong and Ding studied this trade-off between depth and area after FlowMap.
  • Cut enumeration instead of flow. With all cuts listed by cut enumeration, a dynamic program over the cuts gives the same labels, and it can handle other costs. For K=6K = 6 and large circuits, priority cuts keep the dynamic program fast, at the cost of the proof.
  • Retiming. Pan and Lin (1998) and others extend the labels to sequential circuits, so that mapping and retiming are done together.

When to use it

Use FlowMap when the depth of a LUT network matters and a proof of optimality for the given structure is wanted, or as a reference for testing faster mappers. Modern tools use cut-based mapping with priority cuts, which computes depth labels in the same way over a limited set of cuts and then recovers area. FlowMap is not the tool for area, and it does not restructure logic.

Pitfalls

  • Unbounded gates. A gate with more than KK fanins has no KK-feasible cut of its fanins. Split such gates first, for example into a tree of 2-input gates.
  • Merging only tt. The sink must include every node of label pp in the cone. If a node of label pp stays outside the sink, the cut can contain it, and the LUT would have depth p+1p + 1.
  • Splitting the merged nodes. The merged nodes must not get unit capacities, since they may not be cut. In the code of this page, edges out of a merged node are left out. Labels never decrease along a path, so such an edge goes to another merged node, and it does not change the flow.
  • Reading the cut. The cut nodes are the split nodes whose input half is reachable from the source in the residual graph and whose output half is not. Taking all reachable nodes, or the unreachable ones, gives the wrong set.
  • Counting depth with PIs. The PIs have label 0 and are not LUTs. A gate fed only by PIs has label 1.

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.

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

"""FlowMap of Cong and Ding: depth-optimal mapping into k-input LUTs.

The network is a list `fanins` in topological order: every fanin of v is
smaller than v, a node with no fanins is a primary input, and every node
has at most k fanins (the network is k-bounded). `outputs` lists the
nodes that drive primary outputs.

Phase 1 gives each node t a label, the least depth of a LUT mapping of
t. Let p be the largest label of a fanin of t. The label is p when the
cone of t, with t and every node of label p merged into one sink, has a
node cut of at most k nodes between the inputs and the sink; else it is
p + 1. The node cut is found with unit node capacities and augmenting
paths, stopping after k + 1 paths.

Phase 2 builds the LUTs from the outputs down: the LUT of t has the
nodes of its cut as inputs.
"""

from collections import deque
from typing import Sequence

INF = 1 << 30


def cone(fanins: Sequence[Sequence[int]], t: int) -> list:
    """The nodes from which t can be reached, t included, in increasing order."""
    seen, stack = {t}, [t]
    while stack:
        w = stack.pop()
        for u in fanins[w]:
            if u not in seen:
                seen.add(u)
                stack.append(u)
    return sorted(seen)


class FlowNet:
    """A directed graph with integer capacities for augmenting paths."""

    def __init__(self) -> None:
        self.to: list = []
        self.cap: list = []
        self.adj: dict = {}

    def add(self, a, b, c: int) -> None:
        for x in (a, b):
            self.adj.setdefault(x, [])
        self.adj[a].append(len(self.to))
        self.to.append(b)
        self.cap.append(c)
        self.adj[b].append(len(self.to))
        self.to.append(a)
        self.cap.append(0)

    def augment(self, s, t) -> bool:
        """Push one unit along a shortest path with free capacity."""
        prev = {s: None}
        q = deque([s])
        while q and t not in prev:
            x = q.popleft()
            for e in self.adj[x]:
                y = self.to[e]
                if self.cap[e] > 0 and y not in prev:
                    prev[y] = e
                    q.append(y)
        if t not in prev:
            return False
        y = t
        while prev[y] is not None:
            e = prev[y]
            self.cap[e] -= 1
            self.cap[e ^ 1] += 1
            y = self.to[e ^ 1]
        return True

    def reachable(self, s) -> set:
        seen, stack = {s}, [s]
        while stack:
            x = stack.pop()
            for e in self.adj[x]:
                y = self.to[e]
                if self.cap[e] > 0 and y not in seen:
                    seen.add(y)
                    stack.append(y)
        return seen


def min_height_cut(fanins, label, t: int, k: int):
    """Return (label of t, the cut of t) as in phase 1 of FlowMap."""
    p = max(label[u] for u in fanins[t])  # @line L3
    if p == 0:  # @line L4
        return 1, frozenset(fanins[t])
    nodes = cone(fanins, t)
    sink = ("sink",)
    merged = {w for w in nodes if w == t or label[w] == p}  # @line L5
    net = FlowNet()  # @line L6
    src = ("src",)

    def head(w):  # where the edges into w arrive
        return sink if w in merged else ("in", w)

    for w in nodes:
        if w in merged:
            continue
        net.add(("in", w), ("out", w), 1)  # each node may be cut once
        if not fanins[w]:
            net.add(src, ("in", w), INF)
    for w in nodes:
        for u in fanins[w]:
            if u not in merged:  # edges out of the sink are not needed
                net.add(("out", u), head(w), INF)
    flow = 0
    while flow <= k and net.augment(src, sink):  # @line L7
        flow += 1
    if flow > k:  # @line L9
        return p + 1, frozenset(fanins[t])  # @line L10
    side = net.reachable(src)  # @line L8
    cut = frozenset(w for w in nodes if w not in merged
                    and ("in", w) in side and ("out", w) not in side)
    return p, cut


def flowmap(fanins: Sequence[Sequence[int]], outputs: Sequence[int], k: int):
    """Return (labels, luts): luts maps each LUT root to its input nodes."""
    for v, fi in enumerate(fanins):
        if len(fi) > k:
            raise ValueError("the network is not k-bounded")
        if any(u >= v for u in fi):
            raise ValueError("fanins must come before the node")
    label = [0] * len(fanins)  # @line L1
    cut: list = [None] * len(fanins)
    for t, fi in enumerate(fanins):  # @line L2
        if fi:
            label[t], cut[t] = min_height_cut(fanins, label, t, k)
    luts: dict = {}
    todo = [v for v in outputs if fanins[v]]  # @line L11
    while todo:  # @line L12
        v = todo.pop()
        if v in luts:
            continue
        luts[v] = cut[v]  # @line L13
        todo.extend(u for u in cut[v] if fanins[u] and u not in luts)
    return label, luts  # @line L14


def lut_depth(fanins, luts, outputs) -> int:
    """Depth of the LUT network: the most LUTs on a path from an input to an output."""
    memo: dict = {}

    def d(v):
        if not fanins[v]:
            return 0
        if v not in memo:
            memo[v] = 1 + max((d(u) for u in luts[v]), default=0)
        return memo[v]

    return max((d(v) for v in outputs), default=0)
test_flowmap.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flowmap/. The authors are listed in prov/R5X3KJ.jsonl.

import random
from itertools import combinations, product

from flowmap import flowmap, lut_depth

# The example of the page, k = 3: inputs a, b, c, d, e are nodes 0 to 4.
EXAMPLE = [[], [], [], [], [], [0, 1], [1, 2], [2, 3], [5, 6], [6, 7], [8, 9, 4]]


def is_cut(fanins, v, s) -> bool:
    if v in s:
        return True
    seen, stack = set(), [v]
    while stack:
        w = stack.pop()
        if w in seen or w in s:
            continue
        seen.add(w)
        if not fanins[w]:
            return False
        stack.extend(fanins[w])
    return True


def cone(fanins, v) -> set:
    out, stack = set(), [v]
    while stack:
        w = stack.pop()
        if w not in out:
            out.add(w)
            stack.extend(fanins[w])
    return out


def all_lut_cuts(fanins, v, k) -> list:
    """Every set of at most k nodes, without v, that cuts v from the inputs."""
    nodes = sorted(cone(fanins, v) - {v})
    return [frozenset(c) for size in range(1, k + 1) for c in combinations(nodes, size)
            if is_cut(fanins, v, frozenset(c))]


def best_depths(fanins, k) -> list:
    """d(v) = least depth of a LUT mapping of v, over every k-feasible cut."""
    d = [0] * len(fanins)
    for v in range(len(fanins)):
        if fanins[v]:
            d[v] = min(1 + max(d[u] for u in c) for c in all_lut_cuts(fanins, v, k))
    return d


def exhaustive_depth(fanins, outputs, k) -> int:
    """Try every choice of one cut for each inner node."""
    inner = [v for v in range(len(fanins)) if fanins[v]]
    choices = [all_lut_cuts(fanins, v, k) for v in inner]
    best = None
    for pick in product(*choices):
        cut = dict(zip(inner, pick))
        memo: dict = {}

        def depth(v):
            if not fanins[v]:
                return 0
            if v not in memo:
                memo[v] = 1 + max(depth(u) for u in cut[v])
            return memo[v]

        dd = max(depth(v) for v in outputs)
        best = dd if best is None else min(best, dd)
    return best


def random_dag(rng, n_in, n_gates, k):
    f = [[] for _ in range(n_in)]
    for v in range(n_in, n_in + n_gates):
        f.append(sorted(rng.sample(range(v), rng.randint(1, min(k, v)))))
    return f


def evaluate(fanins, ops, n_in, m):
    val = [(m >> (n_in - 1 - i)) & 1 for i in range(n_in)]
    for w in range(n_in, len(fanins)):
        val.append(ops[w]([val[u] for u in fanins[w]]))
    return val


def check_function(fanins, ops, n_in, outputs, luts) -> None:
    """The LUT network computes the outputs of the original network."""
    tables = {}
    for v, leaves in luts.items():
        order = sorted(leaves)
        table = {}
        for m in range(1 << n_in):
            val = evaluate(fanins, ops, n_in, m)
            key = tuple(val[u] for u in order)
            assert table.setdefault(key, val[v]) == val[v]  # v is a function of its cut
        tables[v] = (order, table)
    for m in range(1 << n_in):
        val = evaluate(fanins, ops, n_in, m)
        lut_val = {i: val[i] for i in range(n_in)}

        def get(v):
            if v not in lut_val:
                order, table = tables[v]
                lut_val[v] = table[tuple(get(u) for u in order)]
            return lut_val[v]

        for o in outputs:
            assert get(o) == val[o]


OPS = [lambda xs: int(all(xs)), lambda xs: int(any(xs)), lambda xs: sum(xs) & 1,
       lambda xs: 1 - int(all(xs))]


def test_example() -> None:
    label, luts = flowmap(EXAMPLE, [10], 3)
    assert label == [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2]
    assert luts == {10: frozenset([4, 8, 9]), 9: frozenset([1, 2, 3]),
                    8: frozenset([0, 1, 2])}
    assert lut_depth(EXAMPLE, luts, [10]) == 2
    assert label == best_depths(EXAMPLE, 3)


def test_labels_are_optimal_depths() -> None:
    rng = random.Random(5)
    for _ in range(500):
        k = rng.choice([2, 3, 4])
        f = random_dag(rng, rng.randint(1, 6), rng.randint(1, 14), k)
        outs = [len(f) - 1]
        label, luts = flowmap(f, outs, k)
        assert label == best_depths(f, k)
        assert lut_depth(f, luts, outs) == max(label[o] for o in outs)
        assert all(len(c) <= k for c in luts.values())


def test_against_all_mappings() -> None:
    rng = random.Random(9)
    done = 0
    while done < 40:
        k = 3
        f = random_dag(rng, rng.randint(2, 4), rng.randint(3, 8), k)
        inner = [v for v in range(len(f)) if f[v]]
        size = 1
        for v in inner:
            size *= len(all_lut_cuts(f, v, k))
        if size > 20000 or size < 20:
            continue
        outs = sorted(set([len(f) - 1, rng.randrange(len(f))]))
        outs = [o for o in outs if f[o]] or [len(f) - 1]
        _, luts = flowmap(f, outs, k)
        assert lut_depth(f, luts, outs) == exhaustive_depth(f, outs, k)
        done += 1


def test_function_is_kept() -> None:
    rng = random.Random(13)
    for _ in range(80):
        k = rng.choice([2, 3])
        n_in = rng.randint(2, 5)
        f = random_dag(rng, n_in, rng.randint(1, 10), k)
        ops = [None] * n_in + [rng.choice(OPS) for _ in range(len(f) - n_in)]
        outs = sorted(set(rng.sample(range(n_in, len(f)), min(2, len(f) - n_in))))
        _, luts = flowmap(f, outs, k)
        check_function(f, ops, n_in, outs, luts)


def test_rejects_unbounded() -> None:
    try:
        flowmap([[], [], [], [0, 1, 2]], [3], 2)
    except ValueError:
        return
    raise AssertionError("a node with 3 fanins must be rejected for k = 2")

History

Early LUT mappers, such as Chortle and its depth version by Francis, Rose and their coauthors around 1990 and 1991, worked on trees, where dynamic programming is optimal, and handled general networks by splitting them into trees. Cong and Ding (1992, at ICCAD, and 1994, in IEEE TCAD) showed that depth-optimal mapping of a general KK-bounded network takes polynomial time, with labels and a max-flow test, and called the method FlowMap. In the same year, Farrahi and Sarrafzadeh (1994) proved that minimizing the number of LUTs is NP-hard, which set the line between the two goals. FlowMap and its labels became the base of many later mappers, and the cut-based mappers of the late 1990s and 2000s compute the same labels by dynamic programming over enumerated cuts.

References

  1. FlowMap, an optimal technology mapping algorithm for delay optimization in lookup-table based FPGA designs, the labeling phase, the network with t and the nodes of label p merged, the node-split flow network, the O(K m n) bound, and the proof of depth optimality for K-bounded networks
  2. An optimal technology mapping algorithm for delay optimization in lookup-table based FPGA designs, the conference version of the algorithm (general locator)
  3. Complexity of the lookup-table minimization problem for FPGA technology mapping, the NP-completeness of LUT mapping with the fewest LUTs, the contrast with depth (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.worst
  • a full proof of space.extra
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