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 we track the log-likelihood ratio (LLR)
Positive means "probably 0", and the magnitude is the confidence. On a BSC with flip probability , a received bit gives the channel LLR ; on a Gaussian channel with BPSK (, ) and noise variance , it is .
Two rules combine LLRs:
- At a bit: independent pieces of evidence about the same bit add: .
- 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
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 the channel LLR of bit :
- Bit to check: (all evidence except what check said).
- Check to bit: .
- Decide: total ; if . Stop when .
Excluding the recipient's own message ("extrinsic information") is what keeps the decoder from simply echoing its own beliefs.
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
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 threshold near ; irregular codes with 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):
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
, 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
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 for inputs .
Answer
Exact about , min-sum .
Solution
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…
- the bit is more likely 0
- the bit is more likely 1
- the bit is erased
- the check is satisfied
Why does a bit exclude the message from check i when sending to check i?
- To pass only extrinsic information and avoid echoing beliefs
- To save memory
- Because check i is satisfied
- It does not; all messages are included
On which graphs is belief propagation exact?
- graphs without cycles (trees)
- complete graphs
- graphs with many 4-cycles
- all graphs