Error-Correcting Codes
How can a message survive a channel that flips its bits?
In 1947 Hamming's weekend jobs on a Bell Labs relay computer died whenever its two-out-of-five code detected a bad bit, and he asked why the machine could not locate the error and fix it. The part starts from the binary symmetric channel and the repetition code, which buys reliability only by giving up rate, and from Hamming distance, which says what a code can detect and correct. Hamming(7,4) is built from its parity checks, whose syndrome names the flipped bit, and shown to be perfect; the bounds of the rate-distance plane say how good any code can be. Finite fields give Reed-Solomon codes, polynomials evaluated at many points, and the series' QR code is scratched across 56 modules, which corrupts 8 of its 44 bytes, and still reads. The part turns on Shannon's theorem of 1948: below the capacity 1 - H(p) the error can be made as small as you like, which random codes decoded by table begin to show, at a decoding cost nobody can pay. Viterbi's trellis, LDPC codes under belief propagation and polar codes are the fifty years of work that made the limit reachable. It ends with codes for storage and the open questions of capacity and locality.
What you need. Binary arithmetic and XOR, polynomials, and the binomial distribution.
- Mathematics, ideas and history
- Hamming space, Hamming(7,4), bounds, finite fields, Reed–Solomon, CRCs, Shannon's channel theorem, LDPC, polar codes
- What we build or compute
- a scratched QR code, recovered
What you will be able to do
Degree
- Compute the Hamming distance of a code and say how many errors it detects and corrects.
- Encode four bits with Hamming(7,4), flip one bit, and locate it from the syndrome.
- Compute the error rate and the rate of an n-fold repetition code on a binary symmetric channel.
Graduate
- Prove the Hamming and Singleton bounds, and show that Reed-Solomon codes meet the Singleton bound by counting roots.
- Multiply in GF(256) with log tables, and recover erased Reed-Solomon symbols by Lagrange interpolation.
- State Shannon's theorem for the binary symmetric channel and outline the random-coding argument.
Research
- State what it means for Reed-Muller codes to achieve capacity and what list decoding buys beyond half the distance.
- Analyse the two-query local decoder of the Hadamard code against 1 - 2 delta, and state the open length trade-off for three queries.
Industry
- Choose an error level for a QR code, and explain why erasures cost half of what errors cost.
- Say which damage a CRC of r bits is guaranteed to catch and why it is not a cryptographic hash.
- Compare replication, Reed-Solomon RS(10,4) and a locally repairable code for storage overhead and repair cost.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 12 min · Graduate 40 min · Research 43 min · Industry 21 min.
- 0A scratched messageDegree2 min
- 1Noise and repetitionDegree2 min
- 2Hamming distanceDegree2 min
- 3Hamming(7,4)Degree3 min
- 4How good can a code be?Graduate2 min
- 5Finite fieldsGraduate3 min
- 6Reed–SolomonGraduate3 min
- 7Our QR codeIndustry3 min
- 8Cyclic codes and CRCsIndustry3 min
- 9Shannon's theoremGraduate3 min
- 10Convolutional codes and ViterbiGraduate2 min
- 11LDPC codes and belief propagationGraduate4 min
- 12Polar codesGraduate3 min
- 13Codes for storageIndustry2 min
- 14Frontier: capacity and localityResearch3 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
A scratched messageDegree2 min
In 1947 Richard Hamming was running calculations on a relay computer at Bell Labs. During the week, operators restarted jobs that failed; at weekends nobody was there. The machine stored each digit in a two-out-of-five code, so it could detect a bad bit. When a check fired, it dropped the job and moved on to the next, and on Monday Hamming found his work gone. As he told the story later: if the machine can detect an error, why can't it locate the position of the error and correct it? His answer, published in 1950, started the theory of error-correcting codes. Two years earlier Claude Shannon had proved how far such codes could go. Closing the gap between the two took fifty years, and this part follows it.
Here is a code you use every day. This QR code has twenty-five by twenty-five squares, and holds forty-four bytes: twenty-two of message and twenty-two of checks. You can scan it. Now paint over a piece of it, near the middle. Eight of the forty-four bytes are now wrong, and the decoder is not told which. And still it reads: CS, Built, Part 28. By the end of this part we will have built every step: the finite field, the Reed-Solomon code, and the decoder that found the message.
1Noise and repetitionDegree2 min
Shannon's simplest model of noise is the binary symmetric channel. Each bit goes through unchanged with probability one minus p and flips with probability p, independently of every other bit. It is crude, but memory cells hit by cosmic rays, scratched disks and faint radio all behave like it to a first approximation. There are other channels: in an erasure channel a bit is lost but you know which one, and real noise often comes in bursts. Against all of them the tool is the same: add redundancy, so that the receiver can undo the damage.
The obvious code: say everything several times. Send each bit n times and let the receiver take a majority vote. It is wrong only if more than half the copies flip. With a channel that flips one bit in ten, three copies bring the error down to under three percent, nine copies to under one in a thousand. But the rate, the fraction of the channel carrying real data, falls as one over n. Twenty-five copies bring the error to about one in six million, and then only four percent of the channel carries data. Engineers in the 1940s assumed this was a law: more reliability always costs more rate, without limit. Shannon proved it false, as chapter nine will show. First, though, a picture.
Here is what noise does to a picture, and what codes do about it. A black-and-white image of three thousand eight hundred and forty pixels. Sent as it is through a channel that flips one bit in twenty, it arrives speckled: a hundred and seventy-nine pixels wrong. Sending every pixel three times and voting cuts that to twenty-two, but triples the traffic. Hamming's code, chapter three, gets sixty, while sending less than twice as many bits. Which trade is better depends on the channel; the rest of this part is about doing better than both.
2Hamming distanceDegree2 min
Hamming's first idea was a way to measure how different two words are. The Hamming distance counts the positions where they differ: these two words differ in two places. It behaves like a distance: going from x to z never costs more than going through y. On the binary symmetric channel, every flip makes a received word less likely, so the codeword most likely to have been sent is the one closest to what arrived. Decoding becomes geometry: find the nearest codeword.
Picture all words of three bits as the corners of a cube. Each bit is an axis, and each edge is a single flip. The repetition code uses just two corners, zero zero zero and one one one, three edges apart. Around each codeword draw a ball: the words one flip away. The two balls do not touch, so any single flip is corrected by moving back to the nearer codeword. In four dimensions, take the eight words with an even number of ones, every other corner of the hypercube. Any two are at least two apart. A single flip lands on an odd word, so it is detected, but that word is equally close to several codewords: the error cannot be corrected.
The smallest distance between two codewords decides what a code can do. With distance d, up to d minus one flips can never turn one codeword into another, so they are always detected. And up to half of d minus one can be corrected, because the balls of that radius around codewords do not overlap. You can also trade: correct a few errors and still detect more. Erasures are cheaper than errors. If you know which positions are missing, any d minus one of them can be filled in, because only one codeword agrees with what is left. Chapter seven's QR code will use exactly this.
3Hamming(7,4)Degree3 min
Hamming's construction fits in a picture. Draw three overlapping circles. Put the four data bits, here one zero one one, in the four overlapping regions, and choose a check bit for each circle's private region so that every circle contains an even number of ones. Seven bits are sent for four of data. Now the channel flips one of them. The receiver recounts: circles A and C are odd, B is still even. The flipped bit must lie inside A and C and outside B, and only one region does: it is d two. Every one of the seven positions sits in a different combination of circles, so any single flip is located and corrected, and with no flips, every circle is even.
The same code as a matrix. Write the numbers one to seven in binary as the columns of a three-row matrix H. Codewords are the words that H sends to zero; each row of H is one of the three circles. If the channel flips position j, multiplying by H gives column j: the syndrome spells out the position of the error in binary. Our flipped word gives one zero one: five. The construction works for any number of checks r: two to the r minus one positions, all but r of them data. And the code is perfect: the balls of radius one around the sixteen codewords each hold eight words, and together they cover all a hundred and twenty-eight words of length seven exactly once. No space is wasted.
Hamming's construction gives a whole family. With r checks the block has two to the r minus one bits, and the rate climbs towards one: a hundred and twenty bits of data for seven checks at r equals seven. But every block, however long, still corrects only a single error. So long Hamming codes suit channels where errors are rare and isolated, such as memory. The last row is the one in your server: sixty-four data bits, seven Hamming checks and one overall parity bit, seventy-two bits per memory word.
How much does it help? On a log scale: with no code, the error rate is just p. Three-fold repetition squares it, roughly, at a third of the rate. Hamming's code does almost as well at four sevenths of the rate. At one flip in a hundred, Hamming leaves under nine errors in ten thousand instead of a hundred. The simulated points agree with the exact curves. Hamming codes are still everywhere. Error-correcting memory stores each 64-bit word with eight check bits: a Hamming code plus one overall parity bit. It corrects any single flip and detects any two: part of the defence against cosmic rays, and against the Rowhammer attack of Part 5, though attackers have since found ways to flip several bits at once.
4How good can a code be?Graduate2 min
Every code trades rate for distance. For long codes, plot the rate against the relative distance, the minimum distance divided by the length. The plotted curves describe limiting rates of binary code families, with a correctable error fraction approaching delta over two from below. Some limits are easy. The finite Singleton bound is k plus d at most n plus one; its asymptotic form is rate plus relative distance at most one. Hamming's bound packs disjoint balls. The first linear-programming bound of McEliece, Rodemich, Rumsey and Welch improves Hamming's at larger distances. The limiting rate obeys their minimum. From below, Edgar Gilbert and Rom Varshamov showed that random codes reach one minus the entropy of delta. Between the two lies a gap, and it has been open for nearly seventy years. The blue points are short codes: they can sit above asymptotic curves without contradiction. Nobody knows a family of long binary codes that beats random ones.
A few codes meet Hamming's bound exactly. In 1949 Marcel Golay published a code of length twenty-three carrying twelve bits, generated by this polynomial. We listed all four thousand and ninety-six codewords. The lightest nonzero one has weight seven, so the code corrects any three errors. A ball of radius three holds two thousand and forty-eight words, and four thousand and ninety-six such balls fill all two to the twenty-three words exactly. The code is perfect. Aimo Tietäväinen proved in 1973 that repetition codes, Hamming codes and Golay exhaust the nontrivial perfect binary code parameters. This does not classify every nonlinear code with those parameters. Its extended version carried Voyager's colour images of Jupiter and Saturn. And it builds the Leech lattice, which Henry Cohn and coauthors proved in 2017, building on Maryna Viazovska's method, is the densest way to pack spheres in twenty-four dimensions.
5Finite fieldsGraduate3 min
The codes of the next chapters compute with polynomials, so they need numbers that behave like the rationals but come in a finite supply. That is a field: you can add, subtract, multiply, and divide by anything except zero. The integers modulo a prime form one. In this multiplication table modulo seven, every row contains exactly one 1, so every nonzero number has an inverse. Modulo eight it fails: two times four is zero, and two has no inverse. In any field, a nonzero polynomial of degree d has at most d roots. That one fact carries the Reed-Solomon codes. Évariste Galois found that there is a finite field for every power of a prime, and for no other size.
Computers want a field whose elements are bytes. Two hundred and fifty-six is two to the eighth, so one exists. Read a byte as a polynomial whose coefficients are its bits. Addition is exclusive or. To multiply, multiply the polynomials and take the remainder modulo a fixed polynomial of degree eight that cannot be factored; QR codes use this one. Now take alpha, the byte two, which stands for x, and keep multiplying by it: one, two, four, up to a hundred and twenty-eight, then the reduction kicks in and gives twenty-nine. All two hundred and fifty-five nonzero bytes appear exactly once before the sequence repeats. Alpha generates the whole field. So every nonzero byte is a power of alpha, and multiplication becomes adding exponents: two table lookups and an addition, the way slide rules multiplied with logarithms. And multiplying by alpha itself is a shift and a conditional exclusive or: exactly the linear-feedback shift register of Part 5.
Why that polynomial? There are two hundred and fifty-six polynomials of degree eight over the bits. Thirty of them cannot be factored, and any of those thirty builds a field of two hundred and fifty-six elements; in fact they all build the same field, labelled differently. Sixteen are primitive as well: the powers of x run through every nonzero byte. QR codes use one of those. AES, in Part 29, uses an irreducible polynomial that is not primitive, so its tables are built from the powers of x plus one instead. We checked all of them by brute force; Gauss's counting formula predicts the thirty, and Euler's totient predicts the sixteen.
6Reed–SolomonGraduate3 min
In 1960 Irving Reed and Gustave Solomon turned the root-counting fact into a code. Read the message, here three numbers, as the coefficients of a polynomial. The codeword is the list of its values at nine points. Three numbers in, nine out. Two different quadratics can agree at no more than two points, since their difference has at most two roots. So any two codewords differ in at least seven of the nine places. In general the distance is n minus k plus one: exactly the Singleton bound of chapter four. No code of this length and rate can do better. The arithmetic is really modulo a prime, one thousand and nine, but every value here is smaller, so you can picture it as an ordinary parabola.
Now damage the codeword. Three of the nine values arrive wrong, and the receiver does not know which. Lloyd Welch and Elwyn Berlekamp's method introduces an unknown error-locator polynomial E, which is zero exactly at the bad points. Then y times E equals f times E at every point, good or bad, and with Q standing for f times E, that is a system of linear equations. Solving it and dividing Q by E gives back the message, five, three, two, and the roots of E are exactly the three corrupted positions. The red points snap back onto the curve. With nine values and three unknowns, up to three errors can be fixed: half the redundancy. Erasures are even easier: lose any six values, and the three that remain determine the parabola by Lagrange interpolation. Real decoders use the faster Berlekamp-Massey algorithm, with Chien's search and Forney's formula; our QR decoder does.
Erasures are easier still. Suppose six of the nine values are lost, and the receiver knows which six. Only one quadratic passes through the three that remain, and Lagrange's formula writes it down directly: a sum over the surviving points, each multiplied by a polynomial that is one at its own point and zero at the others. Computed modulo a thousand and nine, it gives back five, three, two: the message, and with it every lost value. So a Reed-Solomon code repairs as many erasures as it has check symbols, twice as many as unknown errors. Chapters seven and thirteen use exactly this.
Reed-Solomon codes are everywhere. Compact discs use two interleaved ones, and survive scratches thousands of bits long. Deep-space missions since Voyager pair one with a convolutional code, chapter ten's. QR codes use them, as do RAID-6 arrays and the storage systems of chapter thirteen, and modems, digital television and solid-state drives. The reason is that their symbols are bytes: a burst of bad bits corrupts only a few symbols. And they use erasures well: a dead disk or an unreadable spot is known to be bad, and each such erasure costs only one check symbol instead of two.
7Our QR codeIndustry3 min
Masahiro Hara's team at Denso Wave designed the QR code in 1994 to track car parts. Ours is version two: twenty-five by twenty-five modules. Three finder squares let a camera find the code and its orientation. Timing stripes and an alignment square recover the grid even on a curved surface. Fifteen format bits record the error-correction level and the mask, stored twice and protected by a small code of their own. Everything else is data: forty-four bytes laid out in zigzags two columns wide, then XOR-ed with one of eight masks, chosen to avoid large blocks and patterns that look like finders. We chose level Q: twenty-two bytes of message and twenty-two Reed-Solomon check bytes, enough to repair any eleven wrong bytes, or twenty-two missing ones whose places are known. Our encoder produces exactly the same modules as a standard library for every mask, so your phone can read it.
Here is where each of the forty-four bytes lives. Each one owns a patch of eight modules, two wide, snaking up and down the code from the bottom right. The first twenty-two hold the message: a mode marker, the length, the text and padding. The last twenty-two are the Reed-Solomon checks, in the generator form used in practice: the message polynomial is shifted up and divided by a polynomial with roots at the first twenty-two powers of alpha, and the remainder is appended. So the whole codeword vanishes at those twenty-two points. The decoder evaluates it there: the twenty-two syndromes are all zero when nothing is wrong, and otherwise they encode where and how the bytes were damaged.
Here is the decoder working on the small scratch, step by step. It evaluates the forty-four bytes it read, as a polynomial, at the twenty-two powers of alpha. A clean code gives all zeros; these are not. The Berlekamp-Massey algorithm turns the syndromes into an error-locator polynomial, here of degree eight: the decoder now believes eight bytes are wrong. Chien's search tries every position and finds the eight roots, which are exactly the eight bytes the paint changed. Forney's formula gives the error value at each, and exclusive-or removes it. All forty-four bytes are back.
Now we damage it, three ways. A small scratch whitens fifty-six modules. Eight bytes come out wrong. That is within the eleven errors the code can find on its own, and the text comes back. A longer blot ruins fifteen bytes. As unknown errors that is too many: the decoder's locator polynomial has no consistent roots, and it gives up rather than guess. But a scanner can see where the damage is. Told which eighteen bytes the blot touched, the decoder treats them as erasures, and twenty-two erasures are allowed. The text comes back. Paint a whole stripe and twenty-four bytes are touched: more than the twenty-two check bytes can cover either way. Nothing helps, and the decoder correctly reports failure.
8Cyclic codes and CRCsIndustry3 min
Most of the time a network only needs to notice damage, and ask again. The cyclic redundancy check treats bits as the coefficients of a polynomial whose coefficients are zero or one. Append a few zeros to the message and divide by a fixed generator polynomial, here x cubed plus x plus one. Long division over this field is just exclusive or, with no borrows. Send the message followed by the remainder. Now the whole word is divisible by the generator. The receiver divides again; a nonzero remainder means something changed. In hardware this is a shift register with exclusive-or taps where the generator has ones, the linear-feedback shift register of Part 5, consuming a bit per clock. The thirty-two-bit version guards every Ethernet frame, zip file and PNG image. Ours agrees with zlib's on every test string.
In hardware the division is a shift register. Three flip-flops hold the running remainder, and exclusive-or gates sit where the generator has a one. The bit leaving the top is fed back into those gates. Clock in the message one bit at a time. After the last bit the register holds the remainder, one zero zero, the same as the long division on paper. Real network chips unroll the same algebra to process dozens or hundreds of bits per clock.
What does a CRC catch? The received word differs from the sent one by an error polynomial, and the damage goes unnoticed only if the generator divides it. A burst, a run of errors no longer than the number of check bits, is a power of x times a polynomial of smaller degree, and the generator can never divide that. Our eight-bit CRC caught every burst we tried of length up to eight, thirty thousand of each length. Bursts of length nine slip through about one time in a hundred and twenty-eight, and random garbage one time in two hundred and fifty-six, exactly as the algebra predicts. The thirty-two-bit CRC of Ethernet catches every burst up to thirty-two bits and misses random damage once in four billion. But it is not a cryptographic hash: anyone can change a message and fix up the CRC. Part 29 builds hashes that resist that.
9Shannon's theoremGraduate3 min
In 1948, two years before Hamming's paper, Claude Shannon had already settled the big question. Every channel has a capacity. Below it, at any rate, there are codes whose error probability can be made as small as you like by making them long enough. Above it, no code works. So noise does not force the rate towards zero, as chapter one's repetition suggested: it costs a fixed fraction. For the binary symmetric channel the capacity is one minus the entropy of p. At one flip in ten, fifty-three percent of the channel can still carry data with arbitrarily few errors. The entropy is Part 21's measure of uncertainty: the channel spends that many bits per bit on the noise. Compare repetition, which needed to drop to four percent of the channel to reach one error in six million.
We can watch the theorem start to work. Take random linear codes of rate one half, and decode them perfectly, with a table of the most likely error for every syndrome. On a channel with five percent flips, whose capacity is point seven one, the block error falls as the codes get longer: from eleven percent at length eight to five percent at twenty-eight. At fifteen percent flips the capacity is below one half, and the error rises instead. Right at capacity it hardly moves. These lengths are tiny, so the trend is gentle, but its direction is Shannon's theorem. And here is the catch that took fifty years: decoding a random code needs a table with two to the n minus k entries. Shannon proved good codes exist. Finding ones that can be decoded fast was the rest of the story.
Shannon's argument is a counting argument. Send n bits; about p n of them flip, so what arrives lies close to a sphere of radius p n around what was sent. That sphere holds about two to the n H of p words, the typical errors of AI, Built's first part. Now choose two to the n R codewords completely at random, and decode to the codeword whose sphere contains what arrived. The chance that some other codeword also lands in that sphere is about two to the minus n times C minus R. When the rate is below capacity, that vanishes, on average over random codes, so at least one code is that good. The converse uses Fano's inequality: no code can push more than the capacity through. The proof constructs nothing. The practical codes that reach capacity, in the next three chapters, took another forty-five years.
10Convolutional codes and ViterbiGraduate2 min
Hamming and Reed-Solomon codes work on fixed blocks. Peter Elias's convolutional codes of 1955 work on streams. Each input bit is shifted into a small register, and two parity bits of the register come out: rate one half. This message, one zero one one zero zero, produces these pairs. The register has four states, and drawing them over time gives a trellis: every possible message is a path through it. Decoding means finding the path whose outputs are closest to what arrived. Andrew Viterbi saw in 1967 that at each step you need to keep only the best path into each state; any path through a state that loses there can never win later. It is dynamic programming, Part 19's idea: eight comparisons per bit, however long the message.
We sent twenty thousand random bits through the code at each noise level. With two percent of the channel bits flipped, Viterbi's decoder leaves about six and a half errors per ten thousand data bits, instead of two hundred. At half a percent, none at all. Real systems use registers with sixty-four states, and soft decisions: the receiver passes on how confident it is in each bit, not just a zero or a one. David Forney showed in 1966 how to combine codes: an inner convolutional code, and an outer Reed-Solomon code to clean up the short bursts of errors a Viterbi decoder leaves behind. That pairing flew on Voyager, and convolutional codes ran GSM, early Wi-Fi and 4G's control channel.
11LDPC codes and belief propagationGraduate4 min
In his 1960 thesis Robert Gallager proposed codes defined by sparse parity checks: each bit takes part in only three checks, and each check involves only six bits. Draw the bits on one side and the checks on the other, joined where a bit is in a check, as Michael Tanner did in 1981. Decoding passes messages along these edges. Each bit tells its checks how likely it is to be a one, from the channel and from the other checks. Each check replies with what the bit must be, judging from the other bits it sees. Repeat until every check is satisfied. This is belief propagation, the message passing of AI, Built's seventh part, and on a sparse graph each round costs time proportional to the length.
Here is the decoder at work on one block of our code. At seven percent noise, three hundred and forty-two bits arrive flipped. Round by round, the beliefs sharpen and the errors melt away: none are left after fourteen rounds. At nine percent, four hundred and thirty-two bits are flipped, and the decoder gets stuck at around three hundred, no matter how long it runs. But it knows: some parity checks are still unsatisfied, so a failed block is reported, not silently passed on.
We built a design-rate-one-half code of length four thousand eight hundred, using bounded swaps to remove four-cycles, and decoded a hundred noisy blocks at each noise level. The decoder stops when all parity checks pass or its iteration budget runs out; a wrong codeword still counts as a failure. At the lower sampled noise levels all hundred blocks came back perfectly. At higher noise levels almost none do: the waterfall. Tom Richardson and Rüdiger Urbanke's density evolution predicts where the cliff falls for very long codes of this kind: about eight point four percent. Shannon's limit for this rate is eleven. On the erasure channel the prediction is a one-line recursion, and numerical iteration gives about point four two nine four, against a capacity of one half. Giving different bits different numbers of checks closes most of the remaining gap. In 2001 Sae-Young Chung, Forney, Richardson and Urbanke designed such a code within four thousandths of a decibel of the Shannon limit.
The history is strange. Gallager's codes needed more computation than the hardware of the 1960s could give, and they were forgotten for thirty years. In 1993 Claude Berrou, Alain Glavieux and Punya Thitimajshima presented turbo codes: two convolutional codes, one fed a shuffled copy of the data, decoded by trading beliefs back and forth. They claimed performance within a fraction of a decibel of Shannon's limit, and many listeners assumed a mistake. There was none, and the decoder turned out to be belief propagation. In 1996 David MacKay and Radford Neal rediscovered Gallager's codes and found them just as good. Today LDPC codes run Wi-Fi, satellite television, ten-gigabit Ethernet, 5G data channels and the flash in solid-state drives. Turbo codes carried 3G and 4G, and spacecraft data since 2000.
12Polar codesGraduate3 min
Here is Arıkan's construction for eight bits. Three stages of the same step: exclusive-or the lower wire into the upper one, first across halves, then quarters, then neighbours. Decoding takes the inputs in order, each using the ones before it, so each input sees a channel of its own. Start from an erasure channel that loses half its bits, and those eight channels already differ wildly: the first is almost always erased, the last almost never. So put the data on the four best channels and freeze the other four to zero, known to both sides.
In 2009 Erdal Arıkan found a code that provably reaches capacity, with a decoder as cheap as sorting. Start with a channel that erases each bit half the time. Take two uses of it and send u one exclusive-or u two, and u two. Decode u one first: it needs both outputs, so it sees a worse channel, erased with probability two epsilon minus epsilon squared. Then decode u two, already knowing u one: it gets two chances, so it sees a better channel, epsilon squared. Do it again and again. With each doubling the channels spread apart: here are the erasure probabilities of all of them, up to sixty-four. At a thousand and twenty-four channels, a third are already nearly perfect and a third nearly useless, and the middle keeps shrinking. The total capacity never changes, so the fraction that becomes perfect tends to exactly the capacity. Send data on the good ones, and freeze the bad ones to zero.
Decoding follows the construction. Decode the bits one at a time, each using the decisions already made, in time N log N. We sent rate-one-half polar codes over the binary symmetric channel, using a BEC-based reliability ordering and a min-sum approximation to successive cancellation. Well below capacity, the longer code makes fewer mistakes; as the channel approaches capacity, both collapse. At practical lengths, plain successive cancellation is not the best decoder. Ido Tal and Alexander Vardy keep a short list of candidate paths and use a CRC, chapter eight's, to pick the right one. In 2016 the standards body for 5G chose polar codes for the control channels and LDPC codes for data: ten years from Arıkan's paper to billions of phones.
13Codes for storageIndustry2 min
Storage is the erasure channel: a dead disk is known to be dead. RAID-5 adds one disk holding the exclusive or of all the others, byte by byte, and so can rebuild any one that fails. RAID-6 adds a second check disk, a weighted sum in the field of chapter five, with a different power of g for each disk. If two disks die, each byte position gives two equations in two unknowns, and the field lets us solve them. We rebuilt both lost disks exactly. This is a Reed-Solomon code with two check symbols, read across the disks; Linux implements it this way, following Peter Anvin.
At data-centre scale, machines fail every day. The simple defence is three copies of everything, which triples the disks. A Reed-Solomon code that splits each block into ten pieces and adds four checks survives any four losses using only one point four times the space. Facebook's f4 warm storage and Hadoop's file system use exactly this. The price is repair: rebuilding one lost piece means reading ten others over the network. Microsoft's Azure storage adds a little more parity, one per local group of six, so the common single repair reads only six pieces. How little you must read to repair, for a given amount of storage, became a research field of its own.
One more storage and broadcast trick. Michael Luby's LT codes, from 2002, make each output block the exclusive or of a random handful of source blocks. The sender can produce outputs forever, like a fountain, and a receiver just collects enough of them, from any source, in any order, whichever ones arrive. Decoding peels: any output with a single unknown source reveals it, which is substituted everywhere, and the process repeats. With Luby's robust soliton distribution of degrees, we needed about thirty percent extra blocks for a hundred source blocks, eighteen percent for a thousand, and nine percent for ten thousand. Amin Shokrollahi's Raptor codes add a precode and bring the overhead to a few percent; they carry broadcast video and multimedia in mobile networks.
14Frontier: capacity and localityResearch3 min
Some of the newest results are about the oldest codes. Reed-Muller codes, from 1954, evaluate low-degree polynomials in many variables. Do they reach Shannon's capacity? On erasure channels, Shrinivas Kudekar and coauthors proved yes in 2016, using only the codes' symmetry. For every binary symmetric channel, Emmanuel Abbe and Colin Sandon proved it in 2023, nearly seventy years after the codes were invented. Another idea: when there are too many errors to decode uniquely, return a short list of candidates. Madhu Sudan showed in 1997 that Reed-Solomon codes can be list-decoded well past half their distance. And Venkatesan Guruswami and Atri Rudra found folded Reed-Solomon codes that correct a fraction of errors approaching one minus the rate: the best possible.
Sometimes you need one bit of a huge encoded file, not all of it. The Hadamard code stores every parity of the message. To learn bit i, read the codeword at a random position a and at a with bit i flipped; their exclusive or is the bit. Each of the two reads lands on a uniformly random position, so if a fraction delta is corrupted, the answer is right with probability at least one minus two delta. Our measurements sit just above that line, and a majority over fifteen pairs is nearly always right. This is a locally decodable code, the cousin of Part 27's linearity test. The price is length: two to the k positions for k bits. Binary two-query codes require exponential length for constant noise and success guarantees. For three queries, the optimal length is still open, with large gaps between the bounds.
Two linked breakthroughs came in 2021. A locally testable code lets you check, by reading a few random symbols, whether a word is a codeword or far from every codeword. For decades nobody knew whether such codes could also have constant rate and constant relative distance, the c-cubed codes. Irit Dinur, Shai Evra, Ron Livne, Alexander Lubotzky and Shahar Mozes built them, and so, independently, did Pavel Panteleev and Gleb Kalachev, using high-dimensional expanders. Panteleev and Kalachev's construction also gave the first good quantum LDPC codes, answering a twenty-year-old question. Quantum computers cannot work at all without error correction, as Part 53 shows. And locally testable codes are what the PCP theorems of Part 27 are made of.
Six open problems. Whether any long binary codes beat the random ones of Gilbert and Varshamov. Where, between that bound and the linear-programming bound, the truth lies. Whether any explicit construction even matches random codes. How short a locally decodable code that reads three symbols can be. How close to capacity fast decoders can get at short lengths, which matter for control messages and the internet of things. And whether Reed-Muller codes reach capacity with an efficient decoder, not just in principle. This part's research problem takes a small, computable case of the fifth.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. The noisy channel and the repetition code. Hamming distance, and Hamming's code, whose syndrome names the bad bit. The bounds on how good any code can be, and the perfect Golay code, enumerated. The field of bytes, Reed-Solomon codes decoded by Berlekamp and Welch, and our own QR code, scratched three ways. CRCs from Part 5's shift registers. Shannon's theorem, watched in random codes. And the codes that reach his limit: Viterbi's trellis, an LDPC waterfall, and polarization.
Where this comes back. Part 29 builds AES, whose S-box is inversion in the field of bytes. Part 30's secret sharing splits a key with exactly a Reed-Solomon code. Part 34 puts RAID and checksums into file systems, Part 36 puts a CRC on every Ethernet frame, and Part 45 computes how long erasure-coded cloud storage survives. And Part 53 needs codes to make quantum computers work at all.
In practice. Detect errors everywhere, with a CRC or checksum, and retry when it fails. Correct them where retrying is impossible or too slow: memory, deep space, broadcast. Prefer erasures: if you know what is missing, a code repairs twice as much. Choose replication when repairs must be fast, and erasure codes when storage costs dominate. And use a tested library: the arithmetic is easy to get subtly wrong, which is why we checked ours against zlib and a QR library.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: a smaller QR code, made with this part's functions and read by your phone. The last, marked with a star, is a research problem: its answer is not known, and the notes say where to start.
Next time: secrets. Codes in this part fought random noise. Part 29 faces an adversary. From frequency analysis and the Enigma to Shannon's perfect secrecy, and then AES, built from scratch on the same field of bytes, with the modes, hashes and message authentication codes that make it safe to use. Part 29, Secrets.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 29 builds AES, whose S-box is inversion in the field of bytes, and Part 30's secret sharing is a Reed-Solomon code. Part 34 puts RAID and checksums into file systems, Part 36 a CRC on every Ethernet frame, Part 45 computes how long erasure-coded storage survives, and Part 53 needs codes to make quantum computers work.
Key results
The part's results in one place, for revision.
Try it
Lab 28 · Hamming(7,4) against its exact curve, and Reed-Solomon's 2e + f rule
Send random 4-bit words through a binary symmetric channel with Hamming(7,4) and compare the decoded bit-error rate with the exact value from all 128 error patterns; then damage RS(30,20) codewords over GF(256) with e errors and f erasures and check that the decoder always recovers them when 2e + f <= 10 and almost never beyond.
python -m videos.cs.labs 28
needs numpy, scipy, matplotlib · download lab28.py ·
source on GitHubHamming(7,4), single errors all 16 x 7 corrected; the syndrome is the flipped position
bit error after decoding, p = 0.01 simulated 0.00081 exact 0.00087 no code 0.01 3 copies 0.00030
bit error after decoding, p = 0.05 simulated 0.01883 exact 0.01943 no code 0.05 3 copies 0.00725
bit error after decoding, p = 0.1 simulated 0.06657 exact 0.06688 no code 0.1 3 copies 0.02800
RS(30,20) over GF(256) rate 0.67, distance 11
damage with 2e + f <= 10 recovered in 180 of 180 trials
damage with 2e + f > 10 recovered in 0 of 340 trials (only by a lucky guess)
An error costs two check symbols (find it, then fix it) and an erasure one, so n - k = 10 checks buy any mix with 2e + f <= 10; one step past the edge the decoder fails or returns another codeword.
The code (117 lines; it asserts its own result)
"""Lab 28: measure Hamming(7,4) on a noisy channel, and find the exact edge of what Reed-Solomon can repair."""
from videos.coursekit import labs
import random
import numpy as np
from explainer.cs.algo import codes as C
TITLE = "Hamming(7,4) against its exact curve, and Reed-Solomon's 2e + f rule"
GOAL = ("Send random 4-bit words through a binary symmetric channel with Hamming(7,4) and compare the decoded bit-error "
"rate with the exact value from all 128 error patterns; then damage RS(30,20) codewords over GF(256) with e "
"errors and f erasures and check that the decoder always recovers them when 2e + f <= 10 and almost never beyond.")
TASKS = [
"Add the overall parity bit (C.secded_decode) and count how many double errors are detected instead of miscorrected.",
"Change NSYM from 10 to 16 with K fixed. Where does the boundary of the green region move, and what is the new rate?",
"At p = 0.2 compare Hamming(7,4) with no code at all. Which is better, and what does the capacity 1 - H(0.2) say is possible?",
]
K, NSYM = 20, 10
WORDS = 25_000
def hamming_bit_error(p):
"""Exact: by linearity, decode each of the 128 error patterns alone and count the data bits it leaves wrong."""
total = 0.0
for e in range(128):
pattern = [(e >> i) & 1 for i in range(7)]
w = sum(pattern)
total += p ** w * (1 - p) ** (7 - w) * sum(C.hamming74_decode(pattern)[0]) / 4
return total
def run(seed=0):
rng = random.Random(int(np.random.default_rng(seed).integers(2 ** 31)))
lab = labs.Lab()
# 1. Hamming(7,4): every single error is corrected, and the syndrome is its position
for d in range(16):
data = [(d >> i) & 1 for i in range(4)]
word = C.hamming74_encode(data)
assert C.hamming74_syndrome(word) == 0
for pos in range(7):
bad = list(word)
bad[pos] ^= 1
fixed, s = C.hamming74_decode(bad)
assert fixed == data and s == pos + 1
lab.row("Hamming(7,4), single errors", "all 16 x 7 corrected; the syndrome is the flipped position")
sim, exact = {}, {}
for p in (0.01, 0.05, 0.1):
errs = 0
for _ in range(WORDS):
d = [rng.randrange(2) for _ in range(4)]
dec, _ = C.hamming74_decode(C.bsc(C.hamming74_encode(d), p, rng))
errs += sum(a != b for a, b in zip(d, dec))
sim[p], exact[p] = errs / (4 * WORDS), hamming_bit_error(p)
lab.row(f"bit error after decoding, p = {p}", f"simulated {sim[p]:.5f} exact {exact[p]:.5f} "
f"no code {p} 3 copies {C.repetition_error(3, p):.5f}")
assert abs(exact[0.01] - 8.7e-4) < 2e-5, "the film's value at p = 0.01"
assert 0.5 < sim[0.01] / exact[0.01] < 1.6 and abs(sim[0.05] / exact[0.05] - 1) < 0.15
assert abs(sim[0.1] / exact[0.1] - 1) < 0.1 and exact[0.1] < 0.1, "simulation matches the exact curve"
# 2. Reed-Solomon over GF(256): e errors (positions unknown) and f erasures (positions known)
E, F, trials = 8, 13, 5
grid, lucky = np.zeros((E, F)), 0
for e in range(E):
for f in range(F):
good = 0
for _ in range(trials):
msg = [rng.randrange(256) for _ in range(K)]
cw = C.rs_encode(msg, NSYM)
pos = rng.sample(range(K + NSYM), e + f)
rx = list(cw)
for q in pos[:e]:
rx[q] ^= rng.randrange(1, 256)
for q in pos[e:]:
rx[q] = rng.randrange(256)
try:
out, _ = C.rs_decode(rx, NSYM, pos[e:])
good += out == cw
except ValueError:
pass
grid[e, f] = good / trials
if 2 * e + f <= NSYM:
assert good == trials, (e, f, good)
else:
lucky += good
inside = sum(1 for e in range(E) for f in range(F) if 2 * e + f <= NSYM)
outside = (E * F - inside) * trials
assert lucky <= 0.03 * outside, "past the bound the decoder is right only by luck"
lab.row(f"RS({K + NSYM},{K}) over GF(256)", f"rate {K / (K + NSYM):.2f}, distance {NSYM + 1}")
lab.row("damage with 2e + f <= 10", f"recovered in {inside * trials} of {inside * trials} trials")
lab.row("damage with 2e + f > 10", f"recovered in {lucky} of {outside} trials (only by a lucky guess)")
lab.note = ("An error costs two check symbols (find it, then fix it) and an erasure one, so n - k = 10 checks buy "
"any mix with 2e + f <= 10; one step past the edge the decoder fails or returns another codeword.")
fig, ax = labs.figure(2, size=(11, 4.3))
ps = np.geomspace(0.003, 0.25, 60)
ax[0].loglog(ps, ps, color=labs.MUTED, ls="--", label="no code (rate 1)")
ax[0].loglog(ps, [C.repetition_error(3, p) for p in ps], color=labs.GREEN, label="3 copies (rate 1/3)")
ax[0].loglog(ps, [hamming_bit_error(p) for p in ps], color=labs.GOLD, label="Hamming(7,4), exact (rate 4/7)")
ax[0].loglog(list(sim), list(sim.values()), "o", color=labs.BLUE, label=f"Hamming(7,4), {WORDS:,} simulated words")
ax[0].set(title="Bit error after decoding on a binary symmetric channel", xlabel="channel flip probability p",
ylabel="decoded bit-error rate")
ax[0].legend()
from matplotlib.colors import ListedColormap
ax[1].imshow(grid, origin="lower", aspect="auto", cmap=ListedColormap([labs.RED, labs.GREEN]), vmin=0.25, vmax=0.75,
extent=(-0.5, F - 0.5, -0.5, E - 0.5), alpha=0.75)
ax[1].grid(False)
f = np.linspace(-0.5, 11.5, 50)
ax[1].plot(f, (NSYM + 0.5 - f) / 2, color=labs.INK, ls="--", label="2e + f ≤ 10 below this line")
ax[1].set(title="RS(30,20): green recovered, red lost", xlabel="erasures f (positions known)",
ylabel="errors e (positions unknown)", xlim=(-0.5, F - 0.5), ylim=(-0.5, E - 0.5))
ax[1].legend(loc="upper right")
lab.fig = fig
return lab
Now change it
- Add the overall parity bit (C.secded_decode) and count how many double errors are detected instead of miscorrected.
- Change NSYM from 10 to 16 with K fixed. Where does the boundary of the green region move, and what is the new rate?
- At p = 0.2 compare Hamming(7,4) with no code at all. Which is better, and what does the capacity 1 - H(0.2) say is possible?
Problems, with solutions
Try each problem before opening its solution.
-
Distance. Prove that a code with minimum distance d detects d − 1 errors and corrects ⌊(d − 1)/2⌋, and that no code can do better.
Solution
If at most d − 1 bits flip, the received word is within distance d − 1 of the codeword sent. It is therefore not another codeword, which would be at distance ≥ d, so the change is detected. Let t = ⌊(d − 1)/2⌋. If at most t bits flip, the received word y satisfies d(c, y) ≤ t. For any other codeword c′, the triangle inequality gives d(c′, y) ≥ d(c, c′) − d(c, y) ≥ d − t > t. So c is the unique nearest codeword.
Optimality: take two codewords c, c′ at distance exactly d. Flipping d bits turns c into c′, which no decoder can detect. For correction, flip ⌈d/2⌉ of the positions where they differ, starting from c. The result is at distance ⌈d/2⌉ ≤ ⌊d/2⌋ + 1 from c, and ⌊d/2⌋ from c′. So when ⌈d/2⌉ = t + 1, nearest-codeword decoding picks c′ or ties. Since maximum likelihood on the BSC is nearest-codeword decoding, no decoder corrects all patterns of t + 1 errors.
-
Reed–Solomon is MDS. Show that with n distinct evaluation points and messages of degree < k, the distance is exactly n − k + 1.
Solution
The code is linear, so its distance is the minimum weight of a nonzero codeword. A nonzero polynomial of degree < k has at most k − 1 roots, so its n values contain at most k − 1 zeros: the weight is at least n − k + 1. The polynomial (x − x₁)(x − x₂)⋯(x − x_{k−1}) has degree k − 1 and exactly k − 1 zeros among the points, so the weight n − k + 1 is attained. The Singleton bound says d ≤ n − k + 1 for every code, so RS codes meet it.
-
CRC guarantees. Prove that a CRC with generator g(x), g(0) = 1, deg g = r, detects every burst of length ≤ r, and every odd number of errors if (x + 1) divides g(x).
Solution
An error goes undetected exactly when g(x) divides the error polynomial e(x). A burst of length ℓ ≤ r is e(x) = xⁱ b(x), with deg b = ℓ − 1 < r and b(0) = 1. Because g(0) = 1, g shares no factor with xⁱ. So g | xⁱ b would force g | b, impossible since deg b < deg g and b ≠ 0. For odd weight: if (x + 1) | g and g | e, then e(1) = 0 over GF(2). But e(1) is the parity of the number of error bits, which is 1 for an odd count. Chapter 8 measured both properties for CRC-8 (whose generator x⁸ + x² + x + 1 = (x + 1)(x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + 1) contains x + 1).
-
Density evolution. Derive x ↦ ε(1 − (1 − x)⁵)² for the (3,6) code on BEC(ε), and find its threshold.
Solution
Let x be the probability that a message from a bit to a check is "erased" (unknown), on a tree-like neighbourhood. A check can tell a bit its value only if all 5 of its other bits are known, which happens with probability (1 − x)⁵; so a check-to-bit message is erased with probability 1 − (1 − x)⁵. A bit stays erased if its channel value was erased (probability ε) and both of its other 2 checks are erased: x′ = ε(1 − (1 − x)⁵)². Decoding succeeds on long codes exactly when the iteration from x = ε goes to 0, that is, when x > ε(1 − (1 − x)⁵)² for all x in (0, ε]. Bisection,
codes.de_bec_threshold(3, 6), gives ε* ≈ 0.4294, against capacity's 0.5. The gap is the price of the regular (3,6) degree profile. -
Build: a version-1 QR code. Encode a version-1 code (21 × 21) with this part's functions and check it against a phone.
Solution
Version 1 drops the alignment pattern, and its dark module sits at (8, 13). Byte-mode capacities are 17, 14, 11 and 7 characters for L, M, Q and H. The data codewords are 19, 16, 13 and 9, the check bytes 7, 10, 13 and 17, in a single block. Changes to
codes.py:- parametrize
QR_SIZEto 21; - drop the alignment loop in
_qr_function_map; - set the codeword counts;
- keep everything else.
The format bits, mask patterns, zigzag placement and
rs_encodeare unchanged. Check the result againstqrcode.QRCode(version=1, …)with the same mask, as we did for version 2. Then display it with a quiet zone of four modules and scan it. - parametrize
-
★ Research: short codes. For block lengths 64 to 256 at rate ½ on the BSC, compare polar SC-list decoding, LDPC codes with BP, and the finite-length bound of Polyanskiy, Poor and Verdú.
Where to start. Shannon's theorem is asymptotic. For short blocks, Polyanskiy, Poor and Verdú (2010) give the normal approximation log₂ M ≈ nC − √(nV) Q⁻¹(ε) + ½ log₂ n, where V is the channel dispersion. Coşkun et al. (2019) survey how today's codes compare with it at short lengths. Extend
codes.polar_scto a list decoder (keep the L best paths, CRC-aided; Tal and Vardy 2015), build short LDPC codes with progressive edge growth (Hu, Eleftheriou and Arnold 2005), and plot block error against p for each. Then ask how far each is from the bound at n = 128, and whether the gap shrinks as the list size grows. Nobody knows a practical decoder that reaches the bound at these lengths.
Notes and sources
Glossary
信道 channel · 二元对称信道 binary symmetric channel (BSC) · 擦除信道 erasure channel · 码率 rate · 重复码 repetition code · 汉明距离 Hamming distance · 最小距离 minimum distance · 汉明码 Hamming code · 校验矩阵 parity-check matrix · 伴随式 syndrome · 完美码 perfect code · SECDED 单纠错双检错 · Golay 码 Golay code · Singleton 界 Singleton bound · Gilbert–Varshamov 界 · 线性规划界 linear-programming bound · 有限域 finite field · 不可约多项式 irreducible polynomial · 本原多项式 primitive polynomial · Reed–Solomon 码 · 最大距离可分 MDS · 拉格朗日插值 Lagrange interpolation · 错误定位多项式 error-locator polynomial · 擦除 erasure · 二维码 QR code · 循环冗余校验 CRC · 突发错误 burst error · 信道容量 channel capacity · 卷积码 convolutional code · 网格图 trellis · Viterbi 算法 · 级联码 concatenated code · LDPC 码 low-density parity-check code · Tanner 图 · 置信传播 belief propagation · 密度演化 density evolution · Turbo 码 · 极化码 polar code · 逐次消除 successive cancellation · 喷泉码 fountain code · 纠删码 erasure code · 局部重构码 local reconstruction code · 局部可解码码 locally decodable code · 列表解码 list decoding · 局部可测试码 locally testable code
Sources
Canon. Books:
- MacKay, Information Theory, Inference, and Learning Algorithms (2003);
- Cover & Thomas, Elements of Information Theory (2nd ed., 2006), ch. 7;
- Guruswami, Rudra & Sudan, Essential Coding Theory (draft, 2023);
- MacWilliams & Sloane, The Theory of Error-Correcting Codes (1977);
- Roth, Introduction to Coding Theory (2006);
- Richardson & Urbanke, Modern Coding Theory (2008);
- Lin & Costello, Error Control Coding (2nd ed., 2004).
Papers:
- Foundations: Shannon (1948); Hamming (1950); Golay (1949); Gilbert (1952); Varshamov (1957); McEliece, Rodemich, Rumsey & Welch (1977); Tietäväinen (1973).
- Algebraic codes: Reed & Solomon (1960); Berlekamp (1968); Massey (1969); Welch & Berlekamp (1986); Chien (1964); Forney (1965, 1966); Peterson & Brown (1961); ISO/IEC 18004 (QR code).
- Probabilistic codes: Elias (1955); Viterbi (1967); Gallager (1962); Tanner (1981); Berrou, Glavieux & Thitimajshima (1993); MacKay & Neal (1996); Richardson & Urbanke (2001); Chung, Forney, Richardson & Urbanke (2001); Arıkan (2009); Tal & Vardy (2015).
- Storage: Patterson, Gibson & Katz (1988); Anvin, "The mathematics of RAID-6"; Luby (2002); Shokrollahi (2006); Huang et al. (2012); Muralidhar et al., "f4" (2014); Dimakis et al. (2010).
- Frontier: Kudekar et al. (2017); Abbe & Sandon (2023); Sudan (1997); Guruswami & Sudan (1999); Guruswami & Rudra (2008); Dinur, Evra, Livne, Lubotzky & Mozes (2022); Panteleev & Kalachev (2022); Polyanskiy, Poor & Verdú (2010); Coşkun et al. (2019).
About this partfrom its README
Part 28 of a sixty-one-part course in computer science (see the series plan and the syllabus), the fourth part of Act V, Limits and Secrets. In 1947 Hamming's weekend jobs kept dying on bad bits, so he taught the machine to fix them. Two years before Hamming published, Shannon had proved that noise costs only a fixed fraction of a channel's rate. It took fifty years to build codes that reach his limit. This part builds the codes from Hamming's to polar codes, runs every one of them, and scratches a QR code and reads it back.
The instrument is codes.py. It holds:
- the binary symmetric channel, entropy and capacity;
- repetition codes; Hamming(7,4), general Hamming codes and SECDED;
- linear codes by enumeration; the [23,12,7] Golay code; the asymptotic bounds (Singleton, Hamming, Plotkin, MRRW, GV);
- GF(256) with exp/log tables (checked against carry-less multiplication); polynomials over it; irreducible and primitive polynomials by brute force;
- Reed–Solomon codes two ways:
- the evaluation view over GF(p), with Lagrange interpolation for erasures and Berlekamp–Welch for errors;
- the generator view over GF(256), with Berlekamp–Massey, Chien search and Forney's formula, errors and erasures together;
- a version-2 QR encoder (byte mode, all four error levels, mask selection by the standard's penalty rules) and a decoder that reads a damaged module matrix, with or without erasure information;
- CRCs as polynomial division; CRC-8 and CRC-32;
- random linear codes with maximum-likelihood syndrome decoding; the (7,5) convolutional code with Viterbi decoding;
- regular LDPC codes (Gallager's construction, with 4-cycles removed) under sum-product belief propagation, and BEC density evolution;
- polar codes: the transform, Bhattacharyya parameters and successive cancellation;
- LT fountain codes with the robust soliton and a peeling decoder; RAID-6 P+Q; the Hadamard code's two-query local decoder.
The rate–distance curves describe asymptotic binary code families; the short Hamming and Golay points can lie above
them. Finite codes obey finite-length bounds, including k + d ≤ n + 1. The perfect-code theorem restricts nontrivial
binary parameters, rather than identifying every nonlinear code with those parameters.
LDPC experiments stop when the receiver's parity checks pass, including when they pass for an incorrect codeword; the sent word is used only to score the result. The (3,6) construction has design rate 1/2, and bounded swaps attempt to remove four-cycles. Density-evolution thresholds are asymptotic numerical references. The polar experiment uses a BEC-based frozen-set ordering and min-sum SC on the BSC; its finite results are not a capacity proof. Binary two-query locally decodable codes require exponential length for constant noise and recovery guarantees; the three-query length tradeoff remains open.
It is tested in tests/test_cs28_codes.py. The tests check:
- Hamming correcting every single error, and SECDED detecting doubles;
- the Golay weight distribution and perfection;
- the order of the bounds, including where the LP bound beats Hamming's;
- GF(256) inverses and tables;
- Reed–Solomon over GF(256) with errors and erasures together, up to 2e + f = 16;
- Lagrange and Berlekamp–Welch over GF(97);
- a QR round trip with 11 corrupted bytes;
- CRC-32 against
zlib.crc32; - Viterbi, LDPC and polar decoding on clean inputs, and BEC density evolution;
- RAID-6, LT and Hadamard local decoding.
Outside the tests, the QR encoder was compared module for module with the qrcode library (version 7.4.2, byte mode,
version 2, every mask and error level): identical in every case.
- A scratched message. Hook.
- Hamming, the Model V and the two-out-of-five code.
- Our QR code, "CS, Built: Part 28": a scratch over 56 modules corrupts 8 of its 44 bytes, and it still reads.
- 1. Noise and repetition.
- The BSC. Repetition at p = 0.1: 2.8% error at three copies, 1.6 × 10⁻⁷ at twenty-five, at 4% of the rate.
- A 96 × 40 picture through BSC(0.05): 179 pixels wrong raw, 22 with three-fold repetition, 60 with Hamming(7,4).
- 2. Hamming distance.
- The 3-cube with the repetition code, and the 4-cube with the even-weight code.
- d detects d − 1 errors and corrects ⌊(d − 1)/2⌋; erasures cost half.
- 3. Hamming(7,4).
- The Venn diagram: data 1011, a flip at position 5 located by circles A and C.
- The parity-check matrix: the syndrome is 101 = 5. Perfection: 16 × 8 = 128.
- The Hamming family up to (127,120), and SECDED (72,64).
- Exact bit-error curves against repetition and no code, confirmed by simulation (8.7 × 10⁻⁴ at p = 0.01).
- 4. How good can a code be?
- The rate–distance plane: Singleton, Hamming, the LP bound (better than Hamming's above δ ≈ 0.12), and Gilbert–Varshamov.
- The Golay code enumerated: 4,096 codewords; weights 7, 8, 11, 12, 15, 16 and 23 (253, 506, 1,288, 1,288, 506, 253, 1); 4,096 × 2,048 = 2²³. Voyager; the Leech lattice.
- 5. Finite fields.
- Multiplication mod 7; why mod 8 fails.
- GF(256) from x⁸ + x⁴ + x³ + x² + 1: the powers of α run through all 255 nonzero bytes; 0x57 × 0x83 = 0x31 by logs.
- Of the 256 polynomials of degree 8, 30 are irreducible and 16 primitive. QR's 0x11d is primitive; AES's 0x11b is not.
- 6. Reed–Solomon.
- 2x² + 3x + 5 at x = 1, …, 9 (mod 1009). Three corrupted values are found and fixed by Berlekamp–Welch.
- Six erased values are restored by Lagrange from the other three.
- MDS; CDs, deep space, QR, RAID-6.
- 7. Our QR code.
- Anatomy: finders, timing, alignment, format, mask 0.
- Where each of the 44 bytes lives; the decoder's trace on the scratch (22 syndromes, a locator of degree 8, Chien's 8 roots equal to the 8 changed bytes).
- Three damage cases:
- scratch: 8 bytes wrong, read as errors;
- blot: 15 wrong, 18 touched; fails as errors, read as erasures;
- hole: 24 touched; fails both ways.
- 8. Cyclic codes and CRCs.
- Long division over GF(2) and the same division as a three-flip-flop shift register: remainder 100.
- CRC-32 matches zlib.
- CRC-8 on 64-byte messages: every burst of length ≤ 8 caught; bursts of 9 missed 0.75% (2⁻⁷); random damage missed 0.39% (2⁻⁸).
- 9. Shannon's theorem.
- C = 1 − H(p).
- Random [n, n/2] codes, decoded optimally for n = 8 to 28. At p = 0.05 the block error falls from 11% to 5%; at p = 0.15 it rises from 36% to 54%.
- The random-coding argument and the converse.
- 10. Convolutional codes and Viterbi.
- The (7,5) trellis; Viterbi as dynamic programming.
- 20,000 bits per point: 6.5 errors per 10,000 at 2% flips, none at 0.5%. Concatenation.
- 11. LDPC codes and belief propagation.
- The Tanner graph and message passing.
- One block, round by round: 342 errors to 0 in 14 rounds at p = 0.07; stuck near 300 at 0.09.
- The waterfall of a (3,6) code of length 4,800: zero failures in 100 trials up to p = 0.0725, almost none recovered past 0.09. The asymptotic BP reference is about 0.084 and Shannon's limit about 0.11.
- BEC density evolution: a numerical threshold about 0.4294. History: Gallager, turbo codes, MacKay–Neal.
- 12. Polar codes.
- The N = 8 butterfly with its synthetic channels (erasure probability 0.004 to 0.996).
- Polarization up to N = 1,024 (a third perfect, a third useless).
- SC decoding at rate ½ for N = 256 and 1,024; 5G.
- 13. Codes for storage.
- RAID-6 rebuilding two lost disks.
- Replication against RS(10,4) and Azure's LRC.
- LT fountain overheads: 30%, 18% and 9% for 100, 1,000 and 10,000 blocks.
- 14. Frontier: capacity and locality.
- Reed–Muller codes achieve capacity (2016, 2023); list decoding and folded RS codes.
- The Hadamard code's two-query decoder, measured against 1 − 2δ.
- c³-LTCs and good quantum LDPC codes (2021).
- Open problems. Outro.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hamming at Bell Labs (1947–50); the binary symmetric channel; repetition codes.
- Hamming distance and the Hamming cube (3D, 4D projected); d detects d − 1 errors and corrects ⌊(d − 1)/2⌋.
- Hamming(7,4): parity checks as a matrix; the syndrome names the bad bit; the Venn picture; a perfect code.
- Bounds: Hamming (sphere packing), Singleton, Gilbert–Varshamov, on the rate–distance plane.
- Linear codes and duality; the Golay code (Voyager, cited) and the Leech lattice, briefly.
- Finite fields GF(p) and GF(2ᵐ) from irreducible polynomials (callback to Part 5's LFSRs); a cyclic multiplicative group.
- Reed–Solomon (1960):
- codewords as evaluations of polynomials, MDS by counting roots (proved);
- erasures by Lagrange interpolation;
- errors by Berlekamp–Welch, linear algebra on screen; Berlekamp–Massey;
- CDs, QR codes, deep space, RAID-6.
- Our QR code: encode a message, scratch the image, decode it back.
- Cyclic codes and CRCs: polynomial division over GF(2) as a shift-register circuit; guarantees for burst errors; CRC-32 (Part 36).
- Shannon's channel coding theorem (1948): BSC capacity 1 − H(p); random coding by typical sets (callback to AI, Built 1), proved; the converse via Fano.
- Concatenated codes (Forney); convolutional codes and Viterbi (callbacks to AI, Built 7 and Part 19).
- Turbo codes (1993) and the rediscovery of LDPC (Gallager 1962; MacKay & Neal): Tanner graphs, belief propagation (callback to AI, Built 7), density evolution, the computed waterfall.
- Polar codes (Arıkan 2009): channel polarization computed and animated, with capacities splitting toward 0 and 1; successive cancellation; 5G.
- List decoding (Sudan, Guruswami–Sudan); locally decodable and testable codes and PCPs (Part 27).
- Storage codes: RAID-5 and 6, LRCs (Azure), fountain and LT codes (Luby). Quantum codes previewed (Part 53). Outro.
Computed: Hamming(7,4) BER curves; the bounds; RS encode and decode of a scratched QR-like image; CRC detection rates; random codes at small n; the LDPC waterfall; polarization. Visuals: spheres around codewords in Hamming space; the Venn diagram; a polynomial through points with a corrupted point pulled back; the polarization fan; messages flowing on a Tanner graph. In practice: ECC memory, RAID and erasure-coded cloud storage, QR codes, Wi-Fi, 5G and satellite links, the CRC in every protocol. Reading: MacKay, Information Theory, Inference, and Learning Algorithms; Cover & Thomas ch. 7; Guruswami, Rudra & Sudan, Essential Coding Theory; MacWilliams & Sloane; Roth, Introduction to Coding Theory; Richardson & Urbanke, Modern Coding Theory; Lin & Costello; Hamming 1950; Reed & Solomon 1960; Gallager 1962; Berrou et al. 1993; Arıkan 2009; Shannon 1948.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
距离。 证明最小距离为 d 的码能检测 d − 1 个错误、纠正 ⌊(d − 1)/2⌋ 个错误,并且没有码能做得更好。
解答
若至多 d − 1 位翻转,收到的字与发送的码字距离至多 d − 1,因此不可能是另一个码字(那至少相距 d),所以变化会被检测到。设 t = ⌊(d − 1)/2⌋。若至多 t 位翻转,收到的字 y 满足 d(c, y) ≤ t;对任何其他码字 c′,三角不等式给出 d(c′, y) ≥ d(c, c′) − d(c, y) ≥ d − t > t,所以 c 是唯一最近的码字。最优性:取两个距离恰为 d 的码字 c、c′。翻转 d 位就把 c 变成 c′,任何解码器都无法察觉。至于纠错, 从 c 出发,在它们不同的位置中翻转 ⌈d/2⌉ 个:结果与 c 相距 ⌈d/2⌉,与 c′ 相距 ⌊d/2⌋。所以当 ⌈d/2⌉ = t + 1 时,最近码字解码会选 c′ 或打平。由于在 BSC 上最大似然就是最近码字解码,没有解码器能纠正所有 t + 1 个错误的模式。
-
Reed–Solomon 码是 MDS 码。 证明用 n 个不同的求值点、次数 < k 的消息,距离恰为 n − k + 1。
解答
码是线性的,所以距离等于非零码字的最小重量。次数 < k 的非零多项式至多有 k − 1 个根,所以它的 n 个值中至多 k − 1 个为零: 重量至少 n − k + 1。多项式 (x − x₁)(x − x₂)⋯(x − x_{k−1}) 次数为 k − 1,在这些点中恰有 k − 1 个零点,所以重量 n − k + 1 能达到。 Singleton 界说对每个码都有 d ≤ n − k + 1,所以 RS 码达到了它。
-
CRC 的保证。 证明生成多项式 g(x) 满足 g(0) = 1、次数为 r 的 CRC 能检测每个长度 ≤ r 的突发错误;若 (x + 1) 整除 g(x),还能 检测每个奇数个错误。
解答
错误恰在 g(x) 整除错误多项式 e(x) 时漏检。长度 ℓ ≤ r 的突发是 e(x) = xⁱ b(x),其中 deg b = ℓ − 1 < r 且 b(0) = 1。因为 g(0) = 1,g 与 xⁱ 没有公因子,所以 g | xⁱ b 会推出 g | b,而 deg b < deg g 且 b ≠ 0,不可能。奇数重量:若 (x + 1) | g 且 g | e,则在 GF(2) 上 e(1) = 0;但 e(1) 是错误位数的奇偶,奇数个时为 1。第 8 章对 CRC-8 测量了这两条性质(它的生成多项式 x⁸ + x² + x + 1 = (x + 1)(x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + 1) 含有因子 x + 1)。
-
密度演化。 推导 (3,6) 码在 BEC(ε) 上的递推 x ↦ ε(1 − (1 − x)⁵)²,并求出阈值。
解答
设 x 为在树状邻域上,从比特到校验的消息被「擦除」(未知)的概率。校验只有在它另外 5 个比特都已知时才能告诉一个比特它的值, 概率为 (1 − x)⁵;所以校验到比特的消息被擦除的概率是 1 − (1 − x)⁵。一个比特保持被擦除,当且仅当它的信道值被擦除(概率 ε)且另外两个 校验都被擦除:x′ = ε(1 − (1 − x)⁵)²。长码解码成功,恰好当从 x = ε 出发的迭代趋于 0,即对 (0, ε] 中所有 x 有 x > ε(1 − (1 − x)⁵)²。 二分法,
codes.de_bec_threshold(3, 6),给出 ε* ≈ 0.4294,而容量是 0.5;差距是正则 (3,6) 度分布的代价。 -
动手:版本 1 的二维码。 用本部分的函数编码一个版本 1 的二维码(21 × 21),并用手机核对。
解答
版本 1 没有对齐图案;暗模块在 (8, 13);字节模式容量为 L、M、Q、H 下 17、14、11、7 个字符;数据码字 19、16、13、9,校验字节 7、10、13、17,都是单块。把
QR_SIZE参数化为 21,去掉_qr_function_map里画对齐图案的循环,设置码字数,其余不变:格式位、掩码、 之字形排布和rs_encode都一样。和我们对版本 2 做的一样,用相同掩码与qrcode.QRCode(version=1, …)对照,然后加上四个模块宽的静区 显示出来并扫描。 -
★ 研究:短码。 在码长 64 到 256、码率 ½ 的 BSC 上,比较极化码的 SC 列表解码、用 BP 解码的 LDPC 码,以及 Polyanskiy、Poor 与 Verdú 的有限长度界。
从哪里入手。 Shannon 定理是渐近的。对短块,Polyanskiy、Poor 与 Verdú(2010)给出正态近似 log₂ M ≈ nC − √(nV) Q⁻¹(ε) + ½ log₂ n, 其中 V 是信道色散。Coşkun 等(2019)综述了当今的码在短码长下与它的比较。把
codes.polar_sc扩展为列表解码器(保留 L 条最好的路径, 用 CRC 辅助;Tal 与 Vardy 2015),用渐进边增长(Hu、Eleftheriou 与 Arnold 2005)构造短 LDPC 码,画出各自的块错误率对 p 的曲线。然后 问:在 n = 128 时它们离这个界有多远,列表变大时差距是否缩小。在这些码长上,还没有人知道能达到这个界的实用解码器。
Build the film
python -m videos.cs.cs28.compute # the part's numbers, into .cache/cs28
python tools/build.py cs28 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs28 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs28. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs28.compute # every number in the part (about a minute and a half)
python tools/build.py cs28 -q l # a 480p preview
python tools/build.py cs28 # 1080p