Lecture 21 · Compression II: Bits-Back Coding, ANS and Flows

Deep Unsupervised Learning · Lecture 21。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

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 p(x)p(x) 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 z=f(x)z = f(x) 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 p(a)=1/4p(a) = 1/4 ANS table, the three schemes).
  • What the code adds: it builds every coder for real. It codes with exact latent-variable models whose −log⁡2p(x)-\log_2 p(x) 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:

  1. Explain why a latent-variable model p(x)=∑zp(z) p(x∣z)p(x) = \sum_z p(z)\,p(x \mid z) is hard to use with arithmetic coding. Compute the expected code length of max-mode, posterior-sampling and bits-back coding.
  2. Derive that bits-back costs exactly −log⁡2p(x)-\log_2 p(x) with the true posterior, and the negative ELBO with an approximate one. The excess is KL(q(z∣x) ∥ p(z∣x))\mathrm{KL}(q(z \mid x)\,\|\,p(z \mid x)).
  3. Explain asymmetric numeral systems: a message is a natural number, a symbol multiplies it by about 1/p1/p, and the coder is a stack. Explain why that is exactly what bits-back needs.
  4. Run BB-ANS with a VAE: discretize the latent, pop zz with qq, push xx and zz. Account for initial bits and clean bits; explain how Bit-Swap cuts the initial bits of hierarchical models.
  5. Explain why a flow cannot be used by coding z=f(x)z = f(x), and how local bits-back coding recovers the flow’s likelihood (including the log⁡∣det⁡J∣\log\lvert\det J\rvert term). Connect bits-back on dequantization noise to Lecture 6’s variational dequantization bound.
  6. Contrast static, dynamic and adaptive models, and explain why LZ77 is universal but slow (Kac’s lemma).

0.2 Prerequisites and scope

AssumedIntroduced hereElsewhere
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 bitsLecture 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

  • xx is a data point and zz a latent variable, with prior p(z)p(z), likelihood p(x∣z)p(x \mid z), marginal p(x)=∑zp(z)p(x∣z)p(x) = \sum_z p(z)p(x \mid z) and posterior p(z∣x)p(z \mid x).
  • q(z∣x)q(z \mid x) is an approximate posterior (the VAE’s encoder).
  • All code lengths are in bits, and "log⁡\log" is log⁡2\log_2 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 p(xt∣x<t)p(x_t \mid x_{<t}) can drive an arithmetic coder, and the message then costs −log⁡2p(x)+2-\log_2 p(x) + 2 bits. Behind it are two assumptions (slide 50):

  1. Huffman needs to enumerate the values of xx; arithmetic coding needs to assign an interval to each value, symbol by symbol. Both work when every symbol takes few values.
  2. Implicitly, the model must give the probabilities that the coder needs, in the order the coder needs them.

Continuous xx is easy to fix (slide 51). A real number carries infinite information, so we code it to a precision tt: discretize into bins of width tt. For X∼N(0,1)X \sim \mathcal{N}(0, 1) the discretized variable has entropy ≈h(X)+log⁡2(1/t)\approx h(X) + \log_2(1/t), where hh 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 xx is harder. Some high-dimensional distributions are still easy to code (slide 52):

  • Factorized distributions, like N(0,I)\mathcal{N}(0, I) 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 p(z)p(z) and an easy p(x∣z)p(x \mid z) for each zz. Their marginal p(x)=∑zp(z)p(x∣z)p(x) = \sum_z p(z) p(x \mid z) 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, zz is continuous and p(x)p(x) is an intractable integral.
  • Even for a mixture with KK components, the conditional p(xt∣x<t)p(x_t \mid x_{<t}) that arithmetic coding needs is a weighted sum over components with weights p(z∣x<t)p(z \mid x_{<t}), which must be recomputed at every step. That is feasible for small KK and hopeless for a VAE.

The slides insist that we not cheat by enumerating a small domain of xx (slide 54). Their illustrations are 1-D only to fit on a slide; the methods are meant for high-dimensional xx.

The question of this lecture: if p(x)p(x) is a latent-variable model built from easily coded pieces, can we code xx in −log⁡2p(x)-\log_2 p(x) bits without ever computing p(x)p(x)?


2. Three ways to code with a latent variable

The natural idea is to send the latent along: transmit zz with the prior, then xx with p(x∣z)p(x \mid z). Both pieces are easy. The question is which zz to send and what that costs.

2.1 Scheme 1: “max-mode” coding (slide 56)

Pick the best latent, z∗=arg⁡max⁡zp(z∣x)=arg⁡max⁡zp(z,x)z^* = \arg\max_z p(z \mid x) = \arg\max_z p(z, x). Send z∗z^* with p(z)p(z), then xx with p(x∣z∗)p(x \mid z^*). The cost is ℓmax(x)=−log⁡p(z∗)−log⁡p(x∣z∗)=−log⁡p(x,z∗)  ≥  −log⁡p(x).\ell_{\text{max}}(x) = -\log p(z^*) - \log p(x \mid z^*) = -\log p(x, z^*) \;\ge\; -\log p(x).

