Algorithm Search⌘K

Algorithmadvanced

Fully connected CRF inference

Also called dense CRF, Krahenbuhl-Koltun CRF.

Mean field inference in a CRF with Gaussian pairwise terms between all pixel pairs, made linear time by high-dimensional filtering of messages.

Time
O(N L W H) worst · average · best
Space
O(L W H) extra
Where
H = the image height in pixels; L = the number of labels; N = the number of mean field iterations; W = the image width in pixels
Properties
approximate inferencenot convergence guaranteeddeterministiciterative
Origin
Philipp Krähenbühl, Vladlen Koltun, 2011

A fully connected CRF (dense CRF) labels each pixel of an image, for example with an object class, using a conditional random field in which every pair of pixels has a pairwise term, not only neighbors. The pairwise term is a Potts penalty times a sum of Gaussian kernels in position and color, so similar pixels that are close prefer the same label. Exact inference is out of reach, so Krähenbühl and Koltun (2011) use the mean field approximation. This page is about that inference: the update, why it is correct, where it can fail, and how the messages, a sum over all pixel pairs, become a Gaussian filter. The general CRF and the general mean field method are on their own pages. In practice a dense CRF refines the per-pixel scores of a classifier, often a convolutional network; the network is outside this page.

In plain words

A classifier looks at each pixel and gives a score for each label, for example "70 percent road, 30 percent car". These scores are noisy, and they often blur at object edges. A dense CRF lets pixels vote. Each pixel asks every other pixel what it believes, and gives more weight to pixels that are close and have a similar color. Then it updates its own belief with the votes and its own score. After a few rounds of this, a region with one color tends to agree on one label, and the label changes where the color changes.

Asking every other pixel is too slow when done one pair at a time. The trick is that the weighted vote is a blur of the belief images with a Gaussian that also looks at color. A fast filter computes such a blur for all pixels at once.

The problem

The input is an image of n=WHn = WH pixels, a label set of size LL, and a unary energy Ui(l)U_i(l) for each pixel ii and label ll, usually Ui(l)=−log⁡pi(l)U_i(l) = -\log p_i(l) for the class probabilities pip_i of a classifier. Pixel ii has the position pi=(ui,vi)p_i = (u_i, v_i) and the color IiI_i. The energy of a labeling xx is (Krähenbühl and Koltun 2011, equations 1 to 3)

E(x)=∑iUi(xi)+∑i<jμ(xi,xj) k(i,j),E(x) = \sum_i U_i(x_i) + \sum_{i < j} \mu(x_i, x_j)\, k(i, j),
k(i,j)=w(1)exp⁡(−∥pi−pj∥22θα2−∥Ii−Ij∥22θβ2)+w(2)exp⁡(−∥pi−pj∥22θγ2),k(i, j) = w^{(1)} \exp\Bigl(-\frac{\lVert p_i - p_j \rVert^2}{2 \theta_\alpha^2} - \frac{\lVert I_i - I_j \rVert^2}{2 \theta_\beta^2}\Bigr) + w^{(2)} \exp\Bigl(-\frac{\lVert p_i - p_j \rVert^2}{2 \theta_\gamma^2}\Bigr),

with the Potts compatibility μ(l,l′)=[l≠l′]\mu(l, l') = [l \ne l'] and weights w(1),w(2)≥0w^{(1)}, w^{(2)} \ge 0. The first kernel is the appearance kernel, the second the smoothness kernel. The model is P(x)∝e−E(x)P(x) \propto e^{-E(x)}, a Markov random field on the complete graph, with the Potts model as its pair term.

The output is a product distribution Q(x)=∏iQi(xi)Q(x) = \prod_i Q_i(x_i) that approximates PP, and the labeling xi=arg⁡max⁡lQi(l)x_i = \arg\max_l Q_i(l). Mean field picks QQ to make KL(Q∥P)\mathrm{KL}(Q \| P) small. Finding the exact minimum energy labeling is NP-hard for the multi-label Potts energy, and this method does not try.

The algorithm

The algorithm is Algorithm 1 of Krähenbühl and Koltun (2011), written for the Potts model with the two kernels merged into k(i,j)k(i, j).

  1. DENSE-CRF(U, k, N) ▷ U_i(l): unary energies; k(i, j): kernel sum, i ≠ j
  2. 1for each pixel i and label l do Q_i(l) ← exp(-U_i(l)) / Σ_l' exp(-U_i(l'))
  3. 2repeat N times
  4. 3for each pixel i and label l do M_i(l) ← Σ_{j ≠ i} k(i, j) Q_j(l) ▷ message passing
  5. 4for each pixel i and label l do B_i(l) ← Σ_l' M_i(l') - M_i(l) ▷ Potts compatibility
  6. 5for each pixel i and label l do Q_i(l) ← exp(-U_i(l) - B_i(l)) ▷ local update
  7. 6for each pixel i do divide each Q_i(l) by Σ_l' Q_i(l') ▷ normalize
  8. 7return Q and the labels x_i = argmax_l Q_i(l)

Line L4 is the compatibility transform: for the Potts model, the penalty for label ll is the total message for all other labels. All pixels update at the same time, from the old QQ.

Messages as filtering. Line L3 is a sum over all pairs, O(n2L)O(n^2 L). For each label, Mi(l)M_i(l) is the value at pixel ii of a Gaussian filter applied to the image Q⋅(l)Q_\cdot(l), minus the value at ii itself (equation 5 of the paper). The smoothness kernel is a Gaussian filter in (u,v)(u, v). The appearance kernel is a Gaussian in the 5D space of position and color, the kernel of the bilateral filter. Krähenbühl and Koltun compute both with the permutohedral lattice of Adams, Baek and Davis (2010), which splats the values onto a lattice, blurs on it, and slices back (Algorithm 2 of the paper). Its cost is linear in nn, and it approximates the sum.

