Algorithmadvanced
Multilevel hypergraph partitioning
Also called hMETIS algorithm.
Karypis, Aggarwal, Kumar and Shekhar's multilevel scheme for hypergraphs with hyperedge coarsening and V-cycles of FM refinement, the base of netlist partitioners.
- Solves
- Hypergraph partitioning
- Time
- O(l (P log P + p (n + P))) worst · averageO(n + P log P) best
- Space
- O(n + l P) extra
- Where
- P = the number of pins; l = the number of levels; m = the number of nets; n = the number of vertices; p = the largest number of FM passes on one level
- Model
- Word RAM
- Properties
- randomizednot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- George Karypis, Rajat Aggarwal, Vipin Kumar, Shashi Shekhar, 1997
Multilevel hypergraph partitioning bisects a netlist in three phases. It merges groups of vertices again and again to get a small hypergraph, it partitions the small hypergraph, and it carries the partition back level by level with Fiduccia-Mattheyses (FM) refinement at each level. Karypis, Aggarwal, Kumar and Shekhar built it for circuits as hMETIS (1997, 1999), with hyperedge coarsening, which merges all pins of a net at once, and V-cycles, which coarsen and refine an existing partition again. It works on nets directly, so it minimizes the true cut of hypergraph partitioning, not a clique model of it. It is a heuristic: it has no approximation guarantee, and its quality is known from benchmarks.
In plain words
FM improves a split by moving one cell at a time. On a big netlist this is short-sighted: a whole cluster of cells may belong on the other side, but moving any one cell of it makes the cut worse, so FM never starts the move.
So first glue cells together. Cells that share a small net almost surely belong on the same side, so glue each such net into one heavy cell. Do this again on the glued netlist, until only a few heavy cells are left. Split those carefully. Then undo the gluing one level at a time, and at each level let FM move the cells of that level. A move of a heavy cell at a coarse level is the move of a whole cluster.
The problem
The input is a hypergraph with vertices (cells) of integer weights , nets of integer weights and pins, and a balance window . The output is a bisection with . The objective is a small cut, the total weight of the nets with pins on both sides. Finding the minimum is NP-hard; see hypergraph partitioning for the variants and the hardness.
The algorithm
A level is a hypergraph . A coarsening of is a map from its vertices onto the vertices of . A coarse vertex weighs the sum of the weights of its preimage. Each net becomes the net ; nets with a single coarse pin are dropped, and equal coarse nets are merged with their weights added.
Hyperedge coarsening (HEC) visits the nets by non-increasing weight, then by non-decreasing size, in random order among ties. If no pin of the net is merged yet, it merges all its pins into one coarse vertex. Pins that no net merges stay as single vertices. Heavy nets come first because cutting them costs most; small nets come first because their pins are most tightly bound. The implementation also offers edge coarsening (EC), which visits the vertices in random order and matches each with the unmatched vertex that maximizes over their shared nets.
The implementation caps the weight of a coarse vertex at , with (by default ). This cap is a choice of this page, made so that a balanced start always exists at the coarsest level.
MULTILEVEL-BISECT(H, lo, hi, c0, t, v)- 1
H_0 ← H; ℓ ← 0 - 2
while H_ℓ has more than c0 vertices - 3
H_{ℓ+1} ← HEC(H_ℓ, cap); if no vertices merged then stop the loop - 4
ℓ ← ℓ + 1; if H_ℓ has more than 9/10 of the vertices of H_{ℓ−1} then stop the loop - 5
repeat t times - 6
s′ ← FM(H_ℓ, GREEDY-FILL(H_ℓ, lo, hi), lo, hi) - 7
if s′ has the least cut so far then s ← s′ - 8
for j ← ℓ − 1 down to 0 - 9
s ← the projection of s: each vertex of H_j takes the side of its coarse vertex - 10
s ← FM(H_j, s, lo, hi) - 11
repeat v times ▷ V-cycles - 12
run lines L1 to L10 again, with HEC restricted to vertices on the same side of s, and with s projected down in place of lines L5 to L7 - 13
return s
GREEDY-FILL puts the vertices on side 0 in random order, while . FM is the Fiduccia-Mattheyses pass with vertex weights: each free vertex moves at most once, always the one of largest gain whose move keeps in , the best prefix of the pass is kept, and passes repeat while the best prefix has a positive gain. The implementation finds the vertex of largest gain by a scan instead of gain buckets, which is simpler but slower.
Restricted coarsening (line L12) merges only vertices on the same side of the current partition . Then is a partition of every coarse level, with the same cut, and FM at the coarse levels can move whole clusters of across the cut.
Example
Take unit cells, unit nets and the window , so :
The first five nets live on , the next five on , and the last two join the groups. The trace below is the run of the implementation with random.Random(7) and .
Coarsening. All weights are 1, so HEC visits the five nets of size 2 first. It merges , , and , then skips because 4 and 5 are already merged. Every net of size 3 then has a merged pin. The cells 3 and 8 stay single. So has 6 vertices:
| coarse vertex | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| cells | 2, 4 | 7, 9 | 0, 1 | 5, 6 | 3 | 8 |
| weight | 2 | 2 | 2 | 2 | 1 | 1 |
The nets of are of weight 1 (from ), of weight 2 (from and , merged), of weight 1, of weight 2, of weight 1 (from ) and of weight 1 (from ). The nets , , and are inside coarse vertices and are dropped. has vertices, so coarsening stops.
Initial partitioning. The first greedy fill puts on side 0, weight 5. Its cut is 7: the nets , (weight 2), , (weight 2) and are cut. FM turns it into , with weight 5 on side 0 and cut 2 (the nets and ). The other three trials, from starts with cuts 6, 7 and 7, end at the same partition.
Uncoarsening. Line L9 gives the cells , with cut 2, the same as at level 1. FM finds no improving prefix.
V-cycle. Restricted coarsening merges , , and again (here the same pairs), each inside one side. FM at both levels keeps the partition. The result is with cut 2, the nets and . A brute force over all splits with 4 to 6 cells on side 0 confirms that 2 is the least cut for this window.
Correctness
The proof shows the following for every input with and .
- Projection keeps the cut and the balance. For every partition of , its projection to has the same cut and the same weight on side 0.
- A balanced start. GREEDY-FILL always ends with , because while every vertex fits.
- FM never worsens. Each FM pass keeps the balance at every step and lowers the cut by its best prefix gain, which is at least 0. So FM ends, and its output is balanced and has a cut no larger than its input.
- Balanced output. By the three items, the output satisfies .
- V-cycles never worsen. Under restricted coarsening the current partition is a partition of every coarse level with the same cut, so a V-cycle returns a cut no larger than the one it started from.
- Termination. Each coarsening level that is kept removes at least one vertex, so there are at most levels; with the 9/10 rule there are .
Proof: The multilevel bisection is balanced, projection keeps the cut, and no phase after the coarsest level increases the cutfull
Let have vertex weights and net weights , all integers. A partition is a map , its balance is , and its cut is . We assume and , which the implementation checks.
Lemma 1 (projection). Let be one coarsening step of HEC or EC, with coarse weights and coarse nets as described on the page. For every partition of , the projection satisfies and .
Proof. The balance: . The cut: a fine net is cut by exactly when is not constant on , because . If , the net is not cut and is dropped, so it adds 0 on both sides. Otherwise is a coarse net, and the coarse net has weight . Group the fine nets by their image: .
By induction on the levels, the same holds for the composed map from to any .
Lemma 2 (weight cap). Every coarse vertex weighs at most .
Proof. HEC merges the pins of a net only if their total weight is at most , and EC merges two vertices only if their total weight is at most . Each coarse vertex is formed by one such merge of vertices of the level below, or is a single vertex of weight at most by induction (at level 0 by the assumption ).
Lemma 3 (greedy fill). On a level with vertex weights at most and total weight , GREEDY-FILL returns with .
Proof. The fill visits the vertices in some order, stops as soon as , and adds a vertex if . While , that is , every vertex satisfies , so every visited vertex is added. Hence after each addition. If the loop stops early, . If it visits all vertices without stopping, all were added, so . If the loop stops at once with . In each case . The total weight is the same on every level by Lemma 1, so holds on every level.
Lemma 4 (FM). If , then FM returns with and , and it stops.
Proof. In a pass, a vertex is chosen only if its move keeps in , so every tentative partition is balanced. The gain of a free vertex on side is , the decrease of the cut if moves alone. The updates in the implementation are the critical net rules of Fiduccia and Mattheyses with the net weight in place of 1: the rules for the target side use the counts before the move, and the rules for the source side use the counts after it. The proof on the Fiduccia-Mattheyses page shows that they keep equal to this decrease for every free vertex, and the weights only scale each term. So after the first moves the cut is , where is the sum of the first gains. The pass keeps the prefix of largest , with allowed, so the cut does not increase and the kept partition is one of the balanced tentative partitions. A new pass starts only if the best was positive, so the integer cut falls by at least 1 per repeated pass, and there are at most passes.
Theorem 1 (balance). The output satisfies .
Proof. At the coarsest level each trial starts from GREEDY-FILL, which is balanced by Lemmas 2 and 3, and FM keeps it balanced by Lemma 4. Line L7 keeps one of these. Each projection in line L9 keeps the balance by Lemma 1, and each FM in line L10 keeps it by Lemma 4. In a V-cycle, the start is the current balanced partition, projected down; by Lemma 1 it is balanced at each level, and the same steps keep it so.
Theorem 2 (monotonicity). Let be the partition chosen at the coarsest level. The cut of the partition after line L10 at level 0 is at most , and each V-cycle returns a cut at most the cut it started from.
Proof. Going up, line L9 keeps the cut (Lemma 1) and line L10 does not increase it (Lemma 4). For a V-cycle, restricted coarsening merges only vertices with the same side, so the current partition is constant on each preimage and defines a coarse partition with . By Lemma 1 the cut of equals the cut of . FM at the coarsest level and at each level on the way up does not increase the cut, and projection keeps it.
Theorem 3 (termination and levels). The loop of lines L2 to L4 runs at most times, and every kept level except possibly the last has at most of the vertices of the level before it, so when .
Proof. Line L3 stops the loop if a step merged nothing, so each kept step lowers the number of vertices by at least 1. Line L4 stops the loop after the first kept level with more than of the vertices of the level before. So all earlier levels shrink by a factor of at least , and the loop also stops when at most vertices remain. Every other loop of the algorithm runs over a finite list, and FM stops by Lemma 4.
Running time. One HEC step sorts the nets in , checks the pins in , and builds the coarse nets by sorting the pin list of each, in , with . EC scans, for each vertex, the pins of its nets, which is . One FM pass with gain buckets costs (see the Fiduccia-Mattheyses page). The implementation uses a scan of all free vertices to pick each move, per pass, and scans all pins of the nets of the moved vertex, per pass, since each vertex moves at most once. By Theorem 3 the number of levels is , which gives the bounds on the page. The levels are stored for the way back, so the space is , because the vertex counts of the levels add up to at most and each level has at most pins.
What is not proved. Nothing above compares the cut with the minimum. The method can return a cut larger than the minimum, as the measured table on the page shows, and no approximation ratio is known for it.
Complexity
Let be the number of levels and the number of pins of .
- Coarsening. One HEC level sorts the nets, scans the pins and builds the coarse nets with sorted pin lists, in . EC costs per level, because each vertex scans the pins of its nets.
- Levels. Every kept level except the last has at most of the vertices of the one before, so , and the vertex counts of all levels add up to at most .
- Refinement. With gain buckets, one FM pass on costs . With passes per level and trials at the coarsest level, the total is for a constant number of V-cycles. The implementation picks the vertex of largest gain by a scan and scans the pins of each net of a moved vertex, so its pass costs .
- Space. All levels are kept for the way back, .
Properties
Multilevel hypergraph partitioning is a heuristic. What is proved and what is measured are kept apart.
What is proved. The items of the correctness section: the output is balanced; projection keeps the cut; each FM pass and each V-cycle never increase the cut; and the output is a local optimum of FM at the finest level, that is, no balanced prefix of one more FM pass lowers the cut. No approximation ratio is known. The method is randomized, through the order of the nets in HEC and the greedy fills.
What is measured. Karypis and coauthors (1999) compared hMETIS with the netlist partitioners of the time on benchmark circuits and reported smaller cuts and shorter run times; the numbers are in their paper. The numbers below are from the implementation of this page, on toy inputs, and are not benchmark results. On 200 random hypergraphs with unit cells and unit nets of sizes 2 to 5 (generator random.Random(2026), run seeded with random.Random(t)), with 6 to 8 cells on side 0 and , compared with exhaustive bisection:
| method | optimal | mean of cut / optimum | worst |
|---|---|---|---|
| multilevel, 4 trials, 1 V-cycle | 191 of 200 | 1.007 | 1.333 |
| multilevel, 1 trial, no V-cycle | 175 of 200 | 1.018 | |
| flat FM from a random bisection | 164 of 200 | 1.031 | 1.667 |
At flat FM already sees the whole netlist, so a small gap is expected. These numbers say nothing about large netlists, where the multilevel scheme was designed to help.
Variants and improvements
- Modified hyperedge coarsening (MHEC). After HEC, the pins of each net that are still unmerged are merged with each other, so fewer single vertices remain.
- Edge coarsening. The EC scheme of the implementation, a heavy edge matching under the clique net model with weight .
- Hyperedge refinement. Besides FM, hMETIS can move all pins of a cut net to one side at once (HER), which FM moves of single vertices cannot do in one step.
- Many trials and the best of them. Run the whole scheme with several seeds and keep the best result; cheap because each run is fast.
- k-way partitioning. Recursive bisection, or direct -way refinement at each level, for the cut-net or the connectivity metric.
- Later tools. PaToH for sparse matrices and KaHyPar, with -level coarsening that removes one vertex per level, follow the same multilevel idea.
When to use it
Use a multilevel hypergraph partitioner for any netlist of more than a few thousand cells, and for hypergraph models of sparse matrices and parallel computations. It is the standard partitioner inside min-cut placement. For a graph, the graph version, multilevel graph partitioning, is simpler and as good. For tiny instances, exhaustive search or an exact solver gives a proof of optimality, which this method never gives.
Pitfalls
- Coarse vertices that are too heavy. If one coarse vertex weighs more than , a balanced partition of the coarse level may not exist, and the greedy start fails. Cap the weight, or allow a looser balance at coarse levels.
- Large nets in HEC. A net with many pins would merge many cells into one vertex. The order by size and the weight cap prevent this; tools also skip nets above a size limit.
- Counting clique edges. The cut is the weight of the cut nets. EC uses clique weights only to choose pairs, never as the objective.
- Dropping merged nets wrongly. Two fine nets with the same coarse image must become one coarse net with the sum of the weights. Dropping one of them makes the coarse cut wrong.
- Stalled coarsening. If a level merges almost nothing, the next level is the same size, and the loop would run forever. Stop when a level removes too few vertices.
- Restricted coarsening forgotten. A V-cycle that merges vertices across the cut destroys the current partition at the coarse levels.
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/multilevel-hypergraph-partitioning/. The authors are listed in prov/FYFXXW.jsonl.
import random
from fractions import Fraction
from typing import Optional, Sequence
def cut_weight(nets: Sequence[Sequence[int]], netw: Sequence[int], side: Sequence[int]) -> int:
"""Total weight of the nets with pins on both sides."""
return sum(w for e, w in zip(nets, netw) if len({side[v] for v in e}) == 2)
def fm_refine(
n: int,
nets: Sequence[Sequence[int]],
netw: Sequence[int],
vw: Sequence[int],
side: Sequence[int],
lo: int,
hi: int,
) -> list[int]:
"""Fiduccia-Mattheyses passes with vertex weights and net weights.
The weight of side 0 stays in [lo, hi] at every step. Each pass moves
every free vertex at most once, always the free vertex of largest gain
whose move keeps the balance (ties: the smaller number), and then keeps
the best prefix. Passes repeat while the best prefix has positive gain.
The vertex of largest gain is found by a scan, and each move scans the
pins of its nets, so a pass costs O(n^2 + sum of |e|^2 over the nets),
instead of O(n + P) for P pins with the gain buckets of FM.
"""
side = list(side)
vnets: list[list[int]] = [[] for _ in range(n)]
for i, e in enumerate(nets):
for v in e:
vnets[v].append(i)
while True:
cnt = [[0, 0] for _ in nets]
for i, e in enumerate(nets):
for v in e:
cnt[i][side[v]] += 1
gain = [0] * n
for v in range(n):
s = side[v]
for i in vnets[v]:
if cnt[i][s] == 1:
gain[v] += netw[i]
if cnt[i][1 - s] == 0:
gain[v] -= netw[i]
locked = [False] * n
w0 = sum(vw[v] for v in range(n) if side[v] == 0)
moves: list[int] = []
total, best_total, best_k = 0, 0, 0
while True:
pick = -1
for v in range(n):
if locked[v]:
continue
nw0 = w0 - vw[v] if side[v] == 0 else w0 + vw[v]
if lo <= nw0 <= hi and (pick < 0 or gain[v] > gain[pick]):
pick = v
if pick < 0:
break
v, f = pick, side[pick]
t = 1 - f
locked[v] = True
for i in vnets[v]:
e, w = nets[i], netw[i]
if cnt[i][t] == 0:
for u in e:
if not locked[u]:
gain[u] += w
elif cnt[i][t] == 1:
for u in e:
if side[u] == t and not locked[u]:
gain[u] -= w
cnt[i][f] -= 1
cnt[i][t] += 1
if cnt[i][f] == 0:
for u in e:
if not locked[u]:
gain[u] -= w
elif cnt[i][f] == 1:
for u in e:
if side[u] == f and u != v and not locked[u]:
gain[u] += w
total += gain[v]
side[v] = t
w0 += -vw[v] if f == 0 else vw[v]
moves.append(v)
if total > best_total:
best_total, best_k = total, len(moves)
for v in moves[best_k:]:
side[v] = 1 - side[v]
if best_total <= 0:
return side
def coarsen(
n: int,
nets: Sequence[Sequence[int]],
netw: Sequence[int],
vw: Sequence[int],
cap: int,
rng: random.Random,
scheme: str = "hec",
side: Optional[Sequence[int]] = None,
) -> tuple[list[int], int, list[list[int]], list[int], list[int]]:
"""One coarsening level by hyperedge coarsening ("hec") or edge coarsening ("ec").
hec visits the nets in order of non-increasing weight, then non-decreasing
size, with random order among ties, and merges all pins of a net if none
of them is merged yet. ec visits the vertices in random order and merges
each unmerged vertex with the unmerged vertex that shares the largest sum
of w(e)/(|e| - 1) over common nets. No coarse vertex weighs more than cap.
If side is given, only vertices on the same side merge (restricted
coarsening for V-cycles). Coarse nets are the images of the nets; nets
with one coarse pin are dropped and equal coarse nets are merged with
their weights added.
Returns (cmap, k, coarse nets, coarse net weights, coarse vertex weights).
"""
cmap = [-1] * n
k = 0
if scheme == "hec":
order = list(range(len(nets)))
rng.shuffle(order)
order.sort(key=lambda i: (-netw[i], len(nets[i])))
for i in order:
e = nets[i]
if len(e) < 2 or any(cmap[v] >= 0 for v in e):
continue
if sum(vw[v] for v in e) > cap:
continue
if side is not None and len({side[v] for v in e}) > 1:
continue
for v in e:
cmap[v] = k
k += 1
elif scheme == "ec":
vnets: list[list[int]] = [[] for _ in range(n)]
for i, e in enumerate(nets):
for v in e:
vnets[v].append(i)
order = list(range(n))
rng.shuffle(order)
for v in order:
if cmap[v] >= 0:
continue
score: dict[int, Fraction] = {}
for i in vnets[v]:
e = nets[i]
for u in e:
if u == v or cmap[u] >= 0 or vw[u] + vw[v] > cap:
continue
if side is not None and side[u] != side[v]:
continue
score[u] = score.get(u, Fraction(0)) + Fraction(netw[i], len(e) - 1)
if score:
u = max(score, key=lambda u: (score[u], -u))
cmap[u] = k
cmap[v] = k
k += 1
else:
raise ValueError("scheme must be 'hec' or 'ec'")
for v in range(n):
if cmap[v] < 0:
cmap[v] = k
k += 1
merged: dict[tuple[int, ...], int] = {}
for e, w in zip(nets, netw):
ce = tuple(sorted({cmap[v] for v in e}))
if len(ce) >= 2:
merged[ce] = merged.get(ce, 0) + w
cvw = [0] * k
for v in range(n):
cvw[cmap[v]] += vw[v]
return cmap, k, [list(e) for e in merged], list(merged.values()), cvw
def _greedy_fill(k: int, cvw: Sequence[int], lo: int, hi: int, rng: random.Random) -> list[int]:
"""Random greedy bisection: add vertices to side 0 in random order until its weight reaches lo."""
order = list(range(k))
rng.shuffle(order)
side, w0 = [1] * k, 0
for v in order:
if w0 >= lo:
break
if w0 + cvw[v] <= hi:
side[v] = 0
w0 += cvw[v]
return side
def _down_and_up(
n: int,
nets: list[list[int]],
netw: list[int],
vw: list[int],
lo: int,
hi: int,
cap: int,
coarsest: int,
rng: random.Random,
scheme: str,
trials: int,
side: Optional[list[int]],
) -> list[int]:
levels = [] # (cmap, graph of the finer level)
cur = (n, nets, netw, vw)
while cur[0] > coarsest: # @line L2
cmap, k, cn, cw, cv = coarsen(*cur, cap, rng, scheme, side) # @line L3
if k == cur[0]:
break
levels.append((cmap, cur))
cur = (k, cn, cw, cv)
if side is not None:
proj = [0] * k
for v, c in enumerate(cmap):
proj[c] = side[v]
side = proj
if k > 0.9 * levels[-1][1][0]: # @line L4
break
k, cn, cw, cv = cur
if side is None:
best, best_cut = None, None
for _ in range(max(1, trials)): # @line L5
s = fm_refine(k, cn, cw, cv, _greedy_fill(k, cv, lo, hi, rng), lo, hi) # @line L6
c = cut_weight(cn, cw, s)
if best_cut is None or c < best_cut:
best, best_cut = s, c
side = best # @line L7
else:
side = fm_refine(k, cn, cw, cv, side, lo, hi)
for cmap, (fn, fnets, fnetw, fvw) in reversed(levels): # @line L8
side = [side[cmap[v]] for v in range(fn)] # @line L9
side = fm_refine(fn, fnets, fnetw, fvw, side, lo, hi) # @line L10
return side
def multilevel_hypergraph_partitioning(
n: int,
nets: Sequence[Sequence[int]],
lo: int,
hi: int,
rng: random.Random,
netw: Optional[Sequence[int]] = None,
vw: Optional[Sequence[int]] = None,
scheme: str = "hec",
coarsest: int = 8,
trials: int = 4,
vcycles: int = 1,
cap: Optional[int] = None,
) -> list[int]:
"""Bisect a hypergraph by the multilevel scheme of hMETIS.
Vertices are 0 .. n-1 with weights vw (default 1), nets are lists of
distinct vertices with weights netw (default 1). The weight of side 0 must
end in [lo, hi]. Coarsening stops at coarsest vertices, or when a level
removes less than a tenth of the vertices. The coarsest hypergraph gets
trials random greedy bisections, each refined by FM, and the best is
projected back with FM refinement at each level. Then vcycles V-cycles
coarsen again inside the two sides and refine on the way up. Coarse
vertices weigh at most cap, by default max(1, hi - lo), so that a
balanced start always exists.
Returns side[v] in {0, 1}. Cost: O(P log P) per coarsening level by hec
(O(sum of |e|^2) by ec), and O(n_l^2 + sum of |e|^2) per FM pass on a
level with n_l vertices.
"""
netw = [1] * len(nets) if netw is None else list(netw)
vw = [1] * n if vw is None else list(vw)
if not 0 <= lo <= hi <= sum(vw):
raise ValueError("need 0 <= lo <= hi <= total vertex weight")
if cap is None:
cap = max(1, hi - lo)
if cap > hi - lo + 1 or max(vw, default=0) > cap:
raise ValueError("need max vertex weight <= cap <= hi - lo + 1")
net_list = [sorted(set(e)) for e in nets] # @line L1
side = _down_and_up(n, net_list, netw, vw, lo, hi, cap, coarsest, rng, scheme, trials, None)
for _ in range(vcycles): # @line L11
side = _down_and_up(n, net_list, netw, vw, lo, hi, cap, coarsest, rng, scheme, trials, side) # @line L12
return side # @line L13
test_multilevel_hypergraph_partitioning.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multilevel-hypergraph-partitioning/. The authors are listed in prov/FYFXXW.jsonl.
import random
from multilevel_hypergraph_partitioning import (
coarsen,
cut_weight,
fm_refine,
multilevel_hypergraph_partitioning,
)
def exhaustive_best(n: int, nets, netw, lo: int, hi: int) -> int:
"""Least cut over all 2^n assignments with lo <= |side 0| <= hi (the brute force)."""
masks = [sum(1 << v for v in e) for e in nets]
full = (1 << n) - 1
best = None
for s in range(1 << n):
if not lo <= bin(s).count("1") <= hi:
continue
c = 0
for m, w in zip(masks, netw):
if m & s and m & (full ^ s):
c += w
if best is None or c < best:
best = c
return best
def random_hypergraph(rng: random.Random, n: int, m: int) -> list[list[int]]:
nets = []
for _ in range(m):
size = rng.choice([2, 2, 2, 3, 3, 4, 5])
nets.append(rng.sample(range(n), min(size, n)))
return nets
def page_example():
# Two clusters {0..4} and {5..9} joined by the nets {4, 5} and {2, 3, 7}.
nets = [[0, 1, 2], [1, 2, 3], [0, 3, 4], [2, 4], [0, 1], [5, 6, 7], [6, 7, 8], [5, 8, 9], [7, 9], [5, 6], [4, 5], [2, 3, 7]]
return 10, nets
def test_page_example():
n, nets = page_example()
side = multilevel_hypergraph_partitioning(n, nets, 4, 6, random.Random(7))
assert 4 <= side.count(0) <= 6
c = cut_weight(nets, [1] * len(nets), side)
assert c == 2 == exhaustive_best(n, nets, [1] * len(nets), 4, 6)
def test_coarsening_keeps_cut_and_weight():
rng = random.Random(11)
for _ in range(200):
n = rng.randint(2, 12)
nets = [sorted(set(e)) for e in random_hypergraph(rng, n, rng.randint(1, 15))]
netw = [rng.randint(1, 3) for _ in nets]
vw = [1] * n
for scheme in ("hec", "ec"):
cap = rng.randint(1, 4)
cmap, k, cn, cw, cv = coarsen(n, nets, netw, vw, cap, rng, scheme)
assert sum(cv) == n and max(cv) <= cap and k <= n
assert all(len(e) >= 2 for e in cn) and len({tuple(e) for e in cn}) == len(cn)
# Every coarse partition projects to a fine partition with the same cut.
for _ in range(5):
cs = [rng.randint(0, 1) for _ in range(k)]
fs = [cs[cmap[v]] for v in range(n)]
assert cut_weight(cn, cw, cs) == cut_weight(nets, netw, fs)
# Restricted coarsening merges only vertices on the same side.
side = [rng.randint(0, 1) for _ in range(n)]
cmap, k, cn, cw, cv = coarsen(n, nets, netw, vw, cap, rng, scheme, side)
for u in range(n):
for v in range(n):
if cmap[u] == cmap[v]:
assert side[u] == side[v]
def test_fm_refine_never_worse_and_balanced():
rng = random.Random(5)
for _ in range(200):
n = rng.randint(2, 10)
nets = [sorted(set(e)) for e in random_hypergraph(rng, n, rng.randint(1, 12))]
netw = [rng.randint(1, 3) for _ in nets]
vw = [rng.randint(1, 2) for _ in range(n)]
side = [rng.randint(0, 1) for _ in range(n)]
w0 = sum(vw[v] for v in range(n) if side[v] == 0)
lo, hi = max(0, w0 - rng.randint(0, 2)), w0 + rng.randint(0, 2)
out = fm_refine(n, nets, netw, vw, side, lo, hi)
assert lo <= sum(vw[v] for v in range(n) if out[v] == 0) <= hi
assert cut_weight(nets, netw, out) <= cut_weight(nets, netw, side)
def test_against_exhaustive_bisection():
rng = random.Random(2026)
for trial in range(300):
n = rng.randint(2, 12) if trial < 260 else 14
nets = random_hypergraph(rng, n, rng.randint(1, 2 * n))
netw = [rng.randint(1, 2) for _ in nets]
half = n // 2
slack = rng.choice([0, 1, 2])
lo, hi = max(0, half - slack), min(n, half + slack)
scheme = rng.choice(["hec", "ec"])
side = multilevel_hypergraph_partitioning(n, nets, lo, hi, random.Random(trial), netw=netw, scheme=scheme, coarsest=rng.choice([2, 4, 8]))
assert len(side) == n and set(side) <= {0, 1}
assert lo <= side.count(0) <= hi
c = cut_weight(nets, netw, side)
# The cut recomputed by bitmasks agrees.
full = (1 << n) - 1
s = sum(1 << v for v in range(n) if side[v] == 0)
masks = [sum(1 << v for v in e) for e in nets]
assert c == sum(w for m, w in zip(masks, netw) if m & s and m & (full ^ s))
assert c >= exhaustive_best(n, nets, netw, lo, hi)
def test_edge_cases():
assert multilevel_hypergraph_partitioning(1, [], 0, 1, random.Random(0)) in ([0], [1])
side = multilevel_hypergraph_partitioning(4, [[0, 1, 2, 3]], 2, 2, random.Random(0))
assert side.count(0) == 2
side = multilevel_hypergraph_partitioning(6, [[0, 1], [0, 1], [2, 3]], 3, 3, random.Random(1))
assert side.count(0) == 3
History
Multilevel partitioning of graphs grew from Bui and Jones (1993) and Hendrickson and Leland (1995), and Karypis and Kumar made it fast and robust in METIS (1995 to 1998). Karypis, Aggarwal, Kumar and Shekhar carried the scheme to hypergraphs as hMETIS, presented at DAC 1997 and published in 1999, with hyperedge coarsening and V-cycles. The authors reported smaller cuts than earlier netlist partitioners on the benchmarks of the time, and hMETIS became a common reference partitioner for placement and for later tools.
References
- George Karypis, Rajat Aggarwal, Vipin Kumar and Shashi Shekhar, Multilevel hypergraph partitioning, applications in VLSI domain, IEEE Transactions on VLSI Systems 7(1), 69 to 79, 1999, the coarsening schemes (edge, hyperedge and modified hyperedge coarsening), the initial partitioning, the FM and hyperedge refinement, and the V-cycle refinement with restricted coarsening
- George Karypis, Rajat Aggarwal, Vipin Kumar and Shashi Shekhar, Multilevel hypergraph partitioning, application in VLSI domain, Proceedings of the 34th Design Automation Conference, 1997, the conference version of the method
- George Karypis and Vipin Kumar, A fast and high quality multilevel scheme for partitioning irregular graphs, SIAM Journal on Scientific Computing 20(1), 359 to 392, 1998, the multilevel scheme for graphs (METIS), with heavy edge matching and boundary refinement, which hMETIS carries over to hypergraphs
- C. M. Fiduccia and R. M. Mattheyses, A linear-time heuristic for improving network partitions, 19th Design Automation Conference, 175 to 181, 1982, the refinement used at each level, with gain buckets and the balance condition with vertex weights
- Andrew B. Kahng, Jens Lienig, Igor L. Markov and Jin Hu, VLSI Physical Design, From Graph Partitioning to Timing Closure, second edition, Springer, 2022, Chapter 2, Netlist and System Partitioning (the multilevel framework; 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.
| 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 FYFXXW Edit this page History Report an error Markdown