Algorithm Search⌘K

Algorithmadvanced

Priority cuts mapping

Also called priority cuts.

Mishchenko and coauthors' LUT mapper that keeps only a few best cuts per node, ranked by depth, area flow and exact area, so that cut-based mapping stays fast for large k.

Time
O(N k C^4 + N^2 C^2) worst
Space
O(N k C) extra
Where
C = the number of cuts kept per node; N = the number of nodes; k = the number of inputs of a LUT
Properties
deterministicnot exactofflineiterative
Origin
Alan Mishchenko, Sungmin Cho, Satrajit Chatterjee, Robert Brayton, 2007

Priority cuts mapping is a method for LUT mapping that does not list all kk-feasible cuts of each node. Each node keeps at most CC cuts, its priority cuts, and the cuts of a node are made by merging only the priority cuts of its fanins. A mapping pass visits the nodes in topological order, makes the candidate cuts of a node, sorts them by the cost of the pass and keeps the first CC, with the first as the best cut. The first pass sorts by depth. Later passes sort by area flow and by exact area, and they keep every node within the required time from the first pass, so the depth found in the first pass does not grow. Mishchenko, Cho, Chatterjee and Brayton (2007) used a small CC and reported that, on their benchmarks, this costs little depth or area while making mapping with 6-input cuts much faster. It is the base of the if LUT mapper of ABC. With CC unlimited the first pass is the exact depth dynamic program. With a small CC it is a heuristic and has no proved bound on the loss.

In plain words

To map a circuit into lookup tables, a mapper must choose, for each gate, a small group of wires that decides the gate. There are many such groups, and listing all of them takes too long when each table has six inputs.

So keep only a few good groups for each gate, say eight. Build the groups of a gate only from the kept groups of the gates that feed it. Rank them, keep the best few, and move on. First rank them by how deep the result is, to find the shortest chain of tables. Then go over the circuit again and rank by how many tables they need, but never let a gate get later than the first pass allows. The kept groups change from pass to pass.

The problem

The input is a kk-bounded network, for example an and-inverter graph, with NN nodes in topological order and a set of outputs, and the LUT size kk. The output is a mapping: for each needed gate a kk-feasible cut, whose LUT computes the gate. The goal is the least depth, then the fewest LUTs at that depth. Least depth alone is solved exactly by FlowMap, and the fewest LUTs is NP-hard, so the second goal is only approached.

The pass costs use these terms. The arrival time of a node is the depth of its best cut, 11 plus the largest arrival time of a leaf, with 0 for the inputs. The area flow of a node vv with best cut BB is

AF(v)=1+∑u∈BAF(u)max⁡(1,fanout(v)),AF(v) = \frac{1 + \sum_{u \in B} AF(u)}{\max(1, \mathrm{fanout}(v))},

with 0 for the inputs, an estimate of the LUTs that vv needs, with shared logic split among its fanouts. The exact area of a cut of vv, in the current mapping, is the number of LUTs that using the cut adds: the LUT of vv and the LUTs of its leaves that no other LUT uses yet, found with reference counts. The required time of a node in the mapping is the latest arrival time that keeps every output within the depth DD of the first pass.

The algorithm

  1. PRIORITY-CUTS(G, k, C)
  2. 1for each gate v: P(v) ← ∅; best(v) ← none
  3. 2for each pass in (depth, area flow, exact area) do
  4. 3if the pass is not the depth pass then find the reference counts and the required times of the mapping from best, with D at the outputs
  5. 4for each gate v in topological order do
  6. 5A ← the unions of one set from P(u) ∪ {{u}} for each fanin u, with at most k leaves and without dominated sets
  7. 6if best(v) ≠ none then add best(v) to A
  8. 7if the pass is exact area and v is in the mapping then dereference best(v)
  9. 8sort A by the key of the pass, with every cut whose arrival time is later than the required time of v at the end
  10. 9P(v) ← the first C cuts of A; best(v) ← the first cut of A
  11. 10set the arrival time and the area flow of v from best(v)
  12. 11if the pass is exact area and v is in the mapping then reference best(v)
  13. 12if the pass is the depth pass then D ← the largest arrival time of an output
  14. 13return the LUTs reached from the outputs through best

