Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 11 · Thu 4/4/2024 · Compression (93 slides), second part (slides 47–93). It covers:
- Latent-variable models. Coding when cannot be enumerated: continuous data, mixture models as the running example, and three schemes (“max-mode”, posterior sampling, bits-back). It then covers bits-back with approximate inference and the source of the random bits.
- Coders built on bits-back. Asymmetric numeral systems (ANS), BB-ANS (discretizing continuous latents, “clean” bits) and Bit-Swap.
- Compression with flows. Why coding fails, local bits-back coding, and discrete data.
- Statistical vs dictionary methods. Lempel–Ziv (LZ77).
- An alternative without bits back. Minimal random coding, from the slides’ extra readings.
Basis: The slides draw on Frey & Hinton (1997), Duda (2007), Townsend, Bird & Barber (BB-ANS, 2019), Kingma, Abbeel & Ho (Bit-Swap, 2019), Ho, Lohn & Abbeel (local bits-back, 2019) and Blelloch’s notes.
- What the notes keep from the slides: their order and their examples (the ANS table, the three schemes).
- What the code adds: it builds every coder for real. It codes with exact latent-variable models whose is known, and with the course’s cached VAEs. Every compressed message is decoded back and checked.
Code:
code/lecture21/(5 scripts +bitsback.py). It uses numpy, scipy and PyTorch (CPU). Script 03 reuses Lecture 7’s cached VAE and trains three small hierarchical VAEs (~12 minutes on the first run). Everything else runs in seconds to ~1 minute. Reading time: 3 hours including running the code
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain why a latent-variable model is hard to use with arithmetic coding. Compute the expected code length of max-mode, posterior-sampling and bits-back coding.
- Derive that bits-back costs exactly with the true posterior, and the negative ELBO with an approximate one. The excess is .
- Explain asymmetric numeral systems: a message is a natural number, a symbol multiplies it by about , and the coder is a stack. Explain why that is exactly what bits-back needs.
- Run BB-ANS with a VAE: discretize the latent, pop with , push and . Account for initial bits and clean bits; explain how Bit-Swap cuts the initial bits of hierarchical models.
- Explain why a flow cannot be used by coding , and how local bits-back coding recovers the flow’s likelihood (including the term). Connect bits-back on dequantization noise to Lecture 6’s variational dequantization bound.
- Contrast static, dynamic and adaptive models, and explain why LZ77 is universal but slow (Kac’s lemma).
0.2 Prerequisites and scope
| Assumed | Introduced here | Elsewhere |
|---|---|---|
| Lecture 20 (entropy, KL, arithmetic coding, “a model is a compressor”) | bits-back coding, ANS, BB-ANS, Bit-Swap | — |
| Lectures 7–8 (VAEs, ELBO, IWAE, hierarchical VAEs, free bits; cached models) | discretized latents, initial / clean bits | Lecture 12 (latent diffusion as a compressor of sorts) |
| Lectures 5–6 (flows, change of variables, dequantization) | local bits-back coding, bits-back on dequantization noise | — |
| static / dynamic / adaptive models, LZ77, Kac’s lemma |
0.3 Map
§1 what Lecture 20 assumed, and when it fails (continuous x, latent variables)
§2 three ways to code with a latent variable; bits-back; the ELBO as a code length ← code 01
§3 where do the random bits come from?
§4 asymmetric numeral systems: a message is a number; a stack ← code 02
§5 BB-ANS: a VAE as a compressor; discretization; initial and clean bits ← code 03, Parts 1-3
§6 Bit-Swap: hierarchical latents ← code 03, Part 4
§7 compression with flows: local bits-back; discrete data ← code 04
§8 statistical vs dictionary methods: Lempel-Ziv ← code 05
§9 without bits back: minimal random coding (extra reading)
§10 summary §11 pitfalls §12 exercises §13 further reading §14 next lecture
0.4 Notation
- is a data point and a latent variable, with prior , likelihood , marginal and posterior .
- is an approximate posterior (the VAE’s encoder).
- All code lengths are in bits, and "" is unless said otherwise.
- An ANS state’s content is the number of bits of information it holds. Push means encode, pop means decode.
1. Where Lecture 20 left off
Lecture 20 ended with a strong result: any model that gives can drive an arithmetic coder, and the message then costs bits. Behind it are two assumptions (slide 50):
- Huffman needs to enumerate the values of ; arithmetic coding needs to assign an interval to each value, symbol by symbol. Both work when every symbol takes few values.
- Implicitly, the model must give the probabilities that the coder needs, in the order the coder needs them.
Continuous is easy to fix (slide 51). A real number carries infinite information, so we code it to a precision : discretize into bins of width . For the discretized variable has entropy , where is the differential entropy. Halving the bins costs one more bit, which matches intuition: more buckets, more information. After discretization, Huffman and arithmetic coding apply again.
High-dimensional is harder. Some high-dimensional distributions are still easy to code (slide 52):
- Factorized distributions, like or independent pixels: one dimension at a time.
- Autoregressive models: Lecture 20.
But the models with the best likelihoods are often latent-variable models: mixtures, VAEs, hierarchical VAEs. They are built from easy pieces, an easy prior and an easy for each . Their marginal is far more expressive than any piece (slide 53: a mixture of Gaussians vs one Gaussian), and that marginal is exactly what we cannot hand to an arithmetic coder.
- For a VAE, is continuous and is an intractable integral.
- Even for a mixture with components, the conditional that arithmetic coding needs is a weighted sum over components with weights , which must be recomputed at every step. That is feasible for small and hopeless for a VAE.
The slides insist that we not cheat by enumerating a small domain of (slide 54). Their illustrations are 1-D only to fit on a slide; the methods are meant for high-dimensional .
The question of this lecture: if is a latent-variable model built from easily coded pieces, can we code in bits without ever computing ?
2. Three ways to code with a latent variable
The natural idea is to send the latent along: transmit with the prior, then with . Both pieces are easy. The question is which to send and what that costs.
2.1 Scheme 1: “max-mode” coding (slide 56)
Pick the best latent, . Send with , then with . The cost is
This is not optimal, for two reasons:
- We also send . The bits that identify are spent, and the receiver did not ask for .
- The scheme codes with the wrong distribution. It effectively uses instead of , so the cost is plus normalization (slide 56; Lecture 20 §5.1).
2.2 Scheme 2: posterior sampling (slide 57)
Draw at random, then send and as before. Why code with and not with ? Because the receiver does not have yet: it decodes first.
The expected cost is
Averaged over , this is . That is perfect if we wanted to send the pair ; but we only wanted , so we overpay by exactly the posterior entropy . It is even worse than max-mode, because for every .
2.3 Scheme 3: bits-back coding (slide 58)
Here is the trick (Wallace 1990; Hinton & van Camp 1993). Posterior sampling consumes randomness to pick : choosing takes about random bits. Now suppose those random bits were not random at all, but were other data we wanted to send anyway.
- The receiver decodes , then .
- Now it knows , so it can compute , and it knows which was chosen.
- It can therefore reconstruct the bits that were used to choose .
Those bits were transmitted for free: they rode inside . The net cost is
This holds for every , not just on average. Bits-back is optimal, and it never computes ; it needs only , and the ability to sample .
2.4 Approximate inference: the ELBO is a code length (slide 60)
For a VAE we cannot sample the true posterior, only the encoder . Run the same scheme with , and the net cost becomes
The negative ELBO, which Lectures 7–8 called a “bound”, is an achievable code length. Training a VAE by maximizing the ELBO is minimizing the length of an actual compressed file.
A unifying view: every scheme costs .
- Max-mode is bits-back with a one-hot , which has no entropy to give back.
- Posterior sampling draws from but gives nothing back.
- Bits-back gives back .
2.5 The schemes measured (script 01)
Part 1: the slides’ running example in 1-D. Two Gaussians with standard deviation 8 and weight 1/2 each, on the integers 0–255. The exact expected code lengths, in bits:
| distance of the means | = bits-back | max-mode | posterior sampling | |
|---|---|---|---|---|
| 0 | 5.047 | 6.047 | 6.047 | 1.000 |
| 8 | 5.208 | 5.762 | 6.047 | 0.839 |
| 16 | 5.533 | 5.808 | 6.047 | 0.514 |
| 32 | 5.960 | 5.999 | 6.047 | 0.087 |
| 48 | 6.042 | 6.044 | 6.047 | 0.006 |
Three things to notice:
- Posterior sampling always costs 6.047 bits, whatever the overlap. It costs , and does not depend on where the components sit.
- Max-mode is not monotone. For identical components it pays the full bit for the useless label. For well-separated components the label is determined by and costs nothing extra. In between it saves part of the bit.
- Bits-back is in every row.
With an approximate posterior at distance 16, the measured excess equals to three decimals:
| posterior used | excess over |
|---|---|
| exact posterior | 0.000 |
| tempered (temperature 2) | 0.108 |
| = prior (ignores ) | 0.957 |
| one-hot at the argmax (= max-mode) | 0.275 |
Part 2: a high-dimensional model with an exact posterior. Noisy ShapeWorld (Lecture 7) is a latent-variable model:
- is the clean image, one of 921,600, with ShapeWorld’s exact prior.
- is with every pixel flipped with probability .
The noise is independent per pixel, so the joint over all 921,600 latents is a table per image, and the posterior is exact. Expected bits per image (200 images):
| exact | max-mode | posterior sampling | bits-back, mean-field | ||
|---|---|---|---|---|---|
| 0.05 | 99.88 | +0.00 | +0.01 | +0.00 | 0.01 |
| 0.1 | 154.20 | +0.04 | +0.07 | +0.02 | 0.07 |
| 0.2 | 223.40 | +0.40 | +0.92 | +0.17 | 0.92 |
| 0.3 | 266.47 | +2.04 | +4.86 | +0.49 | 4.86 |
The lesson: bits-back saves exactly what leaves uncertain about .
- At the noisy image all but pins down the clean one, and all schemes are equivalent.
- At the posterior holds 4.86 bits, and posterior sampling wastes all of them.
The “mean-field” treats the two panels independently, ignoring the copy rule. It is a genuine approximate posterior, and it pays its KL.
Part 3: real bit streams. Script 01 compressed 200 noisy images () into one message per scheme, with the ANS coder of §4. It then decoded every message back and checked it:
| scheme | realized bits per image | excess |
|---|---|---|
| max-mode | 268.08 | +1.90 |
| posterior sampling | 270.67 | +4.49 (= the fresh random bits spent per image) |
| bits-back, exact posterior | 266.18 | −0.00 |
| bits-back, mean-field | 266.78 | +0.61 |
The exact of these images averages 266.18 bits.
3. Where do the random bits come from?
Bits-back assumed “auxiliary random data we would like to transmit anyway” (slide 59). In a compressor that data is simply the rest of the message (slide 61):
- When we code a sequence , the bits already produced for serve as the random source from which is chosen.
- When the receiver decodes (in reverse order), it reconstructs those bits and continues decoding from them.
Only the very first data point has nothing to borrow from. It needs initial bits: a short random prefix that is sent along and that the decoder hands back at the end. Over a long message this overhead is negligible (§5.3).
Two questions remain:
- Order. “Decode from the end of what was already written” and “give those bits back later” require a coder in which the most recently written information is the first to be read: a stack (last in, first out). Arithmetic coding is a queue: the decoder reads bits in the order the encoder wrote them. Frey & Hinton (1996) made bits-back work with arithmetic coding, but awkwardly (slide 62). The natural fit came with ANS (Duda, 2009), and Townsend et al. (2019) put the two together as BB-ANS.
- Are compressed bits random enough? That is the “clean bits” question of §5.4.
4. Asymmetric numeral systems
4.1 A message is a natural number (slides 63–65)
Writing a number in binary is a perfect code for uniform bits: appending a bit maps , and the number grows by one bit. ANS generalizes this to non-uniform symbols. Here is the idea:
- Decide that a fraction of all natural numbers “end in ”.
- Encode by moving from to the -th number that ends in . That number is about , so the message grows by bits.
The slides’ example, and , uses blocks of numbers: in each block, slot 0 belongs to and slots 1–3 to . Script 02, Part 1, reproduces the slides’ table:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| push | 0 | 4 | 8 | 12 | 16 | 20 | 24 |
| push | 1 | 2 | 3 | 5 | 6 | 7 | 9 |
Encoding “bab” from 0 goes .
rANS (“range ANS”, the version used in practice) does this for integer frequencies summing to , with cumulative starts :
Why inverts . Write with . Then , whose remainder mod is . That lies in ‘s range, so finds , and , so returns .
Growth. .
Order. The last symbol pushed is the first popped: encoding “abb” and decoding gives “bba” back. ANS is a stack.
Two practical details:
- Starting from loses information: pushing maps 0 to 0. We start at (or, when streaming, at the bottom of the head’s range).
- At small the integer rounding wastes up to about a bit; it does not accumulate. Over 10 to 10,000 random symbols, exceeded by 0.65–1.15 bits, independent of length.
4.2 Streaming: renormalization
A message of a million symbols would be a million-bit integer. Practical rANS keeps a head in a fixed window (here , so a 64-bit head) and a stack of 32-bit words:
- Before pushing : if the head is so large that would leave the window, move its low 32 bits onto the stack.
- After popping: if the head drops below , pull the top word back in.
Both sides do this at mirror-image moments, so decoding stays exact. The stack only grows and shrinks at its end, so the whole coder is still last-in-first-out.
Content. Script 02 measures an ANS state’s content as . Flushing for transmission costs bits.
4.3 How good is it? (script 02, Parts 2–3)
On 100,000 i.i.d. symbols (bits per symbol, with prec = 16):
| source | entropy | Huffman | arithmetic coding | rANS (flushed) |
|---|---|---|---|---|
| the slides’ | 0.8113 | 1.0000 | 0.8112 | 0.8115 |
| Lecture 20’s Huffman example (6 symbols) | 2.3076 | 2.3594 | 2.3080 | 2.3085 |
| skewed | 0.0808 | 1.0000 | 0.0841 | 0.0845 |
- Like arithmetic coding, rANS has no “+1” per symbol. Huffman pays a full bit per symbol on the skewed source, 12× the entropy.
- rANS is simpler. Per symbol it needs a division (encoder) or a multiplication (decoder), with no pending bits or carries.
- It was faster in our Python implementation: 0.04–0.05 s vs 0.14–0.20 s per 100,000 symbols.
Real implementations also interleave several ANS states for SIMD speed.
Precision. Probabilities must be integers with every , and rounding costs . For :
| prec | measured excess (bits per symbol) |
|---|---|
| 4 | 0.246 |
| 6 | 0.026 |
| 8 | 0.004 |
| 12 | 0.00001 |
With the streaming coder, prec must also stay well below the head’s 32 spare bits. At prec = 32 a small loss reappears: 0.0006 bits per symbol here, and 0.016 bits per point in the flow codes of §7.
4.4 Decoding random bits is sampling (script 02, Part 4)
Here is the property bits-back rests on. Fill a stack with uniformly random bits and pop symbols using a distribution . Each pop reads a uniform slot; slot ranges are proportional to , so the symbols come out distributed as . Each pop consumes bits. Push the symbols back, and the stack is restored bit for bit. With and 10,000 pops:
| what the stack holds | frequencies popped | max | bits per pop | restored |
|---|---|---|---|---|
| uniformly random bits | 0.500 0.305 0.144 0.051 | 1.7 | 1.6435 | yes |
| a compressed message | 0.507 0.302 0.143 0.047 | 1.9 | 1.6279 | yes |
Compressed data behaves like random bits. That is why the previous data points can serve as the random source.
5. BB-ANS: a VAE as a compressor
5.1 The algorithm (slides 66–68)
To encode on top of an ANS stack:
- Pop with . This reads about bits off the stack and uses them as the random choice of .
- Push with .
- Push with .
To decode, mirror the steps:
- Pop with .
- Pop with .
- Push back with . This restores the bits from step 1 of encoding.
The stack grows by per data point: the negative ELBO on average (§2.4). Steps 1 and 3 of the encoder and decoder must use bit-identical probabilities. Our coder therefore runs the networks on one image at a time on both sides, so floating-point results cannot differ.
5.2 Continuous latents (slide 69)
A VAE’s is continuous, so we discretize it. BB-ANS uses buckets of equal prior mass per dimension (the prior’s quantiles), so the prior codec is uniform: bits per dimension. The posterior codec gives each bucket its mass under . The likelihood is evaluated at the bucket centers.
Why does the precision not matter? With bucket width around :
- and .
- The cancels in (Hinton & van Camp 1993).
- The only cost of discretizing is the small mismatch between the continuous densities and their bucketed versions.
The latent is sent to precision at a price of bits per dimension, and those bits come back.
5.3 Measured (script 03, Parts 1–3)
We use Lecture 7’s convolutional VAE (16-dimensional latent, Bernoulli pixels, −ELBO ≈ 67 bits) on 1,000 ShapeWorld test images, with :
| scheme | realized bits per image |
|---|---|
| max-mode: = the posterior mean’s bucket, no bits back | 149.19 |
| posterior sampling: , no bits back | 158.61 |
| BB-ANS | 67.31 |
Reference values:
| reference | bits per image |
|---|---|
| −ELBO (continuous ) | 67.17 (reconstruction 30.30 + KL 36.87) |
| discrete −ELBO with genuinely random | 67.61 |
| IWAE bound, | 61.01 |
| lzma (Lecture 20) | 111.7 |
| exact model (Lecture 20) | 18.8 |
- BB-ANS turns the ELBO into a real file size. Without bits back, the latent costs its full bits.
- Plain BB-ANS codes the ELBO, not the tighter IWAE bound.
- A VAE is a poor model of ShapeWorld compared with the autoregressive models of Lectures 3–4.
Latent precision. Over 300 images, with the posterior’s integer frequencies at 24 bits:
| BB-ANS | without bits back | initial bits (1st image) | |
|---|---|---|---|
| 2 | 138.02 | 148.68 | 13 |
| 4 | 76.28 | 107.39 | 28 |
| 6 | 68.70 | 128.18 | 57 |
| 8 | 67.67 | 158.68 | 87 |
| 12 | 67.50 | 222.61 | 159 |
| 16 | 74.29 (68.80 with 32-bit ) | 293.77 | 213 |
Reading the table:
- Without bits back, every extra bit of precision costs 16 bits per image (one per latent dimension) from on.
- With bits back, the cost is flat from , as the cancellation argument predicts.
- Coarse buckets () make the decoder see a blurred latent.
- The price of fine buckets is initial bits, and a subtle precision requirement. With 24-bit frequencies and 65,536 buckets, every bucket keeps a minimum frequency, so absurd latents far in the tails are sometimes popped. Raising the precision to 32 bits fixes it.
Initial bits, amortized. The first image needed 87 random bits (at ). In one message of images that is a one-time cost:
| images in the message | bits per image, including the initial bits |
|---|---|
| 1 | 151.84 |
| 10 | 83.16 |
| 100 | 69.37 |
| 1,000 | 67.40 (net 67.31) |
5.4 Are the bits clean? (slide 70)
Bits-back assumes the popped bits are uniformly random, so that . They are not quite random: they are compressed images, coded with the model’s and .
- If the model were perfect, the compressed data would be perfectly random bits.
- Otherwise, the popped follows a slightly different distribution. Townsend et al. trace the effect to the mismatch between the aggregate posterior and the prior . The ELBO contains this term, but it is never exactly zero in practice.
Measured:
| quantity | popped from the message | fresh samples |
|---|---|---|
| , bits per image | 91.26 | 91.19 |
| BB-ANS bits on the first 200 images vs discrete −ELBO | 67.96 | 67.61 |
The bits are clean enough that the difference is within noise. Whatever is popped, decoding is always exact: dirty bits can only change the length, never correctness.
6. Bit-Swap: hierarchical latents
Hierarchical latent-variable models reach better likelihoods than single-level ones, especially when encoders and decoders are restricted to factorized distributions (slide 72). Bit-Swap (Kingma, Abbeel & Ho, 2019) handles models whose generative model and inference model are Markov chains:
BB-ANS treats as one big latent:
- Pop , all of them.
- Push , then , then .
Before anything is pushed it must have popped bits. For the first data point, all of them are initial bits.
Bit-Swap interleaves (slides 73–74):
- Pop with , then push with .
- Pop with , then push with .
- Continue the same way up the hierarchy.
- Finally push with .
Every pop is quickly followed by a push that refills the stack. The initial bits are the largest running deficit, not the sum. The code length is the same. The Markov inference model is essential: must not need , because is already pushed.
Measured (script 03, Part 4). Markov VAEs with 2, 3 and 4 levels of 16 dimensions, trained here with free bits (0.5 bits per dimension). Each level’s latent is discretized into buckets placed at that level’s own scale. 200 test images:
| levels | −ELBO | KL per level (bottom … top) | BB-ANS bits | Bit-Swap bits | BB-ANS initial bits | Bit-Swap initial bits |
|---|---|---|---|---|---|---|
| 2 | 62.53 | 26.2 / 10.5 | 62.25 | 62.99 | 199 | 169 |
| 3 | 65.51 | 20.5 / 9.5 / 7.7 | 65.49 | 65.41 | 301 | 179 |
| 4 | 66.52 | 17.0 / 9.4 / 8.3 / 6.5 | 66.59 | 66.17 | 387 | 186 |
Both orders code at the −ELBO. BB-ANS’s initial bits grow by about 100 per level; Bit-Swap’s stay near the cost of the first level.
Two things went wrong first (see the README’s “plan vs reality”):
- Without free bits, the upper levels collapsed onto their priors. They then carry no information but still cost initial bits.
- With buckets for every level, the code was 165 bits per image. The bottom level’s values spread over ±20, so most fell into the few wide outer buckets. Buckets must sit where each level’s values are.
7. Compression with flows
7.1 The target (slides 77–79)
A flow gives a density . Continuous data must be discretized: tile space with cubes of side and code the cube with probability . The target is
Enumerating cubes is exponential in , so we must exploit the flow’s structure, as we did for AR models (Lecture 20) and VAEs (§5).
7.2 Naive: code (slide 80)
Why not send on a grid with the prior? A well-trained flow makes , so coding with the prior is coding pure noise: it gains nothing. The real problem is volume. The grid cells of are not images of the cells of , so the code is either lossy or must use a much finer -grid.
Script 04 uses a known 2-D flow with a full Jacobian, ToyFlow2D. Its data are on a grid of , and the exact code length is 24.816 bits per point:
| -grid | bits per point | vs exact | decoded exactly |
|---|---|---|---|
| 24.090 | −0.727 | 58.6% | |
| 28.090 | +3.273 | 98.1% | |
| 32.090 | +7.273 | 100.0% |
At the same spacing the code is “too cheap” by exactly , and lossy. Making it lossless costs 7 bits per point. The missing piece is the term.
7.3 Local bits-back coding (slides 81–86)
Ho, Lohn & Abbeel (2019) build a tiny VAE around the flow and code it with bits-back: with and small , all discretized on fine grids. The encoder is “the image under the linearized flow of a small Gaussian around ”.
Derivation (first order in ). Write with . Then . The three terms of the bits-back cost (natural log; the grid terms cancel for as in §5.2) are:
- Push : .
- Push : .
- Bits back: .
The Gaussian terms cancel, leaving
The Jacobian enters through the bits we get back: is wider where the flow stretches space.
Measured. 2,000 points, -grid , the unbounded ANS at prec 40:
| excess (bits per point) | sd of a point’s excess | initial bits (1st point) | |
|---|---|---|---|
| +0.2076 | 0.95 | 34 | |
| +0.0147 | 0.19 | 31 | |
| +0.0005 | 0.04 | 27 | |
| +0.0001 | 0.01 | 24 | |
| +0.0048 | 0.11 | 19 | |
| +0.4299 | 0.98 | 15 |
The trade-off in :
- Too large a breaks the linearization.
- Too small a (comparable to the data grid ) breaks the density approximation of .
- In between, the code matches the flow’s likelihood to bits.
Two caveats from the slides:
- Initial bits. The first point needs a few dozen, about per point.
- Precision. The fine grids need precise integer probabilities. The same code with a streaming coder at prec 32 lost 0.0156 bits per point.
Cost and specialization (slide 83). Computing and factorizing costs , which is fine for and too slow for images. The slides list specializations:
- Autoregressive flows can be coded one dimension at a time without any Jacobian; each conditional is a 1-D monotone map, i.e. a CDF.
- Compositions can be coded layer by layer.
- RealNVP-type couplings are Jacobian-free, linear time and parallel.
7.4 Discrete data: bits back on the dequantization noise (slide 84)
Images are discrete. A flow is a density, so it codes , the discrete value plus dequantization noise (Lecture 6). Coding to high precision costs 16–32 extra bits per dimension, so give those bits back:
- Pop with a noise distribution .
- Code with the flow.
- On decoding, recover and push back.
The net cost is , exactly the (variational) dequantization bound of Lecture 6, now as a file size.
Measured (Part 3). Cells of side 0.5, i.e. :
| bits per point | |
|---|---|
| exact | 6.873 |
| uniform-dequantization bound | 6.908 (Jensen gap 0.036) |
| uniform , bits-back (realized) | 6.911 |
| exact posterior , bits-back | 6.870 |
With the optimal noise distribution the bound becomes the exact discrete likelihood. Variational dequantization is the practical middle ground.
8. Statistical vs dictionary methods: Lempel–Ziv
8.1 Static, dynamic, adaptive (slide 88)
| kind | example | strength | weakness |
|---|---|---|---|
| Static: one model for all texts | ASCII, Morse, a generic Huffman code | fast | ignores the data |
| Dynamic: a model fitted to this text | Huffman fitted to the file | fits the data | needs a first pass, and the model must be sent |
| Adaptive: a model learned while coding | LZW, adaptive context models | nothing sent in advance; better as it learns | decoding must start at the beginning |
Learned neural compressors are usually static in this sense: one pretrained model. The model’s size then becomes the two-part-code term of Lecture 20 §8.3.
8.2 LZ77 and why it works (slides 89–91)
LZ algorithms keep no explicit probabilities. At each position they find the longest match in the already-coded past and emit (offset, length, next symbol). Variations differ in how far back they look (the window) and when strings enter the dictionary.
Why does this approach the entropy? The slides’ argument:
- For a stationary ergodic source, the average time back to the previous occurrence of a string is . This is Kac’s lemma.
- An integer can be named in about bits.
- So naming the previous occurrence of a long string costs about bits.
- Over a long time this approaches per symbol, which is optimal.
The catch is “a long time”.
Measured (script 05). An order-1 Markov source on 8 letters with entropy rate :
| symbols | LZ77, window | LZ77, window | zlib | lzma | adaptive order 1 |
|---|---|---|---|---|---|
| 1,000 | 6.120 | 7.140 | 3.080 | 3.936 | 2.175 |
| 10,000 | 4.058 | 4.673 | 2.774 | 2.723 | 2.062 |
| 100,000 | 3.803 | 4.113 | 2.608 | 2.463 | 2.052 |
| 1,000,000 | 3.787 | 4.048 | 2.551 | 2.370 | 2.053 |
What the table shows:
- The adaptive order-1 model is the right model class and sits at from 10,000 symbols on.
- Our LZ77 with fixed-width fields stalls at 3.8 bits. A bigger window is worse: longer offsets cost more than the extra matches save.
- zlib and lzma creep toward by entropy-coding their output; lzma is 15% above after a million symbols. LZ is universal, but slow.
Kac’s lemma, checked on the same source (strings of length ):
| mean of gap × | mean gap | mean | gap / | |
|---|---|---|---|---|
| 1 | 1.000 | 2.34 | 2.91 | 2.336 |
| 4 | 0.999 | 8.24 | 9.06 | 2.059 |
| 8 | 0.847 | 15.05 | 16.17 | 1.881 |
Kac’s lemma holds exactly where strings recur often. For rare strings, the gap is roughly geometric and (Jensen plus Euler’s constant). Per symbol, approaches by . Longer strings have mostly not recurred within a million symbols, which is exactly why LZ needs so much data.
Captions (bits per caption; exact entropy 11.97), for 10,000 captions:
| method | bits per caption |
|---|---|
| static 8-bit | 587.7 |
| dynamic Huffman | 294.1 |
| best adaptive context model () | 30.8 |
| LZ77 (ours) | 67.3 |
| zlib | 32.0 |
| lzma | 24.0 |
Copying whole repeated phrases beats character contexts here. But every generic method stays 2–3× above a model that knows the language.
9. Without bits back: minimal random coding (slide 93, extra reading)
Havasi et al. (2019) reach the same code length without bits back:
- The encoder draws samples from the prior, with a random-number generator whose seed the decoder shares.
- It picks one with probability proportional to , and sends its index: bits.
- The decoder regenerates the same samples and reads off .
The chosen is approximately a sample from . The cost of is the KL term of the ELBO, without any stack or initial bits. The price is samples, which forces the latent to be split into blocks of a few bits of KL each.
10. Summary
- Latent-variable models are built from easy pieces but have marginals no coder can enumerate. Sending the latent along costs extra (posterior sampling) or somewhat less (max-mode). Bits-back recovers the bits spent choosing and costs exactly , or the negative ELBO with an approximate posterior: the VAE objective is a file size. On noisy ShapeWorld bits-back hit the exact to 0.00 bits; the schemes without bits back lost up to 4.9 bits.
- ANS treats a message as a natural number that grows by per symbol, and it is a stack. It matches arithmetic coding’s efficiency; popping from random (or compressed) bits samples, and pushing back restores the bits. That is the operation bits-back needs.
- BB-ANS: pop with , push and . Lecture 7’s VAE compressed ShapeWorld images to 67.3 bits, its −ELBO, vs 149–159 bits without bits back. The latent’s precision is paid with bits that come back, and the first data point’s initial bits are amortized. The bits were clean enough.
- Bit-Swap interleaves the levels of a Markov hierarchy: same length, initial bits that do not grow with depth (169–186 vs 199–387).
- Flows: coding misses the volume term. Local bits-back with a linearized Gaussian VAE around the flow matches its likelihood to bits at a good . Bits-back on dequantization noise turns the dequantization bound into a file size, and the exact noise posterior gives the exact discrete likelihood.
- Lempel–Ziv needs no model and is asymptotically optimal (Kac’s lemma), but converges slowly. A model of the right class gets to the entropy far sooner, and a model that knows the structure beats every generic method.
11. Common pitfalls
- “Sending the latent is free because the model needs it.” Without bits back, the latent’s information is pure overhead: 128 bits per image for our VAE at .
- Using a queue-based coder for bits-back. The bits used to choose must be the most recently written ones, and they must be returned before older data is read. That needs a stack.
- Computing or differently on the two sides. A different batch size or a different order of floating-point operations can change a probability by one unit of the integer frequency, and the decoder fails. Compute them identically, in our case one item at a time.
- Discretizing every latent level with the prior’s buckets. A level whose values spread over ±20 lands mostly in the wide outer buckets (165 vs 66 bits per image).
- Too little precision for fine buckets. Every bucket keeps a minimum integer frequency, so absurd latents get popped (74.3 vs 68.8 bits at 65,536 buckets).
- Forgetting the initial bits for short messages: 87 bits on a single 67-bit image.
- Coding a flow’s on a grid as if it were the data. It is lossy or wasteful, because volume matters.
- Expecting LZ to reach the entropy on small files. It is universal only asymptotically.
12. Exercises
Exercise 1 (bits-back cost — derivation). Show that bits-back with posterior costs on average, and exactly for every when is the true posterior.
Answer
The net cost for a given is . With this is . Taking the expectation over gives . If the log-ratio is 0 for every .
Exercise 2 (posterior sampling vs max-mode — derivation). Show that posterior sampling costs on average, that max-mode costs no more, and that in the 1-D example of §2.5 posterior sampling costs regardless of the distance between the means.
Answer
Posterior sampling costs . Max-mode uses with for all , so .
By the chain rule the other way, . Here , and is the entropy of one discretized Gaussian, which does not change when the Gaussian is shifted (away from the boundaries of 0–255).
Exercise 3 (rANS — derivation). Prove that for the rANS maps of §4.1, and that . Conclude that .
Answer
Invertibility is shown in §4.1. For the bound: . So with . Taking gives , and the last term is . Rounding costs vanish once , which is why streaming coders keep the head far above (§4.3: prec 32 with a 32-bit margin loses a little).
Exercise 4 (why a stack — derivation). BB-ANS encodes : pop , push , pop , push . Write the decoder’s operations in order, and explain why a first-in-first-out coder could not decode before ‘s data.
Answer
The decoder works in reverse:
- Pop with , pop with , push with . This restores the bits from which was popped, i.e. part of ‘s code.
- Pop , pop , push back (the initial bits).
The decoder must first read what the encoder wrote last (), and the bits it puts back must be read next. In a queue, the decoder reads first what the encoder wrote first (‘s data). But ‘s code was partly “consumed” by choosing , and can only be reconstructed after has been decoded. The dependencies run backwards in time, which is exactly a stack.
Exercise 5 (initial bits of Bit-Swap — derivation). For a two-level Markov hierarchy, write the stack content during BB-ANS and Bit-Swap encoding of the first data point, and give the initial bits each needs in terms of , and .
Answer
BB-ANS pops then before any push, so it needs initial bits.
Bit-Swap proceeds:
- Pop : the deficit is .
- Push : the deficit becomes .
- Pop : the deficit becomes .
It needs initial bits. When (the data’s bits refill the stack at least as fast as the next level drains it), Bit-Swap needs only , whatever the number of levels. In script 03 Bit-Swap needed 169–186 bits, about the bottom level’s pop, while BB-ANS grew by ~100 bits per level.
Exercise 6 (local bits-back — derivation). Fill in the first-order derivation of §7.3: show that contributes (plus grid terms) when .
Answer
, and .
Since , we get .
The difference is . Adding gives . The grid terms add for the pushed ; for , the of the push and the pop cancel.
Exercise 7 (Kac’s lemma for an i.i.d. source — derivation). For i.i.d. symbols with , show that the gap between consecutive occurrences of is geometric with mean . Estimate for small .
Answer
After an occurrence, each later position is independently with probability , so , with mean . For small , is approximately exponential with mean 1, and (Euler’s constant 0.577). So . Script 05’s row shows .
Exercise 8 (coding). Change script 01, Part 3 to . Predict the excess of posterior sampling and of max-mode from Part 2’s trend, then run it.
Answer
(Run it.) grows quickly with the noise, and posterior sampling’s excess equals it. Max-mode’s excess grows too, but more slowly, since it never sends an unlikely latent. Bits-back stays at the exact . On 100 images at (exact expectations): , posterior sampling +13.08 (= ), max-mode +5.97.
Exercise 9 (coding). In script 03, Part 2, increase the decoder’s precision prec_x from 16 to 24 bits, and decrease it to 8. Which code lengths change, and why?
Answer
(Run it.) At 8 bits every pixel probability is rounded to a multiple of 1/256, with a floor of 1/256. Confident pixels then cost at least bits each, about 1.6 bits per image over 288 pixels, plus more for the rounding of mid-range probabilities. At 24 bits nothing measurable changes from 16. The latent terms are unaffected.
13. Further reading
From the slides
- G. Hinton, D. van Camp. Keeping Neural Networks Simple by Minimizing the Description Length of the Weights, COLT 1993 — the bits-back idea.
- B. Frey, G. Hinton. Efficient Stochastic Source Coding and an Application to a Bayesian Network Source Model, The Computer Journal 1997.
- J. Duda. Asymmetric Numeral Systems: Entropy Coding Combining Speed of Huffman Coding with Compression Rate of Arithmetic Coding, 2013 (arXiv 1311.2540; first version 2007).
- J. Townsend, T. Bird, D. Barber. Practical Lossless Compression with Latent Variables using Bits Back Coding, ICLR 2019 (BB-ANS).
- F. Kingma, P. Abbeel, J. Ho. Bit-Swap: Recursive Bits-Back Coding for Lossless Compression with Hierarchical Latent Variables, ICML 2019.
- J. Ho, E. Lohn, P. Abbeel. Compression with Flows via Local Bits-Back Coding, NeurIPS 2019.
- G. Blelloch. Introduction to Data Compression (LZ77, LZW, static / dynamic / adaptive models).
- J. Townsend et al. HiLLoC: Lossless Image Compression with Hierarchical Latent Variable Models, ICLR 2020.
- M. Havasi, R. Peharz, J. M. Hernández-Lobato. Minimal Random Code Learning, ICLR 2019.
- Y. Yang et al. Feedback Recurrent Autoencoder, 2019 (lossy).
Added by these notes
- F. Giesen. Interleaved entropy coders (2014) and the
ryg_ranscode — the rans64 layout used inbitsback.py. - J. Ziv, A. Lempel. A Universal Algorithm for Sequential Data Compression, IEEE Trans. Inf. Theory 1977 (LZ77); A. Wyner, J. Ziv. Some Asymptotic Properties of the Entropy of a Stationary Ergodic Data Source, 1989 (recurrence times and entropy).
- M. Kac. On the Notion of Recurrence in Discrete Stochastic Processes, 1947.
- J. Townsend. A Tutorial on the Range Variant of Asymmetric Numeral Systems, arXiv 2001.09186, 2020.
14. Next lecture
Lecture 22 turns to multimodal models. It covers:
- Connecting models. How to connect a pretrained vision encoder to a language model: CLIP as a building block, a LLaVA-style projection, Flamingo-style cross-attention.
- Instruction tuning. Why visual instruction tuning needs little data.
- Generation in one stream. How images and text can be generated in one token stream (Lecture 4’s homework Q6, extended).