TExcelTAD
Home › Information Theory › Sum-Product (Belief Propagation) Decoding

Sum-Product (Belief Propagation) Decoding

Bit flipping throws away how confident the decoder is about each bit. The sum-product algorithm, also called belief propagation, keeps that information: bits and checks exchange probabilities (as log-likelihood ratios) along the edges of the Tanner graph. It computes exact posterior probabilities on graphs without cycles and excellent approximations on sparse graphs with long cycles. With it, LDPC codes come close to the Shannon limit.

Log-likelihood ratios

For a bit xx we track the log-likelihood ratio (LLR)

L=ln⁡P(x=0∣evidence)P(x=1∣evidence)L = \ln\frac{P(x = 0 \mid \text{evidence})}{P(x = 1 \mid \text{evidence})}

Positive means "probably 0", and the magnitude is the confidence. On a BSC with flip probability ff, a received bit rr gives the channel LLR ±ln⁡1−ff\pm\ln\frac{1 - f}{f}; on a Gaussian channel with BPSK (0→+10 \to +1, 1→−11 \to -1) and noise variance σ2\sigma^2, it is 2yσ2\frac{2y}{\sigma^2}.

Two rules combine LLRs:

  • At a bit: independent pieces of evidence about the same bit add: L=∑iLiL = \sum_i L_i.
  • At a check: a parity check says the XOR of its bits is 0. The evidence it gives about one bit from the others is
Lout=2 artanh⁡(∏itanh⁡Li2)L_{\text{out}} = 2\,\operatorname{artanh}\left(\prod_i \tanh\frac{L_i}{2}\right)
python · try it yourself
import numpy as np

def check_rule(llrs):
    return 2 * np.arctanh(np.prod(np.tanh(np.asarray(llrs) / 2)))

print("two confident zeros  ->", round(float(check_rule([4.0, 4.0])), 3), "(the third bit is probably 0)")
print("a confident 0 and 1  ->", round(float(check_rule([4.0, -4.0])), 3), "(probably 1)")
print("one unsure input     ->", round(float(check_rule([4.0, 0.2])), 3), "(weak evidence)")
two confident zeros  -> 3.307 (the third bit is probably 0)
a confident 0 and 1  -> -3.307 (probably 1)
one unsure input     -> 0.193 (weak evidence)

A check's message is never more confident than its least confident input.

The algorithm

Messages flow along every edge in both directions. With λj\lambda_j the channel LLR of bit jj:

  1. Bit to check: qj→i=λj+∑i′≠iri′→jq_{j \to i} = \lambda_j + \sum_{i' \ne i} r_{i' \to j} (all evidence except what check ii said).
  2. Check to bit: ri→j=2artanh⁡∏j′≠jtanh⁡qj′→i2r_{i \to j} = 2\operatorname{artanh}\prod_{j' \ne j}\tanh\frac{q_{j' \to i}}{2}.
  3. Decide: total Lj=λj+∑iri→jL_j = \lambda_j + \sum_i r_{i \to j}; x^j=0\hat x_j = 0 if Lj>0L_j > 0. Stop when Hx^=0H\hat{\mathbf{x}} = \mathbf{0}.

Excluding the recipient's own message ("extrinsic information") is what keeps the decoder from simply echoing its own beliefs.

python · try it yourself
import numpy as np

