Algorithm Search⌘K

Algorithmadvanced

Weighted bipartite matching binding

Also called LYRA binding, bipartite weighted matching allocation.

Huang, Chen, Lin and Hsu's binding that assigns variables to registers step by step through weighted bipartite matching, using the fewest registers and less interconnect.

Time
O(n log n + n L^2 + n L D) worst
Space
O(n + L^2 + L D) extra
Where
D = the number of unit input ports; L = the largest number of values live in one step; n = the number of values
Properties
deterministicnot exactofflineiterative
Origin
Chu Yi Huang, Yen Shen Chen, Youn Long Lin, Yu Chin Hsu, 1990

Weighted bipartite matching binding is a register binder of high-level synthesis, published by Huang, Chen, Lin and Hsu in 1990. It walks through the control steps in order. At each step, the values that start their lifetime there form one side of a bipartite graph, the registers that are free form the other side, and an edge weight counts the wires that a value would share with a register. A largest-weight matching, found as an assignment problem, places the values. For straight-line code it always uses the fewest registers, the largest number of values live in one step, like the left-edge algorithm, but it chooses among the free registers to save multiplexer inputs. Each step is optimal for that step. The whole binding is not always the one with the least interconnect.

In plain words

Registers are boxes, and each box has wires to the units that fill it and to the unit inputs that read it. Every extra wire needs a switch. We go through time from left to right. Whenever new results appear, we see which boxes are empty at that moment and put each new result in a box. A result prefers a box that is already wired to the unit that makes it and to the inputs that will read it, since then no new wire is needed. Many results arrive at once, so we solve a small matching puzzle each time: give each new result a different empty box so that the total of reused wires is largest.

The problem

The input is a set XX of nn values of a scheduled design of straight-line code, as on the register binding page. Each value xx is held in the steps ℓ(x)\ell(x), a set of consecutive steps from b(x)b(x) to e(x)e(x). It is written by one unit src(x)\mathrm{src}(x), and it is read by a set Dst(x)\mathrm{Dst}(x) of unit input ports. A binding ρ\rho puts each value in a register, with no two values of one register live in the same step. A register rr has the sources Src(r)={src(x):ρ(x)=r}\mathrm{Src}(r) = \{\mathrm{src}(x) : \rho(x) = r\} and the destinations Dst(r)=⋃ρ(x)=rDst(x)\mathrm{Dst}(r) = \bigcup_{\rho(x) = r} \mathrm{Dst}(x). The cost is the number of connections,

cost(ρ)=∑r(∣Src(r)∣+∣Dst(r)∣),\mathrm{cost}(\rho) = \sum_r \bigl(|\mathrm{Src}(r)| + |\mathrm{Dst}(r)|\bigr),

a stand-in for the multiplexer inputs in front of the registers and the ports. The goal is the fewest registers, and among those, a small cost.

The algorithm

  1. MATCHING-BIND(X)
  2. 1R ← no registers; each register r will have Src(r), Dst(r) and end(r), the last step of its last value
  3. 2for each step t, in increasing order, such that some value has b(x) = t do
  4. 3A ← the values x with b(x) = t
  5. 4F ← the registers r with end(r) < t
  6. 5add max(0, |A| − |F|) fresh registers to R and to F, with empty Src, empty Dst and end = −∞
  7. 6for each x ∈ A and r ∈ F do w(x, r) ← [src(x) ∈ Src(r)] + |Dst(x) ∩ Dst(r)|
  8. 7M ← a matching that covers A, with each x matched to a distinct r ∈ F, of largest total weight w
  9. 8for each (x, r) ∈ M do ρ(x) ← r; add src(x) to Src(r); add Dst(x) to Dst(r); end(r) ← e(x)
  10. 9return ρ

Line L6 counts the connections that xx needs and rr already has. Line L7 is an assignment problem with ∣A∣|A| rows and ∣F∣≥∣A∣|F| \ge |A| columns, solved by the Hungarian algorithm. Line L5 adds fresh registers only when the free ones are too few.

Example

Two units U0U_0 and U1U_1 write values, and three unit input ports p0p_0, p1p_1 and p2p_2 read them. Four values:

