Algorithmadvanced
QPBO
Also called quadratic pseudo-boolean optimization, roof duality.
Minimize a non-submodular binary pairwise energy by a min cut on a doubled graph, labeling part of the variables with values that some optimum shares, and giving a lower bound.
- Solves
- MAP inference
- Time
- O(F + n + m) worst · average · best
- Space
- O(n + m) extra
- Where
- F = the time of one max flow on 2n + 2 nodes and 2n + 2m edges; m = the number of pair terms; n = the number of variables
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter L. Hammer, Pierre Hansen, Bruno Simeone, 1984
QPBO (quadratic pseudo-Boolean optimization) is a method for energies of binary variables with unary and pairwise terms when some pairwise terms are not submodular, so that a single minimum cut cannot minimize them (the Kolmogorov-Zabih theorem). It doubles the variables: next to each it adds , meant to be , and writes a new energy of the variables that is submodular and equals the old energy when . One minimum cut minimizes the new energy. Where the solution has , the variable gets a label; elsewhere it is left unlabeled. The labeled values are persistent: some minimizer of the original energy has exactly those values. The minimum of the new energy is also a lower bound on the original minimum. The method is the roof duality of Hammer, Hansen and Simeone (1984); its bound equals that of the linear programming relaxation. In vision it solves the nonregular moves of fusion and stereo methods, and in general it fixes part of the variables of a hard problem for free.
In plain words
You have many yes or no questions, and a cost for each answer and for each pair of answers. If every pair prefers to agree, a cut in a graph gives the best answers at once. When some pairs prefer to disagree, that trick fails. QPBO keeps two copies of each question, one for the answer and one for its opposite, and writes the costs so that every pair in the new problem prefers to agree. The cut then solves the new problem. Where the two copies give consistent answers, you can trust them: some best solution uses those answers. Where they do not, the method says "I do not know", and you must decide those questions another way.
The problem
Input. An energy of binary variables
with real values and pair terms. A pair term is submodular if ; the others are not.
Output. A partial labeling: a set of variables with values in such that some global minimizer of has these values, and a lower bound on .
Minimizing is NP-hard in general (it contains maximum cut), so a method that labels all variables in polynomial time on every input is not expected.
The algorithm
QPBO(θ)- 1
for each variable p, make two nodes: p for x_p, and p̄ for x̄_p (meant to be 1 - x_p) - 2
for each p add ½ θ_p(x_p) + ½ θ_p(1 - x̄_p) - 3
for each pair term θ_pq do - 4
if θ_pq is submodular then add ½ θ_pq(x_p, x_q) + ½ θ_pq(1 - x̄_p, 1 - x̄_q) - 5
else add ½ θ_pq(x_p, 1 - x̄_q) + ½ θ_pq(1 - x̄_p, x_q) - 6
(x, x̄) ← a minimizer of the new energy Ẽ by one minimum cut on 2n + 2 nodes - 7
for each p: if x̄_p = 1 - x_p then label p with x_p, else leave p unlabeled - 8
return the partial labeling and the lower bound Ẽ(x, x̄)
Line L4 keeps a submodular term on the original variables and copies it, complemented, on the doubled ones. Line L5 links a non-submodular term between and and between and : replacing one argument by the complement of its twin turns "prefer to disagree" into "prefer to agree". Every term of is then regular, and the graph of the theorem page represents it. The code multiplies everything by 2 to keep integer costs in integers.
Example
Take three variables with the frustrated triangle, each pair paying 1 when the two values agree, and a fourth variable tied to :
- , which are not submodular ();
- , which is submodular;
- , , and no other unary costs.
Every labeling of the triangle has at least one agreeing pair, so , reached by , and . QPBO finds the minimizer , of , with .
| variable | result | ||
|---|---|---|---|
| 0, 1, 2 | 0 | 0 | unlabeled |
| 3 | 0 | 1 | labeled 0 |
The lower bound is , and holds in every minimizer, as persistency promises. The triangle stays unlabeled, because on an odd cycle of disagreeing pairs the doubled energy can reach a smaller value with than any real labeling. In a second example with a chain , a strong unary cost , a non-submodular term on that pays 2 when they agree, and a submodular term on that pays 3 when they differ, QPBO labels all three variables, , which is the minimizer with .
Correctness
The full proof is in proofs/correctness.md. First, each term of is regular: a submodular term keeps its sign under complementing both arguments, and a non-submodular term becomes regular when exactly one argument is complemented. Second, , so . Third, persistency. The map leaves unchanged, and is submodular on . From the minimizer found by the cut, is also a minimizer that agrees with on the labeled variables and is on the others. For any minimizer of , two steps of submodularity with give a point of no larger energy, where takes the QPBO values on the labeled variables and the values of elsewhere. So is also a minimizer.
Proof: Correctness of QPBOfull
Let for , with arbitrary real pair terms. Call a pair term submodular if . Lines L1 to L5 build the energy of binary variables :
We prove: (1) is regular, so line L6 finds a minimizer by one cut; (2) , so ; (3) persistency: if minimizes , then the labeling with for every labeled (those with ) and otherwise also minimizes .
1. is regular
Each term of depends on at most two variables. For a term write ; the term is regular when . Let be the values of at , so .
- has .
- , as a function of , takes the values , so .
- , as a function of , takes the values , so .
- , as a function of , takes the values , so .
Line L4 uses the first two when , and line L5 the last two when . In both cases . So is in the class and regular, and by the Kolmogorov-Zabih theorem the graph of the code, with nodes, represents ; a minimum cut gives a minimizer. The code doubles every value to stay in integers.
2. The diagonal and the lower bound
Put . Then for every , and every bracket becomes twice the matching term of . So , and . Line L8 returns , which is therefore a lower bound on .
3. Persistency
Symmetry. Let . Each bracket of is mapped onto itself by : the unary bracket becomes ; the submodular bracket becomes ; the other bracket becomes . So .
Submodularity. For let and be the componentwise minimum and maximum. A function of two binary variables with satisfies : if or both sides are equal, and otherwise and the inequality is . Summing over the terms, .
Let be the minimizer of line L6, and let .
Step 1. Let . By submodularity and symmetry, , and both terms are at least , so . In coordinates, has and . For a labeled this is , unchanged. For an unlabeled , is or , and both give .
Step 2. Let minimize and , so . Let . Since , submodularity gives .
Step 3. Let . Since , submodularity gives .
Coordinates of . is at a labeled and at an unlabeled . At a labeled , is , and is . At an unlabeled , is because is there, and is the same. So .
Hence , and is a minimizer of .
Consequences
- If every pair term is submodular, then . A minimizer has and both minimizing . If the minimizer of is unique, then and every variable is labeled with the optimum.
- If every variable is labeled, itself is a minimizer of , by persistency with any .
- The proof used only that is some minimizer of . Different minimum cuts can label different sets; each set is persistent.
Complexity
The model is the real RAM; the tests use integer costs.
- Time. Building and its graph takes time. The graph has nodes and at most edges, so the time is that of one max-flow computation on a graph twice as large as for a submodular energy. The code uses Edmonds-Karp; vision codes use the Boykov-Kolmogorov algorithm.
- Space. .
Properties
- Persistency. Labeled values agree with some global minimizer. Fixing them and solving the rest by any method loses nothing.
- Lower bound. , and the gap tells how far a heuristic solution can be from the optimum.
- Exact for submodular energies. If all terms are submodular and the minimizer is unique, all variables are labeled. If there are several minimizers, a cut may leave some variables unlabeled.
- LP equivalence. The roof dual bound equals the optimum of the standard linear programming relaxation of the quadratic 0-1 problem (Hammer, Hansen and Simeone 1984). So QPBO solves that relaxation by one cut.
- Partial in general. On frustrated cycles, as in the example, many variables can stay unlabeled. How many depends on the strength of the non-submodular terms against the unary terms.
- Invariance. Flipping the meaning of a variable () changes which terms are submodular, but not the labeled set. So any energy that becomes submodular after flipping some variables (a "bipartite" frustration pattern) is solved as well as a submodular one.
Variants and improvements
- QPBO-P and QPBO-I. Rother, Kolmogorov, Lempitsky and Szummer (2007) proposed probing, which tries each value of an unlabeled variable and draws conclusions from both runs, and improvement, which takes any complete labeling and returns one of no larger energy by fixing the unlabeled variables to it.
- Fusion moves. In multi-label problems, a move that combines the current labeling with a proposal is a binary energy that is often not submodular; QPBO solves it, and unlabeled sites keep their current label, which never raises the energy.
- Higher order. Energies with terms of three or more variables are first reduced to pairwise form with extra variables, then given to QPBO.
- Implication network. Boros and Hammer compute the same bound by a max flow on an implication network of literals, the same idea in the language of 2-SAT and implication graphs.
When to use it
Use QPBO for binary pairwise energies with some non-submodular terms: image deconvolution, texture synthesis, learned pairwise terms, and the fusion moves of stereo and optical flow. It is fast, it never gives a wrong label, and its bound measures the quality of the rest. When most variables stay unlabeled, add probing, or use loopy belief propagation or simulated annealing on the remaining part. For energies that are already submodular, a plain cut is simpler and half the size.
Pitfalls
- Unlabeled is not wrong. An unlabeled variable has no information from QPBO. Assigning it 0 by default is a heuristic; use QPBO-I to make sure that the energy does not rise.
- Persistency is weak. The labeled values agree with some minimizer, not with every minimizer. Two runs with different cuts can label different sets, each correct.
- Halves. The definition has factors . Doubling all costs avoids fractions; the lower bound is then half the cut value.
- The frustrated case. Strong non-submodular terms on odd cycles, as in max-cut instances, leave almost everything unlabeled. QPBO does not make an NP-hard problem easy.
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/qpbo/. The authors are listed in prov/W42VES.jsonl.
"""QPBO: roof duality for binary pairwise energies by one minimum cut.
The energy of x in {0,1}^n is
E(x) = sum_p unary[p][x_p] + sum_{(p, q, A, B, C, D)} theta_pq(x_p, x_q),
where a pair term is given by its four values A = theta(0,0), B = theta(0,1),
C = theta(1,0), D = theta(1,1). Pair terms need not be submodular.
QPBO doubles the variables: y = (x, xbar), where xbar_p stands for 1 - x_p.
The doubled energy Etilde is submodular, Etilde(x, 1 - x) = E(x), and its
minimum is a lower bound on min E. The variables p with xbar_p = 1 - x_p in
the minimizer found by the cut get a label, and some minimizer of E agrees
with all of them (persistency). All values are doubled inside, so integer
energies give exact integer arithmetic.
"""
from __future__ import annotations
from collections import deque
from typing import List, Optional, Sequence, Tuple
Term = Tuple[int, int, float, float, float, float]
def energy(unary, terms: Sequence[Term], x: Sequence[int]) -> float:
return (sum(unary[p][x[p]] for p in range(len(unary)))
+ sum((A, B, C, D)[2 * x[p] + x[q]] for (p, q, A, B, C, D) in terms))
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 _minimize_regular(nv: int, lin: List[float], terms) -> List[int]:
"""Minimize sum lin[i] y_i + sum theta(y_i, y_j) for regular terms
(i, j, A, B, C, D), up to a constant; y_i = 0 is the source side."""
lin = list(lin)
s, t = nv, nv + 1
edges = []
for (i, j, A, B, C, D) in terms:
k = B + C - A - D
assert k >= 0
lin[i] += C - A
lin[j] += D - C
if k > 0:
edges.append((i, j, k))
for i in range(nv):
if lin[i] > 0:
edges.append((s, i, lin[i]))
elif lin[i] < 0:
edges.append((i, t, -lin[i]))
side = _min_cut_source_side(nv + 2, edges, s, t)
return [0 if side[i] else 1 for i in range(nv)]
def doubled_energy(unary, terms: Sequence[Term], x, xbar) -> float:
"""2 * Etilde(x, xbar), the doubled energy of QPBO times two."""
total = 0
for p, (u0, u1) in enumerate(unary):
total += (u0, u1)[x[p]] + (u0, u1)[1 - xbar[p]]
for (p, q, A, B, C, D) in terms:
th = (A, B, C, D)
if A + D <= B + C:
total += th[2 * x[p] + x[q]] + th[2 * (1 - xbar[p]) + (1 - xbar[q])]
else:
total += th[2 * x[p] + (1 - xbar[q])] + th[2 * (1 - xbar[p]) + x[q]]
return total
def qpbo(unary: Sequence[Tuple[float, float]], terms: Sequence[Term]
) -> Tuple[List[Optional[int]], float]:
"""Return (partial labeling, lower bound on min E).
The labeling has 0 or 1 for labeled variables and None for the others.
"""
n = len(unary)
# Variable i < n is x_i, variable n + i is xbar_i. # @line L1
lin = [0.0] * (2 * n)
pair_terms = []
for p, (u0, u1) in enumerate(unary): # @line L2
lin[p] += u1 - u0 # u(x_p), doubled and halved # @line L2
lin[n + p] += u0 - u1 # u(1 - xbar_p) # @line L2
for (p, q, A, B, C, D) in terms: # @line L3
if A + D <= B + C: # @line L4
pair_terms.append((p, q, A, B, C, D)) # theta(x_p, x_q) # @line L4
# theta(1 - xbar_p, 1 - xbar_q) as a function of (xbar_p, xbar_q)
pair_terms.append((n + p, n + q, D, C, B, A)) # @line L4
else: # @line L5
# theta(x_p, 1 - xbar_q) as a function of (x_p, xbar_q)
pair_terms.append((p, n + q, B, A, D, C)) # @line L5
# theta(1 - xbar_p, x_q) as a function of (xbar_p, x_q)
pair_terms.append((n + p, q, C, D, A, B)) # @line L5
y = _minimize_regular(2 * n, lin, pair_terms) # @line L6
x, xbar = y[:n], y[n:]
labels: List[Optional[int]] = [x[p] if xbar[p] == 1 - x[p] else None # @line L7
for p in range(n)] # @line L7
bound = doubled_energy(unary, terms, x, xbar) / 2 # @line L8
return labels, bound # @line L8
test_qpbo.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/qpbo/. The authors are listed in prov/W42VES.jsonl.
import itertools
import random
from qpbo import doubled_energy, energy, qpbo
def all_minimizers(unary, terms):
n = len(unary)
vals = {x: energy(unary, terms, x) for x in itertools.product((0, 1), repeat=n)}
best = min(vals.values())
return best, [x for x, e in vals.items() if e == best]
def random_energy(rng, n, submodular_only=False):
unary = [(rng.randint(-6, 6), rng.randint(-6, 6)) for _ in range(n)]
terms = []
for (p, q) in itertools.combinations(range(n), 2):
if rng.random() < 0.5:
A, B, C, D = (rng.randint(-5, 5) for _ in range(4))
if submodular_only and A + D > B + C:
A, B = B, A # swap a pair of values to fix the sign
if A + D > B + C:
D = B + C - A
terms.append((p, q, A, B, C, D))
return unary, terms
def test_doubled_energy_on_the_diagonal():
rng = random.Random(1)
for _ in range(50):
n = rng.randint(1, 6)
unary, terms = random_energy(rng, n)
for x in itertools.product((0, 1), repeat=n):
xbar = [1 - v for v in x]
assert doubled_energy(unary, terms, x, xbar) == 2 * energy(unary, terms, x)
def test_persistency_and_bound():
rng = random.Random(2)
labeled_total = 0
for _ in range(300):
n = rng.randint(1, 9)
unary, terms = random_energy(rng, n)
labels, bound = qpbo(unary, terms)
best, mins = all_minimizers(unary, terms)
assert bound <= best
labeled_total += sum(v is not None for v in labels)
# Every minimizer stays a minimizer when the labeled values are imposed.
for z in mins:
z2 = tuple(labels[p] if labels[p] is not None else z[p] for p in range(n))
assert energy(unary, terms, z2) == best
assert labeled_total > 0
def test_doubled_minimum_is_found():
rng = random.Random(3)
for _ in range(60):
n = rng.randint(1, 5)
unary, terms = random_energy(rng, n)
labels, bound = qpbo(unary, terms)
brute = min(doubled_energy(unary, terms, x, xb)
for x in itertools.product((0, 1), repeat=n)
for xb in itertools.product((0, 1), repeat=n))
assert 2 * bound == brute
def test_submodular_with_unique_minimum_is_fully_labeled():
rng = random.Random(4)
checked = 0
for _ in range(300):
n = rng.randint(1, 8)
unary, terms = random_energy(rng, n, submodular_only=True)
best, mins = all_minimizers(unary, terms)
labels, bound = qpbo(unary, terms)
assert bound == best
if len(mins) == 1:
checked += 1
assert tuple(labels) == mins[0]
assert checked > 50
def test_frustrated_triangle():
# Each pair pays 1 when the two values agree; at least one pair agrees.
terms = [(p, q, 1, 0, 0, 1) for (p, q) in ((0, 1), (1, 2), (0, 2))]
unary = [(0, 0)] * 3
labels, bound = qpbo(unary, terms)
assert labels == [None, None, None]
assert bound == 0
assert all_minimizers(unary, terms)[0] == 1
def test_worked_example():
# A path of three variables: one nonsubmodular pair and a strong unary.
unary = [(0, 4), (0, 0), (0, 0)]
terms = [(0, 1, 2, 0, 0, 2), (1, 2, 0, 3, 3, 0)]
labels, bound = qpbo(unary, terms)
assert labels == [0, 1, 1]
assert bound == 0 and energy(unary, terms, (0, 1, 1)) == 0
def test_partial_example():
# The frustrated triangle with a fourth variable tied to variable 0.
terms = [(p, q, 1, 0, 0, 1) for (p, q) in ((0, 1), (1, 2), (0, 2))]
terms.append((0, 3, 0, 1, 1, 0))
unary = [(0, 0)] * 3 + [(0, 3)]
labels, bound = qpbo(unary, terms)
assert labels == [None, None, None, 0]
assert bound == 0.5
best, mins = all_minimizers(unary, terms)
assert best == 1 and all(z[3] == 0 for z in mins)
History
Hammer, Hansen and Simeone (1984) defined the roof dual of a quadratic 0-1 function, showed that it equals the bound of the linear programming relaxation, and proved persistency. Boros and Hammer, with coauthors, developed the network flow computation of the bound and summarized the theory in their 2002 survey. Kolmogorov and Rother (2007) brought the method to vision under the name QPBO, with the doubled graph and an efficient code built on the Boykov-Kolmogorov max-flow algorithm, and Rother et al. (2007) added probing and improvement. QPBO then became the standard solver of fusion moves and of other nonregular binary moves.
References
- Peter L. Hammer, Pierre Hansen and Bruno Simeone, Roof duality, complementation and persistency in quadratic 0-1 optimization, Mathematical Programming 28(2), 1984, 121-155, the roof dual bound, its equality with the bound of the linear programming relaxation, and the persistency theorem
- Endre Boros and Peter L. Hammer, Pseudo-Boolean optimization, Discrete Applied Mathematics 123(1-3), 2002, 155-225, the parts on roof duality, the implication network and the computation of the roof dual by network flows
- Vladimir Kolmogorov and Carsten Rother, Minimizing nonsubmodular functions with graph cuts, a review, IEEE Transactions on Pattern Analysis and Machine Intelligence 29(7), 2007, 1274-1279, the construction of the doubled graph, the reading of the partial labeling, and the properties of the method
- Andrew Blake, Pushmeet Kohli and Carsten Rother (editors), Markov Random Fields for Vision and Image Processing, MIT Press, 2011, Part I, Algorithms for inference of MAP estimates for MRFs (the chapter on optimizing non-submodular binary MRFs)
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 W42VES Edit this page History Report an error Markdown