Example

Take one row of 4 pixels with gray values 0,0,10,100, 0, 10, 10 and two labels. A classifier gives the probabilities 0.2,0.6,0.7,0.90.2, 0.6, 0.7, 0.9 for label 1, so Ui=(−log⁡(1−pi),−log⁡pi)U_i = (-\log(1 - p_i), -\log p_i). Pixel 1 has the color of pixel 0 but leans to label 1. The parameters are w(1)=2w^{(1)} = 2, θα=2\theta_\alpha = 2, θβ=3\theta_\beta = 3, w(2)=0.5w^{(2)} = 0.5, θγ=1\theta_\gamma = 1. The kernel values from pixel 1 are

k(1,0)=2e−1/8+0.5e−1/2≈2.0683,k(1,2)=2e−1/8−100/18+0.5e−1/2≈0.3101,k(1,3)≈0.0724.k(1, 0) = 2 e^{-1/8} + 0.5 e^{-1/2} \approx 2.0683, \quad k(1, 2) = 2 e^{-1/8 - 100/18} + 0.5 e^{-1/2} \approx 0.3101, \quad k(1, 3) \approx 0.0724.

The color difference of 10 almost removes the appearance term between pixels 1 and 2.

In the first iteration, with Q0=(0.8,0.2)Q_0 = (0.8, 0.2), Q2=(0.3,0.7)Q_2 = (0.3, 0.7) and Q3=(0.1,0.9)Q_3 = (0.1, 0.9):

  • M1(0)=2.0683⋅0.8+0.3101⋅0.3+0.0724⋅0.1≈1.7549M_1(0) = 2.0683 \cdot 0.8 + 0.3101 \cdot 0.3 + 0.0724 \cdot 0.1 \approx 1.7549 and M1(1)≈0.6959M_1(1) \approx 0.6959.
  • The Potts penalties are B1(0)=M1(1)≈0.6959B_1(0) = M_1(1) \approx 0.6959 and B1(1)=M1(0)≈1.7549B_1(1) = M_1(0) \approx 1.7549.
  • The new energies are 0.9163+0.6959=1.61220.9163 + 0.6959 = 1.6122 for label 0 and 0.5108+1.7549=2.26570.5108 + 1.7549 = 2.2657 for label 1, so Q1(1)=1/(1+e0.6535)≈0.3422Q_1(1) = 1 / (1 + e^{0.6535}) \approx 0.3422.

Pixel 1 now prefers label 0, like its neighbor with the same color.

iteration Q0(1)Q_0(1) Q1(1)Q_1(1) Q2(1)Q_2(1) Q3(1)Q_3(1) labels F(Q)F(Q)
0 0.2000 0.6000 0.7000 0.9000 0 1 1 1 2.0853
1 0.2815 0.3422 0.9256 0.9541 0 0 1 1 1.7535
2 0.1224 0.4579 0.9306 0.9808 0 0 1 1 1.6964
5 0.1324 0.2934 0.9369 0.9815 0 0 1 1 1.6484

F(Q)F(Q) is the mean field free energy of the correctness section. It stays above −log⁡Z≈1.2960-\log Z \approx 1.2960, computed by brute force over the 16 labelings. The values of Q0(1)Q_0(1) go up and down, a small sign of the parallel update. The test file checks these numbers.

Correctness

The full proof is in proofs/correctness.md. The facts that are proved:

  • Lines L3 to L6 compute the mean field equation (equation 4 of the paper) for the Potts model.
  • For every product distribution QQ, the free energy F(Q)=EQ[E]−H(Q)F(Q) = \mathbb{E}_Q[E] - H(Q) equals KL(Q∥P)−log⁡Z\mathrm{KL}(Q \| P) - \log Z, so F(Q)≥−log⁡ZF(Q) \ge -\log Z.
  • With all other pixels fixed, the update of one pixel is the unique minimizer of FF over that pixel. So sequential updates, one pixel at a time, never increase FF, and the values of FF converge. This is the classical mean field result (Wainwright and Jordan 2008, Section 5). It gives a local result, not the global minimum.
  • The parallel update of lines L3 to L6 has no such guarantee, as Krähenbühl and Koltun (2013) point out. A two-pixel example with a strong link and opposite unaries makes it swap the beliefs of the two pixels at every step (see the proof). The test file checks it.
  • Krähenbühl and Koltun (2013, Section 3) give sufficient conditions under which a parallel scheme converges: positive definite kernels, which the Gaussian kernels are, and a negative semidefinite compatibility, which the Potts model is after a shift by a constant. Their variant of Section 3.2 adds the self term k(i,i)Qi(l)k(i, i) Q_i(l) to each message, and then each parallel update is a step of the concave-convex procedure and does not increase an approximate objective. The proof file proves this.
  • The separable blur of the smoothness kernel, minus the self term, gives the exact messages of line L3 for that kernel.

What is not proved: the error of the permutohedral lattice, which is an approximation, and the quality of the labels, which is measured on benchmarks.

Proof: Correctness of mean field inference in the fully connected CRFfull

This proof covers lines L1 to L7 of the main page, with exact messages. The model has n=WHn = WH pixels and LL labels. The energy of a labeling xx is

