18. LDPC Codes: Messages Live on Edges

PySDR’s Channel Coding chapter ends with the codes that come close to the Shannon limit. Low-density parity-check codes were “first introduced by Robert G. Gallager in his PhD dissertation in 1960”, and they are used in DVB-S2, WiMAX and IEEE 802.11n. PySDR stops at that history. This chapter builds a complete code in C++: the code itself, its encoder, and three decoders. The reference is GNU Radio’s gr-fec, which ships an LDPC decoder and a set of parity-check matrices.

A short reminder of the idea, since Channel Coding worked with Hamming codes. An LDPC code is defined by a parity-check matrix \(H\) with very few ones: a word \(x\) is a codeword when \(Hx = 0\). Draw a node for each code bit (a variable), a node for each row of \(H\) (a check), and an edge for each one in \(H\). That is the code’s Tanner graph. The decoder passes messages along its edges: each variable tells each of its checks what it believes about its bit, each check answers with what the other bits of its parity equation imply, and that repeats until the hard decisions satisfy every check.

The code is in code/include/cppsdr/ldpc.hpp, code/tests/test_ldpc.cpp (the book’s own code, decoded on 300 fixed noisy frames), and code/gnuradio_block/test_gr_ldpc.cc (against gr-fec, on the matrix n_1800_k_0902_gap_28.alist that GNU Radio installs in share/gnuradio/fec/ldpc/).

The Graph Is the Data Structure

Every message belongs to one edge, so a decoder needs one array of values per kind of message, indexed by edge. graph_view numbers the edges once, in check order, and keeps two adjacency lists in compressed sparse row form:

struct graph_view {
    std::size_t n = 0, m = 0;                      // variables (code bits), checks
    std::span<const std::uint32_t> check_start;   // check c owns edges check_start[c] .. check_start[c+1]-1
    std::span<const std::uint32_t> edge_var;      // edge e connects to variable edge_var[e]
    std::span<const std::uint32_t> var_start;     // variable v's edges: var_edge[var_start[v] .. var_start[v+1]-1]
    std::span<const std::uint32_t> var_edge;
};

A check update walks its edges contiguously. A variable update reaches its edges through var_edge. The view is just spans, so the same decoders run on a graph read from a file at run time and on one built by the compiler.

GNU Radio’s decoder (gr-fec/lib/awgn_bp.cc, v3.10.12.0) stores the two kinds of messages as std::vector<std::vector<double>> of size \(M \times N\), a full matrix of which only the edges are used. It also checks for a codeword after each iteration by multiplying each dense row of \(H\) with the decision, both passed by value (operator*(GF2Vec a, GF2Vec b) in gf2vec.cc). For the 1800-bit code that is 25.9 MB of message storage for 5388 edges, where two arrays per edge take 86 kB.

The alist format that gr-fec uses is David MacKay’s. MacKay pads short lists with zeros, but the files GNU Radio ships do not, so read_alist() reads line by line and accepts both. It also checks that the column lists and the row lists describe the same matrix. The test compares the result with gr::fec::alist, edge by edge, and checks that 100 words encoded by gr::fec::cldpc satisfy every parity check of the graph.

A Code Designed by the Compiler

Practical LDPC codes, including those of 802.11n, WiMAX and 5G NR, are quasi-cyclic. \(H\) is built from \(Z \times Z\) blocks, each either zero or an identity matrix with its columns cyclically shifted. A small base matrix of shifts describes the whole code, and the decoder hardware can process \(Z\) checks at once. The book’s code uses the 802.11n format and its smallest size: a \(12 \times 24\) base matrix with \(Z = 27\), giving \(n = 648\), \(k = 324\), rate 1/2. The base matrix is this chapter’s own, not the standard’s.

The decoder is exact on a graph without cycles and only approximate on a graph with them, and the shortest possible cycle, length 4, hurts the most. Fossorier gave the condition for quasi-cyclic codes (“Quasi-cyclic low-density parity-check codes from circulant permutation matrices”, IEEE Transactions on Information Theory, 2004). Two block rows \(i, j\) and two block columns \(a, b\), all four blocks non-zero, close a 4-cycle exactly when

