SoundStream is a neural audio codec that compresses speech, music, and general audio into a form that can be transmitted with few bits, and reconstructs the waveform from it. It was published in 2021 by Zeghidour et al. at Google. Its distinctive feature is that three components are trained jointly: an encoder that compresses the waveform, a quantizer that replaces the result with a finite set of indices, and a decoder that reconstructs the waveform from those indices.
A codec is the mechanism that, when sending audio over a phone call or video conference, turns sound into a bit sequence on the sending side (encoding) and back into sound on the receiving side (decoding). Conventional codecs fall into two families.
Waveform codecs (such as parts of Opus): try to reproduce the waveform faithfully. They work for any audio, but lowering the bitrate makes noise-like artifacts noticeable.
Parametric codecs: assume a model of how speech is produced and transmit only its parameters. They work at low bitrates but are not suited to audio other than speech.
SoundStream borrows techniques from audio generation models such as WaveNet, MelGAN, and HiFi-GAN, aiming to produce audio that is hard to distinguish from the original waveform from few bits. Its three main ideas are as follows.
Residual vector quantization (RVQ): splits quantization into many stages, with each stage quantizing the error left by the previous one.
Quantizer dropout: randomly changes the number of stages used at each training step, so a single model handles various bitrates.
A combination of adversarial and reconstruction losses: discriminators preserve "realism", and spectrogram errors preserve "fidelity to the original audio".
In the paper's listening tests on 24 kHz audio, SoundStream at 3 kbps outperformed Opus at 12 kbps and approached EVS at 9.6 kbps. It runs faster than real time on a single thread of a smartphone CPU.
Architecture
SoundStream consists of a generator that chains an encoder, residual vector quantization, and a decoder, plus two kinds of discriminators used only during training. In the figure at the top of the article, the left side shows the overall flow, the center shows the inside of residual vector quantization, and the right side shows the discriminators and losses.
The encoder is an entirely 1D convolutional network.
Input: a 24 kHz single-channel waveform x∈RT is taken in by a convolution of width 7 with C channels.
Encoder blocks × 4: each block consists of three residual units containing convolutions with dilation rates 1, 3, and 9, followed by a strided convolution. The strides are 2, 4, 5, and 8, and the number of channels doubles at each downsampling.
Output: a convolution of width 3 produces D-dimensional embeddings. One embedding is produced for every M=2⋅4⋅5⋅8=320 samples, the product of the strides, so a 24 kHz waveform becomes 75 frames per second.
The activation function is ELU, and no normalization layers are used. To run in real time, all convolutions are causal (they look only at the past).
The decoder mirrors the encoder. After a convolution of width 7, four decoder blocks that upsample with transposed convolutions are stacked in the reverse stride order 8, 5, 4, 2, and a final convolution of width 7 with 1 channel restores the waveform x^.
Residual vector quantization quantizes the encoder output y=enc(x) in turn with Nq stages of vector quantizers Q1,…,QNq (Algorithm 1 of the paper).
Set y^←0 and the residual r←y.
For i=1,…,Nq in order, set y^←y^+Qi(r) and r←r−Qi(r).
Pass y^ to the decoder.
Each quantizer selects the vector closest to its input from a codebook of N vectors. Only the index of the selected vector is transmitted, which is log2N bits per stage. The bitrate R is determined by the number of frames and stages as follows (fs is the sampling rate).
R=Mfs⋅Nqlog2N
For example, with fs=24000, M=320, Nq=8, and N=1024, this gives 75×8×10=6000 bits per second (6 kbps).
Following VQ-VAE-2, the codebooks are updated with exponential moving averages. Two tricks are added so that the codebooks are well utilized.
k-means initialization: run k-means on the first batch and use the centroids as the initial codebook.
Replacing unused vectors: when the exponential moving average (decay 0.99) of the number of assignments to a vector falls below 2, replace it with a frame randomly chosen from the current batch.
Quantizer dropout samples nq uniformly from 1 to Nq for each example during training and uses only Q1,…,Qnq. It can be thought of as applying Dropout at the level of quantizer stages. At inference, nq is chosen to match the desired bitrate.
There are two kinds of discriminators.
Waveform discriminators: discriminators with the same architecture as MelGAN, applied to three versions of the waveform: the original, and the waveform downsampled by 2× and 4×.
STFT discriminator: takes as input the real and imaginary parts of an STFT with window 1,024 and hop 256, and judges it with 2D convolutions and 6 residual blocks. Finally, it aggregates along the frequency axis and outputs a 1D sequence of judgments along time.
There are three losses: the adversarial loss, the feature loss, and the reconstruction loss. Let G(x)=dec(Q(enc(x))) be the generator, k=0 the STFT discriminator, k=1,…,K (K=3) the waveform discriminators, and Tk the number of outputs along time of the k-th discriminator. The adversarial losses for the discriminator and generator are hinge losses.
The feature loss LGfeat is the mean absolute difference between the original and reconstructed audio in the outputs Dk,t(l) of the discriminators' L intermediate layers.
The reconstruction loss LGrec is the difference between 64-band mel spectrograms Sts computed with six window lengths s=26,…,211 (hop s/4, αs=s/2).
The generator loss is a weighted sum of these. In all experiments, the paper uses λadv=1, λfeat=100, and λrec=1.
LG=λadvLGadv+λfeatLGfeat+λrecLGrec
There is also a version that performs compression and denoising at the same time. A FiLM layer injects a condition indicating "denoise or not" into either the encoder output (just before quantization) or the decoder input. FiLM is a layer that transforms features as a~n,c=γn,can,c+βn,c, with coefficients computed from the condition. When denoising, the model is trained to produce clean speech from noisy audio.
Why few bits yield high audio quality
The key to SoundStream is that it splits quantization into residual stages to keep it to a practical size, and trains everything, including the encoder, for audio quality.
Reaching 6 kbps with ordinary vector quantization requires 80 bits per frame. Representing 80 bits with a single codebook would mean holding 280 vectors, which is entirely impractical. With residual vector quantization, stacking just 8 stages of 10-bit (1,024-vector) codebooks gives the same 80 bits. Each stage finely corrects the error that the previous stages could not represent, so adding stages brings the result closer to the original embedding.
Residual vector quantization is like communicating a location on a map by narrowing it down step by step: "which prefecture → which city → which town". The first index fixes the rough location, and later indices provide finer corrections. Stopping partway still conveys the rough location, so bitrate and quality can be adjusted simply by changing how many indices are sent.
Quantizer dropout is what guarantees this "usable even if stopped partway" property during training. In residual vector quantization, changing the number of stages does not change the embedding dimension, so the bitrate can be switched without changing the shape of the encoder or decoder.
The roles of the other ideas are as follows.
Idea
What it does
What it helps with
Learned encoder
Learns features from the waveform instead of using a fixed mel filterbank
Greatly improves quality at the same bitrate (ViSQOL at 6 kbps rises from 3.33 to 3.96)
Residual vector quantization
Splits quantization into many stages and quantizes the remaining error in turn
Achieves high bitrates without an impractically large codebook
Quantizer dropout
Randomly chooses the number of stages used at each training step
A single model supports 3–18 kbps
Waveform and STFT discriminators
Judge whether the reconstructed audio sounds real
Reduce muffled sound and noise even at low bitrates
Reconstruction and feature losses
Match the spectrogram and discriminator features to the original audio
Preserve fidelity to the original audio
Causal convolutions
Compute using only past samples
Latency is determined solely by the product of strides (320 samples, about 13 ms), enabling streaming
Experimental results
The paper trained on 24 kHz audio: clean speech (LibriTTS), the same speech mixed with Freesound noise, and music (MagnaTagATune). For evaluation it used 200 clips of 2–4 seconds, 50 from each of four categories: these three plus speech recorded in real environments with noise and reverberation. Subjective evaluation used crowdsourced listening tests modeled on MUSHRA, with 20 ratings per clip. For development and ablations, the objective metric ViSQOL (higher is better; maximum 5) was used.
Comparison with conventional codecs (from the text of Section V-A of the paper. Since the numbers are shown in graphs, only the ratios stated in the text are listed)
SoundStream bitrate
Bitrate needed for the same quality
3 kbps
EVS needs 9.6 kbps or more, Opus 12 kbps or more (3.2–4×)
6 kbps
EVS and Opus need 2.2–2.6×
12 kbps
EVS and Opus need 1.3–1.6×
SoundStream at 3 kbps greatly outperformed Opus at 6 kbps and EVS at 5.9 kbps (the lowest bitrates at which each operates), and also outperformed Lyra at the same 3 kbps. For music, too, 3 kbps was rated higher than Opus at 12 kbps.
Encoder and decoder size (6 kbps; speed measured as a multiple of real time on a single thread of a Pixel 4 CPU)
Cenc
Cdec
Parameters
Encoding speed
Decoding speed
ViSQOL
32
32
8.4 M
2.4×
2.3×
4.01 ± 0.03
16
16
2.4 M
7.5×
7.1×
3.98 ± 0.03
16
32
5.5 M
7.5×
2.3×
4.02 ± 0.03
8
32
4.8 M
18.6×
2.3×
3.99 ± 0.03
32
16
5.3 M
2.4×
7.1×
3.97 ± 0.03
32
8
4.4 M
2.4×
17.1×
3.90 ± 0.03
Shrinking the encoder barely changed quality, while shrinking the decoder reduced it.
Number of stages and codebook size (all at 6 kbps)
Number of stages Nq
Codebook size N
ViSQOL
8
1,024
4.01 ± 0.03
16
32
3.98 ± 0.03
80
2
3.92 ± 0.03
Even with 80 stages of 1-bit quantizers, the drop in quality is small, confirming that deep residual vector quantization can be trained.
Latency (all at 6 kbps; the number of stages is adjusted to keep the bits per frame matched)
Strides
Latency
Stages
Encoding speed
Decoding speed
ViSQOL
(1, 4, 5, 8)
7.5 ms
4
1.6×
1.5×
4.01 ± 0.02
(2, 4, 5, 8)
13 ms
8
2.4×
2.3×
4.01 ± 0.03
(4, 4, 5, 8)
26 ms
16
4.1×
4.0×
4.01 ± 0.03
Results of other experiments are as follows.
Bitrate scalability: a single model trained with quantizer dropout achieved almost the same quality as models trained separately for each bitrate. At 9 kbps and 12 kbps it was slightly better.
Room for entropy coding: based on the skew in the frequency of the quantized indices, bits could be reduced by a further 7–20% (the paper evaluates at fixed bitrates).
Joint denoising: on noisy speech from VCTK, performing compression and denoising with a single model gave ViSQOL of 2.93 at 0 dB SNR and 3.58 at 15 dB. This is close to using separate models for compression and denoising (3.02–3.05 at 0 dB, 3.63–3.64 at 15 dB), with half the computation and no added latency.
Practical considerations
Keep the following points in mind when using SoundStream.
Latency vs. bits: latency is determined by the product of the strides (about 13 ms with the default 320 samples). Shortening latency increases the number of frames per second, so at the same bitrate the number of bits per frame (number of stages) must be reduced.
The computational burden belongs on the decoder side: in the paper's experiments, shrinking the decoder reduced quality, while shrinking the encoder barely changed it. When downsizing to fit device performance, shrink the encoder first.
Number of stages and codebook size: fewer stages with larger codebooks give slightly better quality, but increase computation and memory.
Where to inject the denoising condition: denoising on the encoder side (before quantization) makes the index distribution more skewed, which could allow entropy coding to reduce bits further. Denoising on the decoder side does not have this benefit.
The paper's main comparisons are ViSQOL and MUSHRA-style listening tests, and many of the numbers are shown only in graphs. In addition, the training hyperparameters (such as the learning rate) are not given in the paper. The EnCodec paper reports that, because the original training code was not released, it reimplemented SoundStream from the paper's description and found that the STFT discriminator tended to diverge, only becoming stable after adding Layer Normalization. If you reimplement it yourself, you will need to search for such settings again.
Comparison with other codecs
SoundStream and other codecs compare as follows.
Codec
Method
Learned?
Target audio
Bitrate range
Bitrate switching
Opus
Conventional signal processing (combination of waveform and parametric)
No
Speech, music
6–510 kbps
Switched by settings
EVS
Conventional signal processing
No
Speech, music
5.9–128 kbps
Switched by settings
Lyra
Decodes quantized mel spectrograms with an autoregressive model
SoundStream's design plus LSTMs, with a multi-resolution STFT discriminator
All jointly
Speech, music, general audio; 48 kHz stereo
1.5–24 kbps
Same method as SoundStream
As a rule of thumb:
When low latency is needed, as in device-to-device calls: a neural codec that can stream with causal convolutions, like SoundStream, is a good fit.
When compatibility and a proven track record matter: Opus or EVS are good fits. They are widely used and require no distribution of trained models.
When using it as "tokens" for audio generation models: residual vector quantization indices can be handled directly by language models. VALL-E uses the indices of EnCodec, which has the same design as SoundStream, as tokens for speech synthesis.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of SoundStream's encoder, residual vector quantization (with quantizer dropout), and decoder, following Section III and Algorithm 1 of the paper.
PyTorch has no built-in SoundStream. The discriminators and losses follow the same ideas as the HiFi-GAN and MelGAN article implementations, so they are omitted.
"""
class CausalConv1d(nn.Conv1d):
"""Convolution padded only on the past side (never sees future samples)"""
def forward(self, x):
pad = (self.kernel_size[0] - 1) * self.dilation[0]
return super().forward(F.pad(x, (pad, 0)))
class CausalConvT1d(nn.ConvTranspose1d):
"""Trim the right end (future side) of the transposed conv output so its length is input × stride"""
def forward(self, x):
y = super().forward(x)
return y[..., : x.shape[-1] * self.stride[0]]
class ResidualUnit(nn.Module):
def __init__(self, ch, dilation):
super().__init__()
self.conv1 = CausalConv1d(ch, ch, 7, dilation=dilation) # Fig. 3 of the paper: width 7, dilation d → width 1
self.conv2 = CausalConv1d(ch, ch, 1)
def forward(self, x):
return x + self.conv2(F.elu(self.conv1(F.elu(x)))) # ELU, no normalization
class EncoderBlock(nn.Module):
def __init__(self, ch_in, ch_out, stride):
super().__init__()
self.res = nn.Sequential(*[ResidualUnit(ch_in, d) for d in (1, 3, 9)])
self.down = CausalConv1d(ch_in, ch_out, 2 * stride, stride=stride)
def forward(self, x):
return self.down(F.elu(self.res(x)))
class DecoderBlock(nn.Module):
def __init__(self, ch_in, ch_out, stride):
super().__init__()
self.up = CausalConvT1d(ch_in, ch_out, 2 * stride, stride=stride)
self.res = nn.Sequential(*[ResidualUnit(ch_out, d) for d in (1, 3, 9)])
def forward(self, x):
return self.res(self.up(F.elu(x)))
class VectorQuantizer(nn.Module):
"""One stage of vector quantization. The codebook is updated by EMA, and unused vectors are replaced"""
def __init__(self, n_codes=1024, dim=128, decay=0.99, dead_threshold=2.0):
super().__init__()
self.decay, self.dead_threshold = decay, dead_threshold
self.register_buffer("codebook", torch.randn(n_codes, dim))
self.register_buffer("ema_count", torch.ones(n_codes))
self.register_buffer("ema_sum", self.codebook.clone())
self.register_buffer("initialized", torch.tensor(False))
def forward(self, r): # r: [N, D] (frames stacked)
if self.training and not self.initialized: # k-means initialization on the first batch (simplified to a few iterations here)
centers = r[torch.randint(0, r.shape[0], (self.codebook.shape[0],))].clone()
for _ in range(10):
idx = torch.cdist(r, centers).argmin(1)
onehot = F.one_hot(idx, centers.shape[0]).type(r.dtype)
cnt = onehot.sum(0)
centers = torch.where(cnt[:, None] > 0, onehot.t() @ r / cnt.clamp(min=1)[:, None], centers)
self.codebook.copy_(centers); self.ema_sum.copy_(centers); self.initialized.fill_(True)
idx = torch.cdist(r, self.codebook).argmin(1) # Index of the nearest vector (this is what is transmitted)
q = self.codebook[idx]
if self.training: # EMA update of the codebook
with torch.no_grad():
onehot = F.one_hot(idx, self.codebook.shape[0]).type(r.dtype)
self.ema_count.mul_(self.decay).add_(onehot.sum(0), alpha=1 - self.decay)
self.ema_sum.mul_(self.decay).add_(onehot.t() @ r, alpha=1 - self.decay)
self.codebook.copy_(self.ema_sum / self.ema_count.clamp(min=1e-5)[:, None])
dead = self.ema_count < self.dead_threshold # Replace unused vectors with frames from the batch
if dead.any():
pick = r[torch.randint(0, r.shape[0], (int(dead.sum()),))]
self.codebook[dead] = pick; self.ema_sum[dead] = pick; self.ema_count[dead] = 1.0
q_st = r + (q - r).detach() # Pass gradients straight through (straight-through)
return q_st, idx
class ResidualVQ(nn.Module):
def __init__(self, n_q=8, **kw):
super().__init__()
self.layers = nn.ModuleList(VectorQuantizer(**kw) for _ in range(n_q))
def forward(self, y, n_q=None): # y: [B, D, S]
B, D, S_ = y.shape
if n_q is None:
# Training: quantizer dropout (n_q sampled uniformly from 1..N_q). Inference: all stages
n_q = int(torch.randint(1, len(self.layers) + 1, ())) if self.training else len(self.layers)
residual = y.permute(0, 2, 1).reshape(-1, D)
y_hat, codes = torch.zeros_like(residual), []
for layer in self.layers[:n_q]: # Algorithm 1
q, idx = layer(residual)
y_hat = y_hat + q
residual = residual - q.detach()
codes.append(idx.view(B, S_))
return y_hat.view(B, S_, D).permute(0, 2, 1), torch.stack(codes, 1) # codes: [B, n_q, S]
class SoundStream(nn.Module):
def __init__(self, C=32, D=128, strides=(2, 4, 5, 8), n_q=8, n_codes=1024):
super().__init__()
enc = [CausalConv1d(1, C, 7)]
ch = C
for s in strides: # Channels double at each downsampling
enc.append(EncoderBlock(ch, ch * 2, s)); ch *= 2
enc += [nn.ELU(), CausalConv1d(ch, D, 3)]
self.encoder = nn.Sequential(*enc)
self.rvq = ResidualVQ(n_q, n_codes=n_codes, dim=D)
dec = [CausalConv1d(D, ch, 7)]
for s in reversed(strides):
dec.append(DecoderBlock(ch, ch // 2, s)); ch //= 2
dec += [nn.ELU(), CausalConv1d(ch, 1, 7)]
self.decoder = nn.Sequential(*dec)
def forward(self, x, n_q=None): # x: [B, 1, T], T a multiple of 320
y = self.encoder(x) # [B, D, T/320] (75 frames/s at 24 kHz)
y_hat, codes = self.rvq(y, n_q)
return self.decoder(y_hat), codes
model = SoundStream()
x = torch.randn(2, 1, 24000) # 1 second at 24 kHz
model.train()
x_hat, codes = model(x) # Number of stages is random
print(x_hat.shape, codes.shape) # [2, 1, 24000], [2, n_q, 75]
model.eval()
with torch.no_grad():
for n_q in (4, 8): # At inference, choose the number of stages for the desired bitrate
x_hat, codes = model(x, n_q=n_q)
print(n_q, "stages =", 75 * n_q * 10 / 1000, "kbps") # 3.0 kbps, 6.0 kbps
FAQ
Q. How is SoundStream's bitrate determined?
A.
It is frames per second × number of stages × bits per stage. Compressing a 24 kHz waveform by the stride product of 320 gives 75 frames per second, and using 8 stages of 1,024-vector (10-bit) codebooks gives 75×8×10=6000 bits per second, i.e., 6 kbps. Using 4 stages at inference gives 3 kbps.
Q. What happens without quantizer dropout?
A.
A separate model must be trained for each bitrate. In the paper, when a model trained at 18 kbps without dropout was run at lower bitrates by using fewer stages, the quality degradation grew as the bitrate decreased. Training with quantizer dropout eliminated this gap, giving almost the same quality as models trained separately for each bitrate.
Q. What is the difference between SoundStream and EnCodec?
A.
EnCodec inherits SoundStream's encoder, residual vector quantization, and decoder design, adds two-layer LSTMs to the encoder and decoder, consolidates the discriminators into a single multi-resolution STFT discriminator, and adds a mechanism (a balancer) that sets the loss weights according to gradient proportions. It also supports 48 kHz stereo and shows how to reduce the bit count further with a small Transformer.