Algorithm Search⌘K

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.

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
Properties
randomizednot exactiterative
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 H=(V,N)H = (V, N) with nn vertices (cells) of integer weights c(v)≥1c(v) \ge 1, mm nets of integer weights w(e)≥1w(e) \ge 1 and P=∑e∣e∣P = \sum_e |e| pins, and a balance window lo≤hilo \le hi. The output is a bisection V=V0∪V1V = V_0 \cup V_1 with lo≤c(V0)≤hilo \le c(V_0) \le hi. 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 HjH_j. A coarsening of HjH_j is a map πj\pi_j from its vertices onto the vertices of Hj+1H_{j+1}. A coarse vertex weighs the sum of the weights of its preimage. Each net ee becomes the net πj(e)\pi_j(e); 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 ∑w(e)/(∣e∣−1)\sum w(e)/(|e| - 1) over their shared nets.

The implementation caps the weight of a coarse vertex at cap\mathit{cap}, with max⁡vc(v)≤cap≤hi−lo+1\max_v c(v) \le \mathit{cap} \le hi - lo + 1 (by default max⁡(1,hi−lo)\max(1, hi - lo)). This cap is a choice of this page, made so that a balanced start always exists at the coarsest level.

  1. MULTILEVEL-BISECT(H, lo, hi, c0, t, v)
  2. 1H_0 ← H; ℓ ← 0
  3. 2while H_ℓ has more than c0 vertices
  4. 3H_{ℓ+1} ← HEC(H_ℓ, cap); if no vertices merged then stop the loop
  5. 4ℓ ← ℓ + 1; if H_ℓ has more than 9/10 of the vertices of H_{ℓ−1} then stop the loop
  6. 5repeat t times
  7. 6s′ ← FM(H_ℓ, GREEDY-FILL(H_ℓ, lo, hi), lo, hi)
  8. 7if s′ has the least cut so far then s ← s′
  9. 8for j ← ℓ − 1 down to 0
  10. 9s ← the projection of s: each vertex of H_j takes the side of its coarse vertex
  11. 10s ← FM(H_j, s, lo, hi)
  12. 11repeat v times ▷ V-cycles
  13. 12run 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
  14. 13return s

GREEDY-FILL puts the vertices on side 0 in random order, while c(V0)<loc(V_0) < lo. 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 c(V0)c(V_0) in [lo,hi][lo, hi], 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 ss. Then ss is a partition of every coarse level, with the same cut, and FM at the coarse levels can move whole clusters of ss across the cut.

Example

Take n=10n = 10 unit cells, unit nets and the window [4,6][4, 6], so cap=2\mathit{cap} = 2:

{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}.\{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\}.

The first five nets live on {0,…,4}\{0, \ldots, 4\}, the next five on {5,…,9}\{5, \ldots, 9\}, and the last two join the groups. The trace below is the run of the implementation with random.Random(7) and c0=8c_0 = 8.

Coarsening. All weights are 1, so HEC visits the five nets of size 2 first. It merges {2,4}\{2, 4\}, {7,9}\{7, 9\}, {0,1}\{0, 1\} and {5,6}\{5, 6\}, then skips {4,5}\{4, 5\} 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 H1H_1 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 H1H_1 are {A,C}\{A, C\} of weight 1 (from {0,1,2}\{0,1,2\}), {A,C,E}\{A, C, E\} of weight 2 (from {1,2,3}\{1,2,3\} and {0,3,4}\{0,3,4\}, merged), {B,D}\{B, D\} of weight 1, {B,D,F}\{B, D, F\} of weight 2, {A,D}\{A, D\} of weight 1 (from {4,5}\{4,5\}) and {A,B,E}\{A, B, E\} of weight 1 (from {2,3,7}\{2,3,7\}). The nets {2,4}\{2,4\}, {0,1}\{0,1\}, {7,9}\{7,9\} and {5,6}\{5,6\} are inside coarse vertices and are dropped. H1H_1 has 6≤c06 \le c_0 vertices, so coarsening stops.

