Neural Audio Codecs

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).

Turn one second into tokens

8

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

Why Sound Needs Tokens

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.

Count the steps a model must predict

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.

10 s

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 road

  1. The encoder squeezes time: strided convolutions turn 24,000 samples into 75 vectors.
  2. Vector quantization: snap each vector to the nearest codebook entry and keep its index.
  3. Training the codebook: gradients through a snap, and entries that die.
  4. Residual vector quantization: several small codebooks, each fixing the last one's error.
  5. Bitrate: frames times codebooks times bits, and quality you choose after training.
  6. Making it sound real: the discriminator that stops the blur.
  7. The codec, end to end: a real residual quantizer running in your browser.
  8. Audio language models: how VALL-E, MusicGen and Moshi lay out the token grid.
  9. Field guide: the codecs side by side, the code, and where to go next.

The hero's Codebooks kept slider is Chapters 4 and 5. Its grid is Chapter 2. Its frame count is Chapter 1.

Why does an audio language model predict codec tokens instead of raw samples?

Chapter 1

The Encoder Squeezes Time

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.

Say it aloud

f equals f-s divided by M.

f
f the frame rate: latent vectors per second, in hertz.
fs
f-s the sample rate of the input audio, in samples per second.
M
M the total stride: the strides of all encoder blocks multiplied together.
In plain words

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.

With numbers

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.

Stack the strides

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.

An encoder runs on 16 kHz audio with strides 2, 4, 5 and 8. How many latent vectors does it make per second?

Chapter 2

Vector Quantization: Snap to the Nearest Entry

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.

Snap a latent to the codebook

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.

Say it aloud

k equals the j that makes the squared distance between z and c-j smallest.

k
k the token: the index of the winning entry, 0 to N − 1.
argminj
the j that makes it smallest try every entry index j and return the best one, not the distance.
z
z the latent vector from the encoder for one frame.
cj
c-j codebook entry number j.
‖ · ‖
the length of the straight-line distance between two vectors.
2
squared square the length; the winner is the same and it skips a square root.
In plain words

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 numbers

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.

After vector quantization, what does the codec send for one frame?

Chapter 3

Training the Codebook

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.

Say it aloud

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.

LVQ
L-V-Q the extra loss that trains the codebook and the encoder to agree.
‖sg[z] − ck‖2
the codebook term moves only the entry c-k toward z; z is frozen by sg.
β
beta the weight of the second term; DAC uses 0.25.
‖z − sg[ck]‖2
the commitment term moves only the encoder output z toward its entry; c-k is frozen.
In plain words

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 numbers

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.

Dead codes

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.

Train a codebook, revive the dead

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.

A codebook has 1,024 entries but only 256 ever win. How many bits does each token really carry, at most?

Chapter 4

Residual Vector Quantization

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).

Say it aloud

r-i equals r-i-minus-one minus c-super-i.

ri
r-i the residual after level i: what the first i codebooks have not explained.
ri−1
r-i-minus-one the residual coming into level i; r-zero is the latent z.
c(i)
c-super-i the entry of codebook i nearest to r-i-minus-one, found as in Chapter 2.
In plain words

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 numbers

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.

Say it aloud

z-hat equals the sum, over i from one to N-q, of c-super-i.

ẑ
z-hat the rebuilt latent that goes into the decoder.
Σi=1Nq
the sum over i from one to N-q add one term per level; N-q is how many codebooks you keep.
c(i)
c-super-i the entry chosen at level i.
In plain words

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.

With numbers

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.

Add levels, shrink the residual

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.

2

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.

What does codebook number 3 quantize in RVQ?

Chapter 5

Bitrate and Scalable Quality

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.

Say it aloud

R equals f times N-q times log base two of N.

R
R the bitrate, in bits per second.
f
f the frame rate from Chapter 1, frames per second.
Nq
N-q the number of codebooks kept, so tokens per frame.
log2 N
log base two of N the bits in one token; N = 1,024 gives 10.
In plain words

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.

With numbers

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.

Build a bitrate

Pick a frame rate and a codebook size, then drag the codebooks. The marker moves on a log scale past real codecs.

8

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.

Quantizer dropout

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.

A codec runs at 50 frames per second with 4 codebooks of 2,048 entries. What is its bitrate?

Chapter 6

Making It Sound Real

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.

Say it aloud

L-G equals L-rec plus lambda times L-adv.

LG
L-G the codec's total loss; G stands for generator.
Lrec
L-rec the rebuild error, on the waveform and on spectrograms at several window sizes.
λ
lambda the weight that says how much fooling the critic counts.
Ladv
L-adv the adversarial loss: high when the discriminator spots the rebuild as fake.
In plain words

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

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.

Trade squared error for sharpness

Top: the true spectrogram (time across, pitch up). Bottom: a rebuild. Slide toward the critic and watch the harmonics sharpen while squared error rises.

0%

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.

Why does a codec trained only on squared error sound muffled?

Chapter 7

The Codec, End to End

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.

Encode, tokenize, rebuild

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.

2

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

From Codec Tokens to Audio Language Models

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.

Say it aloud

L equals d times f times N-q.

L
L the number of steps the model predicts, one token each, in the flat layout.
d
d the clip duration, in seconds.
f
f the codec frame rate, frames per second.
Nq
N-q the codebooks per frame.
In plain words

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.

With numbers

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.

Order the grid

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.

10 s

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.

MusicGen's delay pattern shifts codebook k by k steps. What does that buy?

Chapter 9

Field Guide

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.

CodecSample rateFrame rateCodebooks × entriesBitrateSource
SoundStream24 kHz75 Hz (stride 320)up to 24 × 1,0243 to 18 kbpsarXiv 2107.03312
EnCodec24 kHz75 Hz (stride 320)2 to 32 × 1,0241.5 to 24 kbpsarXiv 2210.13438
EnCodec, stereo48 kHz150 Hzup to 16 × 1,0243 to 24 kbpssame paper
DAC44.1 kHz86 Hz (stride 512)9 × 1,024about 8 kbpsarXiv 2306.06546
Mimi24 kHz12.5 Hz8 × 2,0481.1 kbpsarXiv 2410.00037
MusicGen's EnCodec32 kHz50 Hz (stride 640)4 × 2,0482.2 kbpsarXiv 2306.05284

Checklist

  1. Frame rate = sample rate / product of strides.
  2. Bitrate = frame rate × codebooks × log2(entries).
  3. Compression = (sample rate × 16) / bitrate, against 16-bit PCM.
  4. Count codebook usage; dead entries mean fewer real bits.
  5. Train with quantizer dropout if you want one model for many bitrates.
  6. Judge quality by listening tests, not by squared error.
  7. For generation, count the steps of your token layout before you train.

The core, in code

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

Keep going

The takeaway. Frames times codebooks times bits is the whole budget. Residual levels make a huge codebook out of small ones, quantizer dropout lets you pick the bitrate later, and a critic keeps the sound sharp.
You keep 4 of EnCodec's codebooks at 24 kHz. What are the bitrate and the compression against 16-bit PCM?

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.

Neural Audio Codecs
SoundStream · EnCodec · DAC · Moshi / Mimi · Back to Gleams