This is not optimal, for two reasons:

  • We also send z∗z^*. The bits that identify z∗z^* are spent, and the receiver did not ask for z∗z^*.
  • The scheme codes with the wrong distribution. It effectively uses Q(x)∝max⁡zp(z,x)Q(x) \propto \max_z p(z, x) instead of p(x)p(x), so the cost is H(X)+KL(P ∥ Q)H(X) + \mathrm{KL}(P\,\|\,Q) plus normalization (slide 56; Lecture 20 §5.1).

2.2 Scheme 2: posterior sampling (slide 57)

Draw z∼p(z∣x)z \sim p(z \mid x) at random, then send zz and xx as before. Why code zz with p(z)p(z) and not with p(z∣x)p(z \mid x)? Because the receiver does not have xx yet: it decodes zz first.

The expected cost is Ez∼p(z∣x)[−log⁡p(z)−log⁡p(x∣z)]=E[−log⁡p(x,z)]=−log⁡p(x)+H(p(z∣x)).\mathbb{E}_{z \sim p(z \mid x)}\big[-\log p(z) - \log p(x \mid z)\big] = \mathbb{E}\big[-\log p(x, z)\big] = -\log p(x) + H\big(p(z \mid x)\big).

Averaged over xx, this is H(X)+H(Z∣X)=H(X,Z)H(X) + H(Z \mid X) = H(X, Z). That is perfect if we wanted to send the pair (x,z)(x, z); but we only wanted xx, so we overpay by exactly the posterior entropy H(Z∣X)H(Z \mid X). It is even worse than max-mode, because p(x,z∗)≥p(x,z)p(x, z^*) \ge p(x, z) for every zz.

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 zz: choosing z∼p(z∣x)z \sim p(z \mid x) takes about −log⁡p(z∣x)-\log p(z \mid x) random bits. Now suppose those random bits were not random at all, but were other data we wanted to send anyway.

  • The receiver decodes zz, then xx.
  • Now it knows xx, so it can compute p(z∣x)p(z \mid x), and it knows which zz was chosen.
  • It can therefore reconstruct the bits that were used to choose zz.

Those −log⁡p(z∣x)-\log p(z \mid x) bits were transmitted for free: they rode inside zz. The net cost is −log⁡p(z)⏟send z−log⁡p(x∣z)⏟send x+log⁡p(z∣x)⏟bits we get back=−log⁡p(z) p(x∣z)p(z∣x)=−log⁡p(x).\underbrace{-\log p(z)}_{\text{send } z} \underbrace{-\log p(x \mid z)}_{\text{send } x} \underbrace{+\log p(z \mid x)}_{\text{bits we get back}} = -\log\frac{p(z)\,p(x \mid z)}{p(z \mid x)} = -\log p(x).

This holds for every zz, not just on average. Bits-back is optimal, and it never computes p(x)p(x); it needs only p(z)p(z), p(x∣z)p(x \mid z) and the ability to sample p(z∣x)p(z \mid x).

2.4 Approximate inference: the ELBO is a code length (slide 60)

For a VAE we cannot sample the true posterior, only the encoder q(z∣x)q(z \mid x). Run the same scheme with qq, and the net cost becomes ℓq(x)=Ez∼q[−log⁡p(z)−log⁡p(x∣z)+log⁡q(z∣x)]=−ELBO(x)=−log⁡p(x)+KL(q(z∣x) ∥ p(z∣x)).\ell_q(x) = \mathbb{E}_{z \sim q}\big[-\log p(z) - \log p(x \mid z) + \log q(z \mid x)\big] = -\mathrm{ELBO}(x) = -\log p(x) + \mathrm{KL}\big(q(z \mid x)\,\|\,p(z \mid x)\big).

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 Eq[−log⁡p(x,z)]−(bits given back)\mathbb{E}_q[-\log p(x, z)] - (\text{bits given back}).

  • Max-mode is bits-back with a one-hot qq, which has no entropy to give back.
  • Posterior sampling draws from p(z∣x)p(z \mid x) but gives nothing back.
  • Bits-back gives back H(q)H(q).

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 meansH(X)H(X) = bits-backmax-modeposterior samplingH(I∣X)H(I \mid X)
05.0476.0476.0471.000
85.2085.7626.0470.839
165.5335.8086.0470.514
325.9605.9996.0470.087
486.0426.0446.0470.006

Three things to notice:

  1. Posterior sampling always costs 6.047 bits, whatever the overlap. It costs H(X,I)=H(I)+H(X∣I)=1+5.047H(X, I) = H(I) + H(X \mid I) = 1 + 5.047, and H(X∣I)H(X \mid I) does not depend on where the components sit.
  2. 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 xx and costs nothing extra. In between it saves part of the bit.
  3. Bits-back is H(X)H(X) in every row.

With an approximate posterior at distance 16, the measured excess equals ExKL(q ∥ p(i∣x))\mathbb{E}_x\mathrm{KL}(q\,\|\,p(i \mid x)) to three decimals:

posterior usedexcess over H(X)H(X)
exact posterior0.000
tempered (temperature 2)0.108
qq = prior (ignores xx)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:

  • zz is the clean image, one of 921,600, with ShapeWorld’s exact prior.
  • xx is zz with every pixel flipped with probability ε\varepsilon.

The noise is independent per pixel, so the joint p(z,x)p(z, x) over all 921,600 latents is a 960×960960 \times 960 table per image, and the posterior is exact. Expected bits per image (200 images):