The keys of line L8 are (arrival time, number of leaves, area flow) in the depth pass, (area flow, arrival time, number of leaves) in the area flow pass and (exact area, area flow, arrival time, number of leaves) in the exact area pass. Ties go to the smaller sorted list of leaves, so the code of this page is deterministic. Line L5 is the merge of cut enumeration, applied to the short lists. Line L6 keeps the best cut of the last pass, which may no longer be a merge of the new priority cuts of the fanins. That cut is what keeps the depth from growing. Dereferencing at line L7 and referencing at line L11 keep the reference counts equal to the number of uses of each node in the current mapping, so that the exact area of line L8 is computed against the mapping without the old cut of vv.

Example

Take k=3k = 3, the inputs a,b,c,da, b, c, d and the gates p=(a,c)p = (a, c), q=(b,p)q = (b, p), r=(d,q)r = (d, q), s=(b,r)s = (b, r) and o=(p,s)o = (p, s), with oo the output. The least depth is 2.

With C=1C = 1, the depth pass keeps one cut per node:

node kept cut arrival
pp {a,c}\{a, c\} 1
qq {a,b,c}\{a, b, c\} 1
rr {d,q}\{d, q\} 2
ss {b,d,q}\{b, d, q\} 2
oo {p,s}\{p, s\} 3

At qq, the cut {a,b,c}\{a, b, c\} has depth 1 and beats {b,p}\{b, p\}, which has depth 2, so {b,p}\{b, p\} is dropped. At rr, the merge of {d}\{d\} with {a,b,c}\{a, b, c\} has 4 leaves, so rr must use qq as a leaf. The pass ends with depth 3 and 4 LUTs, for oo, pp, ss and qq. The area passes keep depth 3 and lower the count to 3 LUTs.

With C=2C = 2, qq keeps {a,b,c}\{a, b, c\} and {b,p}\{b, p\}. Then rr keeps {d,q}\{d, q\} and {b,d,p}\{b, d, p\}, and ss keeps {b,d,p}\{b, d, p\} and {b,d,q}\{b, d, q\}, both of depth 2, with {b,d,p}\{b, d, p\} first because its area flow is lower, 1.5 against 2. At oo, the union of {p}\{p\} and {b,d,p}\{b, d, p\} is {b,d,p}\{b, d, p\}, of depth 2. The mapping has depth 2 and 2 LUTs: oo over {b,d,p}\{b, d, p\} and pp over {a,c}\{a, c\}. The cut that is best at qq alone is not the one that helps at oo, and one more priority cut keeps the useful one.

Correctness

The full proof shows four facts. Every cut that a node keeps is a kk-feasible cut of the node, because it is a union of cuts of the fanins, so every LUT computes its node and the mapping keeps the functions. With CC at least the number of cuts of every node, the depth pass keeps all minimal kk-feasible cuts, by the theorem of cut enumeration, and computes the least depth exactly. The area passes never raise the depth above the depth DD of the first pass: the old best cut of each node in the mapping meets its required time, and it is always a candidate at line L6. The exact area pass never raises the number of LUTs, since the old best cut is a candidate and line L8 prefers a cut with an exact area that is not larger.

Proof: Priority cuts keep the functions, do not lose depth in the area passes, and are exact with unlimited cutsfull

Let GG be a directed acyclic graph whose sources are the primary inputs (PIs), with the gates in topological order and a set of outputs. A cut of vv is a set of nodes that meets every path from a PI to vv, and it is kk-feasible if it has at most kk nodes. Write arr(v)\mathrm{arr}(v) for the arrival time of vv as set at line L10, with arr=0\mathrm{arr} = 0 for a PI, and dep(B)=1+max⁡u∈Barr(u)\mathrm{dep}(B) = 1 + \max_{u \in B} \mathrm{arr}(u) for a cut BB. The mapping is the set of gates reached from the outputs through best: an output gate is in it, and if vv is in it, every gate of best(v)\mathrm{best}(v) is in it.

Lemma 1 (every kept cut is a k-feasible cut). At every moment, every set in P(v)P(v), and best(v)\mathrm{best}(v), is a kk-feasible cut of vv that does not contain vv.