E(x)=∑iUi(xi)+∑i<j[xi≠xj] k(i,j),k(i,j)=∑mw(m)k(m)(fi,fj),E(x) = \sum_i U_i(x_i) + \sum_{i < j} [x_i \ne x_j]\, k(i, j), \qquad k(i, j) = \sum_m w^{(m)} k^{(m)}(f_i, f_j),

with weights w(m)≥0w^{(m)} \ge 0 and Gaussian kernels k(m)k^{(m)}, so k(i,j)=k(j,i)≥0k(i, j) = k(j, i) \ge 0. The distribution is P(x)=e−E(x)/ZP(x) = e^{-E(x)} / Z. A mean field distribution is Q(x)=∏iQi(xi)Q(x) = \prod_i Q_i(x_i), and its free energy is

F(Q)=EQ[E]−H(Q)=∑i∑lQi(l)(Ui(l)+log⁡Qi(l))+∑i<jk(i,j)(1−∑lQi(l)Qj(l)).F(Q) = \mathbb{E}_Q[E] - H(Q) = \sum_i \sum_l Q_i(l) \bigl(U_i(l) + \log Q_i(l)\bigr) + \sum_{i < j} k(i, j) \Bigl(1 - \sum_l Q_i(l) Q_j(l)\Bigr).

The pair term is the probability under QQ that xi≠xjx_i \ne x_j, times k(i,j)k(i, j). Nothing here says that the model labels images well. That is a benchmark question.

Lemma 1 (the lines compute the mean field equation). Given QQ, lines L3 to L6 compute, for each pixel ii,

Qinew(l)=1Ziexp⁡(−Ui(l)−∑j≠ik(i,j)∑l′≠lQj(l′)),Q_i^{\mathrm{new}}(l) = \frac{1}{Z_i} \exp\Bigl(-U_i(l) - \sum_{j \ne i} k(i, j) \sum_{l' \ne l} Q_j(l')\Bigr),

which is equation (4) of Krähenbühl and Koltun (2011) for the Potts compatibility μ(l,l′)=[l≠l′]\mu(l, l') = [l \ne l'].

Proof. Line L3 sets Mi(l)=∑j≠ik(i,j)Qj(l)M_i(l) = \sum_{j \ne i} k(i, j) Q_j(l). Line L4 sets Bi(l)=∑l′Mi(l′)−Mi(l)=∑l′≠lMi(l′)=∑j≠ik(i,j)∑l′≠lQj(l′)B_i(l) = \sum_{l'} M_i(l') - M_i(l) = \sum_{l' \ne l} M_i(l') = \sum_{j \ne i} k(i, j) \sum_{l' \ne l} Q_j(l'). Lines L5 and L6 exponentiate −Ui(l)−Bi(l)-U_i(l) - B_i(l) and divide by the sum over ll. □\square

Lemma 2 (free energy and the partition function). For every product distribution QQ,

F(Q)=KL(Q ∥ P)−log⁡Z≥−log⁡Z,F(Q) = \mathrm{KL}(Q \,\|\, P) - \log Z \ge -\log Z,

with equality if and only if Q=PQ = P.

Proof. KL(Q∥P)=∑xQ(x)log⁡Q(x)−∑xQ(x)log⁡P(x)=−H(Q)+EQ[E]+log⁡Z\mathrm{KL}(Q \| P) = \sum_x Q(x) \log Q(x) - \sum_x Q(x) \log P(x) = -H(Q) + \mathbb{E}_Q[E] + \log Z. The expectation of Ui(xi)U_i(x_i) under QQ is ∑lQi(l)Ui(l)\sum_l Q_i(l) U_i(l). For i≠ji \ne j the labels are independent under QQ, so Pr⁡Q(xi≠xj)=1−∑lQi(l)Qj(l)\Pr_Q(x_i \ne x_j) = 1 - \sum_l Q_i(l) Q_j(l). The entropy of a product is the sum of the entropies. This gives the formula for FF. The KL divergence is nonnegative, and zero only for Q=PQ = P (Gibbs inequality). □\square

Lemma 3 (one pixel update is an exact minimization). Fix QjQ_j for all j≠ij \ne i. Over all distributions QiQ_i on the labels, FF has the unique minimizer QinewQ_i^{\mathrm{new}} of Lemma 1.

Proof. Collect the terms of FF that contain QiQ_i:

∑lQi(l)(Ui(l)+log⁡Qi(l))+∑j≠ik(i,j)(1−∑lQi(l)Qj(l)).\sum_l Q_i(l) \bigl(U_i(l) + \log Q_i(l)\bigr) + \sum_{j \ne i} k(i, j) \Bigl(1 - \sum_l Q_i(l) Q_j(l)\Bigr).

Since ∑lQi(l)=1\sum_l Q_i(l) = 1, the term k(i,j)(1−∑lQi(l)Qj(l))k(i, j)(1 - \sum_l Q_i(l) Q_j(l)) equals ∑lQi(l) k(i,j)∑l′≠lQj(l′)\sum_l Q_i(l)\, k(i, j) \sum_{l' \ne l} Q_j(l'). So the part of FF that depends on QiQ_i is ∑lQi(l)(Ui(l)+Bi(l)+log⁡Qi(l))\sum_l Q_i(l) (U_i(l) + B_i(l) + \log Q_i(l)), with BiB_i as in Lemma 1. With R(l)=e−Ui(l)−Bi(l)/ZiR(l) = e^{-U_i(l) - B_i(l)} / Z_i this is KL(Qi∥R)−log⁡Zi\mathrm{KL}(Q_i \| R) - \log Z_i, which is smallest, and only then, at Qi=R=QinewQ_i = R = Q_i^{\mathrm{new}}. □\square

