Algorithmadvanced
Alpha-beta swap
Also called swap move algorithm.
Minimize a multi-label energy with a semimetric pairwise term by repeated min cuts, each letting the sites labeled alpha or beta exchange those two labels. No constant factor bound.
- Solves
- MAP inference
- Time
- O(k L^2 (F + n + m)) worst · averageO(L^2 (F + n + m)) best
- Space
- O(n + m) extra
- Where
- F = the time of one max flow on n + 2 nodes and n + m edges; L = the number of labels; k = the number of cycles over the label pairs; m = the number of neighbor pairs; n = the number of sites
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Yuri Boykov, Olga Veksler, Ramin Zabih, 2001
Alpha-beta swap is a move algorithm for multi-label energies of the form data cost plus pairwise cost, as in MAP inference for a Markov random field. A swap move takes two labels and and lets every site that has one of them take either one, while all other sites keep their labels. When the pairwise cost is a semimetric, the move energy is a regular binary energy, so the best move is found exactly by one minimum cut (the Kolmogorov-Zabih theorem). The algorithm cycles over all pairs of labels until no swap lowers the energy. Swap needs less of than alpha-expansion, which needs a metric, so it covers the truncated quadratic and other costs without the triangle inequality. The price is that its local minima have no constant factor guarantee: they can be arbitrarily far from the optimum, even for the Potts model.
In plain words
Each pixel has a label, and neighbors with different labels pay a penalty. Pick two labels, say red and blue. Look only at the pixels that are red or blue now, and let each of them be red or blue again, in the best combination. All other pixels stay as they are. A minimum cut in a graph finds the best combination exactly, even though there are very many of them. Do this for every pair of labels and repeat until no pair helps. The method only moves pixels between labels they already use, so it can miss a third label that would be better for a whole group of pixels at once.
The problem
Input. Sites with neighbor pairs and weights , labels, data costs , and a semimetric : , and exactly when . No triangle inequality is needed.
Output. A labeling with small energy
which no -swap improves. An -swap of is a labeling that differs from only on sites labeled or , and has there.
The algorithm
ALPHA-BETA-SWAP(D, V, N, f)- 1
repeat - 2
success ← false - 3
for each pair of labels {α, β} do - 4
P ← the sites p with f_p = α or f_p = β - 5
U_p(0) ← D_p(α) + Σ w V(α, f_q), U_p(1) ← D_p(β) + Σ w V(β, f_q), sums over neighbors q not in P - 6
for each pair (p, q) inside P: θ(0,0) = θ(1,1) = 0, θ(0,1) = w V(α, β), θ(1,0) = w V(β, α) - 7
x ← a minimizer of Σ U_p(x_p) + Σ θ(x_p, x_q) by one minimum cut - 8
f' ← f with f'_p = α if x_p = 0 and f'_p = β if x_p = 1, for p in P - 9
if E(f') < E(f) then f ← f'; success ← true - 10
until success = false - 11
return f
Line L5 folds the pairs with one end outside into the data terms, because the outside label is fixed. Line L6 gives the pairs inside . They are regular, since , so line L7 is one cut on a graph with nodes: an edge of capacity for each inside pair, and source or sink edges for the linear parts. Boykov, Veksler and Zabih use the equivalent graph with a terminal edge to and to for each site and an edge of capacity for each inside pair (Section 4 of their paper).
Example
Two neighboring sites and , , labels , the Potts model with , and data costs , for . Start at , which has .
| swap | labelings in the move space | energies | best |
|---|---|---|---|
| , , , | 6, 24, 9, 9 | ||
| , | 6, 7 | ||
| , | 6, 7 |
No swap helps, so the algorithm stops at with . The optimum is with . A swap with can move only one of the two sites, since the other has a third label, and moving one site alone costs more. The -expansion moves both at once and finds . With and , the swap result costs and the optimum , so the ratio is unbounded.
Correctness
The full proof is in proofs/correctness.md. The binary energy of lines L5 and L6 equals the energy of the swap it describes, up to a constant made of the terms that do not touch . Its pair terms are regular because and , so the cut of line L7 gives the best swap. Each accepted move lowers the energy strictly and there are finitely many labelings, so the loop stops; in the last cycle no pair of labels gives an improving swap. The example above, with , shows that no constant factor bound holds.
Proof: Correctness of alpha-beta swapfull
The energy is with , and is a semimetric: , and exactly when . We prove that each move returns a labeling of least energy among all -swaps of , that the loop stops at a labeling that no swap improves, and that no constant factor bound holds for such labelings.
1. Each move is optimal in its move space
Let . An -swap of is a labeling with for and otherwise. Write for , with if and if . Every swap has this form, and every gives a swap.
Split into four groups of terms.
- Data terms and pair terms with no end in : they do not depend on , so they are a constant .
- The data term of : and .
- A pair with and : the label of is fixed, so the term is a function of alone, or , and lines L5 add it to . The same holds with the roles of and exchanged.
- A pair with both ends in : the term is with , , and .
So . Every pair term is regular, because by . By the Kolmogorov-Zabih theorem, the graph of the code represents this binary energy: the decomposition with and gives an edge of capacity and linear terms, and each linear coefficient becomes an edge from the source or to the sink. A minimum cut (line L7) gives a minimizer with on the source side, and line L8 returns , a swap of least energy.
Only and were used. Symmetry is not needed for the move, but it is part of the usual definition.
2. Termination and local optimality
Line L9 replaces only by a labeling of strictly smaller energy, and there are labelings, so the loop stops. In the last cycle did not change, so for every pair the best swap has energy at least . As is itself a swap of (with where and where ), no swap of any pair lowers the energy.
A change of one site from to another label is an -swap. So the output is also a local minimum for changes of one site.
3. No constant factor bound
Take two neighboring sites with , three labels , the Potts model , and numbers and . Let and for the labels . The labeling has .
- The -swaps are , , , with energies , , , , all at least .
- The -swaps change only (the label of is ): has .
- The -swaps change only : has .
So is a local minimum for all swaps, and the algorithm started there returns it. The labeling has . The ratio is unbounded as , so no bound with a constant holds for swap local minima, even for the Potts model. This is the point of Section 6.2 and Figure 8 of Boykov, Veksler and Zabih (2001). An expansion move to reaches in one step, in line with the bound of alpha-expansion.
Complexity
The model is the real RAM; the tests use integer costs.
- One move. The graph has nodes and at most plus the inside pairs as edges. Building it takes time linear in and the pairs that touch , and the cut takes at most the time of one max flow on nodes and edges.
- One cycle. moves. Each site is in for of them, so the graphs of one cycle have site nodes in total. A crude bound is .
- Number of cycles. With integer costs at most .
- Space. .
Properties
- No approximation bound. Section 6.2 and Figure 8 of Boykov, Veksler and Zabih: a swap local minimum can be arbitrarily far from the global minimum. Theorem 6.2 there gets a bound by a different route, by replacing with a Potts model and running expansion, not by swap itself.
- Weaker condition. Only and are used by the move, so truncated quadratic and other semimetrics are fine.
- Stronger than one site at a time. A change of one site from to is a swap, so a swap local minimum is also a local minimum of ICM.
- Neither move contains the other. A swap can exchange and between sites, which no single expansion does; an expansion can bring sites of many labels to at once, which no single swap does.
- Small graphs. Each cut involves only the sites of two labels, so the graphs are smaller than those of expansion, but a cycle has of them instead of .
Variants and improvements
- Alpha-expansion. For a metric , alpha-expansion is usually better and has the bound .
- Range moves. For ordered labels and truncated convex , Veksler (2007) proposed moves that let a set of sites take any label in a range of consecutive labels, solved by the construction of Ishikawa (2003). They generalize the swap move.
- Nonregular moves. If or a learned breaks the condition, the move energy can be nonregular; QPBO then labels part of the sites.
When to use it
Use swap when is a semimetric but not a metric, for example truncated quadratic smoothness on ordered labels, and when an approximation bound is not needed. In the benchmark of Szeliski et al. (2008), expansion usually reached a lower energy than swap. For a metric , use alpha-expansion. For a few labels on a chain, an exact Viterbi dynamic program is better than any move method.
Pitfalls
- The start and the order matter. The local minimum depends on the starting labeling and on the order of the label pairs. Start from the best data label of each site, and keep the order fixed when you compare runs.
- No guarantee. Do not quote a factor of 2 for swap; that is the expansion bound.
- Ties. Accept a move only if it lowers the energy strictly.
- Number of moves. With many labels the moves per cycle are slow. Skip the pairs whose sites are not neighbors anywhere, or use expansion.
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/alpha-beta-swap/. The authors are listed in prov/Y9ZT41.jsonl.
"""Alpha-beta swap for multi-label energies with a semimetric pairwise term.
The energy of a labeling f (one label in 0 .. L - 1 per site) is
E(f) = sum_p D[p][f[p]] + sum_{(p, q, w) in pairs} w * V[f[p]][f[q]],
with weights w >= 0. A swap move on the labels alpha and beta lets the
sites labeled alpha or beta take either of the two labels; all other sites
keep their labels. Each move is solved exactly by one minimum cut.
"""
from __future__ import annotations
from collections import deque
from itertools import combinations
from typing import List, Optional, Sequence, Tuple
Pairs = Sequence[Tuple[int, int, float]]
def energy(D, pairs: Pairs, V, f: Sequence[int]) -> float:
return (sum(D[p][f[p]] for p in range(len(D)))
+ sum(w * V[f[p]][f[q]] for (p, q, w) in pairs))
def _min_cut_source_side(nn: int, edges, s: int, t: int) -> List[bool]:
"""Edmonds-Karp max flow; return the nodes that s reaches at the end."""
adj: List[List[int]] = [[] for _ in range(nn)]
to: List[int] = []
cap: List[float] = []
for (u, v, c) in edges:
adj[u].append(len(to))
to.append(v)
cap.append(c)
adj[v].append(len(to))
to.append(u)
cap.append(0)
while True:
prev = [-1] * nn
seen = [False] * nn
seen[s] = True
queue = deque([s])
while queue and not seen[t]:
u = queue.popleft()
for e in adj[u]:
if cap[e] > 0 and not seen[to[e]]:
seen[to[e]] = True
prev[to[e]] = e
queue.append(to[e])
if not seen[t]:
return seen
path = []
v = t
while v != s:
path.append(prev[v])
v = to[prev[v] ^ 1]
delta = min(cap[e] for e in path)
for e in path:
cap[e] -= delta
cap[e ^ 1] += delta
def swap_move(D, pairs: Pairs, V, f: Sequence[int], alpha: int, beta: int) -> List[int]:
"""The labeling of least energy among the alpha-beta swaps of f."""
n = len(D)
sites = [p for p in range(n) if f[p] in (alpha, beta)] # @line L4
index = {p: i for i, p in enumerate(sites)} # @line L4
k = len(sites)
# Binary variable x = 0 means alpha, x = 1 means beta.
u0 = [D[p][alpha] for p in sites] # @line L5
u1 = [D[p][beta] for p in sites] # @line L5
edges = []
for (p, q, w) in pairs: # @line L5
ip, iq = index.get(p), index.get(q)
if ip is not None and iq is not None: # @line L6
# theta(0,0) = theta(1,1) = 0, theta(0,1) = w V(a,b), theta(1,0) = w V(b,a)
a, b = w * V[alpha][beta], w * V[beta][alpha]
if a < 0 or b < 0:
raise ValueError("V must be nonnegative")
# theta = b x_p + (0 - b) x_q + (a + b)(1 - x_p) x_q
u1[ip] += b
u1[iq] -= b
if a + b > 0:
edges.append((ip, iq, a + b))
elif ip is not None: # @line L5
u0[ip] += w * V[alpha][f[q]] # @line L5
u1[ip] += w * V[beta][f[q]] # @line L5
elif iq is not None: # @line L5
u0[iq] += w * V[f[p]][alpha] # @line L5
u1[iq] += w * V[f[p]][beta] # @line L5
s, t = k, k + 1
for i in range(k):
lin = u1[i] - u0[i]
if lin > 0:
edges.append((s, i, lin))
elif lin < 0:
edges.append((i, t, -lin))
side = _min_cut_source_side(k + 2, edges, s, t) # @line L7
g = list(f) # @line L8
for i, p in enumerate(sites): # @line L8
g[p] = alpha if side[i] else beta # @line L8
return g
def alpha_beta_swap(D, pairs: Pairs, V, f: Optional[Sequence[int]] = None
) -> Tuple[List[int], int]:
"""Run swap moves over all label pairs until none lowers the energy.
Returns (labeling, number of cycles)."""
L = len(V)
if f is None:
f = [min(range(L), key=lambda l: D[p][l]) for p in range(len(D))]
f = list(f)
e = energy(D, pairs, V, f)
cycles = 0
while True: # @line L1
cycles += 1
success = False # @line L2
for alpha, beta in combinations(range(L), 2): # @line L3
g = swap_move(D, pairs, V, f, alpha, beta) # @line L4
eg = energy(D, pairs, V, g) # @line L9
if eg < e: # @line L9
f, e, success = g, eg, True # @line L9
if not success: # @line L10
return f, cycles # @line L11
def is_semimetric(V) -> bool:
L = len(V)
return all(V[a][b] == V[b][a] and V[a][b] >= 0 and (V[a][b] == 0) == (a == b)
for a in range(L) for b in range(L))
def potts(L: int, lam: float = 1) -> List[List[float]]:
return [[0 if a == b else lam for b in range(L)] for a in range(L)]
def truncated_quadratic(L: int, k: float) -> List[List[float]]:
return [[min((a - b) ** 2, k) for b in range(L)] for a in range(L)]
def grid_pairs(w: int, h: int, weight: float = 1) -> List[Tuple[int, int, float]]:
out = []
for v in range(h):
for u in range(w):
if u + 1 < w:
out.append((v * w + u, v * w + u + 1, weight))
if v + 1 < h:
out.append((v * w + u, (v + 1) * w + u, weight))
return out
test_alpha_beta_swap.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alpha-beta-swap/. The authors are listed in prov/Y9ZT41.jsonl.
import itertools
import random
from alpha_beta_swap import (
alpha_beta_swap,
energy,
grid_pairs,
is_semimetric,
potts,
swap_move,
truncated_quadratic,
)
def brute_swap(D, pairs, V, f, alpha, beta):
sites = [p for p in range(len(D)) if f[p] in (alpha, beta)]
best = None
for bits in itertools.product((alpha, beta), repeat=len(sites)):
g = list(f)
for p, l in zip(sites, bits):
g[p] = l
e = energy(D, pairs, V, g)
if best is None or e < best:
best = e
return best
def random_instance(rng):
w = rng.randint(1, 4)
h = rng.randint(1, 3)
L = rng.randint(2, 4)
while L ** (w * h) > 4096:
h -= 1
n = w * h
D = [[rng.randint(0, 9) for _ in range(L)] for _ in range(n)]
pairs = [(p, q, rng.randint(1, 3)) for (p, q, _) in grid_pairs(w, h)]
if rng.random() < 0.5:
V = potts(L, rng.randint(1, 4))
else:
V = truncated_quadratic(L, rng.randint(1, 9))
return D, pairs, V
def test_move_is_optimal_in_its_space():
rng = random.Random(1)
for _ in range(200):
D, pairs, V = random_instance(rng)
L = len(V)
f = [rng.randrange(L) for _ in D]
alpha, beta = rng.sample(range(L), 2)
g = swap_move(D, pairs, V, f, alpha, beta)
for p in range(len(D)):
if f[p] in (alpha, beta):
assert g[p] in (alpha, beta)
else:
assert g[p] == f[p]
assert energy(D, pairs, V, g) == brute_swap(D, pairs, V, f, alpha, beta)
def test_local_minimum_and_monotone():
rng = random.Random(2)
for _ in range(100):
D, pairs, V = random_instance(rng)
assert is_semimetric(V)
L = len(V)
f0 = [rng.randrange(L) for _ in D]
f, _ = alpha_beta_swap(D, pairs, V, f0)
ef = energy(D, pairs, V, f)
assert ef <= energy(D, pairs, V, f0)
opt = min(energy(D, pairs, V, g) for g in itertools.product(range(L), repeat=len(D)))
assert ef >= opt
for alpha, beta in itertools.combinations(range(L), 2):
assert brute_swap(D, pairs, V, f, alpha, beta) == ef
def test_unbounded_ratio_example():
# Two neighbors p, q, labels a = 0, b = 1, c = 2, Potts with lambda.
for lam, M, delta in ((10, 10, 1), (100, 100, 1), (1000, 1000, 1)):
D = [[0, M, delta], [M, 0, delta]]
pairs = [(0, 1, 1)]
V = potts(3, lam)
f, _ = alpha_beta_swap(D, pairs, V, [0, 1])
assert f == [0, 1] and energy(D, pairs, V, f) == lam
assert energy(D, pairs, V, [2, 2]) == 2 * delta
# The ratio lam / (2 delta) grows without bound.
def test_worked_example():
D = [[0, 9, 1], [9, 0, 1]]
V = potts(3, 6)
pairs = [(0, 1, 1)]
assert swap_move(D, pairs, V, [0, 1], 0, 1) == [0, 1]
assert swap_move(D, pairs, V, [0, 1], 0, 2) == [0, 1]
assert swap_move(D, pairs, V, [0, 1], 1, 2) == [0, 1]
assert energy(D, pairs, V, [0, 1]) == 6
assert energy(D, pairs, V, [2, 2]) == 2
History
Boykov, Veksler and Zabih introduced swap and expansion moves at ICCV 1999 and in the journal paper of 2001. They gave a graph for each move, proved that the swap move is a cut for a semimetric, and showed that swap local minima have no constant factor bound while expansion local minima are within . Kolmogorov and Zabih (2004) explained both conditions as cases of regularity. Szeliski et al. (2008) compared swap with other methods on a common benchmark.
References
- Yuri Boykov, Olga Veksler and Ramin Zabih, Fast approximate energy minimization via graph cuts, IEEE Transactions on Pattern Analysis and Machine Intelligence 23(11), 2001, 1222-1239, Section 3 (the move spaces and the swap algorithm), Section 4 with Theorem 4.4 and Corollary 4.5 (the graph of a swap move), Section 6.2 and Figure 8 (swap local minima can be arbitrarily far from the optimum), Section 8 (experiments)
- Vladimir Kolmogorov and Ramin Zabih, What energy functions can be minimized via graph cuts?, IEEE Transactions on Pattern Analysis and Machine Intelligence 26(2), 2004, 147-159, Theorem 4.1 and Section 4.1 (the graph for a regular binary energy, used here for each move)
- Richard Szeliski, Ramin Zabih, Daniel Scharstein, Olga Veksler, Vladimir Kolmogorov, Aseem Agarwala, Marshall Tappen and Carsten Rother, A comparative study of energy minimization methods for Markov random fields with smoothness-based priors, IEEE Transactions on Pattern Analysis and Machine Intelligence 30(6), 2008, 1068-1080, the comparison of swap with expansion, ICM, loopy belief propagation and TRW-S on vision energies
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 4, Model fitting and optimization (Markov random fields and graph cut moves)
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 Y9ZT41 Edit this page History Report an error Markdown