Proof. Induction on the time of the change. When vv is visited, line L5 forms sets c1∪⋯∪cdc_1 \cup \cdots \cup c_d where each cic_i is {ui}\{u_i\} or a set of P(ui)P(u_i) for the fanin uiu_i. Each cic_i is a cut of uiu_i: {ui}\{u_i\} is, and the sets of P(ui)P(u_i) are by induction. The union is a cut of vv, since every path from a PI to vv ends with an edge ui→vu_i \to v and its part before that edge meets cic_i (Lemma 3 of the proof of cut enumeration). It has at most kk nodes by the test of line L5. It does not contain vv, because each cic_i lies in the cone of uiu_i and GG is acyclic. Line L6 adds the old best(v)\mathrm{best}(v), which is such a cut by induction. Line L9 picks from these sets. □\square

Theorem 1 (the mapping keeps the functions). Each LUT of the returned mapping, for gate vv over best(v)\mathrm{best}(v), can compute vv as a function of the leaves, and the LUT network computes every output.

Proof. A gate is a function of the values on any of its cuts: if two input vectors give the same values on the cut, every path from a PI to vv passes through the cut, so the values of the gates between the cut and vv agree, by induction in topological order. So the LUT of vv stores the function of vv in terms of best(v)\mathrm{best}(v). The leaves are PIs or gates of the mapping, and by induction in topological order every LUT output equals its gate. □\square

Theorem 2 (the area passes do not raise the depth). Let DD be the largest arrival time of an output after the depth pass. After each later pass, every output has arrival time at most DD, and the arrival time of each gate is the depth of its LUT in the final LUT network.

Proof. A node is visited once per pass, after all its fanins, and line L10 sets arr(v)\mathrm{arr}(v) from the arrival times of the leaves of best(v)\mathrm{best}(v), which do not change later in the pass, since the leaves come before vv. So at the end of a pass, arr\mathrm{arr} is the depth function of the mapping given by best. This is the second claim.

Assume that before an area pass, the mapping has all outputs at arrival time at most DD; this holds after the depth pass by the choice of DD. Line L3 sets req(o)=D\mathrm{req}(o) = D for each output and, going backward, req(u)=min⁡(req(u),req(w)−1)\mathrm{req}(u) = \min(\mathrm{req}(u), \mathrm{req}(w) - 1) for each gate ww of the mapping and each u∈best(w)u \in \mathrm{best}(w), with req=∞\mathrm{req} = \infty for nodes outside the mapping. Write arr0\mathrm{arr}_0 and best0\mathrm{best}_0 for the values before the pass.

Claim A: arr0(u)≤req(u)\mathrm{arr}_0(u) \le \mathrm{req}(u) for every node uu with a finite required time. Induction backward. For an output, arr0(o)≤D\mathrm{arr}_0(o) \le D. For another node, req(u)=req(w)−1\mathrm{req}(u) = \mathrm{req}(w) - 1 for some ww of the mapping with u∈best0(w)u \in \mathrm{best}_0(w), and arr0(u)≤arr0(w)−1≤req(w)−1\mathrm{arr}_0(u) \le \mathrm{arr}_0(w) - 1 \le \mathrm{req}(w) - 1.

Claim B: after the pass, arr(v)≤req(v)\mathrm{arr}(v) \le \mathrm{req}(v) for every node vv with a finite required time. Induction in topological order. A PI has arr=0=arr0≤req\mathrm{arr} = 0 = \mathrm{arr}_0 \le \mathrm{req} by Claim A. Let vv be a gate with a finite required time. Then vv is in the old mapping, and every u∈best0(v)u \in \mathrm{best}_0(v) has req(u)≤req(v)−1\mathrm{req}(u) \le \mathrm{req}(v) - 1. By induction arr(u)≤req(u)\mathrm{arr}(u) \le \mathrm{req}(u), so dep(best0(v))≤req(v)\mathrm{dep}(\mathrm{best}_0(v)) \le \mathrm{req}(v), and the cut is not late. Line L6 makes it a candidate. Line L8 puts every late cut after every cut that is not late, so the chosen cut is not late, and arr(v)≤req(v)\mathrm{arr}(v) \le \mathrm{req}(v).

Claim B at the outputs gives arrival times at most DD after the pass, which keeps the assumption for the next pass. □\square

Theorem 3 (the exact area pass does not add LUTs). The number of LUTs of the mapping after the exact area pass is at most the number before it.