Theorem 1 (sequential updates). If the pixels are updated one at a time with the rule of Lemma 1, each with the current values of the others, then FF never increases. FF is bounded below by −log⁡Z-\log Z, so the sequence of values of FF converges.

Proof. Each step replaces QiQ_i by the minimizer of FF over QiQ_i with the rest fixed (Lemma 3), so FF does not increase. A non-increasing sequence that is bounded below (Lemma 2) converges. □\square

This is the classical result for mean field (Wainwright and Jordan 2008, Section 5). It is a statement about the values of FF, at a local minimum or a saddle in general, not about the global minimum of FF over all product distributions.

Parallel updates. Lines L3 to L6 update all pixels at once, from the old QQ. Lemma 3 does not apply, because each pixel uses old values of its neighbors. Krähenbühl and Koltun (2013) point out that the parallel update loses the guarantee. A two-pixel example shows that it can fail to converge: U1=(0,1)U_1 = (0, 1), U2=(1,0)U_2 = (1, 0), and k(1,2)=5e−1/18≈4.73k(1, 2) = 5 e^{-1/18} \approx 4.73. At the start Q1(0)=Q2(1)≈0.731Q_1(0) = Q_2(1) \approx 0.731. In each parallel step each pixel adopts the label that the other pixel had, because the Potts penalty 4.73⋅0.7314.73 \cdot 0.731 outweighs the unary difference 1. The beliefs swap at each step: Q1(0)≈0.731,0.234,0.971,0.031,0.996,…Q_1(0) \approx 0.731, 0.234, 0.971, 0.031, 0.996, \ldots The sequential rule from the same start converges, with both pixels on label 1. The test file checks this example.

Theorem 2 (a convergent parallel variant). Krähenbühl and Koltun (2013, Section 3.2). Add the self term to the message: Mi(l)=∑jk(i,j)Qj(l)M_i(l) = \sum_j k(i, j) Q_j(l) with k(i,i)=∑mw(m)k(i, i) = \sum_m w^{(m)}, the value of the kernels at zero distance. Then each parallel update does not increase

D~(Q)=∑i∑lQi(l)(Ui(l)+log⁡Qi(l))−12∑i,jk(i,j)∑lQi(l)Qj(l),\tilde D(Q) = \sum_i \sum_l Q_i(l) \bigl(U_i(l) + \log Q_i(l)\bigr) - \frac{1}{2} \sum_{i, j} k(i, j) \sum_l Q_i(l) Q_j(l),

where the double sum includes i=ji = j.

