EnCodec is a neural audio codec that compresses speech, music, and general audio into a sequence of indices with few bits, and restores it to a waveform with high quality. It was released in 2022 by Défossez et al. at Meta AI, together with the code and pre-trained models.
In a neural audio codec, an encoder shrinks the waveform and quantizes it, and a decoder turns it back into a waveform. EnCodec inherits the design of SoundStream, "convolutional encoder-decoder + residual vector quantization + adversarial training," and changes the following points.
Add LSTMs to the encoder and decoder: a two-layer LSTM handles long-range temporal structure that convolutions capture poorly.
Use a single type of discriminator: high quality is achieved with only the MS-STFT discriminator, which looks at STFTs with different window lengths. Training also becomes simpler and faster.
Loss balancer: each loss weight is set as "the share of the total gradient that comes from that loss," which stabilizes training regardless of differences in loss magnitude.
Entropy coding with a language model (optional): a small Transformer predicts the probabilities of the indices, and arithmetic coding cuts the transmitted bits by a further 25–40%.
The model was evaluated at 1.5, 3, 6, and 12 kbps on 24 kHz mono audio and at 6, 12, and 24 kbps on 48 kHz stereo music. In the paper's listening tests (MUSHRA), it outperformed traditional codecs and Lyra-v2 in every setting compared. Speech synthesis models such as VALL-E later used EnCodec's indices as "audio tokens."
Architecture
EnCodec consists of a generator made of three parts, encoder E, quantizer Q, and decoder G, plus an MS-STFT discriminator used only during training. In the figure at the top of the article, the left side shows the overall flow, the center shows the discriminator, and the right side shows the losses and the balancer.
Let the audio be x∈[−1,1]Ca×T (Ca is the number of channels and T the number of samples). The encoder produces the latent representation z=E(x), the quantizer produces zq=Q(z), and the decoder restores the waveform x^=G(zq). The same architecture is used at 24 kHz and 48 kHz.
The encoder processes the input in the following order.
Input: a 1D convolution with kernel size 7 and C=32 channels takes in the audio.
Encoder blocks × 4: each block consists of one residual unit and a strided convolution with stride S and kernel size 2S. The strides are 2, 4, 5, and 8, and the number of channels doubles at each downsampling.
LSTM: a two-layer LSTM captures temporal structure.
Output: a convolution with kernel size 7 and D channels produces the latent representation.
This yields 75 latent vectors per second for 24 kHz audio and 150 for 48 kHz. The activation function is ELU. The decoder mirrors the encoder, using transposed convolutions instead of strided convolutions, with strides in reverse order: 8, 5, 4, 2.
Processes 1-second chunks (with 10 ms overlap). 1 second for the 48 kHz model
Residual vector quantization, as in SoundStream, quantizes the remaining quantization error with each successive codebook. Each codebook has 1,024 vectors (10 bits), and up to 32 stages are used at 24 kHz (16 at 48 kHz). The training procedure is also the same as SoundStream's.
Codebook updates: the selected vectors are updated with an exponential moving average with decay 0.99. Unused vectors are replaced with ones sampled from the current batch.
Gradient flow: the straight-through estimator (treating quantization as the identity during backpropagation) delivers gradients to the encoder.
Bitrate switching: at each training step, the number of stages is chosen at random from multiples of 4 (corresponding to 1.5, 3, 6, 12, and 24 kbps at 24 kHz).
Language model and entropy coding (optional) is a mechanism for sending the quantized indices with even fewer bits. A small Transformer with 5 layers, 8 heads, 200 channels, and an 800-dimensional feed-forward layer predicts, from the indices at the previous time step, the probabilities of the indices for each codebook at the current time step. Arithmetic coding with these probabilities sends more frequent indices with shorter bit strings. The model is kept small so that it runs faster than real time on a single CPU core.
The MS-STFT discriminator judges five STFTs, with window lengths 2,048, 1,024, 512, 256, and 128, each with a small network of the same shape. Each network applies a 2D convolution to the concatenated real and imaginary parts of the STFT, then stacks convolutions with dilation rates 1, 2, and 4 along time and stride 2 along frequency, and outputs a judgment. The activation function is Leaky ReLU.
There are five losses.
Time-domain reconstruction loss: the L1 distance between waveforms, ℓt(x,x^)=∥x−x^∥1.
Frequency-domain reconstruction loss: the sum of L1 and L2 over 64-band mel spectrograms Si with window length 2i (i∈e={5,…,11}) and hop 2i/4 (the paper uses αi=1).
Relative feature matching loss: the L1 distance between the features Dkl of the L layers of each discriminator, divided by the magnitude of the features of the original audio.
Commitment loss: at each quantization stage c, the squared error between the residual zc and the selected codebook vector qc(zc). The gradient flows only to the zc side and acts on the encoder.
The balancer changes how these weights are used. Let gi=∂ℓi/∂x^ be the gradient of each loss with respect to the output x^, and ⟨∥gi∥2⟩β the exponential moving average of its norm. The sum of the following g~i is backpropagated (the paper uses R=1 and β=0.999).
g~i=R∑jλjλi⋅⟨∥gi∥2⟩βgi
If ∑iλi=1, then λi is "the share of the total gradient that comes from loss i." The commitment loss is not a function of the output x^, so it is added outside the balancer. The weights of the 24 kHz model are λt=0.1, λf=1, λg=3, and λfeat=3.
Why it achieves stable, high quality
The key point of EnCodec is that it keeps the SoundStream design while simplifying how discriminators and losses are handled, which stabilizes training.
GAN vocoders and codecs usually combined several types of discriminators (HiFi-GAN's multi-period and multi-scale discriminators, SoundStream's waveform and STFT discriminators, and so on). The EnCodec paper showed that a single type of discriminator looking at STFTs with different window lengths achieves the same or better quality. A short STFT window captures fine changes in time and a long one captures fine differences in frequency, so lining up five different windows lets the discriminator distinguish both.
The other innovation, the balancer, reduces the effort of choosing loss weights. Reconstruction losses and adversarial losses differ greatly in magnitude, and their magnitudes change during training. With a plain weighted sum, the loss producing the largest gradient dominates training, and many weight settings had to be tried. The balancer first equalizes the gradient magnitudes of each loss on average and then applies the weights, so each weight has an intuitive meaning: "what fraction of the gradient is entrusted to that loss."
As an analogy, the balancer is like listening to several people who speak at different volumes: first bring everyone to the same volume, then allocate "30% to A's opinion, 10% to B's opinion." The whole group is no longer pulled along by the loudest person (the loss with the largest gradient).
The roles of the other design choices are as follows.
Design choice
What it does
What it helps with
LSTM
Handles temporal structure in the encoder and decoder
Raises SI-SNR (removing the LSTM drops it from 6.67 to 6.40), at the cost of slightly slower processing
MS-STFT discriminator
Judges five STFTs with different windows
A single type of discriminator gives high quality, and training is simpler and faster
Balancer
Equalizes the gradient magnitudes of each loss before applying weights
Weights can be chosen independently of loss magnitude, and training is stable
Per-bitrate discriminators
Picks one bitrate per batch and updates only the discriminator dedicated to it
Improves quality when training multiple bitrates in one model
Less frequent discriminator updates
Updates the discriminator with probability 2/3 at 24 kHz and 0.5 at 48 kHz
Keeps the discriminator from becoming too strong relative to the decoder
Language model + arithmetic coding
Predicts how likely each index is and sends it with fewer bits
Cuts bits by 25–40% without changing quality
Experimental results
The paper trained the 24 kHz mono model on speech (DNS Challenge 4, Common Voice), general audio (AudioSet, FSD50K), and music (Jamendo). The 48 kHz stereo model was trained on music only. Training used batches of 64 one-second clips with Adam (learning rate 3×10−4, β1=0.5, β2=0.9) for 300 epochs, with 2,000 updates per epoch. Subjective evaluation used MUSHRA (scores from 1 to 100; a listening test that mixes in a hidden reference and a low-quality anchor), selecting fifty 5-second clips from each category and collecting ratings from at least 10 people per clip.
MUSHRA results (24 kHz, streaming model. "After entropy coding" is the average bitrate when the language model and arithmetic coding are used)
Model
Bitrate
After entropy coding
Clean speech
Noisy speech
Music 1
Music 2
Reference
−
−
95.5 ± 1.6
93.9 ± 1.8
93.2 ± 2.5
97.1 ± 1.3
Opus
6.0 kbps
−
30.1 ± 2.8
19.1 ± 5.9
20.6 ± 5.8
17.9 ± 5.3
Opus
12.0 kbps
−
76.5 ± 2.3
61.9 ± 2.1
77.8 ± 3.2
65.4 ± 2.7
EVS
9.6 kbps
−
84.4 ± 2.5
80.0 ± 2.4
89.9 ± 2.3
87.7 ± 2.3
Lyra-v2
3.0 kbps
−
53.1 ± 1.9
52.0 ± 4.7
69.3 ± 3.3
42.3 ± 3.5
Lyra-v2
6.0 kbps
−
66.2 ± 2.9
59.9 ± 3.3
75.7 ± 2.6
48.6 ± 2.1
EnCodec
1.5 kbps
0.9 kbps
49.2 ± 2.4
41.3 ± 3.6
68.2 ± 2.2
66.5 ± 2.3
EnCodec
3.0 kbps
1.9 kbps
67.0 ± 1.5
62.5 ± 2.3
89.6 ± 3.1
87.8 ± 2.9
EnCodec
6.0 kbps
4.1 kbps
83.1 ± 2.7
69.4 ± 2.3
92.9 ± 1.8
91.3 ± 2.1
EnCodec
12.0 kbps
8.9 kbps
90.6 ± 2.6
80.1 ± 2.5
91.8 ± 2.5
92.9 ± 1.2
On average, EnCodec at 3 kbps outperformed Lyra-v2 at 6 kbps and Opus at 12 kbps. Lyra-v2 is a codec that includes the official implementation of SoundStream.
Discriminator comparison (higher ViSQOL is better)
Discriminator
SI-SNR
ViSQOL
MUSHRA
MSD + one STFT (same as SoundStream)
5.99
4.22
62.91 ± 2.62
MPD (HiFi-GAN's multi-period discriminator)
7.35
4.24
60.7 ± 2.8
MS-STFT + MPD
6.55
4.34
79.0 ± 1.9
MS-STFT
6.67
4.35
77.5 ± 1.8
The MS-STFT discriminator alone scored about 15 MUSHRA points higher than SoundStream's combination. Adding MPD raises MUSHRA slightly.
Comparison with SoundStream (MUSHRA at 3 kbps. SoundStream was reimplemented by the paper's authors. Opus and EVS at 6 kbps)
Model
MUSHRA
Reference
96.1 ± 1.41
Opus (6 kbps)
21.1 ± 2.62
EVS (6 kbps)
62.9 ± 2.18
SoundStream
71.8 ± 1.51
EnCodec (DiffQ)
72.3 ± 1.18
EnCodec (residual vector quantization)
76.8 ± 1.31
48 kHz stereo music
Model
Bitrate
After entropy coding
Compression ratio
MUSHRA
Reference
−
−
1×
95.1 ± 1.8
MP3
64 kbps
−
24×
82.7 ± 3.2
Opus
6 kbps
−
256×
17.7 ± 5.9
Opus
24 kbps
−
64×
82.9 ± 3.7
EnCodec
6 kbps
4.2 kbps
256×
82.9 ± 2.4
EnCodec
12 kbps
8.9 kbps
128×
88.0 ± 2.7
EnCodec
24 kbps
19.4 kbps
64×
87.5 ± 2.6
EnCodec at 6 kbps was rated about the same as MP3 at 64 kbps.
Latency and speed (6 kbps, one thread on a MacBook Pro 2019 CPU; how many times faster than real time)
Model
Initial latency
Encoding
Decoding
Encoding (with entropy coding)
Decoding (with entropy coding)
Lyra v2 (32 kHz)
−
27.4×
67.2×
−
−
EnCodec 24 kHz
13 ms
9.8×
10.4×
1.6×
1.6×
EnCodec 48 kHz
1 s
6.8×
5.1×
0.68×
0.66×
At 6 kbps on the same mix of speech and music, the streaming model reached a ViSQOL of 4.35 and the non-streaming model 4.39, so streaming caused only a small loss in quality (under the same conditions, Opus scored 2.60 and EVS 2.74).
Practical considerations
Keep the following points in mind when using EnCodec.
Choose the variant by use case: for low latency, as in calls, use the 24 kHz streaming model (13 ms latency). The 48 kHz stereo model has 1 second of latency due to its normalization and runs close to real time on a CPU, so it is suited to storing and distributing music.
Entropy coding trades latency and speed for bits: using the language model and arithmetic coding cuts bits by 25–40%, but even at 24 kHz the processing speed drops from about 10× real time to about 1.6×. Because decoding waits for part of the next frame, latency also increases by 13 ms.
Watch out for floating-point errors: in arithmetic coding, even a tiny difference in probabilities between sender and receiver causes decoding errors. The paper handles this by rounding probabilities to a precision of 10−6, but notes that further verification is needed for use in real environments.
When using it as tokens for other models: the number of stages (the bitrate) changes the number of tokens per frame. For example, at 24 kHz and 6 kbps, one second becomes 75 frames × 8 stages of indices. More stages improve quality but also increase the tokens the generative model must handle.
Entropy coding with the language model becomes less effective at higher bitrates. In the paper's results, the 1.5 kbps model dropped to 0.9 kbps on average (about 40%), but the 12 kbps model only to 8.9 kbps (about 26%). The paper attributes this to the difficulty a small Transformer has in predicting many codebooks jointly.
Comparison with other codecs
The table below compares EnCodec with other codecs from the same perspectives. The quality figures are MUSHRA scores from the EnCodec paper (24 kHz, clean speech).
To start right away with a publicly available pre-trained model: EnCodec is a good fit. The code and the 24 kHz and 48 kHz models are public.
To run as fast as possible on a CPU: in the paper's measurements, Lyra v2 processed faster than EnCodec (at 6 kbps, about 27× real time for encoding and about 67× for decoding).
To use as tokens for speech synthesis or music generation: EnCodec's indices can be handled directly by a language model, as in VALL-E. VALL-E uses EnCodec at 24 kHz and 6 kbps (8 stages), predicting the first stage autoregressively and stages 2–8 non-autoregressively.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of EnCodec's two innovations (one scale of the MS-STFT discriminator, and the loss balancer), following Section 3.4 and Eq. (5) of the paper.
The encoder, decoder, and residual vector quantization are almost the same as the implementation in the SoundStream article (with a two-layer LSTM added to the encoder and decoder).
PyTorch has no built-in EnCodec. Pre-trained models are available via the official encodec package (pip install encodec) or EncodecModel in Hugging Face transformers.
"""
class STFTDiscriminator(nn.Module):
"""One scale of the MS-STFT discriminator: concatenate the real and imaginary parts of the STFT and judge with 2D convolutions (Figure 2 of the paper)"""
def __init__(self, win, ch=32):
super().__init__()
self.win = win
wn = nn.utils.parametrizations.weight_norm
self.convs = nn.ModuleList([
wn(nn.Conv2d(2, ch, (3, 9), padding=(1, 4))),
wn(nn.Conv2d(ch, ch, (3, 9), stride=(1, 2), dilation=(1, 1), padding=(1, 4))), # dilation 1 along time
wn(nn.Conv2d(ch, ch, (3, 9), stride=(1, 2), dilation=(2, 1), padding=(2, 4))), # dilation 2
wn(nn.Conv2d(ch, ch, (3, 9), stride=(1, 2), dilation=(4, 1), padding=(4, 4))), # dilation 4 (stride 2 along frequency)
wn(nn.Conv2d(ch, ch, (3, 3), padding=(1, 1))),
])
self.post = wn(nn.Conv2d(ch, 1, (3, 3), padding=(1, 1)))
def forward(self, x): # x: [B, T]
spec = torch.stft(x, self.win, hop_length=self.win // 4, window=torch.hann_window(self.win, device=x.device),
normalized=True, return_complex=True) # [B, F, time]
h = torch.stack([spec.real, spec.imag], 1).transpose(2, 3) # [B, 2, time, F]
feats = []
for conv in self.convs:
h = F.leaky_relu(conv(h), 0.2)
feats.append(h)
return self.post(h), feats
class MSSTFTDiscriminator(nn.Module):
def __init__(self, wins=(2048, 1024, 512, 256, 128)):
super().__init__()
self.ds = nn.ModuleList(STFTDiscriminator(w) for w in wins)
def forward(self, x):
return [d(x) for d in self.ds]
class Balancer:
"""Divide each loss's gradient w.r.t. the output by the EMA of its norm, then sum with shares λ (Eq. 5, R = 1, β = 0.999)"""
def __init__(self, weights, R=1.0, beta=0.999):
self.weights, self.R, self.beta = weights, R, beta
self.avg = {k: None for k in weights}
def backward(self, losses, x_hat):
total_w = sum(self.weights.values())
grad = torch.zeros_like(x_hat)
for k, loss in losses.items():
g, = torch.autograd.grad(loss, x_hat, retain_graph=True) # g_i = ∂ℓ_i / ∂x̂
norm = g.norm().detach()
self.avg[k] = norm if self.avg[k] is None else self.beta * self.avg[k] + (1 - self.beta) * norm
grad = grad + self.R * self.weights[k] / total_w * g / (self.avg[k] + 1e-12)
x_hat.backward(grad) # backpropagate the combined gradient into the generator
def mel_loss(x, x_hat, sr=24000):
"""Frequency-domain reconstruction loss: L1 + L2 of 64-band mel spectrograms with windows 2^5 to 2^11 (α = 1)"""
import torchaudio
loss = 0
for i in range(5, 12):
# Use an FFT length of at least 128 so that 64 bands can be built even for short windows (an implementation detail)
mel = torchaudio.transforms.MelSpectrogram(sr, n_fft=max(2 ** i, 128), win_length=2 ** i,
hop_length=2 ** i // 4, n_mels=64, normalized=True).to(x.device)
a, b = mel(x), mel(x_hat)
loss = loss + (a - b).abs().mean() + ((a - b) ** 2).mean()
return loss / 7
# --- Usage (the generator G combines encoder, quantizer, and decoder; a shape-only stand-in is used here) ---
G = nn.Conv1d(1, 1, 7, padding=3)
D = MSSTFTDiscriminator()
balancer = Balancer({"t": 0.1, "f": 1.0, "g": 3.0, "feat": 3.0}) # weights for 24 kHz
opt_g = torch.optim.Adam(G.parameters(), lr=3e-4, betas=(0.5, 0.9))
opt_d = torch.optim.Adam(D.parameters(), lr=3e-4, betas=(0.5, 0.9))
x = torch.rand(4, 1, 24000) * 2 - 1 # 1 second of audio
x_hat = G(x)
commit = torch.tensor(0.0) # commitment loss of residual vector quantization (omitted here)
# Generator: the four losses go through the balancer; the commitment loss is backpropagated outside it
outs_f, outs_r = D(x_hat.squeeze(1)), D(x.squeeze(1))
l_g = sum(F.relu(1 - o).mean() for o, _ in outs_f) / len(outs_f)
l_feat = sum((ff - fr.detach()).abs().mean() / fr.detach().abs().mean()
for (_, fs_f), (_, fs_r) in zip(outs_f, outs_r) for ff, fr in zip(fs_f, fs_r)) / (len(outs_f) * len(outs_f[0][1]))
losses = {"t": (x - x_hat).abs().mean(), "f": mel_loss(x.squeeze(1), x_hat.squeeze(1)), "g": l_g, "feat": l_feat}
opt_g.zero_grad()
balancer.backward(losses, x_hat)
opt_g.step()
# Discriminator: hinge loss. At 24 kHz, update only with probability 2/3
if torch.rand(()) < 2 / 3:
outs_f, outs_r = D(x_hat.detach().squeeze(1)), D(x.squeeze(1))
l_d = sum(F.relu(1 - r).mean() + F.relu(1 + f).mean() for (r, _), (f, _) in zip(outs_r, outs_f)) / len(outs_r)
opt_d.zero_grad(); l_d.backward(); opt_d.step()
FAQ
Q. How does EnCodec differ from SoundStream?
A.
The overall design of encoder, residual vector quantization, and decoder is the same. The four main differences are:
LSTM: a two-layer LSTM is added to the encoder and decoder
Discriminator: the combination of waveform and STFT discriminators is replaced by a single MS-STFT discriminator that looks at five STFTs with different windows
Balancer: loss weights are used as shares of the gradient
Entropy coding: optionally, a small Transformer and arithmetic coding reduce the bits further
In a 3 kbps comparison with SoundStream as reimplemented by the paper's authors, MUSHRA scores were 71.8 and 76.8.
Q. How many tokens does EnCodec at 6 kbps produce?
A.
For 24 kHz audio, one second becomes 75 frames, and at 6 kbps each frame is represented by 8 stages of codebooks with 1,024 entries (10 bits) each. Since 75×8×10=6000 bits per second, one second of audio is 75×8=600 indices (tokens). VALL-E uses indices from this setting as tokens for speech synthesis.
Q. What is the benefit of using the balancer?
A.
It lets you choose loss weights without worrying about the magnitudes of the losses. With a plain weighted sum, the loss with the largest gradient dominates training, so many weight settings have to be tried. The balancer first equalizes the gradient magnitudes of each loss on average and then applies the weights, so each weight means "the share of the total gradient that comes from that loss." The paper reports that this greatly stabilized training.