Proof. Let r(u)r(u) be the reference count of gate uu. The invariant is that r(u)r(u) equals the number of uses of uu in the current mapping: once per output that is uu, and once per gate ww of the mapping with u∈best(w)u \in \mathrm{best}(w). Then the mapping is the set SS of gates with r>0r > 0. Line L3 sets up the invariant. Referencing a cut BB of vv adds one use to each gate of BB, and when a count goes from 0 to 1 that gate joins SS and its own best cut is referenced in turn. The returned value is $1 + $ the number of gates that join SS. Dereferencing is the exact reverse, with $1 + $ the number of gates that leave SS.

Let vv be a gate of the mapping when it is visited, and ∣S∣=A|S| = A. Line L7 dereferences best0(v)\mathrm{best}_0(v), which returns $a_0 = 1 + $ the number of gates that leave. Now vv still has r(v)>0r(v) > 0, but its cut is not counted. The exact area of a candidate BB is the value of referencing BB in this state, then dereferencing it, which restores the state. For B=best0(v)B = \mathrm{best}_0(v), referencing reverses line L7 exactly, so its exact area is a0a_0. If line L9 picks B∗B^* with exact area a∗a^*, line L11 references it, and the new size is A−(a0−1)+(a∗−1)=A−a0+a∗A - (a_0 - 1) + (a^* - 1) = A - a_0 + a^*.

By Theorem 2, best0(v)\mathrm{best}_0(v) is not late. Line L8 sorts the cuts that are not late by exact area first, so a∗≤a0a^* \le a_0, and ∣S∣|S| does not grow. A gate that is not in the mapping when it is visited changes only its own best cut, which no LUT of the mapping uses, so SS does not change. If such a gate joins the mapping later, through the cut of a later gate, its LUTs are counted in the exact area of that cut. By induction over the visits, the final ∣S∣|S| is at most the first. □\square

Theorem 4 (unlimited cuts give the least depth). If CC is at least the number of candidates of every node, the depth pass sets arr(v)\mathrm{arr}(v) to the least depth of vv over all kk-LUT mappings, for every node vv.

Proof. With no limit, P(v)P(v) is the whole set AA of line L8, and in the depth pass line L6 adds nothing. Lines L5 and L9 are then the algorithm CUTS of cut enumeration, with P(u)∪{{u}}P(u) \cup \{\{u\}\} in the role of Φ(u)\Phi(u). By its theorem, P(v)P(v) is the set of minimal kk-feasible cuts of vv other than {v}\{v\}. Let d(v)d(v) be the least of dep\mathrm{dep} over all kk-feasible cuts of vv without vv, computed from the values dd of the leaves, with d=0d = 0 at the PIs. A minimal cut inside a cut has no larger depth, so the minimum over minimal cuts is the same. The depth key sorts first by depth, so line L10 sets arr(v)=d(v)\mathrm{arr}(v) = d(v) by induction in topological order. By Lemma 1 of the proof of FlowMap, d(v)d(v) is the least depth of vv in any kk-LUT mapping. □\square

Corollary. For any CC, the depth after all passes is at least the least depth and at most the depth DD of the first pass. The lower bound holds for every mapping by Lemma 1 of the FlowMap proof, and the upper bound is Theorem 2.

Termination. Each pass visits each gate once, and every step handles finite sets. Referencing and dereferencing recurse only into gates whose count crosses 0, and each recursion goes to earlier nodes, so they end.

Complexity

With 2-input gates, line L5 makes at most (C+1)2(C + 1)^2 unions of O(k)O(k) cost each, and the dominance test of the code of this page compares pairs, O(kC4)O(k C^4) in the worst case. Line L8 sorts O(C2)O(C^2) cuts. The exact area of a cut costs O(N)O(N) in the worst case, since referencing can walk a large cone, but on circuits the walk is short, and implementations bound its depth. A pass is O(NkC4)O(N k C^4) without the exact area walks, and the walks add O(N2C2)O(N^2 C^2) in the worst case. Without the walks, for a fixed CC and kk, a pass is linear in NN, the main gain over full enumeration, whose lists have no fixed bound. The priority cuts take O(NkC)O(N k C) space, and only the best cut of each node must survive between passes.

Properties

What is proved. The mapping computes the same functions as the network. The depth after the area passes is at most the depth of the first pass. The exact area pass never increases the number of LUTs of the mapping. With CC unlimited, the first pass gives the least depth. With any CC, the depth is at least the least depth, since every mapping is.

What is not proved. With a small CC there is no bound on the gap to the least depth or to the fewest LUTs, and the example above loses one level with C=1C = 1. The area passes are heuristics, and nothing is proved about the LUT count after the area flow pass.