ε\varepsilonexact −log⁡2p(x)-\log_2 p(x)max-modeposterior samplingbits-back, mean-field qqH(z∣x)H(z \mid x)
0.0599.88+0.00+0.01+0.000.01
0.1154.20+0.04+0.07+0.020.07
0.2223.40+0.40+0.92+0.170.92
0.3266.47+2.04+4.86+0.494.86

The lesson: bits-back saves exactly what xx leaves uncertain about zz.

  • At ε=0.05\varepsilon = 0.05 the noisy image all but pins down the clean one, and all schemes are equivalent.
  • At ε=0.3\varepsilon = 0.3 the posterior holds 4.86 bits, and posterior sampling wastes all of them.

The “mean-field” qq 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 (ε=0.3\varepsilon = 0.3) into one message per scheme, with the ANS coder of §4. It then decoded every message back and checked it:

schemerealized bits per imageexcess
max-mode268.08+1.90
posterior sampling270.67+4.49 (= the fresh random bits spent per image)
bits-back, exact posterior266.18−0.00
bits-back, mean-field qq266.78+0.61

The exact −log⁡2p(x)-\log_2 p(x) 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 x1,x2,…x_1, x_2, \dots, the bits already produced for x1,…,xt−1x_1, \dots, x_{t-1} serve as the random source from which ztz_t is chosen.
  • When the receiver decodes xtx_t (in reverse order), it reconstructs those bits and continues decoding xt−1x_{t-1} 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:

  1. Order. “Decode zz 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.
  2. 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 bb maps x↦2x+bx \mapsto 2x + b, and the number grows by one bit. ANS generalizes this to non-uniform symbols. Here is the idea:

  • Decide that a fraction p(s)p(s) of all natural numbers “end in ss”.
  • Encode ss by moving from xx to the xx-th number that ends in ss. That number is about x/p(s)x / p(s), so the message grows by −log⁡2p(s)-\log_2 p(s) bits.

The slides’ example, p(a)=1/4p(a) = 1/4 and p(b)=3/4p(b) = 3/4, uses blocks of M=4M = 4 numbers: in each block, slot 0 belongs to aa and slots 1–3 to bb. Script 02, Part 1, reproduces the slides’ table:

xx0123456
push aa04812162024
push bb1235679

Encoding “bab” from 0 goes 0→1→4→60 \to 1 \to 4 \to 6.