Initial partitioning. The first greedy fill puts {C,D,F}\{C, D, F\} on side 0, weight 5. Its cut is 7: the nets {A,C}\{A, C\}, {A,C,E}\{A, C, E\} (weight 2), {B,D}\{B, D\}, {B,D,F}\{B, D, F\} (weight 2) and {A,D}\{A, D\} are cut. FM turns it into {A,C,E}∣{B,D,F}\{A, C, E\} \mid \{B, D, F\}, with weight 5 on side 0 and cut 2 (the nets {A,D}\{A, D\} and {A,B,E}\{A, B, E\}). The other three trials, from starts with cuts 6, 7 and 7, end at the same partition.

Uncoarsening. Line L9 gives the cells {0,1,2,3,4}∣{5,…,9}\{0, 1, 2, 3, 4\} \mid \{5, \ldots, 9\}, with cut 2, the same as at level 1. FM finds no improving prefix.

V-cycle. Restricted coarsening merges {2,4}\{2,4\}, {5,6}\{5,6\}, {0,1}\{0,1\} and {7,9}\{7,9\} again (here the same pairs), each inside one side. FM at both levels keeps the partition. The result is {0,…,4}∣{5,…,9}\{0, \ldots, 4\} \mid \{5, \ldots, 9\} with cut 2, the nets {4,5}\{4, 5\} and {2,3,7}\{2, 3, 7\}. A brute force over all 2102^{10} 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 max⁡vc(v)≤cap≤hi−lo+1\max_v c(v) \le \mathit{cap} \le hi - lo + 1 and lo≤c(V)lo \le c(V).

  • Projection keeps the cut and the balance. For every partition ss of Hj+1H_{j+1}, its projection to HjH_j has the same cut and the same weight on side 0.
  • A balanced start. GREEDY-FILL always ends with lo≤c(V0)≤hilo \le c(V_0) \le hi, because while c(V0)<loc(V_0) < lo 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 lo≤c(V0)≤hilo \le c(V_0) \le hi.
  • 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 nn levels; with the 9/10 rule there are O(log⁡n)O(\log n).
Proof: The multilevel bisection is balanced, projection keeps the cut, and no phase after the coarsest level increases the cutfull

Let H=(V,N)H = (V, N) have vertex weights c(v)≥1c(v) \ge 1 and net weights w(e)≥1w(e) \ge 1, all integers. A partition is a map s:V→{0,1}s : V \to \{0, 1\}, its balance is c0(s)=∑s(v)=0c(v)c_0(s) = \sum_{s(v) = 0} c(v), and its cut is cut(s)=∑{w(e):e∈N, s is not constant on e}\mathrm{cut}(s) = \sum \{ w(e) : e \in N, \ s \text{ is not constant on } e \}. We assume 0≤lo≤hi≤c(V)0 \le lo \le hi \le c(V) and max⁡vc(v)≤cap≤hi−lo+1\max_v c(v) \le \mathit{cap} \le hi - lo + 1, which the implementation checks.