What is measured. The code of this page was run on 20 random networks of 2-input gates, each with 16 inputs, 150 gates whose fanins come from the 12 nodes before them, and 8 outputs (seed 77). For k=4k = 4, the sum of the depths over the 20 networks was 241 with C=1C = 1, 223 with C=2C = 2, 214 with C=4C = 4, 179 with C=8C = 8 and 178 with no limit, the least depth. The LUT counts after the area passes were 1449, 1280, 1161, 1023 and 1020. For k=6k = 6 the depth sums were 58, 49, 44 and 40 for C=1,2,4,8C = 1, 2, 4, 8, with 412, 326, 283 and 252 LUTs. These are toy measurements to show the trend, not benchmark results. The paper reports its own measurements on benchmark circuits, against mapping with all cuts.

Variants and improvements

  • Structural choices. Run the mapper on a network that keeps several equivalent structures of the same logic, found by SAT sweeping. The cuts of a node then come from all its choices, and the mapper can pick the better structure for each cut. The paper of Mishchenko, Chatterjee and Brayton on improvements to LUT mapping maps with such choices.
  • Sequential mapping. The same cut lists work across registers, so that mapping and retiming are done together, the second topic of the 2007 paper.
  • Standard cells. With the truth table of each cut and Boolean matching, the same passes can map into a cell library instead of LUTs.
  • Other costs. The keys of line L8 can count wire length, edge count or power instead of LUTs.
  • More cuts for critical nodes. A mapper can keep more cuts at nodes on critical paths and fewer elsewhere.

When to use it

Use priority cuts for LUT mapping of large circuits with k=6k = 6 or more, where full cut enumeration is too slow or too large, and when both depth and LUT count matter. For a proof of depth optimality on small designs, use FlowMap or full enumeration. Run AIG optimization such as rewriting first, since the mapper does not restructure logic.

Pitfalls

  • Dropping the old best cut. If the best cut of the last pass is not a candidate, an area pass can be forced to a later cut, and the depth can grow.
  • Stale required times. The required times must come from the current mapping, not from the network, since a node that the mapping does not use has no required time.
  • Reference counts out of step. In the exact area pass, the old cut of a node in the mapping must be dereferenced before the candidates are costed and the new one referenced after, or the exact area counts the node's own LUTs as shared.
  • Fanout counts in area flow. Count an output as a fanout, and divide by 1 for a node with no fanout. If outputs are not counted, an output node that also feeds one gate looks fully owned by that gate.
  • Trusting a small C. A small CC can lose depth, as the example shows. Check the depth against a pass with more cuts when it matters.

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.

priority_cuts.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/priority-cuts/. The authors are listed in prov/TMZ6X8.jsonl.

"""LUT mapping with priority cuts, after Mishchenko, Cho, Chatterjee and Brayton.

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. Each node
keeps at most C cuts of at most k leaves, its priority cuts. The cuts of
a node are the merges of the priority cuts of its fanins (each fanin
also offers its trivial cut), with the best cut of the last pass always
kept. They are sorted by a key, and the first C are kept. The first of
them is the best cut of the node.

Pass 1 sorts by (depth, number of leaves, area flow). It gives a mapping
and its depth D. The area passes keep the depth: a node may only use a
cut whose depth is at most the required time of the node in the last
mapping. Pass 2 sorts by area flow, pass 3 by exact area, the number of
LUTs that the cut adds to the current mapping.
"""

from typing import Sequence

INF = float("inf")


def drop_dominated(cuts) -> list:
    kept: list = []
    for c in sorted(set(cuts), key=lambda c: (len(c), sorted(c))):
        if not any(d <= c for d in kept):
            kept.append(c)
    return kept