Proof. Write D~=f+g\tilde D = f + g with f(Q)=∑i,lQi(l)log⁡Qi(l)f(Q) = \sum_{i, l} Q_i(l) \log Q_i(l), which is convex, and g(Q)=∑i,lQi(l)Ui(l)−12∑lql⊤Kqlg(Q) = \sum_{i, l} Q_i(l) U_i(l) - \frac{1}{2} \sum_l q_l^{\top} K q_l, where ql=(Q1(l),…,Qn(l))q_l = (Q_1(l), \ldots, Q_n(l)) and KK is the matrix of k(i,j)k(i, j) with the diagonal included. Each Gaussian kernel is positive definite (its Fourier transform is positive, by Bochner's theorem), and the appearance kernel is a Gaussian in the joint feature of position and color. So KK, a sum of Gram matrices with weights w(m)≥0w^{(m)} \ge 0, is positive semidefinite, and gg is concave.

The concave-convex procedure takes Q′=arg⁡min⁡Qf(Q)+∇g(Qold)⋅QQ' = \arg\min_Q f(Q) + \nabla g(Q^{\mathrm{old}}) \cdot Q over products of distributions. The objective splits over the pixels, and ∇g\nabla g at pixel ii and label ll is Ui(l)−Mi(l)U_i(l) - M_i(l). By the argument of Lemma 3, the minimizer is Qi′(l)∝exp⁡(−Ui(l)+Mi(l))Q'_i(l) \propto \exp(-U_i(l) + M_i(l)). The line L4 penalty is ∑l′Mi(l′)−Mi(l)\sum_{l'} M_i(l') - M_i(l), which differs from −Mi(l)-M_i(l) by a constant in ll, so lines L5 and L6 give the same Qi′Q'_i. Then

D~(Q′)=f(Q′)+g(Q′)≤f(Q′)+g(Qold)+∇g(Qold)⋅(Q′−Qold)≤f(Qold)+g(Qold).\tilde D(Q') = f(Q') + g(Q') \le f(Q') + g(Q^{\mathrm{old}}) + \nabla g(Q^{\mathrm{old}}) \cdot (Q' - Q^{\mathrm{old}}) \le f(Q^{\mathrm{old}}) + g(Q^{\mathrm{old}}).

The first inequality is concavity of gg, and the second is the choice of Q′Q'. □\square

D~\tilde D differs from F+log⁡ZF + \log Z only by the self terms −12k(i,i)∑lQi(l)2-\frac{1}{2} k(i, i) \sum_l Q_i(l)^2 and a constant. Krähenbühl and Koltun argue that for wide kernels this part is small. That is an approximation, not a bound proved here. On the two-pixel example the variant converges, but to a state where each pixel keeps its own label, which shows that the self term changes the fixed points.

Lemma 4 (separable filtering of the spatial kernel). For the spatial kernel k(i,j)=exp⁡(−∥pi−pj∥2/(2θ2))k(i, j) = \exp(-\lVert p_i - p_j \rVert^2 / (2 \theta^2)) on the grid, a blur of each label plane along the rows with the 1D Gaussian g(d)=e−d2/(2θ2)g(d) = e^{-d^2 / (2\theta^2)}, then along the columns, gives ∑jk(i,j)Qj(l)\sum_j k(i, j) Q_j(l) over all jj, including j=ij = i. Subtracting Qi(l)Q_i(l) gives the message of line L3.

Proof. k(i,j)=g(ui−uj) g(vi−vj)k(i, j) = g(u_i - u_j)\, g(v_i - v_j). The row blur gives R(u,v)=∑xg(u−x)Q(x,v)(l)R(u, v) = \sum_{x} g(u - x) Q_{(x, v)}(l), and the column blur gives ∑yg(v−y)R(u,y)=∑x,yg(u−x)g(v−y)Q(x,y)(l)\sum_y g(v - y) R(u, y) = \sum_{x, y} g(u - x) g(v - y) Q_{(x, y)}(l). The self term has k(i,i)=1k(i, i) = 1. □\square

The appearance kernel does not split in this way, because it depends on the colors. Krähenbühl and Koltun filter it with the permutohedral lattice of Adams, Baek and Davis (2010), which downsamples, blurs and upsamples. That step is an approximation of the sum, and the proofs above do not cover its error.

Cost. With exact messages, line L3 costs O(n2L)O(n^2 L), line L4 costs O(nL)O(n L) for the Potts model (O(nL2)O(n L^2) for a general compatibility matrix), and lines L5 and L6 cost O(nL)O(n L). So NN iterations cost O(Nn2L)O(N n^2 L) time in the real-RAM model, with n=WHn = WH, plus O(n2)O(n^2) for the kernel matrix if it is stored. With a filter whose cost is linear in nn, an iteration costs O(nL)O(n L) times the cost per sample of the filter.

Complexity

The front matter gives the cost with a linear-time filter for the messages, as in the paper, for a fixed feature dimension. The filter is an approximation. With exact messages an iteration costs O(n2L)O(n^2 L) time for line L3 and O(nL)O(nL) for lines L4 to L6, with n=WHn = WH. That is O(NLW2H2)O(N L W^2 H^2) for NN iterations, in the real-RAM model. With a filter that is linear in nn, an iteration costs O(nL)O(nL) times the cost per sample of the filter, so O(NLWH)O(N L W H) for fixed feature dimension. Adams, Baek and Davis state that their filter is linear in the input size and polynomial in the dimension of the feature space. Krähenbühl and Koltun also downsample the images before filtering, by a factor tied to the kernel width (Section 5 of their paper). A general compatibility matrix instead of Potts adds O(nL2)O(n L^2) per iteration for line L4. The extra space is O(nL)O(nL) for QQ and the messages, plus the lattice. The number of iterations is a choice; it is not given by a bound.

Properties

  • Approximate inference. Mean field gives a product distribution and a labeling, not the minimum energy labeling.
  • Parallel and simple. Each step is a few filters and per-pixel arithmetic, which suits GPUs.
  • No convergence guarantee for the plain parallel update. In practice a few iterations are run. That is a heuristic choice, not a result.
  • Edge-preserving. The appearance kernel lets labels follow color edges, like a bilateral filter of the beliefs.
  • Differentiable. Each step is smooth in UU and in the kernel weights. This is what lets later work train the CRF together with a network.

Variants and improvements

  • Sequential or damped updates. Updating a subset of pixels at a time, or mixing the new QQ with the old one, avoids oscillation. A sequential schedule has the guarantee of the correctness section, but it is slow with filtering, which works on all pixels at once.
  • Convergent parallel mean field (Krähenbühl and Koltun 2013). A CCCP form (Section 3.1) and the cheaper concave approximation (Section 3.2) both converge under the conditions above. The same paper learns the kernel parameters by gradient descent through the inference.
  • General compatibilities. A learned matrix μ(l,l′)\mu(l, l') lets, for example, "person" and "bicycle" be next to each other at a lower cost than "person" and "sky".
  • CRF as a network layer. Later work wrote the mean field iterations as layers of a recurrent network and trained them with a convolutional network end to end (CRF-as-RNN), and the DeepLab models used a dense CRF to sharpen network outputs. These are applications of the same update.
  • Other inference. For a CRF with only neighbor terms, graph cuts find the exact minimum of a binary submodular energy, and alpha-expansion is within a factor 2 of the optimum for Potts. These methods do not scale to all pixel pairs.

When to use it

Use a dense CRF to sharpen the output of a per-pixel classifier near object boundaries, when the image colors carry the boundary. It adds long-range consistency at a low cost. Do not use it when the classifier is already sharp at boundaries, as many recent networks are; the gain then is small or negative. Do not use it when you need the exact minimum energy labeling or a certificate, and do not use it when the colors of two classes are the same, because the appearance kernel then pulls their labels together.

Pitfalls

  • Self term. The message of line L3 excludes j=ij = i. A filter that sums over all pixels includes it, with weight k(i,i)=w(1)+w(2)k(i, i) = w^{(1)} + w^{(2)}. Forgetting to subtract it gives the variant of the 2013 paper, which has different fixed points: in the two-pixel example of the proof, each pixel then keeps its own label.
  • Oscillation. Strong kernel weights can make the parallel update oscillate. Watch the labels, or use damping.
  • Units of the kernels. θα\theta_\alpha and θγ\theta_\gamma are in pixels and θβ\theta_\beta in color units. A change of image size or color range changes the model unless the parameters change with it. Krähenbühl and Koltun report that w(2)=θγ=1w^{(2)} = \theta_\gamma = 1 worked well on their data; this is a tuned value, not a result.
  • Unary scale. If UU comes from a network with overconfident probabilities, the pairwise terms have little effect. The balance between UU and w(m)w^{(m)} needs tuning.
  • Free energy is not accuracy. A lower FF means a better fit to the model, not more correct labels.
  • Filter error. The permutohedral lattice and the downsampling are approximations. Results can differ between implementations, and the messages are not exactly symmetric.

Implementations

The Python code in impl/python/dense_crf.py implements lines L1 to L7 with exact messages over all pixel pairs, for tiny images. It also has the separable Gaussian filter for the smoothness kernel, the sequential update, the variant with the self term, the free energy, and log⁡Z\log Z by brute force. It does not implement the permutohedral lattice. The tests check that the marginals are distributions, that zero weights give the unary softmax, that the filter equals the exact sum, that sequential updates never raise FF, that F≥−log⁡ZF \ge -\log Z, the oscillation example, the monotone objective of the variant, and a small denoising example.

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.

dense_crf.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dense-crf/. The authors are listed in prov/9CMFRH.jsonl.

"""Mean field inference in a fully connected CRF with Gaussian edge potentials.

Pixel i = v * w + u is (u, v) with the gray value img[v][u]. The energy of a
labeling x is

    E(x) = sum_i U[i][x_i] + sum_{i < j} [x_i != x_j] k(i, j),
    k(i, j) = w1 exp(-|p_i - p_j|^2 / (2 ta^2) - |I_i - I_j|^2 / (2 tb^2))
            + w2 exp(-|p_i - p_j|^2 / (2 tg^2)),

the Potts model with the two kernels of Kraehenbuehl and Koltun (2011). The
messages here are exact sums over all pixel pairs, O(n^2 L) per iteration,
for tiny images. gaussian_messages shows the filtering idea for the spatial
kernel: a separable Gaussian blur minus the self term.
"""

import itertools
import math


def kernel_matrix(img, w1, ta, tb, w2, tg):
    """Return the n x n matrix of k(i, j), with zero diagonal."""
    h, w = len(img), len(img[0])
    pix = [(u, v, img[v][u]) for v in range(h) for u in range(w)]
    n = len(pix)
    k = [[0.0] * n for _ in range(n)]
    for i in range(n):
        ui, vi, ci = pix[i]
        for j in range(i + 1, n):
            uj, vj, cj = pix[j]
            dp = (ui - uj) ** 2 + (vi - vj) ** 2
            dc = (ci - cj) ** 2
            val = w1 * math.exp(-dp / (2 * ta * ta) - dc / (2 * tb * tb)) + w2 * math.exp(-dp / (2 * tg * tg))
            k[i][j] = k[j][i] = val
    return k


def softmax_neg(e):
    """Return the distribution proportional to exp(-e)."""
    m = min(e)
    q = [math.exp(m - x) for x in e]
    s = sum(q)
    return [x / s for x in q]


def dense_crf(unary, kmat, iters, include_self=0.0):
    """Run iters parallel mean field updates and return Q (n lists of L probabilities).

    unary[i][l] is the unary energy and kmat the kernel matrix with zero diagonal.
    include_self adds include_self * Q_i(l) to the message of pixel i, which
    gives the convergent variant of Kraehenbuehl and Koltun (2013, Section 3.2)
    when include_self = k(i, i) = w1 + w2.
    """
    n, nl = len(unary), len(unary[0])
    q = [softmax_neg(unary[i]) for i in range(n)]  # @line L1
    for _ in range(iters):  # @line L2
        msg = [[include_self * q[i][l] for l in range(nl)] for i in range(n)]
        for i in range(n):  # @line L3
            row, mi = kmat[i], msg[i]
            for j in range(n):
                kij = row[j]
                if kij:
                    qj = q[j]
                    for l in range(nl):
                        mi[l] += kij * qj[l]
        new = []
        for i in range(n):
            total = sum(msg[i])
            pen = [total - msg[i][l] for l in range(nl)]  # @line L4
            e = [unary[i][l] + pen[l] for l in range(nl)]  # @line L5
            new.append(softmax_neg(e))  # @line L6
        q = new
    return q  # @line L7


def labels_of(q):
    """Return the label with the largest marginal for each pixel."""
    return [max(range(len(qi)), key=lambda l: qi[l]) for qi in q]


def mean_field_sequential(unary, kmat, sweeps, trace=None):
    """Update one pixel at a time, in index order. If trace is a list, append the free energy after each update."""
    n, nl = len(unary), len(unary[0])
    q = [softmax_neg(unary[i]) for i in range(n)]
    for _ in range(sweeps):
        for i in range(n):
            m = [0.0] * nl
            for j in range(n):
                if kmat[i][j]:
                    for l in range(nl):
                        m[l] += kmat[i][j] * q[j][l]
            total = sum(m)
            q[i] = softmax_neg([unary[i][l] + total - m[l] for l in range(nl)])
            if trace is not None:
                trace.append(free_energy(q, unary, kmat))
    return q


def free_energy(q, unary, kmat):
    """Return F(Q) = E_Q[E] - H(Q). F(Q) >= -log Z, with equality only for the true distribution."""
    n, nl = len(unary), len(unary[0])
    f = 0.0
    for i in range(n):
        for l in range(nl):
            if q[i][l] > 0:
                f += q[i][l] * (unary[i][l] + math.log(q[i][l]))
        for j in range(i + 1, n):
            if kmat[i][j]:
                f += kmat[i][j] * (1.0 - sum(q[i][l] * q[j][l] for l in range(nl)))
    return f


def concave_objective(q, unary, kmat, self_weight):
    """The approximate KL divergence (up to log Z) of Kraehenbuehl and Koltun (2013, eq. 9) for the Potts model.

    The Potts compatibility is written as -[l = l'], which differs from
    [l != l'] by a constant, and the kernel matrix gets the diagonal self_weight.
    """
    n, nl = len(unary), len(unary[0])
    f = 0.0
    for i in range(n):
        for l in range(nl):
            if q[i][l] > 0:
                f += q[i][l] * (unary[i][l] + math.log(q[i][l]))
        for j in range(n):
            kij = self_weight if i == j else kmat[i][j]
            if kij:
                f -= 0.5 * kij * sum(q[i][l] * q[j][l] for l in range(nl))
    return f


def energy(x, unary, kmat):
    n = len(x)
    e = sum(unary[i][x[i]] for i in range(n))
    for i in range(n):
        for j in range(i + 1, n):
            if x[i] != x[j]:
                e += kmat[i][j]
    return e


def log_partition(unary, kmat):
    """Return log Z by summing over all labelings. Only for tiny problems."""
    n, nl = len(unary), len(unary[0])
    es = [-energy(x, unary, kmat) for x in itertools.product(range(nl), repeat=n)]
    m = max(es)
    return m + math.log(sum(math.exp(e - m) for e in es))


def gaussian_messages(q, w, h, theta):
    """Return sum_{j != i} exp(-|p_i - p_j|^2 / (2 theta^2)) Q_j(l) by a separable blur minus the self term.

    The spatial Gaussian factors into a Gaussian in u times a Gaussian in v, so
    a blur along the rows and then along the columns gives the full sum over j.
    The blur is exact here: it uses all pixels, with no truncation.
    """
    nl = len(q[0])
    g = [math.exp(-d * d / (2 * theta * theta)) for d in range(max(w, h))]
    rows = [[[0.0] * nl for _ in range(w)] for _ in range(h)]
    for v in range(h):
        for u in range(w):
            acc = rows[v][u]
            for x in range(w):
                c = g[abs(u - x)]
                qx = q[v * w + x]
                for l in range(nl):
                    acc[l] += c * qx[l]
    out = []
    for v in range(h):
        for u in range(w):
            acc = [0.0] * nl
            for y in range(h):
                c = g[abs(v - y)]
                ry = rows[y][u]
                for l in range(nl):
                    acc[l] += c * ry[l]
            qi = q[v * w + u]
            out.append([acc[l] - qi[l] for l in range(nl)])
    return out
test_dense_crf.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dense-crf/. The authors are listed in prov/9CMFRH.jsonl.

import math
import random

from dense_crf import (
    concave_objective,
    dense_crf,
    free_energy,
    gaussian_messages,
    kernel_matrix,
    labels_of,
    log_partition,
    mean_field_sequential,
    softmax_neg,
)


def random_problem(rng, w, h, nl, levels=3):
    img = [[rng.randrange(levels) * 4 for _ in range(w)] for _ in range(h)]
    unary = [[rng.uniform(0.0, 2.0) for _ in range(nl)] for _ in range(w * h)]
    return img, unary


def test_row_example():
    img = [[0, 0, 10, 10]]
    unary = [[-math.log(1 - p), -math.log(p)] for p in (0.2, 0.6, 0.7, 0.9)]
    k = kernel_matrix(img, 2.0, 2.0, 3.0, 0.5, 1.0)
    assert abs(k[0][1] - 2.0683) < 1e-4 and abs(k[1][2] - 0.3101) < 1e-4
    q = dense_crf(unary, k, 1)
    assert abs(q[1][1] - 0.3422) < 1e-4
    assert labels_of(q) == [0, 0, 1, 1]
    q5 = dense_crf(unary, k, 5)
    assert labels_of(q5) == [0, 0, 1, 1]
    assert abs(free_energy(q5, unary, k) - 1.6484) < 1e-4
    assert free_energy(q5, unary, k) >= -log_partition(unary, k)


def test_marginals_are_distributions():
    rng = random.Random(11)
    img, unary = random_problem(rng, 4, 3, 3)
    q = dense_crf(unary, kernel_matrix(img, 1.5, 2.0, 3.0, 1.0, 1.0), 4)
    for qi in q:
        assert all(x > 0 for x in qi) and abs(sum(qi) - 1.0) < 1e-12


def test_zero_weights_give_the_unary_softmax():
    rng = random.Random(12)
    img, unary = random_problem(rng, 3, 3, 4)
    q = dense_crf(unary, kernel_matrix(img, 0.0, 2.0, 3.0, 0.0, 1.0), 5)
    for qi, ui in zip(q, unary):
        z = sum(math.exp(-x) for x in ui)
        assert all(abs(a - math.exp(-x) / z) < 1e-12 for a, x in zip(qi, ui))


def test_separable_filter_equals_the_naive_sum():
    rng = random.Random(13)
    w, h, nl, theta = 5, 4, 3, 1.3
    q = [softmax_neg([rng.uniform(0, 3) for _ in range(nl)]) for _ in range(w * h)]
    k = kernel_matrix([[0] * w for _ in range(h)], 0.0, 1.0, 1.0, 1.0, theta)
    fast = gaussian_messages(q, w, h, theta)
    for i in range(w * h):
        for l in range(nl):
            naive = sum(k[i][j] * q[j][l] for j in range(w * h))
            assert abs(fast[i][l] - naive) < 1e-12


def test_sequential_updates_never_raise_the_free_energy():
    rng = random.Random(14)
    for _ in range(5):
        img, unary = random_problem(rng, 3, 2, 3)
        k = kernel_matrix(img, 3.0, 2.0, 2.0, 2.0, 1.0)
        trace = []
        q = mean_field_sequential(unary, k, 4, trace)
        start = free_energy([softmax_neg(u) for u in unary], unary, k)
        values = [start] + trace
        assert all(b <= a + 1e-12 for a, b in zip(values, values[1:]))
        assert values[-1] >= -log_partition(unary, k) - 1e-12


def test_free_energy_bounds_log_z_and_is_tight_without_coupling():
    rng = random.Random(15)
    img, unary = random_problem(rng, 4, 2, 2)
    k = kernel_matrix(img, 1.0, 2.0, 3.0, 1.0, 1.0)
    q = dense_crf(unary, k, 6)
    assert free_energy(q, unary, k) >= -log_partition(unary, k)
    zero = kernel_matrix(img, 0.0, 2.0, 3.0, 0.0, 1.0)
    q0 = dense_crf(unary, zero, 1)
    assert abs(free_energy(q0, unary, zero) + log_partition(unary, zero)) < 1e-10


def test_parallel_update_can_oscillate():
    # Two pixels with a strong Potts link and opposite unaries swap their beliefs each step.
    unary = [[0.0, 1.0], [1.0, 0.0]]
    k = kernel_matrix([[0, 0]], 0.0, 1.0, 1.0, 5.0, 3.0)
    q = [dense_crf(unary, k, t) for t in range(6)]
    assert labels_of(q[1]) == [1, 0] and labels_of(q[2]) == [0, 1]
    assert labels_of(q[3]) == [1, 0] and labels_of(q[4]) == [0, 1]
    seq = mean_field_sequential(unary, k, 3)
    assert labels_of(seq) == [1, 1]


def test_self_term_variant_decreases_its_objective():
    rng = random.Random(16)
    cases = [([[0, 0]], [[0.0, 1.0], [1.0, 0.0]], (0.0, 1.0, 1.0, 5.0, 3.0))]
    for _ in range(4):
        img, unary = random_problem(rng, 3, 3, 3)
        cases.append((img, unary, (2.0, 1.5, 3.0, 1.0, 1.0)))
    for img, unary, (w1, ta, tb, w2, tg) in cases:
        k = kernel_matrix(img, w1, ta, tb, w2, tg)
        values = [concave_objective(dense_crf(unary, k, t, include_self=w1 + w2), unary, k, w1 + w2) for t in range(8)]
        assert all(b <= a + 1e-12 for a, b in zip(values, values[1:]))


def test_denoising_two_regions():
    rng = random.Random(17)
    w = h = 10
    truth = [1 if u >= 5 else 0 for v in range(h) for u in range(w)]
    img = [[100 * (1 if u >= 5 else 0) + rng.randint(-10, 10) for u in range(w)] for v in range(h)]
    unary = []
    for t in truth:
        # The probability of the true label: right with chance 0.75, wrong otherwise.
        p = rng.uniform(0.55, 0.9) if rng.random() < 0.75 else rng.uniform(0.1, 0.45)
        probs = [1 - p, p] if t == 1 else [p, 1 - p]
        unary.append([-math.log(x) for x in probs])
    k = kernel_matrix(img, 3.0, 3.0, 20.0, 1.0, 1.0)
    before = sum(a == b for a, b in zip(labels_of(dense_crf(unary, k, 0)), truth))
    after = sum(a == b for a, b in zip(labels_of(dense_crf(unary, k, 5)), truth))
    assert before < 90 and after == 100

History

Earlier CRFs for segmentation used pairwise terms between neighbor pixels, or terms over regions, because inference over all pairs of pixels was too slow. Krähenbühl and Koltun (2011) noticed that the mean field messages with Gaussian kernels are a high-dimensional Gaussian filter, and used the permutohedral lattice of Adams, Baek and Davis (2010) to compute them in time linear in the number of pixels. They evaluated the method on the MSRC-21 and PASCAL VOC 2010 data sets. In 2013 they studied the convergence of the parallel update and learned the parameters. The method then became a common post-processing step for semantic segmentation with networks.

References

  1. Philipp Krähenbühl and Vladlen Koltun, Efficient inference in fully connected CRFs with Gaussian edge potentials, NIPS 24, 109-117, 2011, Section 2 (model, equations 1 to 3), Section 3 (mean field, equations 4 and 5, Algorithms 1 and 2), Section 4 (parameters)
  2. Philipp Krähenbühl and Vladlen Koltun, Parameter learning and convergent inference for dense random fields, ICML 2013, PMLR 28(3), 513-521, Section 3 (convergence conditions, Sections 3.1 and 3.2)
  3. Andrew Adams, Jongmin Baek and Abe Davis, Fast high-dimensional filtering using the permutohedral lattice, Computer Graphics Forum 29(2), 753-762, 2010, The permutohedral lattice (splat, blur and slice)
  4. Martin J. Wainwright and Michael I. Jordan, Graphical models, exponential families, and variational inference, Foundations and Trends in Machine Learning 1(1-2), 2008, Section 5, Mean field methods

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