value steps held written by read by
aa {1}\{1\} U0U_0 p0,p2p_0, p_2
bb {2}\{2\} U1U_1 p2p_2
cc {2,3,4}\{2, 3, 4\} U0U_0 p0,p1p_0, p_1
dd {3}\{3\} U0U_0 p0,p1p_0, p_1

At most two values are live in one step, so two registers are needed.

  • Step 1. A={a}A = \{a\} and no register is free, so L5 makes R0R_0 and aa goes there. Now Src(R0)={U0}\mathrm{Src}(R_0) = \{U_0\} and Dst(R0)={p0,p2}\mathrm{Dst}(R_0) = \{p_0, p_2\}.
  • Step 2. A={b,c}A = \{b, c\}. R0R_0 is free, and L5 adds R1R_1. The weights are w(b,R0)=0+1=1w(b, R_0) = 0 + 1 = 1, w(c,R0)=1+1=2w(c, R_0) = 1 + 1 = 2 and 00 for R1R_1. Placing cc in R0R_0 has weight 2, placing bb there has weight 1, so cc goes to R0R_0 and bb to R1R_1.
  • Step 3. A={d}A = \{d\}. R0R_0 holds cc until step 4, so only R1R_1 is free, and dd goes there.

The binding is R0={a,c}R_0 = \{a, c\} with 1 source and 3 ports, and R1={b,d}R_1 = \{b, d\} with 2 sources and 3 ports: cost 9. The binding {a,b,d}\{a, b, d\}, {c}\{c\} costs (2+3)+(1+2)=8(2 + 3) + (1 + 2) = 8. At step 2, cc looked like the better match for R0R_0, but it kept R0R_0 busy at step 3, when dd, which reads the same ports, needed a register. So each step was optimal for itself, and the whole binding was not.

Correctness

What is proved, in the full proof:

  • Valid. A value enters a register only when the register's last value has ended, so no two values of one register are live in a common step.
  • Fewest registers. The number of registers is exactly the largest number of values live in one step, which is the least possible. Fresh registers appear at step tt only when every register holds a value live at tt.
  • Each step is optimal for its step. Given the bindings of the earlier steps, the connections added at step tt equal ∑x∈A(1+∣Dst(x)∣)−w(M)\sum_{x \in A} (1 + |\mathrm{Dst}(x)|) - w(M). So a matching of largest weight adds the fewest connections at that step.

What is not proved, and is false: that the total cost is least. The example above is an instance where it costs 9 and 8 is possible. In a measured run of the tests, on 500 random instances with at most 6 values, 2 units and 3 ports, the binder matched the exhaustive optimum on 479, was 1 above on 16 and 2 above on 5. This is a measurement on small random instances, not a bound.

Proof: The matching binder uses the fewest registers and is optimal step by stepfull

We use the notation of the page. Each value xx is held in the consecutive steps b(x),…,e(x)b(x), \ldots, e(x), and two values conflict when these sets meet. Let L=max⁡t∣{x:b(x)≤t≤e(x)}∣L = \max_t |\{x : b(x) \le t \le e(x)\}| be the largest number of values live in one step. The steps tt of line L2 are processed in increasing order.

Lemma 1 (each step places every new value). At line L7, ∣F∣≥∣A∣|F| \ge |A|, so a matching that covers AA exists, and after L8 every value of AA has a register.

Proof. Line L5 adds max⁡(0,∣A∣−∣F∣)\max(0, |A| - |F|) registers to FF, so afterwards ∣F∣≥∣A∣|F| \ge |A|. Matching the values of AA to distinct registers of FF in any order covers AA, so the largest-weight matching that covers AA exists, and L8 gives every x∈Ax \in A a register. Each value has exactly one first step b(x)b(x), so it is placed exactly once. □\square

Lemma 2 (validity). After the loop, no two values of one register share a step.

