Algorithm Search⌘K

Algorithmadvanced

CutMap

Also called Cong-Hwang CutMap.

Cong and Hwang's LUT mapper that keeps FlowMap's optimal depth and cuts area by choosing cuts that reuse already chosen LUT roots off the critical path.

Time
O(n c^d K) cut enumerationO(n c K) labels and mapping
Space
O(n c K) total
Where
K = the number of LUT inputs; c = the largest number of K-feasible cuts of a gate; d = the largest fanin of a gate; n = the number of gates
Properties
deterministicnot exactiterative
Origin
Jason Cong, Yean Yow Hwang, 1995

CutMap is an algorithm for LUT mapping, a step of FPGA CAD: it maps a network of gates into KK-input lookup tables (LUTs) with the least possible depth, the same depth that FlowMap gets, and tries to use fewer LUTs than FlowMap does. FlowMap gives each LUT root a cut of least height. CutMap only needs a cut whose height meets a required time, and among those cuts it takes the one of least cost, where a node that is already a LUT output costs nothing. Cong and Hwang gave it at FPGA 1995 and reported about 15% fewer LUTs than FlowMap at the same depth.

In plain words

A LUT mapper picks, for each signal that must come out of a LUT, a set of at most KK signals to feed that LUT. FlowMap always picks the set that is as early as possible, so every LUT is as fast as it can be. That is more than needed: only the LUTs on the longest path must be that fast. CutMap first finds the best depth DD, then works backward from the outputs and tells each LUT how late its inputs may arrive. Among the input sets that meet that deadline, it picks the one that makes the fewest new LUTs, which usually means it reuses signals that are already LUT outputs.

The problem

Input. A KK-bounded Boolean network, a directed acyclic graph of gates with at most KK fanins each, a set of output gates, and an integer K≥2K \ge 2.

Output. A LUT mapping: a set of LUT roots, which includes every output gate, and for each root vv a KK-feasible cut CvC_v of vv (a set of at most KK nodes, not containing vv, that meets every path from a primary input to vv). Every gate in a cut is a LUT root too. The LUT of vv computes vv as a function of CvC_v.

Goal. Under the unit delay model the depth of the mapping is the largest number of LUTs on a path from an input to an output. The goal is the fewest LUTs among mappings of least depth DD. Finding that is NP-hard in general (Chen and Cong cite this for area mapping), so CutMap is a heuristic for the count. The depth part is exact.

The algorithm

CutMap first computes the FlowMap label ℓ(v)\ell(v) of every node: ℓ(v)=0\ell(v) = 0 for a primary input, and for a gate ℓ(v)=1+min⁡Cmax⁡u∈Cℓ(u)\ell(v) = 1 + \min_C \max_{u \in C} \ell(u) over the KK-feasible cuts CC of vv. The height of a cut is max⁡u∈Cℓ(u)\max_{u \in C} \ell(u). The optimal depth is D=max⁡oℓ(o)D = \max_o \ell(o) over the outputs. Then the mapping phase below runs. The cost of a cut is the number of its gates that are not yet LUT roots, because each of them makes a new LUT.

  1. CUTMAP-MAP(N, outputs, K, D)
  2. 1r(o) ← D for each output o; roots ← outputs
  3. 2for each gate v in reverse topological order, skipping v if it is not in roots:
  4. 3b ← r(v) − 1
  5. 4F ← the K-feasible cuts C of v with max over u in C of ℓ(u) ≤ b
  6. 5C* ← the cut in F of least cost (ties: fewer nodes, then lower height)
  7. 6the LUT of v is C*
  8. 7for each node u in C*:
  9. 8if u is a gate then add u to roots
  10. 9r(u) ← min(r(u), r(v) − 1) ▷ r(u) is D when not yet set
  11. 10return the LUTs

Line L4 is where CutMap differs from FlowMap. FlowMap keeps only cuts of height exactly ℓ(v)−1\ell(v) - 1. CutMap keeps every cut of height up to r(v)−1r(v) - 1, and on a node off the critical path r(v)r(v) is larger than ℓ(v)\ell(v), so there are more cuts to choose from. On the critical path r(v)=ℓ(v)r(v) = \ell(v) and the choice is the same as in FlowMap, except that CutMap still picks the cheapest of the least-height cuts.