rANS (“range ANS”, the version used in practice) does this for integer frequencies fsf_s summing to M=2precM = 2^{\text{prec}}, with cumulative starts csc_s: C(x,s)=⌊xfs⌋M+cs+(x mod fs),D(x′):  r=x′ mod M,  s:cs≤r<cs+fs,  x=fs⌊x′M⌋+r−cs.C(x, s) = \Big\lfloor \frac{x}{f_s} \Big\rfloor M + c_s + (x \bmod f_s), \qquad D(x') :\; r = x' \bmod M,\; s: c_s \le r < c_s + f_s,\; x = f_s \Big\lfloor \frac{x'}{M} \Big\rfloor + r - c_s.

Why DD inverts CC. Write x=qfs+r0x = q f_s + r_0 with 0≤r0<fs0 \le r_0 < f_s. Then C(x,s)=qM+cs+r0C(x, s) = qM + c_s + r_0, whose remainder mod MM is cs+r0c_s + r_0. That lies in ss‘s range, so DD finds ss, and ⌊x′/M⌋=q\lfloor x'/M \rfloor = q, so DD returns fsq+r0=xf_s q + r_0 = x.

Growth. C(x,s)≈xM/fs=x/p(s)C(x, s) \approx x M / f_s = x / p(s).

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 x=0x = 0 loses information: pushing aa maps 0 to 0. We start at x=1x = 1 (or, when streaming, at the bottom of the head’s range).
  • At small xx the integer rounding wastes up to about a bit; it does not accumulate. Over 10 to 10,000 random symbols, log⁡2x\log_2 x exceeded ∑−log⁡2p\sum -\log_2 p 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 [L,232L)[L, 2^{32} L) (here L=232L = 2^{32}, so a 64-bit head) and a stack of 32-bit words:

  • Before pushing ss: if the head is so large that CC would leave the window, move its low 32 bits onto the stack.
  • After popping: if the head drops below LL, 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 32⋅#words+log⁡2(head)−3232 \cdot \#\text{words} + \log_2(\text{head}) - 32. Flushing for transmission costs 32⋅#words+6432 \cdot \#\text{words} + 64 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):

sourceentropyHuffmanarithmetic codingrANS (flushed)
the slides’ p=(1/4,3/4)p = (1/4, 3/4)0.81131.00000.81120.8115
Lecture 20’s Huffman example (6 symbols)2.30762.35942.30802.3085
skewed (0.99,0.01)(0.99, 0.01)0.08081.00000.08410.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 f/2precf/2^{\text{prec}} with every f≥1f \ge 1, and rounding costs KL(p ∥ quantized)\mathrm{KL}(p\,\|\,\text{quantized}). For p=(0.9,0.05,0.03,0.015,0.004,0.001)p = (0.9, 0.05, 0.03, 0.015, 0.004, 0.001):

precmeasured excess (bits per symbol)
40.246
60.026
80.004
120.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 qq. Each pop reads a uniform slot; slot ranges are proportional to qq, so the symbols come out distributed as qq. Each pop consumes −log⁡2q(s)-\log_2 q(s) bits. Push the symbols back, and the stack is restored bit for bit. With q=(0.5,0.3,0.15,0.05)q = (0.5, 0.3, 0.15, 0.05) and 10,000 pops:

what the stack holdsfrequencies poppedmax ∣z∣\lvert z\rvertbits per poprestored
uniformly random bits0.500 0.305 0.144 0.0511.71.6435yes
a compressed message0.507 0.302 0.143 0.0471.91.6279yes

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 xx on top of an ANS stack:

  1. Pop zz with q(z∣x)q(z \mid x). This reads about −log⁡q(z∣x)-\log q(z \mid x) bits off the stack and uses them as the random choice of zz.
  2. Push xx with p(x∣z)p(x \mid z).
  3. Push zz with p(z)p(z).

To decode, mirror the steps:

  1. Pop zz with p(z)p(z).
  2. Pop xx with p(x∣z)p(x \mid z).
  3. Push zz back with q(z∣x)q(z \mid x). This restores the bits from step 1 of encoding.

The stack grows by −log⁡p(z)−log⁡p(x∣z)+log⁡q(z∣x)-\log p(z) - \log p(x \mid z) + \log q(z \mid x) 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 zz is continuous, so we discretize it. BB-ANS uses 2k2^k buckets of equal prior mass per dimension (the prior’s quantiles), so the prior codec is uniform: kk bits per dimension. The posterior codec gives each bucket its mass under q(z∣x)=N(μ,σ2)q(z \mid x) = \mathcal{N}(\mu, \sigma^2). The likelihood is evaluated at the bucket centers.

Why does the precision not matter? With bucket width δ\delta around zz:

  • P(bucket)≈p(z)δP(\text{bucket}) \approx p(z)\delta and Q(bucket)≈q(z∣x)δQ(\text{bucket}) \approx q(z \mid x)\delta.
  • The δ\delta cancels in log⁡Q−log⁡P\log Q - \log P (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 δ\delta at a price of log⁡(1/δ)\log(1/\delta) 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 k=8k = 8:

schemerealized bits per image
max-mode: zz = the posterior mean’s bucket, no bits back149.19
posterior sampling: z∼qz \sim q, no bits back158.61
BB-ANS67.31

Reference values:

referencebits per image
−ELBO (continuous zz)67.17 (reconstruction 30.30 + KL 36.87)
discrete −ELBO with genuinely random zz67.61
IWAE bound, K=1,000K = 1{,}00061.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 16×8=12816 \times 8 = 128 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:

kkBB-ANSwithout bits backinitial bits (1st image)
2138.02148.6813
476.28107.3928
668.70128.1857
867.67158.6887
1267.50222.61159
1674.29 (68.80 with 32-bit qq)293.77213

Reading the table:

  • Without bits back, every extra bit of precision costs 16 bits per image (one per latent dimension) from k=6k = 6 on.
  • With bits back, the cost is flat from k=6k = 6, as the cancellation argument predicts.
  • Coarse buckets (k=2,4k = 2, 4) 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 k=8k = 8). In one message of NN images that is a one-time cost:

images in the messagebits per image, including the initial bits
1151.84
1083.16
10069.37
1,00067.40 (net 67.31)

5.4 Are the bits clean? (slide 70)

Bits-back assumes the popped bits are uniformly random, so that z∼q(z∣x)z \sim q(z \mid x). They are not quite random: they are compressed images, coded with the model’s p(x∣z)p(x \mid z) and p(z)p(z).

  • If the model were perfect, the compressed data would be perfectly random bits.
  • Otherwise, the popped zz follows a slightly different distribution. Townsend et al. trace the effect to the mismatch between the aggregate posterior Exq(z∣x)\mathbb{E}_x q(z \mid x) and the prior p(z)p(z). The ELBO contains this term, but it is never exactly zero in practice.

Measured:

quantitypopped from the messagefresh samples
−log⁡2Q(z∣x)-\log_2 Q(z \mid x), bits per image91.2691.19
BB-ANS bits on the first 200 images vs discrete −ELBO67.9667.61

The bits are clean enough that the difference is within noise. Whatever zz 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: p(zL) p(zL−1∣zL)⋯p(x∣z1),q(z1∣x) q(z2∣z1)⋯q(zL∣zL−1).p(z_L)\,p(z_{L-1} \mid z_L) \cdots p(x \mid z_1), \qquad q(z_1 \mid x)\,q(z_2 \mid z_1) \cdots q(z_L \mid z_{L-1}).

BB-ANS treats (z1,…,zL)(z_1, \dots, z_L) as one big latent:

  1. Pop z1,…,zLz_1, \dots, z_L, all of them.
  2. Push xx, then z1,…,zL−1z_1, \dots, z_{L-1}, then zLz_L.

Before anything is pushed it must have popped ∑l−log⁡q(zl∣⋅)\sum_l -\log q(z_l \mid \cdot) bits. For the first data point, all of them are initial bits.

Bit-Swap interleaves (slides 73–74):

  1. Pop z1z_1 with q(z1∣x)q(z_1 \mid x), then push xx with p(x∣z1)p(x \mid z_1).
  2. Pop z2z_2 with q(z2∣z1)q(z_2 \mid z_1), then push z1z_1 with p(z1∣z2)p(z_1 \mid z_2).
  3. Continue the same way up the hierarchy.
  4. Finally push zLz_L with p(zL)p(z_L).

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: q(z2∣z1)q(z_2 \mid z_1) must not need xx, because xx 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 282^8 buckets placed at that level’s own scale. 200 test images:

levels−ELBOKL per level (bottom … top)BB-ANS bitsBit-Swap bitsBB-ANS initial bitsBit-Swap initial bits
262.5326.2 / 10.562.2562.99199169
365.5120.5 / 9.5 / 7.765.4965.41301179
466.5217.0 / 9.4 / 8.3 / 6.566.5966.17387186

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”):

  1. Without free bits, the upper levels collapsed onto their priors. They then carry no information but still cost initial bits.
  2. With N(0,1)\mathcal{N}(0, 1) 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 p(x)=pZ(f(x)) ∣det⁡Jf(x)∣p(x) = p_Z(f(x))\,\lvert\det J_f(x)\rvert. Continuous data must be discretized: tile space with cubes of side δ\delta and code the cube B(x)B(x) with probability P(B(x))≈p(x)δdP(B(x)) \approx p(x)\delta^d. The target is ℓ(x)≈−log⁡p(x)−dlog⁡δ.\ell(x) \approx -\log p(x) - d\log\delta.

Enumerating cubes is exponential in dd, so we must exploit the flow’s structure, as we did for AR models (Lecture 20) and VAEs (§5).

7.2 Naive: code z=f(x)z = f(x) (slide 80)

Why not send z=f(x)z = f(x) on a grid with the prior? A well-trained flow makes z∼N(0,I)z \sim \mathcal{N}(0, I), so coding zz with the prior is coding pure noise: it gains nothing. The real problem is volume. The grid cells of zz are not images of the cells of xx, so the code is either lossy or must use a much finer zz-grid.

Script 04 uses a known 2-D flow with a full Jacobian, ToyFlow2D. Its data are on a grid of 2−102^{-10}, and the exact code length is 24.816 bits per point:

zz-gridbits per pointvs exactdecoded exactly
2−102^{-10}24.090−0.72758.6%
2−122^{-12}28.090+3.27398.1%
2−142^{-14}32.090+7.273100.0%

At the same spacing the code is “too cheap” by exactly Elog⁡∣det⁡J∣\mathbb{E}\log\lvert\det J\rvert, and lossy. Making it lossless costs 7 bits per point. The missing piece is the log⁡∣det⁡J∣\log\lvert\det J\rvert 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: q(z∣x)=N(f(x), σ2JJ⊤),p(x∣z)=N(f−1(z), σ2I),p(z)=N(0,I),q(z \mid x) = \mathcal{N}\big(f(x),\, \sigma^2 J J^\top\big), \qquad p(x \mid z) = \mathcal{N}\big(f^{-1}(z),\, \sigma^2 I\big), \qquad p(z) = \mathcal{N}(0, I), with J=Jf(x)J = J_f(x) and small σ\sigma, all discretized on fine grids. The encoder is “the image under the linearized flow of a small Gaussian around xx”.

Derivation (first order in σ\sigma). Write z=f(x)+σJϵz = f(x) + \sigma J\epsilon with ϵ∼N(0,I)\epsilon \sim \mathcal{N}(0, I). Then f−1(z)≈x+σϵf^{-1}(z) \approx x + \sigma\epsilon. The three terms of the bits-back cost (natural log; the grid terms log⁡δ\log\delta cancel for zz as in §5.2) are:

  • Push xx: −log⁡p(x∣z)≈d2log⁡(2πσ2)+12∥ϵ∥2−dlog⁡δx-\log p(x \mid z) \approx \frac{d}{2}\log(2\pi\sigma^2) + \frac{1}{2}\lVert\epsilon\rVert^2 - d\log\delta_x.
  • Push zz: −log⁡p(z)≈−log⁡pZ(f(x))-\log p(z) \approx -\log p_Z(f(x)).
  • Bits back: +log⁡q(z∣x)=−d2log⁡(2πσ2)−log⁡∣det⁡J∣−12∥ϵ∥2+\log q(z \mid x) = -\frac{d}{2}\log(2\pi\sigma^2) - \log\lvert\det J\rvert - \frac{1}{2}\lVert\epsilon\rVert^2.

The Gaussian terms cancel, leaving −log⁡pZ(f(x))−log⁡∣det⁡J∣−dlog⁡δx=−log⁡(p(x)δxd).-\log p_Z(f(x)) - \log\lvert\det J\rvert - d\log\delta_x = -\log\big(p(x)\delta_x^d\big).

The Jacobian enters through the bits we get back: qq is wider where the flow stretches space.

Measured. 2,000 points, zz-grid 2−162^{-16}, the unbounded ANS at prec 40:

σ\sigmaexcess (bits per point)sd of a point’s excessinitial bits (1st point)
2−22^{-2}+0.20760.9534
2−42^{-4}+0.01470.1931
2−62^{-6}+0.00050.0427
2−82^{-8}+0.00010.0124
2−102^{-10}+0.00480.1119
2−122^{-12}+0.42990.9815

The trade-off in σ\sigma:

  • Too large a σ\sigma breaks the linearization.
  • Too small a σ\sigma (comparable to the data grid 2−102^{-10}) breaks the density approximation of p(x∣z)p(x \mid z).
  • In between, the code matches the flow’s likelihood to 10−410^{-4} bits.

Two caveats from the slides:

  1. Initial bits. The first point needs a few dozen, about 2log⁡2(σ/δz)+log⁡2∣det⁡J∣+42\log_2(\sigma/\delta_z) + \log_2\lvert\det J\rvert + 4 per point.
  2. 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 JJ costs O(d3)O(d^3), which is fine for d=2d = 2 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 x=y+ux = y + u, the discrete value plus dequantization noise uu (Lecture 6). Coding uu to high precision costs 16–32 extra bits per dimension, so give those bits back:

  1. Pop uu with a noise distribution q(u∣y)q(u \mid y).
  2. Code y+uy + u with the flow.
  3. On decoding, recover yy and push uu back.

The net cost is Eq[−log⁡p(y+u)+log⁡q(u∣y)]\mathbb{E}_q[-\log p(y + u) + \log q(u \mid y)], exactly the (variational) dequantization bound of Lecture 6, now as a file size.

Measured (Part 3). Cells of side 0.5, i.e. y=⌊x/0.5⌋y = \lfloor x/0.5 \rfloor:

bits per point
exact −log⁡2P(y)-\log_2 P(y)6.873
uniform-dequantization bound6.908 (Jensen gap 0.036)
uniform uu, bits-back (realized)6.911
exact posterior q(u∣y)∝p(yΔ+u)q(u \mid y) \propto p(y\Delta + u), bits-back6.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)