Proof. Values enter a register in increasing order of their first step, and at most one per step, since MM is a matching. When xx enters rr at step t=b(x)t = b(x), line L4 put rr in FF only if end(r)<t\mathrm{end}(r) < t, where end(r)\mathrm{end}(r) is the last step of the latest value in rr. All earlier values of rr end at or before the latest one, since each entered only after the previous one had ended. So every earlier value yy of rr has e(y)<b(x)e(y) < b(x), and xx and yy share no step. □\square

Lemma 3 (busy registers). After line L8 at step tt, if L5 added a register at step tt, then every register holds a value live in step tt.

Proof. If L5 added registers, then after L5 ∣F∣=∣A∣|F| = |A|, and since MM covers AA with distinct registers of FF, every register of FF gets a value xx with b(x)=tb(x) = t, live in step tt. A register r∉Fr \notin F has end(r)≥t\mathrm{end}(r) \ge t. Its latest value yy entered at a step b(y)<tb(y) < t, since the steps are processed in increasing order, and e(y)=end(r)≥te(y) = \mathrm{end}(r) \ge t, so yy is live in step tt. □\square

Theorem 1 (fewest registers). The binder uses exactly LL registers, and no valid binding uses fewer.

Proof. The LL values live in one step pairwise conflict, so every valid binding uses at least LL registers. For the binder, consider the last step tt at which L5 added a register. Registers are never removed, so the final number of registers equals the number after step tt. By Lemma 3, each of them holds a value live in step tt, and by Lemma 2 these values are distinct, so there are at most LL of them. If L5 never adds a register, there are none and XX is empty. □\square

Theorem 2 (each step is optimal for its step). Fix the bindings of the steps before tt, which fix Src(r)\mathrm{Src}(r) and Dst(r)\mathrm{Dst}(r) before step tt. Among all ways to place the values of AA in distinct registers of FF, the matching of L7 adds the fewest connections to the cost.

Proof. Placing xx in rr adds the source src(x)\mathrm{src}(x) to Src(r)\mathrm{Src}(r) if it is not already there, and the ports of Dst(x)∖Dst(r)\mathrm{Dst}(x) \setminus \mathrm{Dst}(r) to Dst(r)\mathrm{Dst}(r). The number of new connections is

(1−[src(x)∈Src(r)])+(∣Dst(x)∣−∣Dst(x)∩Dst(r)∣)=1+∣Dst(x)∣−w(x,r).\bigl(1 - [\mathrm{src}(x) \in \mathrm{Src}(r)]\bigr) + \bigl(|\mathrm{Dst}(x)| - |\mathrm{Dst}(x) \cap \mathrm{Dst}(r)|\bigr) = 1 + |\mathrm{Dst}(x)| - w(x, r).

In a matching, each register of FF receives at most one value of AA, so the new connections of different pairs fall in different registers and add up. A placement PP of AA adds

∑(x,r)∈P(1+∣Dst(x)∣−w(x,r))=∑x∈A(1+∣Dst(x)∣)−w(P)\sum_{(x, r) \in P} \bigl(1 + |\mathrm{Dst}(x)| - w(x, r)\bigr) = \sum_{x \in A} \bigl(1 + |\mathrm{Dst}(x)|\bigr) - w(P)

connections. The first sum does not depend on PP, so the fewest added connections come from the largest w(P)w(P), which is the matching of line L7. □\square

What is not claimed. Theorem 2 fixes the earlier steps. A choice that is best at step tt can force a worse choice later, and the page gives an instance with four values where the binder costs 9 while 8 is possible. So the binder is exact for the register count and optimal step by step for the interconnect, and it is a heuristic for the total interconnect. ■\blacksquare

Complexity

Sorting the values by their first step takes O(nlog⁡n)O(n \log n). The free registers number at most LL, since only LL registers exist. At step tt with ata_t new values, L6 computes at⋅La_t \cdot L weights, each in O(D)O(D) time with bit sets or hash sets, and the Hungarian method takes O(at2L)O(a_t^2 L) time. Since at≤La_t \le L and ∑tat=n\sum_t a_t = n, the total is O(nlog⁡n+nL2+nLD)O(n \log n + n L^2 + n L D). The space is O(n)O(n) for the binding, O(L2)O(L^2) for one weight matrix and O(LD)O(L D) for the sets of the registers.