\[s_{ia} - s_{ib} + s_{jb} - s_{ja} \equiv 0 \pmod Z.\]

That is cheap to check, so the compiler designs the code and proves it free of 4-cycles:

template <std::size_t Z>
constexpr base_matrix<12, 24> design_rate_half()
{
    ...  // parity part: 802.11n's dual-diagonal structure
    for (std::size_t j = 0; j < Kb; ++j)
        for (std::size_t r : {j, (j + 5) % Mb, (j + 9) % Mb}) {
            int s = int((7 * j + 11 * r + 3 * j * r) % Z);
            for (h[r][j] = s; closes_4_cycle(h, Z, r, j);) h[r][j] = s = (s + 1) % int(Z);
        }
    return h;
}

constexpr auto base = ldpc::design_rate_half<27>();
static_assert(!ldpc::has_4_cycle(base, 27));
using code_t = ldpc::qc_code<base, 27>;    // the base matrix is a template argument
constexpr code_t code{};                   // the lifted graph, 1647 edges, in std::arrays

Information column \(j\) uses block rows \(j\), \(j+5\) and \(j+9\) modulo 12. The differences between those rows, 4, 5 and 9, and their negatives 3, 7 and 8, are six distinct numbers, so no two information columns share two block rows. The shift search only has to avoid the few 4-cycles that remain with the parity columns. qc_code takes the base matrix as a template argument, so the number of edges is a compile-time constant, and the lifted graph is a constexpr object of std::array s. Its row and column weights are static_assert ed. At run time, a breadth-first search measures its girth (the length of its shortest cycle): 6.

The same search on GNU Radio’s 1800-bit matrix gives girth 4. Its columns 22 and 24 (1-based, as in the file) share checks 22 and 882, and 31 pairs of columns share two checks.

The 802.11n parity structure also gives a linear-time encoder. Its first parity block column has shift 1 in the top and bottom block rows and 0 in the middle one, and the remaining parity columns form a staircase of identities. Add up all block rows: each staircase block appears twice and cancels, the two blocks with shift 1 cancel, and only the identity in the middle remains. The first parity block is therefore the sum of all \(\lambda_r\), the contributions of the information bits to block row \(r\). Every further parity block follows from the one before it by one addition:

for (std::size_t r = 0; r < Mb; ++r)
    for (std::size_t z = 0; z < Z; ++z) p(0, z) ^= lambda[r * Z + z];
for (std::size_t z = 0; z < Z; ++z) p(1, z) = lambda[z] ^ shifted(cw, Kb, s, z);            // row 0
for (std::size_t i = 1; i + 1 < Mb; ++i)                                                    // rows 1 .. Mb-2
    for (std::size_t z = 0; z < Z; ++z)
        p(i + 1, z) = lambda[i * Z + z] ^ p(i, z) ^ (i == Mb / 2 ? p(0, z) : std::uint8_t(0));

encode() is constexpr, so static_assert(ldpc::is_codeword(code.view(), code_t::encode(pattern(1)))) checks the encoder against the graph while compiling. At run time, all 324 unit vectors encode to systematic codewords.

Sum-Product, Checked Against GNU Radio

The sum-product decoder works with log-likelihood ratios, \(L = \log P(0)/P(1)\). A check sends each of its edges

\[R_e = 2 \operatorname{atanh} \prod_{e' \neq e} \tanh(Q_{e'}/2),\]

and a variable sends each edge its channel LLR plus the messages from all its other checks. awgn_bp forms each product by looping over the other edges, \(d_c (d_c - 1)\) multiplications and tanh calls per check. sum_product computes each tanh once and gets “all but one” from a prefix and a suffix product, \(O(d_c)\) per check:

for (std::uint32_t e = b; e < end; ++e) t_[e] = std::tanh(std::clamp(q_[e] / 2.0, -18.0, 18.0));
double prefix = 1;
for (std::uint32_t e = b; e < end; ++e) { r_[e] = prefix; prefix *= t_[e]; }
double suffix = 1;
for (std::uint32_t e = end; e-- > b;) { r_[e] = 2.0 * std::atanh(r_[e] * suffix); suffix *= t_[e]; }