kindexamplestrengthweakness
Static: one model for all textsASCII, Morse, a generic Huffman codefastignores the data
Dynamic: a model fitted to this textHuffman fitted to the filefits the dataneeds a first pass, and the model must be sent
Adaptive: a model learned while codingLZW, adaptive context modelsnothing sent in advance; better as it learnsdecoding 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 TT back to the previous occurrence of a string ww is 1/p(w)1/p(w). This is Kac’s lemma.
  • An integer TT can be named in about log⁡2T\log_2 T bits.
  • So naming the previous occurrence of a long string costs about −log⁡2p(w)-\log_2 p(w) bits.
  • Over a long time this approaches HH 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 H=2.0547H = 2.0547:

symbolsLZ77, window 2122^{12}LZ77, window 2162^{16}zliblzmaadaptive order 1
1,0006.1207.1403.0803.9362.175
10,0004.0584.6732.7742.7232.062
100,0003.8034.1132.6082.4632.052
1,000,0003.7874.0482.5512.3702.053

What the table shows:

  • The adaptive order-1 model is the right model class and sits at HH 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 HH by entropy-coding their output; lzma is 15% above HH after a million symbols. LZ is universal, but slow.

Kac’s lemma, checked on the same source (strings of length kk):

kkmean of gap × p(w)p(w)mean log⁡2\log_2 gapmean −log⁡2p(w)-\log_2 p(w)log⁡2\log_2 gap / kk
11.0002.342.912.336
40.9998.249.062.059
80.84715.0516.171.881

