AI Logic

Architectures

EnCodec

Updated:

EnCodec architecture. Left: the overall flow (waveform → convolution → encoder blocks with strides 2, 4, 5, 8 → two-layer LSTM → 75 Hz embeddings → residual vector quantization → optional language model and arithmetic coding → decoder → reconstructed waveform). Center: the MS-STFT discriminator (judges the real and imaginary parts of five STFTs with different windows using 2D convolutions). Right: the losses and the balancer (time-domain L1, mel L1 + L2, adversarial loss, and feature matching are combined by the balancer; the commitment loss is added outside it)

Background and overview

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 EE, quantizer QQ, and decoder GG, 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×Tx \in [-1, 1]^{C_a \times T} (CaC_a is the number of channels and TT the number of samples). The encoder produces the latent representation z=E(x)z = E(x), the quantizer produces zq=Q(z)z_q = Q(z), and the decoder restores the waveform x^=G(zq)\hat{x} = G(z_q). The same architecture is used at 24 kHz and 48 kHz.

The encoder processes the input in the following order.

  1. Input: a 1D convolution with kernel size 7 and C=32C = 32 channels takes in the audio.
  2. Encoder blocks × 4: each block consists of one residual unit and a strided convolution with stride SS and kernel size 2S2S. The strides are 2, 4, 5, and 8, and the number of channels doubles at each downsampling.
  3. LSTM: a two-layer LSTM captures temporal structure.
  4. Output: a convolution with kernel size 7 and DD 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.

There are two variants for different uses.

VariantPaddingNormalizationLatency
StreamingAll on the past side (causal)Weight NormalizationAfter receiving the first 320 samples (13 ms), it can output 320 samples
Non-streamingSplit equally before and afterLayer Normalization, including over timeProcesses 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\ell_t(x, \hat{x}) = \|x - \hat{x}\|_1.
  • Frequency-domain reconstruction loss: the sum of L1 and L2 over 64-band mel spectrograms SiS_i with window length 2i2^i (i∈e={5,…,11}i \in e = \{5, \dots, 11\}) and hop 2i/42^i/4 (the paper uses αi=1\alpha_i = 1).
ℓf(x,x^)=1∣α∣⋅∣s∣∑αi∈α∑i∈e∥Si(x)−Si(x^)∥1+αi∥Si(x)−Si(x^)∥2\ell_f(x, \hat{x}) = \frac{1}{|\alpha| \cdot |s|} \sum_{\alpha_i \in \alpha} \sum_{i \in e} \left\| S_i(x) - S_i(\hat{x}) \right\|_1 + \alpha_i \left\| S_i(x) - S_i(\hat{x}) \right\|_2
  • Adversarial loss: a hinge loss over KK discriminators DkD_k. The discriminators minimize LdL_d, and the generator minimizes ℓg\ell_g.
ℓg(x^)=1K∑kmax⁡(0,1−Dk(x^)),Ld(x,x^)=1K∑k=1Kmax⁡(0,1−Dk(x))+max⁡(0,1+Dk(x^))\ell_g(\hat{x}) = \frac{1}{K} \sum_k \max(0, 1 - D_k(\hat{x})), \qquad L_d(x, \hat{x}) = \frac{1}{K} \sum_{k=1}^{K} \max(0, 1 - D_k(x)) + \max(0, 1 + D_k(\hat{x}))
  • Relative feature matching loss: the L1 distance between the features DklD^l_k of the LL layers of each discriminator, divided by the magnitude of the features of the original audio.
ℓfeat(x,x^)=1KL∑k=1K∑l=1L∥Dkl(x)−Dkl(x^)∥1mean(∥Dkl(x)∥1)\ell_{\mathrm{feat}}(x, \hat{x}) = \frac{1}{KL} \sum_{k=1}^{K} \sum_{l=1}^{L} \frac{\left\| D^l_k(x) - D^l_k(\hat{x}) \right\|_1}{\mathrm{mean}\left(\left\| D^l_k(x) \right\|_1\right)}
  • Commitment loss: at each quantization stage cc, the squared error between the residual zcz_c and the selected codebook vector qc(zc)q_c(z_c). The gradient flows only to the zcz_c side and acts on the encoder.
ℓw=∑c=1C∥zc−qc(zc)∥22\ell_w = \sum_{c=1}^{C} \left\| z_c - q_c(z_c) \right\|_2^2

The generator loss is a weighted sum of these.

LG=λtℓt(x,x^)+λfℓf(x,x^)+λgℓg(x^)+λfeatℓfeat(x,x^)+λwℓwL_G = \lambda_t \ell_t(x, \hat{x}) + \lambda_f \ell_f(x, \hat{x}) + \lambda_g \ell_g(\hat{x}) + \lambda_{\mathrm{feat}} \ell_{\mathrm{feat}}(x, \hat{x}) + \lambda_w \ell_w

The balancer changes how these weights are used. Let gi=∂ℓi/∂x^g_i = \partial \ell_i / \partial \hat{x} be the gradient of each loss with respect to the output x^\hat{x}, and ⟨∥gi∥2⟩β\langle \|g_i\|_2 \rangle_\beta the exponential moving average of its norm. The sum of the following g~i\tilde{g}_i is backpropagated (the paper uses R=1R = 1 and β=0.999\beta = 0.999).

g~i=R λi∑jλj⋅gi⟨∥gi∥2⟩β\tilde{g}_i = R \, \frac{\lambda_i}{\sum_j \lambda_j} \cdot \frac{g_i}{\langle \|g_i\|_2 \rangle_\beta}

