Algorithmcore
Tseng-Siewiorek clique partitioning
Also called clique partitioning binding, Facet algorithm.
Tseng and Siewiorek's greedy heuristic that merges the pair of compatible nodes with the most common neighbours until the compatibility graph is split into cliques.
- Time
- O(n^2 m) worst
- Space
- O(n + m) extra
- Where
- m = the number of its edges; n = the number of vertices of the compatibility graph
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Chia Jeng Tseng, Daniel P. Siewiorek, 1986
Tseng-Siewiorek clique partitioning is a greedy heuristic for the clique cover problem on a resource compatibility graph, published by Tseng and Siewiorek in 1986 for high-level synthesis. Each vertex starts as its own group. While two groups are joined by an edge, the algorithm merges the pair with the most common neighbours, breaking ties by the fewest edges lost, and keeps only the edges to the common neighbours. Each final group is a clique, and so one shared unit, register or bus. The result is always a valid binding in which no two groups can be merged, in time. It is not optimal in general, and it is not optimal even on the interval graphs of straight-line code, where the left-edge algorithm is.
In plain words
Think of each operation as a person, and draw a line between two people who could share a desk because they are never in the office at the same time. We want few desks. Start with one desk per person. Then pick two people who could share and who have the most other possible deskmates in common, and seat them together. From then on, the pair counts as one, and it can only take in someone who could share with both. Repeat until no pair can be joined. Choosing the pair with the most shared friends keeps many options open for later merges. It is fast and usually good, but it can miss the fewest desks.
The problem
Given an undirected graph with vertices and edges, partition into the fewest cliques. In binding, is the compatibility graph of the operations of one unit type, of the values that need registers, or of the data transfers that need buses, and each clique is one shared unit, register or bus. See resource binding, register binding and interconnect binding. The problem is NP-hard in general, so the algorithm is a heuristic.
The algorithm
A supernode is a group of vertices, with a list of member vertices and a set of neighbouring supernodes. Merging two adjacent supernodes and removes the edges at and and gives the new supernode an edge to each common neighbour. The number of edges lost is
since the edges at or number , and the common neighbours keep one edge each.
TSENG-SIEWIOREK(G)- 1
make one supernode per vertex v, with members {v} and N(v) the neighbours of v in G - 2
while some supernode has a neighbour do - 3
for each pair of adjacent supernodes i < j do - 4
key(i, j) ← (−|N(i) ∩ N(j)|, del(i, j), i, j); keep the pair (i, j) with the least key - 5
members(i) ← members(i) ∪ members(j) - 6
N(i) ← (N(i) ∩ N(j)) \ {i, j}; delete j and update the neighbour sets of the others - 7
return the member lists of the supernodes
Line L4 takes the most common neighbours first, then the fewest lost edges, then the smallest pair of indices, so the run is deterministic. Line L6 keeps an edge from the new supernode only to supernodes that were joined to both and .
Example
Take the values of the straight-line example on the register binding page, with lifetimes , , , , , and , numbered to in this order. Two values are compatible when their lifetimes do not meet. The compatibility graph has 13 edges:
| merge | pair | common neighbours | edges lost | groups after the merge |
|---|---|---|---|---|
| 1 | (4) | 5 | ||
| 2 | (2) | 5 | ||
| 3 | none (0) | 1 | , | |
| 4 | none (0) | 2 | , |
In merge 1, and share four neighbours, more than any other pair. After merges 1 and 2, the edges left are , and , each pair with no common neighbour. Merge 3 takes , which loses only 1 edge. Merge 4 has a tie between and , both losing 2 edges, and takes by its smaller index. Then and are left with no edge, since their lifetimes are equal. The result is , and , three registers. Three values are live in step 2, so three is the least, and the left-edge algorithm gives the same groups here.
Correctness
What is proved, in the full proof:
- Each group is a clique, and the groups are fully joined exactly when they are adjacent. Two supernodes are adjacent exactly when every member of one is adjacent in to every member of the other. This holds at L1 and is kept by L5 and L6, so each merge at L5 joins two cliques with all edges between them into one clique.
- Termination. Each pass of the loop removes one supernode, so there are at most merges.
- Valid and maximal. The output partitions into cliques, so it is a valid binding. No two output groups can be merged into a larger clique.
- Exact on unions of cliques. If is a disjoint union of cliques, the output is exactly those cliques, which is optimal.
What is not proved, and is false: that the number of groups is the least.
- On the graph made of a triangle with one pendant vertex on each corner, the algorithm merges the triangle first and ends with 4 groups, while the 3 pendant edges are a partition into 3 cliques.
- On the interval lifetimes , at most 4 intervals share a point, so 4 registers suffice, for example , , , . The algorithm merges with (4 common neighbours), then with , then the two pairs, and ends with 5 groups. Every order of breaking the ties ends with 5.
These failures are measured as well, as tests and not as bounds. Over all graphs on 6 labelled vertices, the algorithm misses the optimum on 180, and it is optimal on every graph with at most 5 vertices. On 1000 random graphs with 2 to 9 vertices, it uses one extra clique on 11 of them and is optimal on the rest. On 1000 random interval instances with at most 9 intervals, it reached the depth every time, so the interval failure above is rare.
Proof: Tseng-Siewiorek clique partitioning returns a maximal clique partitionfull
We use the notation of the page. has vertices. At any moment the supernodes have member sets and neighbour sets , and exactly when . Two sets are fully joined when every and every are adjacent in .
Lemma 1 (invariants). Before each test of line L2:
- the sets partition ;
- each is a clique of ;
- for two supernodes , exactly when and are fully joined.
Proof. By induction on the number of merges. After L1, each , so (1) and (2) hold, and is the set of neighbours of in , which is (3) for single vertices.
Assume the claims before a merge of and with . Line L5 replaces and by their union, so (1) still holds. By (2), and are cliques, and by (3) they are fully joined, so their union is a clique, and (2) holds. For (3), take another supernode . By line L6, is a neighbour of the new supernode exactly when . By (3) before the merge, that is when is fully joined to and to , which is when it is fully joined to . Line L6 removes from every neighbour set and adds the new supernode only to the sets of its new neighbours, so the adjacency between two supernodes other than the merged one is unchanged, and (3) holds for them by the assumption.
Lemma 2 (termination). The loop runs at most times.
Proof. Each pass of the loop deletes one supernode and creates none, and there are supernodes after L1. When one supernode is left it has no neighbour, so the loop stops. A pass starts only when some supernode has a neighbour, so line L4 always finds a pair.
Theorem 1 (valid and maximal). The output is a partition of into cliques of . No two output sets are fully joined, so no two of them can be replaced by their union to get a partition into fewer cliques.
Proof. By Lemma 2 the loop stops, and then no supernode has a neighbour. By Lemma 1 (1) and (2) the output sets partition into cliques. If two output sets and were fully joined, then by Lemma 1 (3) we would have , and the loop would not have stopped.
By the resource compatibility graph page, a partition of the compatibility graph into cliques is a valid binding, so the output is a valid binding with one unit, register or bus per output set.
Theorem 2 (exact on unions of cliques). If is a disjoint union of cliques , the output is , which has the fewest cliques.
Proof. Every clique of lies inside one , since there are no edges between different . So every partition into cliques has at least parts, one for each nonempty at least. By Lemma 1 (2), each output set is a clique and lies inside one . If two output sets lay inside the same , they would be fully joined, against Theorem 1. So each is exactly one output set.
What is not claimed. The number of output sets is not always the least. The page gives two graphs where it is not: a triangle with a pendant vertex on each corner, with 4 sets against 3, and an interval graph on 8 lifetimes of depth 4, with 5 sets against 4. On the interval graph, every order of breaking ties in line L4 gives 5 sets. These instances are checked in the tests of the implementation.
Complexity
Each pass of the loop scans the adjacent pairs, at most , and intersects two neighbour sets of size at most , for time per pass. There are at most passes, so the time is . Keeping the number of common neighbours of each edge up to date after each merge lowers the cost of a pass. The space is for the members and the neighbour sets.
Properties
- Deterministic. The tie rule of L4 fixes the run. Other tie rules give other partitions, sometimes of a different size.
- Not exact. It can use more cliques than needed, also on interval graphs.
- Maximal output. No two output groups can be joined, so the output is never improved by merging alone.
- Uses only the graph. The rule looks at common neighbours, not at lifetimes or schedules, so it applies to conditional code and loops, where the conflict graph is not an interval graph.
Variants and improvements
- Weighted merges. Weight each edge by the interconnect two operations save when they share a unit, such as common operand sources, and merge the heaviest edge first. This trades unit count for multiplexer inputs, see interconnect binding.
- Faster bookkeeping. Keep the number of common neighbours for each edge, and update only the edges near the merged pair.
- Bus allocation. The same greedy on the compatibility graph of data transfers groups transfers into buses.
- Coloring the conflict graph instead. A partition into cliques of is a coloring of its complement, so coloring heuristics such as DSatur are an alternative.
When to use it
Use it when the compatibility graph has no special structure, for example with mutually exclusive branches or loop lifetimes, and the graph is small enough for . For straight-line code, where the conflict graph is an interval graph, use the left-edge algorithm or interval partitioning, which are exact and faster. For chordal conflict graphs, chordal graph coloring is exact. When interconnect matters as much as the count, weighted bipartite matching binding is a common choice for registers.
Pitfalls
- Assuming it is optimal on straight-line code. It is not, as the interval example shows. An implementation that checks its result against the largest number of values live in one step must allow a larger count.
- Mixing unit types in one graph. The graph must be built for one unit type, or a clique may contain operations that no single unit can run, see the non-examples on the resource compatibility graph page.
- Forgetting to drop edges. After a merge, the new supernode may only stay adjacent to common neighbours. Keeping the union of the neighbour sets produces groups that are not cliques.
- Missed mutual exclusion. Fewer detected exclusions means fewer edges, and so more units.
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/tseng-siewiorek-clique-partitioning/. The authors are listed in prov/FCVE23.jsonl.
"""Tseng-Siewiorek greedy clique partitioning of a compatibility graph.
The graph has the vertices 0, ..., n - 1 and a list of undirected edges.
An edge joins two operations or values that may share one unit or register.
The result is a list of cliques that partition the vertices; each clique is
one unit or register. The greedy merges, while an edge remains, the pair of
supernodes with the most common neighbours. Ties go to the merge that deletes
the fewest edges, then to the smallest pair of indices.
"""
def tseng_siewiorek(n: int, edges: list[tuple[int, int]]) -> list[list[int]]:
"""Return a partition of range(n) into cliques of the graph, by the greedy merge rule."""
members: dict[int, list[int]] = {}
nbr: dict[int, set[int]] = {}
for v in range(n): # @line L1
members[v] = [v]
nbr[v] = set()
for u, v in edges:
if u != v:
nbr[u].add(v)
nbr[v].add(u)
while any(nbr[v] for v in nbr): # @line L2
best = None
for i in sorted(nbr): # @line L3
for j in sorted(nbr[i]):
if j <= i:
continue
common = len(nbr[i] & nbr[j])
deleted = len(nbr[i]) + len(nbr[j]) - 1 - common
key = (-common, deleted, i, j) # @line L4
if best is None or key < best:
best = key
_, _, i, j = best
members[i] = sorted(members[i] + members[j]) # @line L5
del members[j]
keep = (nbr[i] & nbr[j]) - {i, j} # @line L6
for x in nbr[i] | nbr[j]:
nbr[x].discard(i)
nbr[x].discard(j)
del nbr[j]
nbr[i] = keep
for x in keep:
nbr[x].add(i)
return sorted(members.values()) # @line L7
def merge_trace(n: int, edges: list[tuple[int, int]]) -> list[tuple[int, int, int, int]]:
"""The merges of the greedy as (i, j, common neighbours, deleted edges), in order."""
nbr: dict[int, set[int]] = {v: set() for v in range(n)}
for u, v in edges:
if u != v:
nbr[u].add(v)
nbr[v].add(u)
out: list[tuple[int, int, int, int]] = []
while any(nbr[v] for v in nbr):
best = None
for i in sorted(nbr):
for j in sorted(nbr[i]):
if j > i:
common = len(nbr[i] & nbr[j])
key = (-common, len(nbr[i]) + len(nbr[j]) - 1 - common, i, j)
if best is None or key < best:
best = key
c, d, i, j = best
out.append((i, j, -c, d))
keep = (nbr[i] & nbr[j]) - {i, j}
for x in nbr[i] | nbr[j]:
nbr[x].discard(i)
nbr[x].discard(j)
del nbr[j]
nbr[i] = keep
for x in keep:
nbr[x].add(i)
return out
def is_clique_partition(n: int, edges: list[tuple[int, int]], parts: list[list[int]]) -> bool:
"""True when parts cover range(n) once each and every part is a clique."""
adj = {(min(u, v), max(u, v)) for u, v in edges}
seen = sorted(v for p in parts for v in p)
if seen != list(range(n)):
return False
for p in parts:
for a in range(len(p)):
for b in range(a + 1, len(p)):
if (min(p[a], p[b]), max(p[a], p[b])) not in adj:
return False
return True
def min_clique_partition(n: int, edges: list[tuple[int, int]]) -> int:
"""The least number of cliques that partition the graph, by a dynamic program over subsets."""
adj = [0] * n
for u, v in edges:
if u != v:
adj[u] |= 1 << v
adj[v] |= 1 << u
full = (1 << n) - 1
clique = [True] * (full + 1)
for s in range(1, full + 1):
low = (s & -s).bit_length() - 1
rest = s & ~(1 << low)
clique[s] = clique[rest] and (rest & ~adj[low]) == 0
best = [0] * (full + 1)
for s in range(1, full + 1):
low = s & -s
rest = s & ~low
value = n + 1
t = rest
while True:
c = t | low
if clique[c] and 1 + best[s & ~c] < value:
value = 1 + best[s & ~c]
if t == 0:
break
t = (t - 1) & rest
best[s] = value
return best[full]
def interval_compatibility(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Edges between closed integer intervals that do not overlap."""
n = len(intervals)
return [(u, v) for u in range(n) for v in range(u + 1, n)
if intervals[u][1] < intervals[v][0] or intervals[v][1] < intervals[u][0]]
def depth(intervals: list[tuple[int, int]]) -> int:
"""The largest number of closed integer intervals that share one point."""
if not intervals:
return 0
points = sorted({a for a, _ in intervals})
return max(sum(1 for a, b in intervals if a <= p <= b) for p in points)
test_tseng_siewiorek_clique_partitioning.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tseng-siewiorek-clique-partitioning/. The authors are listed in prov/FCVE23.jsonl.
import random
from tseng_siewiorek_clique_partitioning import (depth, interval_compatibility, is_clique_partition,
merge_trace, min_clique_partition, tseng_siewiorek)
# The lifetimes of the example on the page, in the order a, b, c, d, e, f, g.
LIFETIMES = [(1, 2), (1, 1), (2, 3), (3, 5), (4, 4), (5, 5), (2, 3)]
# Interval lifetimes on which the greedy needs 5 registers and 4 suffice.
BAD_INTERVALS = [(0, 0), (0, 2), (1, 1), (1, 3), (1, 3), (2, 4), (3, 3), (4, 4)]
# The net: a triangle with one pendant vertex on each corner.
NET = [(0, 1), (0, 2), (0, 5), (1, 2), (1, 4), (2, 3)]
def brute_min_partition(n: int, edges: list[tuple[int, int]]) -> int:
"""The least number of cliques, by trying every map of the vertices to labels."""
adj = {(min(u, v), max(u, v)) for u, v in edges}
best = n
for k in range(1, n + 1):
def place(v: int, label: list[int]) -> bool:
if v == n:
return True
for c in range(min(k, max(label, default=-1) + 2)):
if all((min(u, v), max(u, v)) in adj for u in range(v) if label[u] == c):
if place(v + 1, label + [c]):
return True
return False
if place(0, []):
return k
return best
def maximal(n: int, edges: list[tuple[int, int]], parts: list[list[int]]) -> bool:
"""True when no two parts could be joined into one larger clique."""
adj = {(min(u, v), max(u, v)) for u, v in edges}
for a in range(len(parts)):
for b in range(a + 1, len(parts)):
if all((min(x, y), max(x, y)) in adj for x in parts[a] for y in parts[b]):
return False
return True
def test_page_example():
n = len(LIFETIMES)
edges = interval_compatibility(LIFETIMES)
assert merge_trace(n, edges) == [(4, 5, 4, 5), (1, 4, 2, 5), (0, 3, 0, 1), (1, 2, 0, 2)]
assert tseng_siewiorek(n, edges) == [[0, 3], [1, 2, 4, 5], [6]]
assert depth(LIFETIMES) == 3
def sizes_over_all_tie_orders(n: int, edges: list[tuple[int, int]]) -> set[int]:
"""The numbers of cliques the greedy can end with, over every way of breaking ties in (common, deleted)."""
start = {v: frozenset() for v in range(n)}
for u, v in edges:
start[u] = start[u] | {v}
start[v] = start[v] | {u}
out: set[int] = set()
def run(nbr: dict[int, frozenset]) -> None:
pairs = [(i, j) for i in nbr for j in nbr[i] if i < j]
if not pairs:
out.add(len(nbr))
return
def key(p):
c = len(nbr[p[0]] & nbr[p[1]])
return (-c, len(nbr[p[0]]) + len(nbr[p[1]]) - 1 - c)
best = min(key(p) for p in pairs)
for i, j in pairs:
if key((i, j)) != best:
continue
keep = (nbr[i] & nbr[j]) - {i, j}
nxt = {x: s - {i, j} for x, s in nbr.items() if x != j}
nxt[i] = keep
for x in keep:
nxt[x] = nxt[x] | {i}
run(nxt)
run(start)
return out
def test_interval_counterexample():
edges = interval_compatibility(BAD_INTERVALS)
assert merge_trace(8, edges) == [(0, 7, 4, 7), (2, 6, 1, 4), (0, 2, 0, 3)]
parts = tseng_siewiorek(8, edges)
assert is_clique_partition(8, edges, parts)
assert len(parts) == 5
assert depth(BAD_INTERVALS) == 4
assert min_clique_partition(8, edges) == 4
assert sizes_over_all_tie_orders(8, edges) == {5}
def test_net_counterexample():
parts = tseng_siewiorek(6, NET)
assert parts == [[0, 1, 2], [3], [4], [5]]
assert min_clique_partition(6, NET) == 3
def test_subset_dp_matches_label_search():
rng = random.Random(7)
for _ in range(300):
n = rng.randint(1, 7)
edges = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.5]
assert min_clique_partition(n, edges) == brute_min_partition(n, edges)
def test_random_graphs_measured_against_optimum():
rng = random.Random(1)
gaps: dict[int, int] = {}
for _ in range(1000):
n = rng.randint(2, 9)
p = rng.choice([0.3, 0.5, 0.7])
edges = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < p]
parts = tseng_siewiorek(n, edges)
assert is_clique_partition(n, edges, parts)
assert maximal(n, edges, parts)
gap = len(parts) - min_clique_partition(n, edges)
assert gap >= 0
gaps[gap] = gaps.get(gap, 0) + 1
assert gaps == {0: 989, 1: 11}
def test_all_small_graphs():
fails = {}
for n in (1, 2, 3, 4, 5, 6):
pairs = [(u, v) for u in range(n) for v in range(u + 1, n)]
fails[n] = 0
for mask in range(1 << len(pairs)):
edges = [pairs[k] for k in range(len(pairs)) if mask >> k & 1]
parts = tseng_siewiorek(n, edges)
assert is_clique_partition(n, edges, parts)
if len(parts) > min_clique_partition(n, edges):
fails[n] += 1
assert fails == {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 180}
def test_interval_classes_where_greedy_is_optimal():
rng = random.Random(3)
for _ in range(500):
horizon = rng.randint(4, 12)
# Short lifetimes that never overlap, plus long ones that span the whole horizon.
cuts = sorted(rng.sample(range(horizon), rng.randint(1, horizon // 2)))
short = [(c, c) for c in cuts]
long = [(0, horizon - 1)] * rng.randint(0, 3)
lifetimes = short + long
rng.shuffle(lifetimes)
n = len(lifetimes)
edges = interval_compatibility(lifetimes)
parts = tseng_siewiorek(n, edges)
assert is_clique_partition(n, edges, parts)
assert len(parts) == depth(lifetimes) == min_clique_partition(n, edges)
for _ in range(500):
# A compatibility graph that is a disjoint union of cliques.
n = rng.randint(1, 10)
label = [rng.randrange(4) for _ in range(n)]
edges = [(u, v) for u in range(n) for v in range(u + 1, n) if label[u] == label[v]]
assert len(tseng_siewiorek(n, edges)) == len(set(label))
def test_random_interval_instances_measured():
rng = random.Random(2)
matched = 0
for _ in range(1000):
n = rng.randint(2, 9)
horizon = rng.randint(3, 8)
lifetimes = []
for _ in range(n):
a = rng.randrange(horizon)
lifetimes.append((a, rng.randrange(a, horizon)))
edges = interval_compatibility(lifetimes)
parts = tseng_siewiorek(n, edges)
assert is_clique_partition(n, edges, parts)
assert len(parts) >= depth(lifetimes)
matched += len(parts) == depth(lifetimes)
assert matched == 1000
History
Tseng and Siewiorek (1986) described data path synthesis as three clique partitioning problems, for functional units, registers and buses, and gave this greedy for all three. Their system at Carnegie Mellon was called Facet. Kurdahi and Parker (1987) showed that for registers in straight-line code the left-edge algorithm is exact and faster, and later binders added interconnect weights, or replaced the greedy by matching, as in the binder of Huang, Chen, Lin and Hsu (1990).
References
- Chia-Jeng Tseng and Daniel P. Siewiorek, Automated synthesis of data paths in digital systems, IEEE Transactions on Computer-Aided Design 5(3), 379 to 395, 1986, the clique partitioning heuristic (merge the pair with the most common neighbours, ties by the fewest deleted edges) and its use for units, registers and buses
- Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 6, Resource Sharing and Binding (the clique partitioning heuristic of Tseng and Siewiorek)
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 FCVE23 Edit this page History Report an error Markdown