Kac’s lemma holds exactly where strings recur often. For rare strings, the gap is roughly geometric and Elog⁡2T≈−log⁡2p(w)−0.83\mathbb{E}\log_2 T \approx -\log_2 p(w) - 0.83 (Jensen plus Euler’s constant). Per symbol, log⁡2T/k\log_2 T / k approaches HH by k=4k = 4. 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:

methodbits per caption
static 8-bit587.7
dynamic Huffman294.1
best adaptive context model (k=4k = 4)30.8
LZ77 (ours)67.3
zlib32.0
lzma24.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:

  1. The encoder draws K≈2KL(q ∥ p)K \approx 2^{\mathrm{KL}(q\,\|\,p)} samples z1,…,zKz_1, \dots, z_K from the prior, with a random-number generator whose seed the decoder shares.
  2. It picks one with probability proportional to q(zk∣x)/p(zk)q(z_k \mid x)/p(z_k), and sends its index: log⁡2K≈KL\log_2 K \approx \mathrm{KL} bits.
  3. The decoder regenerates the same KK samples and reads off zz.

The chosen zz is approximately a sample from qq. The cost of zz is the KL term of the ELBO, without any stack or initial bits. The price is 2KL2^{\mathrm{KL}} samples, which forces the latent to be split into blocks of a few bits of KL each.