Everything else follows awgn_bp: the clip at 18, the flooding schedule (all checks, then all variables), the stopping rule, and the first test of whether the input’s hard decision already is a codeword. On 100 frames of GNU Radio’s code at \(E_b/N_0 = 2\) dB, both decoders reach the same decision after the same number of iterations in every frame.

Their posterior LLRs differ by up to \(5 \times 10^{-4}\) (relative), which is more than double rounding. awgn_bp computes in double, but it clips with gr::branchless_clip (gnuradio/math.h), which takes and returns float:

static inline float branchless_clip(float x, float clip)
{
    return 0.5 * (std::abs(x + clip) - std::abs(x - clip));
}

So every tanh argument is rounded to float, and the float sum x + 18 drops the bits of x below the precision of 18, about \(2 \times 10^{-6}\). The test includes a replica of awgn_bp with exactly that clip and its product order. It matches awgn_bp’s posteriors bit for bit in 10 of 10 frames. The difference does not change any decision here, but the double arithmetic around the clip does not buy double precision.

Per frame, awgn_bp takes about 23 ms and sum_product 1.8 ms on the M1. The replica sits in between at 5.1 ms. It has awgn_bp’s arithmetic, but messages stored per edge and no dense parity checks. Storage accounts for most of the difference, and the \(O(d_c)\) check update for the rest.

LLRs, Not Samples

For BPSK with bit 0 sent as \(+1\) in Gaussian noise of variance \(\sigma^2\), the channel LLR of a received sample \(y\) is \(2y/\sigma^2\). Sum-product needs exactly that scale. Here it is on the book’s code, on 300 fixed frames at \(E_b/N_0 = 2\) dB, with the LLRs multiplied by a factor:

decoder input

frames failed

mean iterations

\(0.3 \times 2y/\sigma^2\)

300

50.0

\(0.5 \times 2y/\sigma^2\)

110

31.8

\(2y/\sigma^2\)

32

15.6

\(1.4 \times 2y/\sigma^2\)

36

16.8

\(2 \times 2y/\sigma^2\)

39

18.0

\(y\)

300

50.0

Overestimating the LLRs costs a little; underestimating them costs everything. \(y\) alone is \(0.32 \times 2y/\sigma^2\) at this \(E_b/N_0\), and no frame decodes.

awgn_bp takes its input as LLRs as they are, and the FEC API wrapper gr::fec::ldpc_decoder negates them first (rx[k] = in[i + k] * (-1)). It therefore expects positive values for bit 1, the convention of digital.map_bb([-1, 1]) in GNU Radio’s fecapi_ldpc_decoders.grc example. The test confirms both points on GNU Radio’s code. With \(-L\) all 20 frames come out right, with \(+L\) none. Fed the raw samples \(y\), awgn_bp fails all 20 frames that it decodes with LLRs. A 2023 rewrite of awgn_bp removed its noise-variance parameter, so the scaling is now the job of whatever comes before it. In GNU Radio that is constellation_soft_decoder_cf, which computes \(\log P(1)/P(0)\) from the distances to the constellation points and a noise power (calc_soft_dec in gr-digital/lib/constellation.cc), with the sign ldpc_decoder expects. A flowgraph that connects raw soft symbols to the LDPC decoder needs a multiply by \(2/\sigma^2\) in between, so either way the receiver needs an estimate of the noise variance.

Min-sum avoids the question. It replaces the tanh rule with the product of the other signs times the smallest other magnitude, scaled by \(\alpha = 3/4\). This is normalized min-sum (J. Chen and M. Fossorier, “Near optimum universal belief propagation based decoding of low-density parity check codes”, IEEE Transactions on Communications, 2002):

for (std::uint32_t e = b; e < end; ++e) {
    const float mag = alpha_ * (e == at ? min2 : min1);
    r_[e] = (odd != std::signbit(q_[e])) ? -mag : mag;   // sign of the others = total sign * own sign
}

