One second of 24 kHz sound is 24,000 numbers. EnCodec turns it into 600 small integers, 64 times fewer bits, and a language model can predict those integers like words.
Pick a codec, then drag Codebooks kept. Watch one second of sound become a grid of tokens, and watch the bitrate move. Then we build, piece by piece, the encoder, the codebook, the residual levels and the critic that make the grid.
You need a little Python and the idea that a language model predicts the next token. We build the rest from zero.
Numbers from the papers: Zeghidour et al., SoundStream (2021); Défossez et al., EnCodec (2022); Kumar et al., DAC (2023); Défossez et al., Moshi and its codec Mimi (2024).
Frame rates, codebook sizes and codebook counts come from each paper (SoundStream Sec. III; EnCodec Sec. 3.2; DAC Table 1; Moshi Sec. 3.3). The waveform and the token values are illustrative. Compression is against 16-bit PCM at the codec's sample rate.
Chapter 0
See why a language model cannot eat raw audio, and what a codec hands it instead
You want a model that talks. You already have a recipe that works for text: a transformer reads a sequence of tokens and predicts the next one. Text arrives in tokens. Sound does not.
A microphone gives you a waveform: a list of air-pressure readings, called samples, taken thousands of times per second. At 24 kHz that is 24,000 real numbers for every second. Ten seconds of speech is 240,000 steps. The same ten seconds of text is about 30 to 40 tokens (Moshi paper, Sec. 3.4).
Predicting 240,000 steps one by one is slow, and each step carries almost no meaning. A neural audio codec is a learned compressor that turns the waveform into a short grid of small integers, and turns the grid back into sound. Those integers are the audio tokens. Drag the duration and compare the sequence lengths.
Each bar is the number of steps for the same clip, on a log scale: every grid line is ten times the last. Drag the duration.
Raw is 24,000 samples per second. EnCodec at 6 kbps is 75 frames times 8 codebooks; Mimi is 12.5 frames times 8 codebooks, all laid end to end. Text uses the Moshi paper's 3 to 4 tokens per second (we draw 4).
With numbers: ten seconds at 24 kHz is 24,000 × 10 = 240,000 samples. EnCodec at 6 kbps makes 75 × 8 × 10 = 6,000 tokens. Mimi makes 12.5 × 8 × 10 = 1,000. The codec cuts the sequence 40 to 240 times before the model sees it.
The failure to avoid: a codec that compresses well but sounds dull or robotic. The symptom is a listener who hears muffled speech. Measure it with a listening test (the papers use MUSHRA, where people rate clips from 0 to 100). The fix, in Chapter 6, is a second network that judges realism.
The hero's Codebooks kept slider is Chapters 4 and 5. Its grid is Chapter 2. Its frame count is Chapter 1.
Chapter 1
Stack strided convolutions until one vector stands for 320 samples
A codec is an autoencoder: an encoder network shrinks the input, and a decoder network rebuilds it. Training asks the rebuild to match the input. In SoundStream, EnCodec and DAC, both halves are 1-D convolutions.
The squeeze comes from the stride: a convolution with stride 2 slides two samples at a time, so it outputs half as many steps. Stack four such blocks with strides 2, 4, 5 and 8, and each output step covers 2 × 4 × 5 × 8 = 320 input samples. Each output step is a latent vector: a list of numbers that sums up 320 samples. The decoder mirrors the encoder with transposed convolutions and the same strides in reverse.
How many latent vectors per second? Call the sample rate fs and the product of the strides M. Call the output f, the frame rate.
f equals f-s divided by M.
Multiply the strides to get M. Divide the sample rate f-s by M. The answer f is how many latent vectors the encoder makes each second.
EnCodec at 24 kHz: f-s is 24,000 and M is 2 × 4 × 5 × 8 = 320, so f = 24,000 / 320 = 75 frames per second. DAC: 44,100 / 512 = 86.1. Each latent vector covers 13.3 ms of sound in EnCodec.
Each row is one encoder block. The bar shows how many steps per second leave that block. Pick a codec's encoder.
Strides from EnCodec Sec. 3.1, the DAC model section and Moshi Sec. 3.3.1 (Mimi's last stride-2 layer comes after a transformer). Bar lengths use a log scale.
Why not stride 320 in one layer? One big jump throws away detail before the network can summarise it. Small strides let each block mix nearby samples first.
The failure: a frame rate that is too low for the bits you give it. The symptom: smeared consonants and lost transients. Measure it by plotting quality against frame rate at a fixed bitrate. Mimi goes as low as 12.5 Hz and adds transformer layers to the encoder and decoder to cope.
Chapter 2
Replace each latent vector with the closest vector from a fixed list, and keep only its index
Rounding 3.7 to 4 turns a real number into a whole number. Vector quantization (VQ) does the same for a vector. It rounds to a learned list of allowed vectors instead of to the integers.
The list is the codebook: N vectors, each called an entry or code. To quantize a latent vector, find the closest entry. The token is that entry's index, an integer from 0 to N − 1. The decoder looks the index up and gets the entry back. Drag the latent below.
Teal dots are the 8 codebook entries. The warm dot is the latent. Drag it anywhere and watch which entry wins.
Two dimensions so you can see it; Mimi’s latents have 512. The 8 entries are illustrative; codecs use 1,024 or 2,048 per codebook.
Call the latent vector z. Call the codebook entries c0 to cN−1. The token is k.
k equals the j that makes the squared distance between z and c-j smallest.
For each entry c-j, subtract it from z, square each difference and add them up. The index with the smallest total is the token k. Send k; the decoder uses c-k in place of z.
With made-up numbers: z = (0.62, 0.31) and four entries (0, 0), (0.5, 0.5), (1, 0), (0.5, 0). The squared distances are 0.4805, 0.0505, 0.2405 and 0.1105. The smallest is 0.0505, so k = 1. The leftover 0.0505 is the quantization error.
The token needs log2 N bits: 1,024 entries is 10 bits, 2,048 is 11. That is why codebook sizes are powers of two.
The failure: a codebook too small for the data. The symptom is a rebuild that sounds grainy or loses timbre. Measure the average quantization error per frame. The fix is more entries, or the trick in Chapter 4.
Chapter 3
Pass gradients through a snap, pull entries toward the data, and revive entries that die
Training needs a gradient from the loss back to the encoder. The snap has none: move z a little and k stays the same, so the output does not change. The fix comes from VQ-VAE (van den Oord et al., 2017). It is the straight-through estimator: in the backward pass, pretend the snap was the identity and copy the decoder's gradient straight to z.
The codebook still has to learn. Two extra loss terms do it. Call the chosen entry ck. Write sg[·] for "stop gradient": treat the value inside as a constant.
L-V-Q equals the squared distance from stop-gradient z to c-k, plus beta times the squared distance from z to stop-gradient c-k.
Pull the chosen entry c-k toward the latent z. Also pull z toward c-k, more gently, by beta. The two meet in the middle, so the snap costs less each step.
With the Chapter 2 numbers: the squared distance is 0.0505. The codebook term is 0.0505 and the commitment term is 0.25 × 0.0505 = 0.0126. L-V-Q = 0.0631. The two terms have the same value but send their gradients to different places.
SoundStream and EnCodec replace the codebook term with an exponential moving average: each entry drifts toward the mean of the latents it wins. DAC keeps the two loss terms.
Now the classic failure, codebook collapse. Some entries start far from the data, win nothing, and never move. They are dead codes. A 1,024-entry codebook that uses 200 entries carries log2 200 = 7.6 bits, not 10. Press Train with and without the restart.
Warm dots are latents. Teal rings are 16 entries that start in one corner. Red rings have won nothing. Train, then turn on the restart and train again.
An illustrative toy: moving-average updates on 2-D points. The restart rule follows SoundStream Sec. III-C: an entry that wins too little for several batches moves to a random latent from the current batch.
Measure collapse by counting how many entries win at least once on a test set, or by the entropy of the usage. DAC fixes it differently: it looks entries up in an 8 or 32 number space and normalises the vectors to length 1. Its paper shows near-full use without restarts.
Chapter 4
Quantize, then quantize what is left, with a new small codebook each time
SoundStream asks for 6,000 bits per second at 75 frames. That is 80 bits per frame. One codebook with 80-bit tokens needs 280 entries, about 1.2 × 1024 vectors. No memory holds that.
Residual vector quantization (RVQ) splits the 80 bits into 8 codebooks of 10 bits. The first codebook quantizes the latent. The residual is what it missed: the latent minus the chosen entry. The second codebook quantizes that residual, the third quantizes the next residual, and so on. Eight codebooks of 1,024 entries store 8,192 vectors, yet they can name 1,0248 = 280 different sums.
Call the residual after level i ri, and start with r0 = z. Call codebook number i C(i) and its chosen entry c(i).
r-i equals r-i-minus-one minus c-super-i.
At level i, snap the incoming residual r-i-minus-one to its nearest entry c-super-i in codebook i. Write down that entry's index. Subtract the entry; what is left is r-i, the input to level i plus one.
With made-up 1-D codebooks: z = 0.737. Level 1 entries are −1, −0.5, 0, 0.5, 1; it picks 0.5, so r-1 = 0.237. Level 2 entries step by 0.1 up to ±0.2; it picks 0.2, so r-2 = 0.037. Level 3 steps by 0.02; it picks 0.04, so r-3 = −0.003.
The decoder adds the chosen entries back up. Call the rebuilt latent ẑ and the number of levels Nq.
z-hat equals the sum, over i from one to N-q, of c-super-i.
Look up the N-q indices, one per codebook, and add the entries. The sum z-hat is off from z by exactly the last residual.
From the example: 0.5 + 0.2 + 0.04 = 0.74, and z was 0.737. The errors after 1, 2 and 3 levels are 0.237, 0.037 and 0.003. Each level cuts the error, so the first level is coarse and the last is fine.
Left: the latent (warm) and the sum of chosen entries (teal path). Right: the residual after the last level, zoomed, with the next codebook. Drag the latent on the left; slide the levels.
An illustrative toy: each level is a 4 by 4 grid, a quarter the size of the last. So each level costs 4 bits and cuts the error about 4 times. Learned codebooks are not grids, but they shrink the same way.
The failure: training with all levels always on. The model then spreads detail over every level, and dropping the last few levels sounds broken. Chapter 5 shows the fix, quantizer dropout.
Chapter 5
Multiply frames, codebooks and bits, then pick the number of codebooks after training
A streaming call has a budget: maybe 6,000 bits per second. How many bits does a codec spend? Count them per second. Call the frame rate f, the number of codebooks kept Nq and the entries per codebook N. The bitrate is R.
R equals f times N-q times log base two of N.
Each second has f frames. Each frame has N-q tokens. Each token costs log base two of N bits. Multiply the three to get R.
EnCodec at 24 kHz: f = 75, N-q = 8, N = 1,024. R = 75 × 8 × 10 = 6,000 bits per second, or 6 kbps. Mimi: 12.5 × 8 × 11 = 1,100 bits per second.
How much smaller is that than plain audio? Uncompressed 16-bit audio at 24 kHz costs 24,000 × 16 = 384,000 bits per second. Divide by R: 384,000 / 6,000 = 64 times smaller for EnCodec, and 384,000 / 1,100 = 349 times for Mimi. DAC compresses 44.1 kHz audio: 705,600 / 7,752 = 91 times, the "90x" in its abstract.
Pick a frame rate and a codebook size, then drag the codebooks. The marker moves on a log scale past real codecs.
Reference points from the papers: Mimi 1.1 kbps, MusicGen's EnCodec 2.2 kbps (4 codebooks of 2,048 at 50 Hz), EnCodec 6 and 24 kbps, DAC 7.75 kbps, and 16-bit PCM at 24 kHz.
RVQ gives a free dial: keep fewer codebooks and the bitrate falls in steps. EnCodec uses 2, 4, 8, 16 or 32 codebooks for 1.5, 3, 6, 12 or 24 kbps. One model serves all of them because of quantizer dropout (SoundStream). For each training example, pick a random count nq from 1 to Nq. Use only the first nq levels. The model learns to put the most useful detail in the first levels.
The failure: dropout on every example costs quality at full bitrate. DAC applies it with probability 0.5 instead, and reports that this keeps low-bitrate quality while closing the gap at full bitrate.
Chapter 6
Add a critic that rewards sharp detail, because squared error rewards blur
Train the codec only to make the rebuild close to the input, and it sounds muffled. The reason is the squared error. When the decoder is unsure where a harmonic sits, the safest guess is a smear across every likely place. The smear scores well on average and sounds dull.
The fix is a discriminator: a second network that sees real clips and rebuilt clips and tries to tell them apart. Training pushes the codec to fool it. A smear is easy to spot, so the codec learns to commit to sharp detail. This pairing is a GAN (generative adversarial network).
Call the rebuild error Lrec and the fooling loss Ladv. A weight λ sets the balance. The codec minimises LG.
L-G equals L-rec plus lambda times L-adv.
Score the rebuild twice: once for closeness, L-rec, and once for realism, L-adv. Weight realism by lambda and add. The codec lowers the sum, so it must stay close and also sound real.
With made-up numbers: L-rec = 0.40, L-adv = 0.90 and lambda = 0.1 give L-G = 0.40 + 0.09 = 0.49. A blurrier rebuild might drop L-rec to 0.38 but raise L-adv to 1.50, so L-G = 0.53. The critic makes blur cost more.
Top: the true spectrogram (time across, pitch up). Bottom: a rebuild. Slide toward the critic and watch the harmonics sharpen while squared error rises.
An illustrative toy. The squared-error rebuild is the true spectrogram blurred. The critic's rebuild is sharp, with some harmonics one row off. The slider mixes the two; the numbers are computed live.
Real codecs use several discriminators that look at different views. SoundStream uses a waveform critic at three resolutions and an STFT critic. EnCodec uses a multi-scale STFT discriminator on five window sizes, from 2,048 down to 128. DAC adds multi-period and band-split critics. Mimi goes further: it drops the reconstruction loss and keeps only the adversarial and feature-matching losses, and listeners rated it higher.
The failure: an unstable GAN. The symptom is losses that swing or a critic that wins outright. EnCodec's loss balancer scales each loss by the size of its gradient to calm this.
Chapter 7
Run a real residual quantizer on a waveform and hear it in numbers
Here is a small codec that runs in your browser. It skips the neural encoder: each frame is 8 raw samples, used as an 8-number latent. Everything else is real. It learns each codebook with k-means on 2,048 training frames, quantizes level by level on the residual, and adds the entries back up.
Top: the input (blue) and the rebuild (teal). Middle: the token grid, one row per level. Bottom: the error (red). Change levels and codebook size.
Toy codec: an 8 kHz signal of notes and noise, frames of 8 samples, so 1,000 frames per second. Codebooks come from k-means (12 rounds) on separate training audio. The signal-to-noise ratio and the bitrate are computed live.
Read the result as a signal-to-noise ratio: SNR = 10 log10(signal power / error power), in decibels (dB). Every 10 dB is ten times less error power. Try 16 entries: each added level buys several dB, and each costs 4 more bits per frame.
Now compare two settings with the same bits. Two levels of 64 entries cost 12 bits per frame. Three levels of 16 entries also cost 12. Which wins? Try it. SoundStream ran the same test at 6 kbps (Table II): 8 codebooks of 1,024 scored 4.01 on ViSQOL, a quality score, and 80 codebooks of 2 entries still scored 3.92.
The middle grid is the whole point. It is a short array of small integers: rows are levels, columns are frames. A language model can predict that grid. The next chapter shows how.
Chapter 8
Lay the token grid out as a sequence, and choose the order the model fills it in
A transformer predicts one sequence. The codec gives a grid: Nq tokens per frame. The simplest layout lays every token end to end. Call the clip length d and the number of prediction steps L.
L equals d times f times N-q.
Count the frames in the clip, d times f. Each frame has N-q tokens. In the flat layout, every token is one step, so multiply.
Moshi's example: Mimi at f = 12.5 and N-q = 8 makes 100 tokens per second. Five minutes, d = 300, gives L = 300 × 12.5 × 8 = 30,000 steps. Text for the same speech needs about 1,000.
Real systems cut the steps. Pick a layout below and compare.
Each cell is one token; its number is the step that predicts it. Cells with the same number come out together. Pick a layout and a duration.
The step counts use EnCodec at 6 kbps: 75 frames, 8 codebooks. The grid draws 6 frames and 4 codebooks to fit. "Coarse, then fine" counts one pass per remaining codebook, as in VALL-E.
Three real designs:
The failure: predicting all codebooks of a frame at once, with no delay. The fine codebooks then cannot see the coarse ones they correct. The symptom is noisy, unstable audio; the delay or a depth model fixes it.
Chapter 9
Keep the numbers, the checks and the code in one place
A neural audio codec is a strided encoder, a stack of small codebooks, and a decoder trained with a critic. The encoder sets the frame rate. The codebooks set the bits per frame. Their product is the bitrate. The token grid is what audio language models predict.
| Codec | Sample rate | Frame rate | Codebooks × entries | Bitrate | Source |
|---|---|---|---|---|---|
| SoundStream | 24 kHz | 75 Hz (stride 320) | up to 24 × 1,024 | 3 to 18 kbps | arXiv 2107.03312 |
| EnCodec | 24 kHz | 75 Hz (stride 320) | 2 to 32 × 1,024 | 1.5 to 24 kbps | arXiv 2210.13438 |
| EnCodec, stereo | 48 kHz | 150 Hz | up to 16 × 1,024 | 3 to 24 kbps | same paper |
| DAC | 44.1 kHz | 86 Hz (stride 512) | 9 × 1,024 | about 8 kbps | arXiv 2306.06546 |
| Mimi | 24 kHz | 12.5 Hz | 8 × 2,048 | 1.1 kbps | arXiv 2410.00037 |
| MusicGen's EnCodec | 32 kHz | 50 Hz (stride 640) | 4 × 2,048 | 2.2 kbps | arXiv 2306.05284 |
pythonimport numpy as np def rvq_encode(z, books): # z: (T, D) latents; books: list of (N, D) codebooks r, codes = z.copy(), [] for C in books: # one level per codebook d = ((r[:, None, :] - C[None]) ** 2).sum(-1) # (T, N) squared distances k = d.argmin(1) # (T,) token ids for this level r = r - C[k] # the residual goes to the next level codes.append(k) return np.stack(codes) # (Nq, T) the token grid def rvq_decode(codes, books, nq=None): # keep the first nq levels nq = nq or len(books) return sum(books[i][codes[i]] for i in range(nq)) # (T, D) z-hat def bitrate(frame_rate, nq, entries): return frame_rate * nq * np.log2(entries) # bitrate(75, 8, 1024) == 6000.0
Now press Present or Teach and explain from memory: the frame rate, the snap, the residual levels, the bitrate and the critic. Then go back to the hero, pick Mimi, and say why its grid is so short.