The implementation finds all KK-feasible cuts by cut enumeration and computes the labels from them. The paper instead finds the least-cost cut of bounded height by a max-flow computation on a network with node costs, as FlowMap does for the labels, and uses a pruning theorem to make that fast. Both give a cut of least cost under the same height bound. The paper also starts with a guess of the nodes that will be LUT roots (for example the roots of large fanout-free cones) and gives them a low cost from the start; the implementation does not, so its costs come only from roots that are already chosen.

Example

Take K=3K = 3 and the network g0=c⊕bg_0 = c \oplus b, g1=d∨bg_1 = d \lor b, g2=g1∨g0g_2 = g_1 \lor g_0, g3=g2⊕ag_3 = g_2 \oplus a, with output g3g_3.

The labels are ℓ(g0)=ℓ(g1)=1\ell(g_0) = \ell(g_1) = 1, since their fanins are inputs. ℓ(g2)=1\ell(g_2) = 1, since the cut {b,c,d}\{b, c, d\} has height 0. The 3-feasible cuts of g3g_3 are {a,g2}\{a, g_2\} and {a,g0,g1}\{a, g_0, g_1\}, because every cut that reaches the inputs has the 4 inputs a,b,c,da, b, c, d. Both have height 1, so ℓ(g3)=2\ell(g_3) = 2 and D=2D = 2.

step content
line L1 r(g3)=2r(g_3) = 2, roots ={g3}= \{g_3\}
v=g3v = g_3, L3 to L4 b=1b = 1; both cuts have height 1, so F={{a,g2},{a,g0,g1}}F = \{\{a, g_2\}, \{a, g_0, g_1\}\}
L5 {a,g2}\{a, g_2\} makes one new root, {a,g0,g1}\{a, g_0, g_1\} makes two; C∗={a,g2}C^* = \{a, g_2\}
L7 to L9 g2g_2 is a root with r(g2)=1r(g_2) = 1
v=g2v = g_2, L3 to L5 b=0b = 0; only {b,c,d}\{b, c, d\} has height 0, so it is the LUT of g2g_2
L10 2 LUTs: g3g_3 over {a,g2}\{a, g_2\} and g2g_2 over {b,c,d}\{b, c, d\}; depth 2

FlowMap's mapping phase at g3g_3 takes a cut of height 1 that covers the most gates, which is {a,g0,g1}\{a, g_0, g_1\}, because it puts both g2g_2 and g3g_3 in one LUT. Then g0g_0 and g1g_1 need their own LUTs, and the result has 3 LUTs. A brute force over all cut choices confirms that 2 is the least count at depth 2. The test file checks this example.

Correctness

The full proof shows that the result is a valid mapping that computes the same outputs, and that its depth is exactly DD. The key step is the invariant ℓ(u)≤r(u)\ell(u) \le r(u) for every root uu. It holds at the outputs because DD is the largest output label. At a root vv, the definition of ℓ(v)\ell(v) gives a cut of height ℓ(v)−1≤r(v)−1\ell(v) - 1 \le r(v) - 1, so the set FF of line L4 is never empty. Every node of the chosen cut has label at most r(v)−1r(v) - 1, so line L9 keeps the invariant. Then by induction in topological order, the LUT of a root uu has depth at most r(u)r(u), and every output has depth at most DD. That no mapping has depth below DD is FlowMap's theorem that ℓ(v)\ell(v) is the least depth of vv; this page cites it from FlowMap and does not prove it again.

Proof: CutMap returns a valid LUT mapping with the same outputs and the least possible depthfull

We use the notation of the page. NN is a KK-bounded network, a directed acyclic graph whose sources are the primary inputs (PIs). A cut of a gate vv is a set CC of nodes with v∉Cv \notin C that meets every path from a PI to vv. It is KK-feasible if ∣C∣≤K|C| \le K. The cone of vv over CC is the set of nodes ww with a path from ww to vv that has no node of CC (including vv and excluding CC). The label ℓ\ell is as on the page, and D=max⁡oℓ(o)D = \max_o \ell(o).

Lemma 1 (the cut lists). For every gate vv, every set in the list of vv made by cut enumeration is a KK-feasible cut of vv, and every minimal KK-feasible cut of vv is in the list.