10. Summary

  1. Latent-variable models are built from easy pieces but have marginals no coder can enumerate. Sending the latent along costs H(Z∣X)H(Z \mid X) extra (posterior sampling) or somewhat less (max-mode). Bits-back recovers the bits spent choosing zz and costs exactly −log⁡2p(x)-\log_2 p(x), or the negative ELBO with an approximate posterior: the VAE objective is a file size. On noisy ShapeWorld bits-back hit the exact −log⁡2p(x)-\log_2 p(x) to 0.00 bits; the schemes without bits back lost up to 4.9 bits.
  2. ANS treats a message as a natural number that grows by 1/p(s)1/p(s) 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.
  3. BB-ANS: pop zz with qq, push xx and zz. 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.
  4. Bit-Swap interleaves the levels of a Markov hierarchy: same length, initial bits that do not grow with depth (169–186 vs 199–387).
  5. Flows: coding z=f(x)z = f(x) misses the volume term. Local bits-back with a linearized Gaussian VAE around the flow matches its likelihood to 10−410^{-4} bits at a good σ\sigma. Bits-back on dequantization noise turns the dequantization bound into a file size, and the exact noise posterior gives the exact discrete likelihood.
  6. 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

  1. “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 k=8k = 8.
  2. Using a queue-based coder for bits-back. The bits used to choose zz must be the most recently written ones, and they must be returned before older data is read. That needs a stack.
  3. Computing qq or pp 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.
  4. 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).
  5. 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).
  6. Forgetting the initial bits for short messages: 87 bits on a single 67-bit image.
  7. Coding a flow’s zz on a grid as if it were the data. It is lossy or wasteful, because volume matters.
  8. 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 qq costs −log⁡p(x)+KL(q(z∣x) ∥ p(z∣x))-\log p(x) + \mathrm{KL}(q(z \mid x)\,\|\,p(z \mid x)) on average, and exactly −log⁡p(x)-\log p(x) for every zz when qq is the true posterior.

Answer

The net cost for a given zz is −log⁡p(z)−log⁡p(x∣z)+log⁡q(z∣x)=−log⁡p(x,z)+log⁡q(z∣x)-\log p(z) - \log p(x \mid z) + \log q(z \mid x) = -\log p(x, z) + \log q(z \mid x). With p(x,z)=p(x)p(z∣x)p(x, z) = p(x)p(z \mid x) this is −log⁡p(x)+log⁡q(z∣x)p(z∣x)-\log p(x) + \log\frac{q(z \mid x)}{p(z \mid x)}. Taking the expectation over z∼qz \sim q gives −log⁡p(x)+KL(q ∥ p(z∣x))-\log p(x) + \mathrm{KL}(q\,\|\,p(z \mid x)). If q=p(z∣x)q = p(z \mid x) the log-ratio is 0 for every zz.

Exercise 2 (posterior sampling vs max-mode — derivation). Show that posterior sampling costs H(X)+H(Z∣X)H(X) + H(Z \mid X) on average, that max-mode costs no more, and that in the 1-D example of §2.5 posterior sampling costs H(I)+H(X∣I)H(I) + H(X \mid I) regardless of the distance between the means.

Answer

Posterior sampling costs ExEz∼p(z∣x)[−log⁡p(x,z)]=H(X,Z)=H(X)+H(Z∣X)\mathbb{E}_{x}\mathbb{E}_{z \sim p(z \mid x)}[-\log p(x, z)] = H(X, Z) = H(X) + H(Z \mid X). Max-mode uses z∗z^* with p(x,z∗)≥p(x,z)p(x, z^*) \ge p(x, z) for all zz, so −log⁡p(x,z∗)≤Ez∼p(z∣x)[−log⁡p(x,z)]-\log p(x, z^*) \le \mathbb{E}_{z \sim p(z \mid x)}[-\log p(x, z)].

By the chain rule the other way, H(X,I)=H(I)+H(X∣I)H(X, I) = H(I) + H(X \mid I). Here H(I)=1H(I) = 1, and H(X∣I)H(X \mid I) 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 D(C(x,s))=(s,x)D(C(x, s)) = (s, x) for the rANS maps of §4.1, and that C(x,s)≥xM/fs−MC(x, s) \ge x M / f_s - M. Conclude that log⁡2C(x,s)≥log⁡2x−log⁡2p(s)−O(M/x)\log_2 C(x, s) \ge \log_2 x - \log_2 p(s) - O(M/x).

Answer

Invertibility is shown in §4.1. For the bound: C(x,s)≥⌊x/fs⌋M≥(x/fs−1)M=xM/fs−MC(x, s) \ge \lfloor x/f_s \rfloor M \ge (x/f_s - 1)M = xM/f_s - M. So C≥xp(s)(1−p(s)M/x)C \ge \frac{x}{p(s)}(1 - p(s)M/x) with p(s)=fs/Mp(s) = f_s/M. Taking log⁡2\log_2 gives log⁡2C≥log⁡2x−log⁡2p(s)+log⁡2(1−fs/x)\log_2 C \ge \log_2 x - \log_2 p(s) + \log_2(1 - f_s/x), and the last term is O(fs/x)=O(M/x)O(f_s/x) = O(M/x). Rounding costs vanish once x≫Mx \gg M, which is why streaming coders keep the head far above MM (§4.3: prec 32 with a 32-bit margin loses a little).

Exercise 4 (why a stack — derivation). BB-ANS encodes x1,x2x_1, x_2: pop z1z_1, push x1,z1x_1, z_1, pop z2z_2, push x2,z2x_2, z_2. Write the decoder’s operations in order, and explain why a first-in-first-out coder could not decode z2z_2 before x1x_1‘s data.

Answer