def gallager_H(n, wc, wr, rng):
    band = np.zeros((n // wr, n), dtype=np.int8)
    for i in range(n // wr):
        band[i, i * wr:(i + 1) * wr] = 1
    return np.vstack([band] + [band[:, rng.permutation(n)] for _ in range(wc - 1)]).astype(int)

def sum_product(H, llr, max_iter=50):
    rows, cols = np.nonzero(H)                             # one entry per edge, grouped by check
    wr = int(H[0].sum())                                   # every check has wr bits (regular code)
    r = np.zeros(len(cols))                                # check-to-bit messages, one per edge
    for it in range(max_iter):
        total = llr + np.bincount(cols, weights=r, minlength=H.shape[1])
        x = (total < 0).astype(int)
        if not np.any(H @ x % 2):
            return x, it, True
        q = total[cols] - r                                # bit-to-check, excluding the check's own message
        t = np.tanh(np.clip(q, -30, 30) / 2).reshape(-1, wr)
        t = np.where(np.abs(t) < 1e-12, 1e-12, t)
        prod = np.prod(t, axis=1, keepdims=True)           # product over each check, then divide out one edge
        r = (2 * np.arctanh(np.clip(prod / t, -0.999999, 0.999999))).ravel()
    return x, max_iter, False

rng = np.random.default_rng(0)
n, f = 480, 0.06
H = gallager_H(n, 3, 6, rng)
received = (rng.random(n) < f).astype(int)                # all-zero codeword sent
llr = np.log((1 - f) / f) * (1 - 2 * received)
x, iters, ok = sum_product(H, llr)
print(f"{received.sum()} channel errors; converged {ok} after {iters} iterations; remaining errors {x.sum()}")
27 channel errors; converged True after 8 iterations; remaining errors 0

Sum-product versus bit flipping

python · try it yourself
import numpy as np

def gallager_H(n, wc, wr, rng):
    band = np.zeros((n // wr, n), dtype=np.int8)
    for i in range(n // wr):
        band[i, i * wr:(i + 1) * wr] = 1
    return np.vstack([band] + [band[:, rng.permutation(n)] for _ in range(wc - 1)]).astype(int)

def sum_product(H, llr, max_iter=50):
    rows, cols = np.nonzero(H); wr = int(H[0].sum()); r = np.zeros(len(cols))
    for _ in range(max_iter):
        total = llr + np.bincount(cols, weights=r, minlength=H.shape[1]); x = (total < 0).astype(int)
        if not np.any(H @ x % 2):
            return x
        t = np.tanh(np.clip(total[cols] - r, -30, 30) / 2).reshape(-1, wr)
        t = np.where(np.abs(t) < 1e-12, 1e-12, t)
        r = (2 * np.arctanh(np.clip(np.prod(t, axis=1, keepdims=True) / t, -0.999999, 0.999999))).ravel()
    return x

def bit_flip(H, x, max_iter=50):
    x = x.copy()
    for _ in range(max_iter):
        z = H @ x % 2
        if not z.any():
            return x
        votes = z @ H; flip = votes >= 3
        if not flip.any():
            flip = votes == votes.max()
        x[flip] ^= 1
    return x

rng = np.random.default_rng(1)
n = 480
H = gallager_H(n, 3, 6, rng)
for f in [0.03, 0.05, 0.07, 0.09]:
    bp = bf = 0
    for _ in range(100):
        rx = (rng.random(n) < f).astype(int)
        bp += int(sum_product(H, np.log((1 - f) / f) * (1 - 2 * rx)).any())
        bf += int(bit_flip(H, rx).any())
    print(f"f = {f:.2f}: block error rate  bit flipping {bf / 100:.2f}   sum-product {bp / 100:.2f}")
f = 0.03: block error rate  bit flipping 0.20   sum-product 0.02
f = 0.05: block error rate  bit flipping 0.60   sum-product 0.01
f = 0.07: block error rate  bit flipping 0.93   sum-product 0.16
f = 0.09: block error rate  bit flipping 1.00   sum-product 0.76

Sum-product decodes reliably at noise levels where bit flipping almost always fails. Longer codes push the working region toward the (3,6)(3, 6) threshold near f=0.084f = 0.084; irregular codes with nn in the tens of thousands get within a few percent of capacity.

Soft channel values

On a Gaussian channel the decoder can use the received voltages directly. Hard-decision decoding first converts them to bits, which loses information (The Binary Symmetric Channel):

python · try it yourself
import numpy as np
from scipy.stats import norm

def gallager_H(n, wc, wr, rng):
    band = np.zeros((n // wr, n), dtype=np.int8)
    for i in range(n // wr):
        band[i, i * wr:(i + 1) * wr] = 1
    return np.vstack([band] + [band[:, rng.permutation(n)] for _ in range(wc - 1)]).astype(int)

def sum_product(H, llr, max_iter=50):
    rows, cols = np.nonzero(H); wr = int(H[0].sum()); r = np.zeros(len(cols))
    for _ in range(max_iter):
        total = llr + np.bincount(cols, weights=r, minlength=H.shape[1]); x = (total < 0).astype(int)
        if not np.any(H @ x % 2):
            return x
        t = np.tanh(np.clip(total[cols] - r, -30, 30) / 2).reshape(-1, wr)
        t = np.where(np.abs(t) < 1e-12, 1e-12, t)
        r = (2 * np.arctanh(np.clip(np.prod(t, axis=1, keepdims=True) / t, -0.999999, 0.999999))).ravel()
    return x

rng = np.random.default_rng(2)
n, sigma = 480, 0.75
H = gallager_H(n, 3, 6, rng)
f = norm.cdf(-1 / sigma)
soft = hard = 0
for _ in range(100):
    y = 1 + sigma * rng.normal(size=n)                    # all-zero codeword sent as +1
    soft += int(sum_product(H, 2 * y / sigma**2).any())
    hard += int(sum_product(H, np.log((1 - f) / f) * np.sign(y)).any())
print(f"sigma = {sigma}: hard-decision flip rate {f:.3f}")
print(f"block error rate  hard-decision BP {hard / 100:.2f}   soft-decision BP {soft / 100:.2f}")
sigma = 0.75: hard-decision flip rate 0.091
block error rate  hard-decision BP 0.76   soft-decision BP 0.01

Why it works, and when it is exact

On a tree-shaped graph, the messages are exact marginal posteriors, by the same argument as dynamic programming on trees. LDPC graphs have cycles, but they are long, so for many iterations each bit's "neighbourhood" looks like a tree and the messages are nearly independent. The same algorithm is used across machine learning for inference in graphical models, and its min-sum approximation (replace the tanh rule by the minimum magnitude and product of signs) is what most hardware decoders run.

In software

  • Real decoders work with LLRs in fixed point and use min-sum or offset min-sum to avoid tanh and artanh.
  • Layered (serial) scheduling updates checks one group at a time and roughly halves the number of iterations.
  • Clip LLRs and tanh values, as in the code above, to avoid infinities when the decoder becomes very confident.

Exercises

Exercise 1: Adding evidence

A bit has channel LLR 1.2 and receives check messages 0.8, -0.3 and 2.0. What is its total LLR and decision?

Answer

3.7; decide 0.

Solution

1.2+0.8−0.3+2.0=3.7>01.2 + 0.8 - 0.3 + 2.0 = 3.7 > 0, so the bit is probably 0.

Exercise 2: A check with an erased input

What does a check send to bit A if another of its bits has LLR 0 (completely unknown)?

Answer

LLR 0: no information.

Solution

tanh⁡(0)=0\tanh(0) = 0 makes the product zero. If any other bit of the parity check is a coin flip, the check says nothing about bit A.

Exercise 3: Min-sum approximation (code)

Compare the exact check rule with the min-sum approximation sign⁡∏Li⋅min⁡∣Li∣\operatorname{sign}\prod L_i \cdot \min|L_i| for inputs (2.0,−1.5,3.0)(2.0, -1.5, 3.0).

Answer

Exact about −0.94-0.94, min-sum −1.5-1.5.

Solution
python · try it yourself
import numpy as np

L = np.array([2.0, -1.5, 3.0])
exact = 2 * np.arctanh(np.prod(np.tanh(L / 2)))
minsum = np.prod(np.sign(L)) * np.abs(L).min()
print(round(float(exact), 4), float(minsum))
-0.9391 -1.5

Min-sum is overconfident, which is why practical decoders scale or offset its messages.

Test yourself

A positive log-likelihood ratio for a bit means…

  1. the bit is more likely 0
  2. the bit is more likely 1
  3. the bit is erased
  4. the check is satisfied

Why does a bit exclude the message from check i when sending to check i?

  1. To pass only extrinsic information and avoid echoing beliefs
  2. To save memory
  3. Because check i is satisfied
  4. It does not; all messages are included

On which graphs is belief propagation exact?

  1. graphs without cycles (trees)
  2. complete graphs
  3. graphs with many 4-cycles
  4. all graphs