Proof. By induction in topological order. Every set in the list is a union over the fanins ff of vv of either {f}\{f\} or a set from the list of ff, and has at most KK nodes. A path from a PI to vv passes a fanin ff last. If {f}\{f\} was taken, the path meets it. Otherwise it meets the cut of ff, by induction. So the union is a cut of vv.

Now let CC be a minimal cut of vv with ∣C∣≤K|C| \le K. For a fanin ff in CC take {f}\{f\}. A fanin ff that is a PI is in CC, because the path f,vf, v must meet CC and v∉Cv \notin C. For a gate fanin f∉Cf \notin C, every path from a PI to ff extends to a path to vv, which meets CC at a node before vv, so C∩(nodes with a path to f)C \cap (\text{nodes with a path to } f) is a cut of ff. It contains a minimal cut CfC_f of ff with ∣Cf∣≤K|C_f| \le K, which is in the list of ff by induction. The union UU of the chosen sets is a subset of CC and a cut of vv by the first part, so U=CU = C by the minimality of CC. The enumeration made UU, and it is not removed as dominated, because no strict subset of CC is a cut of vv. □\square

Lemma 2 (labels). The labels computed from the lists equal 1+min⁡Cmax⁡u∈Cℓ(u)1 + \min_C \max_{u \in C} \ell(u) over all KK-feasible cuts CC of vv.

