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.
- Solves
- Register binding
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of values of a scheduled design of straight-line code, as on the register binding page. Each value is held in the steps , a set of consecutive steps from to . It is written by one unit , and it is read by a set of unit input ports. A binding puts each value in a register, with no two values of one register live in the same step. A register has the sources and the destinations . The cost is the number of connections,
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
MATCHING-BIND(X)- 1
R ← no registers; each register r will have Src(r), Dst(r) and end(r), the last step of its last value - 2
for each step t, in increasing order, such that some value has b(x) = t do - 3
A ← the values x with b(x) = t - 4
F ← the registers r with end(r) < t - 5
add max(0, |A| − |F|) fresh registers to R and to F, with empty Src, empty Dst and end = −∞ - 6
for each x ∈ A and r ∈ F do w(x, r) ← [src(x) ∈ Src(r)] + |Dst(x) ∩ Dst(r)| - 7
M ← a matching that covers A, with each x matched to a distinct r ∈ F, of largest total weight w - 8
for each (x, r) ∈ M do ρ(x) ← r; add src(x) to Src(r); add Dst(x) to Dst(r); end(r) ← e(x) - 9
return ρ
Line L6 counts the connections that needs and already has. Line L7 is an assignment problem with rows and columns, solved by the Hungarian algorithm. Line L5 adds fresh registers only when the free ones are too few.
Example
Two units and write values, and three unit input ports , and read them. Four values:
| value | steps held | written by | read by |
|---|---|---|---|
At most two values are live in one step, so two registers are needed.
- Step 1. and no register is free, so L5 makes and goes there. Now and .
- Step 2. . is free, and L5 adds . The weights are , and for . Placing in has weight 2, placing there has weight 1, so goes to and to .
- Step 3. . holds until step 4, so only is free, and goes there.
The binding is with 1 source and 3 ports, and with 2 sources and 3 ports: cost 9. The binding , costs . At step 2, looked like the better match for , but it kept busy at step 3, when , 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 only when every register holds a value live at .
- Each step is optimal for its step. Given the bindings of the earlier steps, the connections added at step equal . 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 is held in the consecutive steps , and two values conflict when these sets meet. Let be the largest number of values live in one step. The steps of line L2 are processed in increasing order.
Lemma 1 (each step places every new value). At line L7, , so a matching that covers exists, and after L8 every value of has a register.
Proof. Line L5 adds registers to , so afterwards . Matching the values of to distinct registers of in any order covers , so the largest-weight matching that covers exists, and L8 gives every a register. Each value has exactly one first step , so it is placed exactly once.
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 is a matching. When enters at step , line L4 put in only if , where is the last step of the latest value in . All earlier values of end at or before the latest one, since each entered only after the previous one had ended. So every earlier value of has , and and share no step.
Lemma 3 (busy registers). After line L8 at step , if L5 added a register at step , then every register holds a value live in step .
Proof. If L5 added registers, then after L5 , and since covers with distinct registers of , every register of gets a value with , live in step . A register has . Its latest value entered at a step , since the steps are processed in increasing order, and , so is live in step .
Theorem 1 (fewest registers). The binder uses exactly registers, and no valid binding uses fewer.
Proof. The values live in one step pairwise conflict, so every valid binding uses at least registers. For the binder, consider the last step at which L5 added a register. Registers are never removed, so the final number of registers equals the number after step . By Lemma 3, each of them holds a value live in step , and by Lemma 2 these values are distinct, so there are at most of them. If L5 never adds a register, there are none and is empty.
Theorem 2 (each step is optimal for its step). Fix the bindings of the steps before , which fix and before step . Among all ways to place the values of in distinct registers of , the matching of L7 adds the fewest connections to the cost.
Proof. Placing in adds the source to if it is not already there, and the ports of to . The number of new connections is
In a matching, each register of receives at most one value of , so the new connections of different pairs fall in different registers and add up. A placement of adds
connections. The first sum does not depend on , so the fewest added connections come from the largest , which is the matching of line L7.
What is not claimed. Theorem 2 fixes the earlier steps. A choice that is best at step 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.
Complexity
Sorting the values by their first step takes . The free registers number at most , since only registers exist. At step with new values, L6 computes weights, each in time with bit sets or hash sets, and the Hungarian method takes time. Since and , the total is . The space is for the binding, for one weight matrix and 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 only if its last value ends before . With the timing rules of the resource compatibility graph page, a register read in step can be written at the end of step and hold a value from step .
- 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6HS42N Edit this page History Report an error Markdown