Properties

  • Not exact for the interconnect. It reaches the fewest registers, but not always the least cost, as the example shows.
  • Deterministic. With a fixed tie rule in the matching, the same input gives the same binding.
  • Greedy over time. Each step looks only at the registers and connections built so far, never at later values.
  • Polynomial. Each step is one assignment problem, so it scales to large designs, unlike exact integer programs.

Variants and improvements

  • Other weights. The weights can count the multiplexer inputs saved, include the wire lengths of a floorplan, or add a term for switching activity. The weights of the original paper also come from the interconnect between registers and units, and the count of shared connections used here is one simple form of them.
  • Unit binding by matching. The same idea binds operations to functional units, step by step, with weights from shared operand sources.
  • Joint register and port choice. Later binders choose the operand ports of commutative operations together with the registers, see interconnect binding.
  • Unweighted version. With all weights 0, any matching works and the binder becomes interval partitioning, which also reaches the fewest registers. The maximum matching can then come from Hopcroft-Karp, though any free register will do.

When to use it

Use it for register binding of straight-line code, or of loop bodies after unrolling, when the interconnect matters and the register count must stay least. If only the register count matters, the left-edge algorithm is simpler. If the conflict graph is not an interval graph, for example with mutually exclusive values, the step-by-step order no longer gives the fewest registers, and a general method such as Tseng-Siewiorek clique partitioning or an integer program applies.

Pitfalls

  • Expecting the least interconnect. Each step is optimal only for itself. Later values can make an early choice bad.
  • Off-by-one in freeing. A register is free at step tt only if its last value ends before tt. With the timing rules of the resource compatibility graph page, a register read in step t−1t - 1 can be written at the end of step t−1t - 1 and hold a value from step tt.
  • Rectangular matching. The matching must cover the new values, not the registers. A solver that expects a square matrix needs dummy rows with weight 0.
  • Early steps have no guidance. At the first steps the registers are empty and every weight is 0, so the first choices are arbitrary.

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.

weighted_bipartite_matching_binding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-bipartite-matching-binding/. The authors are listed in prov/6HS42N.jsonl.

"""Register binding step by step through weighted bipartite matching.

A value is a tuple (birth, death, src, dst): it is held in a register in the
steps birth, ..., death (a closed interval), it is written by the unit src,
and it is read by the set dst of unit input ports. A register collects the
sources and the ports of all its values. The cost of a binding is the number
of connections: the sum over registers of |sources| + |ports|.

At each birth step, the new values are matched to the free registers, plus
fresh registers when there are too few free ones. The weight of a pair (v, r)
counts the connections that v needs and r already has. Each step takes a
matching of the largest weight that places every new value.
"""

Value = tuple[int, int, int, frozenset]


def hungarian_max(weight: list[list[int]]) -> list[int]:
    """Columns for each row of a matching that places every row and has the largest total weight.

    weight has n rows and m >= n columns. This is the O(n^2 m) Hungarian method with
    potentials, run on the costs top - weight.
    """
    n = len(weight)
    if n == 0:
        return []
    m = len(weight[0])
    top = max(max(row) for row in weight)
    inf = float("inf")
    u = [0] * (n + 1)
    v = [0] * (m + 1)
    p = [0] * (m + 1)
    way = [0] * (m + 1)
    for i in range(1, n + 1):
        p[0] = i
        j0 = 0
        minv = [inf] * (m + 1)
        used = [False] * (m + 1)
        while True:
            used[j0] = True
            i0 = p[j0]
            delta = inf
            j1 = 0
            for j in range(1, m + 1):
                if not used[j]:
                    cur = (top - weight[i0 - 1][j - 1]) - u[i0] - v[j]
                    if cur < minv[j]:
                        minv[j] = cur
                        way[j] = j0
                    if minv[j] < delta:
                        delta = minv[j]
                        j1 = j
            for j in range(m + 1):
                if used[j]:
                    u[p[j]] += delta
                    v[j] -= delta
                else:
                    minv[j] -= delta
            j0 = j1
            if p[j0] == 0:
                break
        while True:
            j1 = way[j0]
            p[j0] = p[j1]
            j0 = j1
            if j0 == 0:
                break
    col = [0] * n
    for j in range(1, m + 1):
        if p[j]:
            col[p[j] - 1] = j - 1
    return col