Proof. Each listed set is a KK-feasible cut (Lemma 1), so the computed minimum is at least the true one. A cut CC that reaches the true minimum contains a minimal cut C′⊆CC' \subseteq C, with ∣C′∣≤K|C'| \le K and max⁡C′ℓ≤max⁡Cℓ\max_{C'} \ell \le \max_C \ell, and C′C' is in the list. So the computed minimum is at most the true one. □\square

Lemma 3 (order). Every root is visited once at line L2, and when it is visited, its value r(u)r(u) does not change again.

Proof. A gate uu becomes a root at line L8 when it is in the cut of a root vv. A node of a cut of vv has a path to vv, so it comes before vv in topological order, and after vv in the reverse order of line L2. So the loop reaches uu after it was added. The value r(u)r(u) changes only at line L9 while some root vv with u∈Cvu \in C_v is visited, and every such vv comes before uu in the reverse order. □\square

Lemma 4 (invariant). For every root uu, ℓ(u)≤r(u)\ell(u) \le r(u) at all times after r(u)r(u) is first set, and the set FF of line L4 is never empty.

Proof. At line L1, r(o)=D≥ℓ(o)r(o) = D \ge \ell(o) for each output. Let vv be the root visited at line L2, with ℓ(v)≤r(v)\ell(v) \le r(v). By Lemma 2 there is a listed cut of height ℓ(v)−1≤r(v)−1=b\ell(v) - 1 \le r(v) - 1 = b, so FF is not empty. Every node uu of the chosen cut C∗C^* has ℓ(u)≤b=r(v)−1\ell(u) \le b = r(v) - 1. Every value of rr is at most DD, by line L1 and line L9. If r(u)r(u) was not set, line L9 sets it to min⁡(D,r(v)−1)=r(v)−1≥ℓ(u)\min(D, r(v) - 1) = r(v) - 1 \ge \ell(u). If r(u)r(u) was set, then ℓ(u)≤r(u)\ell(u) \le r(u) already, and the minimum of two values that are both at least ℓ(u)\ell(u) is at least ℓ(u)\ell(u). □\square

Theorem 5 (valid mapping, same function). Every LUT has at most KK inputs, every gate input of a LUT is a root with its own LUT, and the LUT network computes the same value as NN at every root, for every input vector.

Proof. The cut of each LUT is in a list, so it has at most KK nodes. Every gate of C∗C^* becomes a root at line L8, and it gets its LUT when it is visited (Lemma 3, Lemma 4). The LUT of vv evaluates the gates of the cone of vv over C∗C^*, reading the values of the nodes of C∗C^*. This is well defined: a node of the cone that is a PI would give a path from a PI to vv that misses C∗C^*, which is not possible because C∗C^* is a cut. By induction in topological order over the roots, each node of C∗C^* is a PI or a root whose LUT gives the value of the node in NN, so the LUT of vv gives the value of vv in NN. □\square

Theorem 6 (depth). The LUT depth of every root uu is at most r(u)r(u). In particular, every output has depth at most DD.

Proof. By induction in topological order. The depth of a root vv is 1+max⁡u∈C∗depth(u)1 + \max_{u \in C^*} \mathrm{depth}(u), where a PI has depth 0. A gate u∈C∗u \in C^* has r(u)≤r(v)−1r(u) \le r(v) - 1 after line L9, and this value is final when the depth of uu is fixed (Lemma 3), so depth(u)≤r(u)≤r(v)−1\mathrm{depth}(u) \le r(u) \le r(v) - 1 by induction. A PI has depth 0≤r(v)−10 \le r(v) - 1, because r(v)≥ℓ(v)≥1r(v) \ge \ell(v) \ge 1 by Lemma 4. So depth(v)≤r(v)\mathrm{depth}(v) \le r(v). □\square

Theorem 7 (optimal depth, cited). No KK-LUT mapping of NN has depth below DD, so the depth of CutMap is exactly DD.

Proof. Cong and Ding proved for FlowMap that the label ℓ(v)\ell(v) is the least depth of a LUT that computes vv in any KK-LUT mapping of a KK-bounded network. The proof is on the FlowMap page and is not repeated here. With Lemma 2, the labels used by CutMap are those labels. So every mapping has an output of depth at least DD, and with Theorem 6 the depth of CutMap is exactly DD. □\square

Relaxed bound. If the caller gives a bound D′≥DD' \ge D, line L1 sets r(o)=D′r(o) = D' and the proofs of Lemma 4 and Theorem 6 go through with D′D' in place of DD, so the depth is at most D′D'.

What is not proved. Nothing here says that the number of LUTs is least. The choice at line L5 is greedy, and the page reports measured counts only. The reduction against FlowMap (15% in the abstract of Cong and Hwang 1995, 13% in the survey of Cong and Ding 1996, Section 5.4) is measured by those authors, not proved.

Complexity

Let cc be the largest number of KK-feasible cuts of a gate and d≤Kd \le K the largest fanin. Cut enumeration takes, at each gate, the product of the cut lists of its fanins, so it costs O(cdK)O(c^d K) per gate and O(ncdK)O(n c^d K) in total, before the removal of dominated cuts. The labels cost O(cK)O(c K) per gate. The mapping phase visits each root once, filters its cuts at line L4 and computes their costs at line L5 in O(cK)O(c K) time, so it costs O(ncK)O(n c K). The space is O(ncK)O(n c K) for the cut lists. For a fixed KK, cc is at most O(nK)O(n^K), but on real circuits it is much smaller. The flow-based version of the paper does not list cuts; Chen and Cong (2004) give its worst case as O(2Kmn⌊K/2⌋+1)O(2^K m n^{\lfloor K/2 \rfloor + 1}) with mm edges, and the survey of Cong and Ding says the pruning theorem makes it much faster in practice.

Properties

What is proved. The mapping is valid, computes the same outputs, and has depth DD, the least possible depth (the last step by FlowMap's label theorem, cited by link). If a larger depth bound D′≥DD' \ge D is given, the same proof shows the depth is at most D′D'.

What is cited. Cong and Hwang (1995) reported fewer LUTs than FlowMap with the same depth on MCNC benchmarks. The abstract of the paper gives 15% fewer LUTs; the survey of Cong and Ding (1996, Section 5.4) states the average as a 13% area reduction. The two numbers may come from different benchmark sets or settings; this page does not decide between them. Chen and Cong (2004) report that DAOmap uses 16.02% fewer LUTs than CutMap with 5-input LUTs on the 20 largest MCNC benchmarks.

What is measured. The tests compare the LUT count with an exhaustive search over every cut choice at depth DD, on 200 random networks of 3 to 7 two-input gates with K=3K = 3 (seed 5). CutMap reaches the least count on all 200, and uses fewer LUTs than the FlowMap mapping phase on 1 of them. On another 400 networks (seed 0), it reaches the least count on 399, uses fewer LUTs than FlowMap on 3 and more on 1. These are tiny networks; they show that the greedy choice is often right, not that it is optimal.

Not optimal for the count. The choice at each root is greedy in reverse topological order. A cut that is cheap now can force more LUTs below, and the cost does not see that.

Variants and improvements

  • Area recovery with relaxed depth. If the depth bound is set above DD, more cuts pass line L4 and the count can drop. The implementation takes the bound as a parameter.
  • FlowMap-r (Cong and Ding) starts from the FlowMap mapping and improves it afterward by remapping and relaxing the depth of non-critical nodes, instead of choosing the cuts with costs from the start.
  • DAOmap (Chen and Cong, 2004) enumerates cuts, gives them an area-flow cost that counts the duplication of nodes, and repeats the cut selection several times. It reports 16.02% fewer LUTs than CutMap and is 24.2 times faster.
  • Priority cuts keep only a few cuts per node, so that cut-based depth and area mapping scales to large networks.

When to use it

Use CutMap when the depth of the LUT network must be the least possible and the LUT count should be small. Its idea, a required time from the optimal depth and a cheap cut under that bound, is the same as the slack used in static timing analysis and the critical path method, and it is the base of most later depth-optimal area mappers. For new tools, DAOmap and priority cuts give better counts at the same depth.

Pitfalls

  • Using the label as the bound. If line L4 uses ℓ(v)−1\ell(v) - 1 in place of r(v)−1r(v) - 1, the algorithm is FlowMap with a tie-break and loses most of the gain.
  • Order of the roots. A root must be processed after every root that reads it, so that r(u)r(u) is final. Reverse topological order does this. An order by label alone can fail, because a node and a node in its cut can have the same label.
  • The required time of a shared node. A node read by several LUTs takes the least of their bounds at line L9. Overwriting it with the last bound can break the depth.
  • Dominated cuts. Keep only cuts that are not strict supersets of another cut. A superset never has a smaller cost or height, and it makes the cut lists larger.
  • A cost without reuse. A cost that counts only the size of the cut, without asking whether a node is already a root, gives no reuse and little gain over FlowMap.

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.

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

"""CutMap: depth-optimal LUT mapping with fewer LUTs.

A network is a dict that maps a gate name to (op, fanins). op is one of
"AND", "OR", "XOR", "NAND", "NOR", "XNOR", "NOT", "BUF". A signal that is not
a gate is a primary input. Every gate input is a signal name.

The FlowMap labels are computed from all K-feasible cuts (found by cut
enumeration, not by max-flow). Then the outputs are given the required time
D, the optimal depth, and the gates are visited in reverse topological order.
Each gate that must be a LUT root takes the K-feasible cut of least cost
among the cuts whose nodes all have label at most r(v) - 1. A cut node costs
0 if it is a primary input or already a LUT root, and 1 otherwise, so the
cost counts the new LUT roots that the cut makes.
"""

from itertools import product

GATE_OPS = {"AND", "OR", "XOR", "NAND", "NOR", "XNOR", "NOT", "BUF"}


def gate_value(op: str, vals: list) -> int:
    if op in ("AND", "NAND"):
        r = int(all(vals))
    elif op in ("OR", "NOR"):
        r = int(any(vals))
    elif op in ("XOR", "XNOR"):
        r = sum(vals) % 2
    elif op in ("BUF", "NOT"):
        r = vals[0]
    else:
        raise ValueError(op)
    return 1 - r if op in ("NAND", "NOR", "XNOR", "NOT") else r


def topo_order(net: dict) -> list:
    order, state = [], {}

    def visit(s):
        if s not in net or state.get(s) == 2:
            return
        if state.get(s) == 1:
            raise ValueError("the network has a cycle")
        state[s] = 1
        for f in net[s][1]:
            visit(f)
        state[s] = 2
        order.append(s)

    for g in sorted(net):
        visit(g)
    return order


def primary_inputs(net: dict) -> list:
    return sorted({f for _, (_, fanins) in net.items() for f in fanins if f not in net})


def enumerate_cuts(net: dict, k: int) -> dict:
    """For each gate, the list of its K-feasible cuts, not counting the
    trivial cut {v}. Dominated cuts (strict supersets of another) are kept
    out."""
    cuts = {}
    for p in primary_inputs(net):
        cuts[p] = [frozenset([p])]
    for g in topo_order(net):
        fanin_choices = []
        for f in net[g][1]:
            opts = [frozenset([f])]
            if f in net:
                opts = opts + cuts[f]
            fanin_choices.append(opts)
        found = set()
        for combo in product(*fanin_choices):
            c = frozenset().union(*combo)
            if len(c) <= k:
                found.add(c)
        minimal = [c for c in found if not any(o < c for o in found)]
        cuts[g] = sorted(minimal, key=lambda c: (len(c), sorted(c)))
    return cuts


def flowmap_labels(net: dict, cuts: dict) -> dict:
    """l(PI) = 0 and l(v) = 1 + min over cuts C of v of max l(u), u in C."""
    label = {p: 0 for p in primary_inputs(net)}
    for g in topo_order(net):
        label[g] = min(1 + max(label[u] for u in c) for c in cuts[g])
    return label


def cutmap(net: dict, outputs: list, k: int, depth=None):
    """Returns (luts, depth) where luts maps a root gate to its cut."""
    for g, (op, fanins) in net.items():
        if op not in GATE_OPS or not fanins or len(fanins) > k:
            raise ValueError(f"gate {g} is not K-bounded or has a bad op")
    cuts = enumerate_cuts(net, k)
    label = flowmap_labels(net, cuts)
    gate_outs = [o for o in outputs if o in net]
    d_opt = max((label[o] for o in gate_outs), default=0)
    d = d_opt if depth is None else depth
    if d < d_opt:
        raise ValueError("the depth bound is below the optimal depth")
    required = {o: d for o in gate_outs}  # @line L1
    roots = set(gate_outs)
    luts = {}
    for v in reversed(topo_order(net)):  # @line L2
        if v not in roots:
            continue
        bound = required[v] - 1  # @line L3
        feasible = [c for c in cuts[v] if max(label[u] for u in c) <= bound]  # @line L4

        def cost(c):
            new = sum(1 for u in c if u in net and u not in roots)
            return (new, len(c), max(label[u] for u in c), sorted(c))

        best = min(feasible, key=cost)  # @line L5
        luts[v] = best  # @line L6
        for u in best:  # @line L7
            if u in net:
                roots.add(u)  # @line L8
                required[u] = min(required.get(u, d), required[v] - 1)  # @line L9
    return luts, d  # @line L10


def lut_value(net: dict, root: str, cut, values: dict) -> int:
    memo = {}

    def ev(s):
        if s in cut or s not in net:
            return values[s]
        if s not in memo:
            op, fanins = net[s]
            memo[s] = gate_value(op, [ev(f) for f in fanins])
        return memo[s]

    return ev(root)


def eval_network(net: dict, outputs: list, values: dict) -> dict:
    memo = dict(values)

    def ev(s):
        if s not in memo:
            op, fanins = net[s]
            memo[s] = gate_value(op, [ev(f) for f in fanins])
        return memo[s]

    return {o: ev(o) for o in outputs}


def eval_luts(net: dict, luts: dict, outputs: list, values: dict) -> dict:
    memo = dict(values)

    def ev(s):
        if s not in memo:
            cut = luts[s]
            memo[s] = lut_value(net, s, cut, {u: ev(u) for u in cut})
        return memo[s]

    return {o: ev(o) for o in outputs}


def lut_depth(net: dict, luts: dict, outputs: list) -> int:
    memo = {}

    def dep(s):
        if s not in net:
            return 0
        if s not in memo:
            memo[s] = 1 + max(dep(u) for u in luts[s])
        return memo[s]

    return max((dep(o) for o in outputs), default=0)


def equivalent(net: dict, luts: dict, outputs: list) -> bool:
    pis = primary_inputs(net)
    for bits in product((0, 1), repeat=len(pis)):
        values = dict(zip(pis, bits))
        if eval_network(net, outputs, values) != eval_luts(net, luts, outputs, values):
            return False
    return True


if __name__ == "__main__":
    from_page = {
        "g0": ("XOR", ["c", "b"]),
        "g1": ("OR", ["d", "b"]),
        "g2": ("OR", ["g1", "g0"]),
        "g3": ("XOR", ["g2", "a"]),
    }
    luts, d = cutmap(from_page, ["g3"], 3)
    print(d, {v: sorted(c) for v, c in luts.items()})
test_cutmap.py 191 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cutmap/. The authors are listed in prov/7KTJSE.jsonl.

import random
from itertools import combinations

from cutmap import (
    cutmap,
    enumerate_cuts,
    equivalent,
    flowmap_labels,
    lut_depth,
    primary_inputs,
    topo_order,
)

PAGE_NET = {
    "g0": ("XOR", ["c", "b"]),
    "g1": ("OR", ["d", "b"]),
    "g2": ("OR", ["g1", "g0"]),
    "g3": ("XOR", ["g2", "a"]),
}


def random_net(rng: random.Random, n_in: int, n_gates: int, fanin: int) -> tuple[dict, list]:
    net = {}
    signals = [f"x{i}" for i in range(n_in)]
    for i in range(n_gates):
        g = f"g{i}"
        d = rng.randint(2, min(fanin, len(signals)))
        net[g] = (rng.choice(["AND", "OR", "XOR", "NAND"]), rng.sample(signals, d))
        signals.append(g)
    read = {f for _, fs in net.values() for f in fs}
    outs = [g for g in net if g not in read]
    return net, outs


def brute_cuts(net: dict, v: str, k: int) -> list:
    """Minimal K-feasible cuts of v, found by testing every small node set."""
    cone, stack = set(), [v]
    while stack:
        s = stack.pop()
        if s in net:
            for f in net[s][1]:
                if f not in cone:
                    cone.add(f)
                    stack.append(f)

    def is_cut(c):
        # every path from a primary input to v meets c
        seen, stack = set(), [v]
        while stack:
            s = stack.pop()
            if s in c:
                continue
            if s not in net:
                return False
            for f in net[s][1]:
                if f not in seen:
                    seen.add(f)
                    stack.append(f)
        return True

    found = [frozenset(c) for r in range(1, k + 1) for c in combinations(sorted(cone), r) if is_cut(set(c))]
    return [c for c in found if not any(o < c for o in found)]


def brute_labels(net: dict, k: int) -> dict:
    label = {p: 0 for p in primary_inputs(net)}
    for g in topo_order(net):
        label[g] = min(1 + max(label[u] for u in c) for c in brute_cuts(net, g, k))
    return label


def brute_min_luts(net: dict, outputs: list, k: int, depth: int) -> int:
    """The fewest LUTs of a mapping with depth at most `depth`, by trying
    every choice of a minimal cut at every LUT root."""
    label = brute_labels(net, k)
    cuts = {g: brute_cuts(net, g, k) for g in net}
    order = list(reversed(topo_order(net)))
    best = [10**9]

    def search(i, roots, required):
        if len(roots) >= best[0]:
            return
        while i < len(order) and order[i] not in roots:
            i += 1
        if i == len(order):
            best[0] = len(roots)
            return
        v = order[i]
        for c in cuts[v]:
            if max(label[u] for u in c) > required[v] - 1:
                continue
            new_roots = set(roots)
            new_req = dict(required)
            for u in c:
                if u in net:
                    new_roots.add(u)
                    new_req[u] = min(new_req.get(u, depth), required[v] - 1)
            search(i + 1, new_roots, new_req)

    gate_outs = [o for o in outputs if o in net]
    search(0, set(gate_outs), {o: depth for o in gate_outs})
    return best[0]


def flowmap_count(net: dict, outputs: list, k: int) -> int:
    """FlowMap's mapping phase: each root takes a least-height cut, and among
    those the one that covers the most gates."""
    cuts = enumerate_cuts(net, k)
    label = flowmap_labels(net, cuts)

    def volume(v, c):
        seen, stack = set(), [v]
        while stack:
            s = stack.pop()
            if s in c or s in seen or s not in net:
                continue
            seen.add(s)
            stack.extend(net[s][1])
        return len(seen)

    roots, stack = set(), [o for o in outputs if o in net]
    while stack:
        v = stack.pop()
        if v in roots:
            continue
        roots.add(v)
        h = label[v] - 1
        c = max((c for c in cuts[v] if max(label[u] for u in c) == h), key=lambda c: (volume(v, c), sorted(c)))
        stack.extend(u for u in c if u in net)
    return len(roots)


def test_page_example():
    labels = flowmap_labels(PAGE_NET, enumerate_cuts(PAGE_NET, 3))
    assert [labels[g] for g in ("g0", "g1", "g2", "g3")] == [1, 1, 1, 2]
    luts, d = cutmap(PAGE_NET, ["g3"], 3)
    assert d == 2
    assert {v: sorted(c) for v, c in luts.items()} == {"g3": ["a", "g2"], "g2": ["b", "c", "d"]}
    assert equivalent(PAGE_NET, luts, ["g3"])
    assert lut_depth(PAGE_NET, luts, ["g3"]) == 2
    assert brute_min_luts(PAGE_NET, ["g3"], 3, 2) == 2
    assert flowmap_count(PAGE_NET, ["g3"], 3) == 3


def test_labels_match_brute_force():
    rng = random.Random(11)
    for _ in range(40):
        net, outs = random_net(rng, rng.randint(2, 5), rng.randint(2, 7), 3)
        for k in (3, 4):
            assert flowmap_labels(net, enumerate_cuts(net, k)) == brute_labels(net, k)


def test_depth_optimal_and_equivalent():
    rng = random.Random(1995)
    for _ in range(200):
        net, outs = random_net(rng, rng.randint(2, 5), rng.randint(2, 8), 3)
        for k in (3, 4):
            luts, d = cutmap(net, outs, k)
            label = brute_labels(net, k)
            assert d == max(label[o] for o in outs)
            assert lut_depth(net, luts, outs) == d
            assert equivalent(net, luts, outs)
            for v, c in luts.items():
                assert len(c) <= k


def test_area_against_exhaustive():
    rng = random.Random(5)
    equal = 0
    total = 0
    for _ in range(200):
        net, outs = random_net(rng, rng.randint(3, 5), rng.randint(3, 7), 2)
        luts, d = cutmap(net, outs, 3)
        opt = brute_min_luts(net, outs, 3, d)
        assert len(luts) >= opt
        total += 1
        equal += len(luts) == opt
    assert equal >= total // 2


def test_relaxed_depth():
    rng = random.Random(3)
    for _ in range(20):
        net, outs = random_net(rng, 4, 6, 2)
        luts, d = cutmap(net, outs, 3)
        luts2, d2 = cutmap(net, outs, 3, depth=d + 1)
        assert lut_depth(net, luts2, outs) <= d + 1
        assert equivalent(net, luts2, outs)

History

Cong and Ding gave FlowMap in 1992, and it found the least depth in polynomial time, but it used more LUTs than area mappers such as Chortle-crf. FlowMap-r improved the count by changes after the mapping. In 1995, Cong and Hwang presented CutMap at the FPGA symposium. It put the area cost into the cut computation itself and used the depth bound only where it is needed. It was part of the RASP synthesis system of UCLA and became the standard depth-optimal area mapper in academic work, until later cut-based mappers such as DAOmap (2004) and the priority cuts of ABC gave better counts.

References

  1. Jason Cong and Yean-Yow Hwang, Simultaneous depth and area minimization in LUT-based FPGA mapping, Proceedings of the 3rd ACM International Symposium on Field-Programmable Gate Arrays (FPGA 1995), Monterey, pages 68 to 74, the least-cost cut of bounded height, the required times from the optimal depth, the node costs that favor existing LUT roots, and the comparison with FlowMap on MCNC benchmarks, 15% fewer LUTs in the abstract (general locator for the body)
  2. Jason Cong and Yuzheng Ding, Combinational logic synthesis for LUT based field programmable gate arrays, ACM Transactions on Design Automation of Electronic Systems 1(2), 145 to 204, 1996, Section 4.3.2 (the cost of a cut as the sum of node costs, low cost for nodes that are or will be LUT roots, the pruning theorem) and Section 5.4 (13% fewer LUTs than FlowMap)
  3. Deming Chen and Jason Cong, DAOmap, a depth-optimal area optimization mapping algorithm for FPGA designs, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design (ICCAD 2004), pages 752 to 759, Section 1 (CutMap computes min-cost min-height cuts for critical nodes and min-cost cuts for non-critical nodes) and Table 1 (DAOmap against CutMap on the 20 largest MCNC benchmarks)

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.cut enumeration
  • a full proof of time.labels and mapping
  • 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