Lemma 1 (projection). Let π:V→V′\pi : V \to V' be one coarsening step of HEC or EC, with coarse weights c′(x)=∑π(v)=xc(v)c'(x) = \sum_{\pi(v) = x} c(v) and coarse nets as described on the page. For every partition s′s' of V′V', the projection s=s′∘πs = s' \circ \pi satisfies c0(s)=c0′(s′)c_0(s) = c'_0(s') and cut(s)=cut′(s′)\mathrm{cut}(s) = \mathrm{cut}'(s').

Proof. The balance: c0(s)=∑x:s′(x)=0∑π(v)=xc(v)=c0′(s′)c_0(s) = \sum_{x : s'(x) = 0} \sum_{\pi(v) = x} c(v) = c'_0(s'). The cut: a fine net ee is cut by ss exactly when s′s' is not constant on π(e)\pi(e), because s(v)=s′(π(v))s(v) = s'(\pi(v)). If ∣π(e)∣=1|\pi(e)| = 1, the net is not cut and is dropped, so it adds 0 on both sides. Otherwise π(e)\pi(e) is a coarse net, and the coarse net ff has weight w′(f)=∑{w(e):π(e)=f}w'(f) = \sum \{ w(e) : \pi(e) = f \}. Group the fine nets by their image: cut(s)=∑f[s′ not constant on f]∑π(e)=fw(e)=cut′(s′)\mathrm{cut}(s) = \sum_f [s' \text{ not constant on } f] \sum_{\pi(e) = f} w(e) = \mathrm{cut}'(s'). □\square

By induction on the levels, the same holds for the composed map from H0H_0 to any HjH_j.

Lemma 2 (weight cap). Every coarse vertex weighs at most cap\mathit{cap}.

Proof. HEC merges the pins of a net only if their total weight is at most cap\mathit{cap}, and EC merges two vertices only if their total weight is at most cap\mathit{cap}. Each coarse vertex is formed by one such merge of vertices of the level below, or is a single vertex of weight at most cap\mathit{cap} by induction (at level 0 by the assumption max⁡vc(v)≤cap\max_v c(v) \le \mathit{cap}). □\square

Lemma 3 (greedy fill). On a level with vertex weights at most cap≤hi−lo+1\mathit{cap} \le hi - lo + 1 and total weight c(V)≥loc(V) \ge lo, GREEDY-FILL returns ss with lo≤c0(s)≤hilo \le c_0(s) \le hi.

Proof. The fill visits the vertices in some order, stops as soon as c0≥loc_0 \ge lo, and adds a vertex vv if c0+c(v)≤hic_0 + c(v) \le hi. While c0<loc_0 < lo, that is c0≤lo−1c_0 \le lo - 1, every vertex satisfies c0+c(v)≤lo−1+hi−lo+1=hic_0 + c(v) \le lo - 1 + hi - lo + 1 = hi, so every visited vertex is added. Hence c0≤hic_0 \le hi after each addition. If the loop stops early, c0≥loc_0 \ge lo. If it visits all vertices without stopping, all were added, so c0=c(V)≥loc_0 = c(V) \ge lo. If lo=0lo = 0 the loop stops at once with c0=0c_0 = 0. In each case lo≤c0≤hilo \le c_0 \le hi. The total weight is the same on every level by Lemma 1, so c(V)≥loc(V) \ge lo holds on every level. □\square

Lemma 4 (FM). If lo≤c0(s)≤hilo \le c_0(s) \le hi, then FM(s)(s) returns s∗s^{*} with lo≤c0(s∗)≤hilo \le c_0(s^{*}) \le hi and cut(s∗)≤cut(s)\mathrm{cut}(s^{*}) \le \mathrm{cut}(s), and it stops.

Proof. In a pass, a vertex is chosen only if its move keeps c0c_0 in [lo,hi][lo, hi], so every tentative partition is balanced. The gain of a free vertex vv on side ff is g(v)=∑{w(e):e∋v,Nf(e)=1}−∑{w(e):e∋v,N1−f(e)=0}g(v) = \sum \{w(e) : e \ni v, N_f(e) = 1\} - \sum \{w(e) : e \ni v, N_{1-f}(e) = 0\}, the decrease of the cut if vv moves alone. The updates in the implementation are the critical net rules of Fiduccia and Mattheyses with the net weight w(e)w(e) 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 gg equal to this decrease for every free vertex, and the weights only scale each term. So after the first kk moves the cut is cut(s)−Gk\mathrm{cut}(s) - G_k, where GkG_k is the sum of the first kk gains. The pass keeps the prefix of largest GkG_k, with G0=0G_0 = 0 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 GkG_k was positive, so the integer cut falls by at least 1 per repeated pass, and there are at most cut(s)+1\mathrm{cut}(s) + 1 passes. □\square

Theorem 1 (balance). The output satisfies lo≤c0(s)≤hilo \le c_0(s) \le hi.

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. □\square

Theorem 2 (monotonicity). Let scs_c be the partition chosen at the coarsest level. The cut of the partition after line L10 at level 0 is at most cut(sc)\mathrm{cut}(s_c), 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 ss is constant on each preimage π−1(x)\pi^{-1}(x) and defines a coarse partition s′s' with s=s′∘πs = s' \circ \pi. By Lemma 1 the cut of s′s' equals the cut of ss. FM at the coarsest level and at each level on the way up does not increase the cut, and projection keeps it. □\square

Theorem 3 (termination and levels). The loop of lines L2 to L4 runs at most nn times, and every kept level except possibly the last has at most 9/109/10 of the vertices of the level before it, so ℓ≤1+log⁡10/9(n/c0)\ell \le 1 + \log_{10/9}(n / c_0) when c0≥1c_0 \ge 1.

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 9/109/10 of the vertices of the level before. So all earlier levels shrink by a factor of at least 9/109/10, and the loop also stops when at most c0c_0 vertices remain. Every other loop of the algorithm runs over a finite list, and FM stops by Lemma 4. ■\blacksquare

Running time. One HEC step sorts the mjm_j nets in O(mjlog⁡mj)O(m_j \log m_j), checks the pins in O(Pj)O(P_j), and builds the coarse nets by sorting the pin list of each, in O(Pjlog⁡Pj)O(P_j \log P_j), with mj≤Pj≤Pm_j \le P_j \le P. EC scans, for each vertex, the pins of its nets, which is O(∑e∣e∣2)O(\sum_e |e|^2). One FM pass with gain buckets costs O(nj+Pj)O(n_j + P_j) (see the Fiduccia-Mattheyses page). The implementation uses a scan of all free vertices to pick each move, O(nj2)O(n_j^2) per pass, and scans all pins of the nets of the moved vertex, O(∑e∣e∣2)O(\sum_e |e|^2) per pass, since each vertex moves at most once. By Theorem 3 the number of levels is O(log⁡n)O(\log n), which gives the bounds on the page. The levels are stored for the way back, so the space is O(n+ℓP)O(n + \ell P), because the vertex counts of the levels add up to at most 10n10 n and each level has at most PP 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 ℓ\ell be the number of levels and Pj≤PP_j \le P the number of pins of HjH_j.

  • Coarsening. One HEC level sorts the nets, scans the pins and builds the coarse nets with sorted pin lists, in O(Pjlog⁡Pj)O(P_j \log P_j). EC costs O(∑e∣e∣2)O(\sum_e |e|^2) per level, because each vertex scans the pins of its nets.
  • Levels. Every kept level except the last has at most 9/109/10 of the vertices of the one before, so ℓ≤1+log⁡10/9(n/c0)=O(log⁡n)\ell \le 1 + \log_{10/9}(n / c_0) = O(\log n), and the vertex counts of all levels add up to at most 10n10 n.
  • Refinement. With gain buckets, one FM pass on HjH_j costs O(nj+Pj)O(n_j + P_j). With pp passes per level and tt trials at the coarsest level, the total is O(ℓ(Plog⁡P+p(n+P)))O(\ell (P \log P + p (n + P))) 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 O(nj2+∑e∣e∣2)O(n_j^2 + \sum_e |e|^2).
  • Space. All levels are kept for the way back, O(n+ℓP)O(n + \ell P).

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 n=14n = 14 unit cells and m=20m = 20 unit nets of sizes 2 to 5 (generator random.Random(2026), run tt seeded with random.Random(t)), with 6 to 8 cells on side 0 and c0=4c_0 = 4, 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 n=14n = 14 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 1/(∣e∣−1)1/(|e| - 1).
  • 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 kk-way refinement at each level, for the cut-net or the connectivity metric.
  • Later tools. PaToH for sparse matrices and KaHyPar, with nn-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 hi−lo+1hi - lo + 1, 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.

multilevel_hypergraph_partitioning.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

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