def pair_weight(value: Value, srcs: set, ports: set) -> int:
    """Connections that value needs and the register with these sources and ports already has."""
    return (1 if value[2] in srcs else 0) + len(value[3] & ports)


def matching_bind(values: list[Value], trace: list | None = None) -> list[int]:
    """The register of each value, by one weighted bipartite matching per birth step.

    When trace is a list, each step appends (step, new values, candidate registers,
    weight matrix, chosen columns) to it.
    """
    reg_src: list[set] = []                                      # @line L1
    reg_dst: list[set] = []
    reg_end: list[int] = []
    where = [-1] * len(values)
    for t in sorted({b for b, _, _, _ in values}):               # @line L2
        new = [k for k, val in enumerate(values) if val[0] == t]  # @line L3
        free = [r for r in range(len(reg_end)) if reg_end[r] < t]  # @line L4
        for _ in range(max(0, len(new) - len(free))):            # @line L5
            reg_src.append(set())
            reg_dst.append(set())
            reg_end.append(-1)
            free.append(len(reg_end) - 1)
        w = [[pair_weight(values[k], reg_src[r], reg_dst[r]) for r in free]
             for k in new]                                       # @line L6
        col = hungarian_max(w)                                   # @line L7
        if trace is not None:
            trace.append((t, list(new), list(free), w, list(col)))
        for a, k in enumerate(new):                              # @line L8
            r = free[col[a]]
            where[k] = r
            reg_src[r].add(values[k][2])
            reg_dst[r] |= values[k][3]
            reg_end[r] = values[k][1]
    return where                                                 # @line L9


def connections(values: list[Value], where: list[int]) -> int:
    """Sum over registers of the number of distinct sources and of distinct ports."""
    srcs: dict[int, set] = {}
    ports: dict[int, set] = {}
    for val, r in zip(values, where):
        srcs.setdefault(r, set()).add(val[2])
        ports.setdefault(r, set()).update(val[3])
    return sum(len(srcs[r]) + len(ports[r]) for r in srcs)


def is_valid(values: list[Value], where: list[int]) -> bool:
    """True when no two values in one register are live in a common step."""
    for a in range(len(values)):
        for b in range(a + 1, len(values)):
            if where[a] == where[b]:
                if not (values[a][1] < values[b][0] or values[b][1] < values[a][0]):
                    return False
    return True


def max_live(values: list[Value]) -> int:
    """The largest number of values live in one step."""
    if not values:
        return 0
    return max(sum(1 for b, e, _, _ in values if b <= t <= e) for t in {b for b, _, _, _ in values})
test_weighted_bipartite_matching_binding.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-bipartite-matching-binding/. The authors are listed in prov/6HS42N.jsonl.

import itertools
import random

from weighted_bipartite_matching_binding import (connections, hungarian_max, is_valid, matching_bind,
                                                 max_live, pair_weight)

# The counterexample of the page: values a, b, c, d as (birth, death, unit, ports).
COUNTER = [(0, 0, 0, frozenset({0, 2})), (1, 1, 1, frozenset({2})),
           (1, 3, 0, frozenset({0, 1})), (2, 2, 0, frozenset({0, 1}))]


def random_values(rng: random.Random, n: int) -> list:
    """n values with lifetimes in a short horizon, 2 units and 3 ports."""
    horizon = rng.randint(2, 5)
    out = []
    for _ in range(n):
        b = rng.randrange(horizon)
        e = rng.randrange(b, horizon)
        ports = frozenset(rng.sample(range(3), rng.randint(1, 2)))
        out.append((b, e, rng.randrange(2), ports))
    return out


def conflict(x, y) -> bool:
    return not (x[1] < y[0] or y[1] < x[0])