If ∑iλi=1\sum_i \lambda_i = 1, then λi\lambda_i is "the share of the total gradient that comes from loss ii." The commitment loss is not a function of the output x^\hat{x}, so it is added outside the balancer. The weights of the 24 kHz model are λt=0.1\lambda_t = 0.1, λf=1\lambda_f = 1, λg=3\lambda_g = 3, and λfeat=3\lambda_{\mathrm{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 choiceWhat it doesWhat it helps with
LSTMHandles temporal structure in the encoder and decoderRaises SI-SNR (removing the LSTM drops it from 6.67 to 6.40), at the cost of slightly slower processing
MS-STFT discriminatorJudges five STFTs with different windowsA single type of discriminator gives high quality, and training is simpler and faster
BalancerEqualizes the gradient magnitudes of each loss before applying weightsWeights can be chosen independently of loss magnitude, and training is stable
Per-bitrate discriminatorsPicks one bitrate per batch and updates only the discriminator dedicated to itImproves quality when training multiple bitrates in one model
Less frequent discriminator updatesUpdates the discriminator with probability 2/3 at 24 kHz and 0.5 at 48 kHzKeeps the discriminator from becoming too strong relative to the decoder
Language model + arithmetic codingPredicts how likely each index is and sends it with fewer bitsCuts 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−43 \times 10^{-4}, β1=0.5\beta_1 = 0.5, β2=0.9\beta_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)

ModelBitrateAfter entropy codingClean speechNoisy speechMusic 1Music 2
Reference−−95.5 ± 1.693.9 ± 1.893.2 ± 2.597.1 ± 1.3
Opus6.0 kbps−30.1 ± 2.819.1 ± 5.920.6 ± 5.817.9 ± 5.3
Opus12.0 kbps−76.5 ± 2.361.9 ± 2.177.8 ± 3.265.4 ± 2.7
EVS9.6 kbps−84.4 ± 2.580.0 ± 2.489.9 ± 2.387.7 ± 2.3
Lyra-v23.0 kbps−53.1 ± 1.952.0 ± 4.769.3 ± 3.342.3 ± 3.5
Lyra-v26.0 kbps−66.2 ± 2.959.9 ± 3.375.7 ± 2.648.6 ± 2.1
EnCodec1.5 kbps0.9 kbps49.2 ± 2.441.3 ± 3.668.2 ± 2.266.5 ± 2.3
EnCodec3.0 kbps1.9 kbps67.0 ± 1.562.5 ± 2.389.6 ± 3.187.8 ± 2.9
EnCodec6.0 kbps4.1 kbps83.1 ± 2.769.4 ± 2.392.9 ± 1.891.3 ± 2.1
EnCodec12.0 kbps8.9 kbps90.6 ± 2.680.1 ± 2.591.8 ± 2.592.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)

DiscriminatorSI-SNRViSQOLMUSHRA
MSD + one STFT (same as SoundStream)5.994.2262.91 ± 2.62
MPD (HiFi-GAN's multi-period discriminator)7.354.2460.7 ± 2.8
MS-STFT + MPD6.554.3479.0 ± 1.9
MS-STFT6.674.3577.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)

ModelMUSHRA
Reference96.1 ± 1.41
Opus (6 kbps)21.1 ± 2.62
EVS (6 kbps)62.9 ± 2.18
SoundStream71.8 ± 1.51
EnCodec (DiffQ)72.3 ± 1.18
EnCodec (residual vector quantization)76.8 ± 1.31

48 kHz stereo music

ModelBitrateAfter entropy codingCompression ratioMUSHRA
Reference−−1×95.1 ± 1.8
MP364 kbps−24×82.7 ± 3.2
Opus6 kbps−256×17.7 ± 5.9
Opus24 kbps−64×82.9 ± 3.7
EnCodec6 kbps4.2 kbps256×82.9 ± 2.4
EnCodec12 kbps8.9 kbps128×88.0 ± 2.7
EnCodec24 kbps19.4 kbps64×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)

ModelInitial latencyEncodingDecodingEncoding (with entropy coding)Decoding (with entropy coding)
Lyra v2 (32 kHz)−27.4×67.2×−−
EnCodec 24 kHz13 ms9.8×10.4×1.6×1.6×
EnCodec 48 kHz1 s6.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−610^{-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).

CodecApproachTemporal modelingDiscriminatorBitrate rangeMUSHRA (clean speech)
OpusTraditional signal processing−−6–510 kbps6 kbps: 30.1, 12 kbps: 76.5
EVSTraditional signal processing−−5.9–128 kbps9.6 kbps: 84.4
SoundStreamConvolutional encoder-decoder + residual vector quantizationResidual units with dilation 1, 3, 9Waveform (3 scales) + one STFT3–18 kbps (in the paper)Lyra-v2 3 kbps: 53.1, 6 kbps: 66.2
EnCodecSoundStream design + LSTM, optional entropy codingOne residual unit + two-layer LSTMMS-STFT (5 windows)1.5–24 kbps, also 48 kHz stereo3 kbps: 67.0, 6 kbps: 83.1

Rough guidelines for choosing:

  • 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=600075 \times 8 \times 10 = 6000 bits per second, one second of audio is 75×8=60075 \times 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.

References

  1. Défossez, A., Copet, J., Synnaeve, G., & Adi, Y. (2022). High Fidelity Neural Audio Compression. arXiv:2210.13438.
  2. facebookresearch. Official implementation and pre-trained models of EnCodec.
  3. Zeghidour, N., Luebs, A., Omran, A., Skoglund, J., & Tagliasacchi, M. (2021). SoundStream: An End-to-End Neural Audio Codec. arXiv:2107.03312.
  4. Wang, C., et al. (2023). Neural Codec Language Models are Zero-Shot Text to Speech Synthesizers. arXiv:2301.02111.