The decoder works in reverse:

  1. Pop z2z_2 with pp, pop x2x_2 with p(⋅∣z2)p(\cdot \mid z_2), push z2z_2 with q(⋅∣x2)q(\cdot \mid x_2). This restores the bits from which z2z_2 was popped, i.e. part of x1x_1‘s code.
  2. Pop z1z_1, pop x1x_1, push z1z_1 back (the initial bits).

The decoder must first read what the encoder wrote last (z2z_2), and the bits it puts back must be read next. In a queue, the decoder reads first what the encoder wrote first (x1x_1‘s data). But x1x_1‘s code was partly “consumed” by choosing z2z_2, and can only be reconstructed after x2x_2 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 a1=−log⁡q(z1∣x)a_1 = -\log q(z_1 \mid x), a2=−log⁡q(z2∣z1)a_2 = -\log q(z_2 \mid z_1) and bx=−log⁡p(x∣z1)b_x = -\log p(x \mid z_1).

Answer

BB-ANS pops a1a_1 then a2a_2 before any push, so it needs a1+a2a_1 + a_2 initial bits.

Bit-Swap proceeds:

  1. Pop a1a_1: the deficit is a1a_1.
  2. Push bxb_x: the deficit becomes a1−bxa_1 - b_x.
  3. Pop a2a_2: the deficit becomes a1−bx+a2a_1 - b_x + a_2.

It needs max⁡(a1, a1−bx+a2)\max(a_1,\, a_1 - b_x + a_2) initial bits. When bx≥a2b_x \ge a_2 (the data’s bits refill the stack at least as fast as the next level drains it), Bit-Swap needs only a1a_1, 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 log⁡q(z∣x)−log⁡p(x∣z)\log q(z \mid x) - \log p(x \mid z) contributes −log⁡∣det⁡J∣-\log\lvert\det J\rvert (plus grid terms) when z=f(x)+σJϵz = f(x) + \sigma J\epsilon.

Answer

log⁡N(z;f(x),σ2JJ⊤)=−d2log⁡2πσ2−12log⁡det⁡(JJ⊤)−12ϵ⊤ϵ\log \mathcal{N}(z; f(x), \sigma^2 JJ^\top) = -\frac{d}{2}\log 2\pi\sigma^2 - \frac{1}{2}\log\det(JJ^\top) - \frac{1}{2}\epsilon^\top\epsilon, and 12log⁡det⁡(JJ⊤)=log⁡∣det⁡J∣\frac{1}{2}\log\det(JJ^\top) = \log\lvert\det J\rvert.

Since f−1(z)=x+σJ−1Jϵ+O(σ2)=x+σϵ+O(σ2)f^{-1}(z) = x + \sigma J^{-1}J\epsilon + O(\sigma^2) = x + \sigma\epsilon + O(\sigma^2), we get log⁡N(x;f−1(z),σ2I)=−d2log⁡2πσ2−12ϵ⊤ϵ+O(σ)\log \mathcal{N}(x; f^{-1}(z), \sigma^2 I) = -\frac{d}{2}\log 2\pi\sigma^2 - \frac{1}{2}\epsilon^\top\epsilon + O(\sigma).

The difference is −log⁡∣det⁡J∣+O(σ)-\log\lvert\det J\rvert + O(\sigma). Adding −log⁡pZ(z)=−log⁡pZ(f(x))+O(σ)-\log p_Z(z) = -\log p_Z(f(x)) + O(\sigma) gives −log⁡p(x)+O(σ)-\log p(x) + O(\sigma). The grid terms add −dlog⁡δx-d\log\delta_x for the pushed xx; for zz, the δz\delta_z 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 P(X=a)=pP(X = a) = p, show that the gap between consecutive occurrences of aa is geometric with mean 1/p1/p. Estimate Elog⁡2T\mathbb{E}\log_2 T for small pp.

Answer

After an occurrence, each later position is aa independently with probability pp, so P(T=t)=(1−p)t−1pP(T = t) = (1 - p)^{t-1}p, with mean 1/p1/p. For small pp, pTpT is approximately exponential with mean 1, and Eln⁡(pT)≈−γ\mathbb{E}\ln(pT) \approx -\gamma (Euler’s constant 0.577). So Elog⁡2T≈−log⁡2p−γ/ln⁡2=−log⁡2p−0.83\mathbb{E}\log_2 T \approx -\log_2 p - \gamma/\ln 2 = -\log_2 p - 0.83. Script 05’s k=4k = 4 row shows 9.06−8.24=0.829.06 - 8.24 = 0.82.

Exercise 8 (coding). Change script 01, Part 3 to ε=0.4\varepsilon = 0.4. Predict the excess of posterior sampling and of max-mode from Part 2’s trend, then run it.

Answer

(Run it.) H(z∣x)H(z \mid x) 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 −log⁡2p(x)-\log_2 p(x). On 100 images at ε=0.4\varepsilon = 0.4 (exact expectations): −log⁡2p(x)=284.10-\log_2 p(x) = 284.10, posterior sampling +13.08 (= H(z∣x)H(z \mid x)), 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 −log⁡2(255/256)≈0.006-\log_2(255/256) \approx 0.006 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_rans code — the rans64 layout used in bitsback.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).
← 返回课程目录