def all_bindings(values: list, k: int):
    """Every map of the values to registers 0, ..., k - 1 with no two conflicting values together."""
    n = len(values)

    def rec(i: int, where: list[int], used: int):
        if i == n:
            yield list(where)
            return
        for r in range(min(used + 1, k)):
            if all(not (where[j] == r and conflict(values[j], values[i])) for j in range(i)):
                where.append(r)
                yield from rec(i + 1, where, max(used, r + 1))
                where.pop()

    yield from rec(0, [], 0)


def least_registers(values: list) -> int:
    """The least number of registers, by trying k = 1, 2, ... with every binding."""
    k = 0
    while True:
        if next(all_bindings(values, k), None) is not None:
            return k
        k += 1


def best_matching_weight(weight: list[list[int]]) -> int:
    """The largest weight of a matching that places every row, over all injective maps."""
    n = len(weight)
    m = len(weight[0]) if n else 0
    return max(sum(weight[a][c] for a, c in enumerate(cols))
               for cols in itertools.permutations(range(m), n))


def test_counterexample():
    trace: list = []
    where = matching_bind(COUNTER, trace)
    assert where == [0, 1, 0, 1]
    assert connections(COUNTER, where) == 9
    assert trace[1] == (1, [1, 2], [0, 1], [[1, 0], [2, 0]], [1, 0])
    best = min(connections(COUNTER, w) for w in all_bindings(COUNTER, 2))
    assert best == 8
    assert connections(COUNTER, [0, 0, 1, 0]) == 8


def test_hungarian_against_all_injective_maps():
    rng = random.Random(5)
    for _ in range(600):
        n = rng.randint(1, 4)
        m = rng.randint(n, 5)
        w = [[rng.randint(0, 4) for _ in range(m)] for _ in range(n)]
        cols = hungarian_max(w)
        assert len(set(cols)) == n
        assert sum(w[a][c] for a, c in enumerate(cols)) == best_matching_weight(w)


def test_each_step_is_optimal_for_its_step():
    rng = random.Random(6)
    for _ in range(500):
        values = random_values(rng, rng.randint(1, 7))
        trace: list = []
        where = matching_bind(values, trace)
        srcs: dict[int, set] = {}
        ports: dict[int, set] = {}
        for t, new, free, w, cols in trace:
            for a, k in enumerate(new):
                for c, r in enumerate(free):
                    assert w[a][c] == pair_weight(values[k], srcs.get(r, set()), ports.get(r, set()))
            assert sum(w[a][c] for a, c in enumerate(cols)) == best_matching_weight(w)
            for a, k in enumerate(new):
                r = free[cols[a]]
                assert where[k] == r
                srcs.setdefault(r, set()).add(values[k][2])
                ports.setdefault(r, set()).update(values[k][3])


def test_register_count_and_measured_cost():
    rng = random.Random(8)
    gaps: dict[int, int] = {}
    for _ in range(500):
        values = random_values(rng, rng.randint(1, 6))
        where = matching_bind(values, None)
        assert is_valid(values, where)
        k = len(set(where))
        assert k == max_live(values) == least_registers(values)
        best = min(connections(values, w) for w in all_bindings(values, k))
        gap = connections(values, where) - best
        assert gap >= 0
        gaps[gap] = gaps.get(gap, 0) + 1
    assert gaps == {0: 479, 1: 16, 2: 5}

History

Kurdahi and Parker (1987) bound registers in straight-line code with the left-edge algorithm, which reaches the fewest registers but ignores interconnect. Huang, Chen, Lin and Hsu (1990) kept the step-by-step order and replaced the arbitrary choice among the free registers by a weighted bipartite matching, so that the register count stays least while the interconnect falls. They also bound functional units by matching. Later work added port choices and multiplexer costs for FPGA targets.

References

  1. Chu-Yi Huang, Yen-Shen Chen, Youn-Long Lin and Yu-Chin Hsu, Data path allocation based on bipartite weighted matching, Proceedings of the 27th Design Automation Conference, 1990, whole paper (register allocation by one weighted bipartite matching per control step, with weights from the interconnect, then unit allocation)
  2. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 6, Resource Sharing and Binding (register sharing and interconnect)

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
  • at least three sources
  • a scene preset for the example