class Mapper:
    def __init__(self, fanins: Sequence[Sequence[int]], outputs: Sequence[int], k: int, c: int) -> None:
        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")
        self.f, self.outs, self.k, self.c = fanins, list(outputs), k, c
        n = len(fanins)
        self.pis = [not fi for fi in fanins]
        self.fanout = [0] * n
        for fi in fanins:
            for u in fi:
                self.fanout[u] += 1
        for o in outputs:
            self.fanout[o] += 1
        self.prio: list = [[] for _ in range(n)]
        self.best: list = [None] * n
        self.arr = [0] * n
        self.af = [0.0] * n
        self.req = [INF] * n
        self.ref = [0] * n

    # ---- cut costs
    def depth(self, cut) -> int:
        return 1 + max(self.arr[u] for u in cut)

    def area_flow(self, cut) -> float:
        return 1 + sum(self.af[u] for u in cut)

    def ref_cut(self, cut) -> int:
        """Add the LUTs of a cut to the mapping; return how many are new."""
        area = 1
        for u in cut:
            if not self.pis[u]:
                self.ref[u] += 1
                if self.ref[u] == 1:
                    area += self.ref_cut(self.best[u])
        return area

    def deref_cut(self, cut) -> int:
        area = 1
        for u in cut:
            if not self.pis[u]:
                self.ref[u] -= 1
                if self.ref[u] == 0:
                    area += self.deref_cut(self.best[u])
        return area

    def exact_area(self, cut) -> int:
        a = self.ref_cut(cut)
        self.deref_cut(cut)
        return a

    # ---- one pass
    def candidates(self, v) -> list:
        acc = {frozenset()}
        for u in self.f[v]:  # @line L5: merge the priority cuts of the fanins
            offer = self.prio[u] + [frozenset([u])]
            acc = {a | b for a in acc for b in offer if len(a | b) <= self.k}
        cands = drop_dominated(acc)
        if self.best[v] is not None and self.best[v] not in cands:  # @line L6
            cands.append(self.best[v])
        return cands

    def run_pass(self, mode: str) -> None:
        for v in range(len(self.f)):  # @line L4
            if self.pis[v]:
                continue
            in_map = self.ref[v] > 0
            if mode == "exact" and in_map:  # @line L7
                self.deref_cut(self.best[v])
            cands = self.candidates(v)

            def key(cut):
                d = self.depth(cut)
                late = d > self.req[v]
                if mode == "depth":
                    return (d, len(cut), self.area_flow(cut))
                if mode == "flow":
                    return (late, self.area_flow(cut), d, len(cut))
                return (late, self.exact_area(cut), self.area_flow(cut), d, len(cut))

            cands.sort(key=lambda cut: (key(cut), sorted(cut)))  # @line L8
            self.prio[v] = cands[: self.c]  # @line L9
            self.best[v] = cands[0]
            self.arr[v] = self.depth(self.best[v])  # @line L10
            self.af[v] = self.area_flow(self.best[v]) / max(1, self.fanout[v])
            if mode == "exact" and in_map:  # @line L11
                self.ref_cut(self.best[v])

    def luts(self) -> dict:
        out: dict = {}
        todo = [o for o in self.outs if not self.pis[o]]
        while todo:
            v = todo.pop()
            if v not in out:
                out[v] = self.best[v]
                todo.extend(u for u in self.best[v] if not self.pis[u])
        return out

    def set_mapping(self, target: int) -> None:
        """Reference counts and required times of the current mapping."""
        self.ref = [0] * len(self.f)
        for o in self.outs:
            if not self.pis[o]:
                self.ref[o] += 1
                if self.ref[o] == 1:
                    self.ref_cut(self.best[o])
        self.req = [INF] * len(self.f)
        for o in self.outs:
            self.req[o] = target
        for v in range(len(self.f) - 1, -1, -1):
            if self.ref[v] > 0 and self.req[v] < INF:
                for u in self.best[v]:
                    self.req[u] = min(self.req[u], self.req[v] - 1)


def priority_cut_map(fanins, outputs, k: int, c: int, area_passes: int = 2):
    """Return (luts, depth after pass 1, depth at the end, mapper)."""
    m = Mapper(fanins, outputs, k, c)  # @line L1
    m.run_pass("depth")  # @line L2: the depth pass
    d1 = max((m.arr[o] for o in outputs), default=0)  # @line L12
    modes = ["flow", "exact"][:area_passes]
    for mode in modes:  # the area passes of line L2
        m.set_mapping(d1)  # @line L3
        m.run_pass(mode)
    luts = m.luts()  # @line L13
    return luts, d1, max((m.arr[o] for o in outputs), default=0), m
test_priority_cuts.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/priority-cuts/. The authors are listed in prov/TMZ6X8.jsonl.

import random
from itertools import combinations