Each check needs only the two smallest magnitudes and the sign parity. Every operation (minimum, sign, sum, multiplication by \(\alpha\)) scales with its input, so multiplying all LLRs by a positive constant multiplies every message by the same constant and changes no decision. The test checks this with a factor of 1/4, which is exact in floating point: all 300 frames decode bit-identically. Fed \(y\) instead of \(2y/\sigma^2\), min-sum gives the same decision in 300 of 300 frames, and on GNU Radio’s code it decodes all 20 frames that awgn_bp fails with raw samples. The price is accuracy: on the book’s code, flooding min-sum fails 72 of the 300 frames where sum-product fails 32.

Min-Sum in Fixed Point, Check by Check

Hardware decoders are min-sum decoders in fixed point, and they make two more changes. The first is the schedule. Flooding updates all checks from the messages of the previous iteration. A layered decoder (D. Hocevar, “A reduced complexity decoder architecture via layered decoding of LDPC codes”, IEEE Workshop on Signal Processing Systems, 2004) keeps one posterior per variable and updates it after every check, so later checks in the same iteration already see the new values. The second is storage. Under min-sum, all messages of a check are rebuilt from four values: the two smallest magnitudes, where the smallest one was, and the signs. So layered_min_sum keeps one 8-byte record per check instead of a value per edge:

struct check_record {
    std::uint8_t min1 = 0, min2 = 0;   // already scaled by 3/4
    std::uint8_t at = 0;               // position of min1 within the check
    std::uint32_t signs = 0;           // bit k: sign of message k
};
static_assert(sizeof(check_record) == 8);

static int message(check_record const& r, std::uint32_t k)
{
    const int mag = k == r.at ? r.min2 : r.min1;
    const bool negative = (std::popcount(r.signs) & 1) != ((r.signs >> k) & 1);
    return negative ? -mag : mag;
}

The posteriors are 16-bit integers saturated to \(\pm 127\). The channel values are \(\operatorname{round}(8y)\), saturated to 6 bits (\(\pm 31\)), with no noise estimate. For the book’s code, the decoder state is 3888 bytes, against 13 176 for flooding min-sum in float and 44 712 for sum-product in double.

The normalization by 3/4 is a shift and an add, (3 * m) >> 2, and its rounding matters. Rounded down, it turns a magnitude of 1 into 0 and 2 into 1, and small messages vanish. On the 300 frames:

decoder

frames failed

mean iterations

sum-product, double, flooding

32

15.6

min-sum, float, flooding

72

22.3

min-sum, fixed point, layered, (3 * m + 2) >> 2

56

15.7

min-sum, fixed point, layered, (3 * m) >> 2

116

24.9

With rounding to the nearest value, the 8-bit layered decoder fails fewer frames than float flooding min-sum and needs 30 % fewer iterations. Rounded down, it fails twice as many. On GNU Radio’s 1800-bit code, it decodes all 20 test frames in 6.3 iterations on average, where sum-product needs 10.0.

These are 300 frames at one \(E_b/N_0\), enough to compare the decoders on the same noise and to test the claims above, but not an error-rate curve. Small differences, such as 56 against 72 frames, would need many more frames and several \(E_b/N_0\) values before they could be called a property of the decoders.

Key Takeaways

  • Store LDPC messages per edge, in two compressed adjacency lists of the Tanner graph. GNU Radio’s awgn_bp keeps full \(M \times N\) matrices: 25.9 MB of messages for a code with 5388 edges.

  • A quasi-cyclic code is a base matrix of shifts, small enough to be a template argument. The compiler can lift it, check it for 4-cycles with Fossorier’s condition, and run the dual-diagonal encoder in a static_assert. GNU Radio’s 1800-bit example matrix has 4-cycles; the book’s code has girth 6.

  • Compute “the product of all the others” from a prefix and a suffix: \(O(d_c)\) instead of \(O(d_c^2)\) per check. Same decisions as awgn_bp in every test frame, 13 times faster.

  • gr::branchless_clip is a float function, so awgn_bp’s double arithmetic rounds every tanh argument to float.

  • Sum-product needs real LLRs, \(2y/\sigma^2\), and gr::fec::ldpc_decoder expects them with positive meaning bit 1. Fed raw samples, it decoded none of the test frames. Min-sum is invariant to the scale of its input and needs no noise estimate.

  • A fixed-point layered min-sum decoder keeps 8 bytes per check. Round its normalization to nearest: rounding down doubled the failed frames.