from priority_cuts import priority_cut_map


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:
    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:
    """Least LUT depth of each node over every k-feasible cut (brute force)."""
    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 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 lut_depth(fanins, luts, outputs) -> int:
    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])
        return memo[v]

    return max(d(v) for v in outputs)


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:
    """Each LUT is a function of its inputs, and the LUT network gives the outputs."""
    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]
        tables[v] = (order, table)
    for m in range(1 << n_in):
        val = evaluate(fanins, ops, n_in, m)
        got = {i: val[i] for i in range(n_in)}

        def get(v):
            if v not in got:
                order, table = tables[v]
                got[v] = table[tuple(get(u) for u in order)]
            return got[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 case(rng, k):
    n_in = rng.randint(2, 5)
    f = random_dag(rng, n_in, rng.randint(2, 12), k)
    inner = list(range(n_in, len(f)))
    outs = sorted(set([len(f) - 1] + rng.sample(inner, min(2, len(inner)))))
    return n_in, f, outs


def test_stored_cuts_are_k_feasible() -> None:
    rng = random.Random(3)
    for _ in range(150):
        k = rng.choice([2, 3, 4])
        _, f, outs = case(rng, k)
        luts, _, _, m = priority_cut_map(f, outs, k, rng.choice([1, 2, 4]))
        for v in range(len(f)):
            if not f[v]:
                continue
            assert 1 <= len(m.prio[v]) <= m.c
            for c in m.prio[v] + [m.best[v]]:
                assert len(c) <= k and v not in c and is_cut(f, v, c)


def test_unlimited_c_gives_optimal_depth() -> None:
    rng = random.Random(4)
    for _ in range(200):
        k = rng.choice([2, 3, 4])
        _, f, outs = case(rng, k)
        luts, d1, d_end, _ = priority_cut_map(f, outs, k, 10 ** 6)
        opt = max(best_depths(f, k)[o] for o in outs)
        assert d1 == opt
        assert d_end <= d1 and lut_depth(f, luts, outs) == d_end


def test_small_c_never_beats_the_optimum_and_area_keeps_depth() -> None:
    rng = random.Random(6)
    for _ in range(200):
        k = rng.choice([2, 3, 4])
        _, f, outs = case(rng, k)
        luts, d1, d_end, _ = priority_cut_map(f, outs, k, rng.choice([1, 2, 3]))
        opt = max(best_depths(f, k)[o] for o in outs)
        assert d1 >= opt
        assert d_end <= d1
        assert lut_depth(f, luts, outs) == d_end


def test_exact_area_pass_does_not_add_luts() -> None:
    rng = random.Random(8)
    for _ in range(200):
        k = rng.choice([3, 4])
        _, f, outs = case(rng, k)
        c = rng.choice([1, 2, 4, 8])
        after_flow, _, _, _ = priority_cut_map(f, outs, k, c, area_passes=1)
        after_exact, _, _, _ = priority_cut_map(f, outs, k, c, area_passes=2)
        assert len(after_exact) <= len(after_flow)


def test_function_is_kept() -> None:
    rng = random.Random(10)
    for _ in range(80):
        k = rng.choice([2, 3])
        n_in, f, outs = case(rng, k)
        ops = [None] * n_in + [rng.choice(OPS) for _ in range(len(f) - n_in)]
        luts, _, _, _ = priority_cut_map(f, outs, k, rng.choice([1, 3]))
        check_function(f, ops, n_in, outs, luts)

History

Cut-based LUT mapping lists the kk-feasible cuts of each node and picks one by dynamic programming, as in the mappers of Pan and Lin (1998) and of Cong, Wu and Ding (1999), who already ranked cuts and kept only part of them. Mishchenko, Chatterjee and Brayton improved the area passes of such mappers with area flow, exact local area and structural choices, in a paper that appeared in IEEE TCAD in 2007. In the same year, Mishchenko, Cho, Chatterjee and Brayton replaced full enumeration by a few priority cuts per node, computed again in each pass, and applied it to both combinational and sequential mapping. The method is the base of the if LUT mapper of ABC.

References

  1. Combinational and sequential mapping with priority cuts, the priority cuts, the order of the mapping passes for depth, area flow and exact area, and the experiments (general locator; the default number of cuts and the exact sort keys are not checked)
  2. Improvements to technology mapping for LUT-based FPGAs, area flow, exact local area with reference counting, and mapping with structural choices (general locator)
  3. Cut ranking and pruning, enabling a general and efficient FPGA mapping solution, the earlier idea of ranking cuts and keeping part of them (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.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