33 / 33 · Audio Generation
Audio generation: text-to-speech and music
The course's tools applied to sound: waveforms and mel spectrograms, the text-to-speech pipeline, Glow-TTS as a normalizing flow with a text-conditioned prior and monotonic alignment search, neural audio codecs with residual vector quantization, and MusicGen, one transformer over parallel codebook streams with text, melody and audio prompts.
Autoregressive transformers: ImageGPT, VQGAN, DALL·E and Parti · Flow architectures · VAE variants: β-VAE and VQ-VAE · Latent diffusion and Stable Diffusion
On this page 11
The previous note turned images into sequences of discrete tokens and generated them with a transformer, steered by temperature, top- and classifier-free guidance. Sound poses the same problem at a larger scale. One second of audio is tens of thousands of numbers, more than a small image, and a piece of music lasts minutes. This note follows two answers. Text-to-speech keeps a continuous intermediate representation, the mel spectrogram, and Glow-TTS generates it with a normalizing flow whose prior is set by the text. Music generation compresses the waveform with a neural codec into a few parallel streams of tokens, and MusicGen models all of them with one transformer, conditioned on a text, a melody or the beginning of a recording.
Notation. A waveform is seconds of sound sampled at samples per second. A mel spectrogram has frequency bands and frames. A text is a sequence of tokens : phonemes for speech, subwords for music descriptions. A codec encodes a waveform into latent frames at a frame rate and quantizes each frame with codebooks of vectors each, which gives codes . As in the flow notes, a flow maps the latent to the data, , and the variance is the second argument of .
Sound as a signal#
A microphone records air pressure. Sampled times per second, it becomes a waveform, a sequence of numbers in , and the sampling theorem says that frequencies up to are kept. Speech is commonly sampled at 16 to 22.05 kHz; music needs the whole audible range and is recorded at 44.1 or 48 kHz (Copet et al., 2023, §1). The LJ Speech dataset, a standard single-speaker corpus, stores 16-bit mono audio at 22,050 Hz: 352,800 bits and 22,050 numbers per second (Ito and Johnson, 2017). An autoregressive model over raw samples, such as WaveNet (van den Oord et al., 2016), takes one network pass per sample, 22,050 passes per second of speech.
The spectrogram describes the same sound by which frequencies are present when. The short-time Fourier transform cuts the waveform into overlapping windows and takes the Fourier transform of each; the magnitudes form a time–frequency image. For example, with a window of 1024 samples (46.4 ms at 22,050 Hz) and a hop of 256 samples (11.6 ms) there are frames per second.
The mel spectrogram compresses the frequency axis the way hearing does. Pitch perception is roughly linear below 1 kHz and logarithmic above, and the mel scale follows it; one common form is , which maps 1000 Hz to 1000 mel and 11,025 Hz to 3176 mel. A bank of triangular filters, equally spaced in mel, sums the magnitudes into bands, narrow at low frequencies and wide at high ones, and the result is put on a log scale. With bands, one second of speech becomes numbers instead of 22,050, about 3.2 times fewer, and neighbouring frames are strongly correlated, which makes the sequence easy to model.
The price is the phase. The magnitudes say how much of each frequency is present but not how the waves line up, and the filter bank discards detail as well, so a mel spectrogram does not determine its waveform. A vocoder has to produce a plausible one. The classical method, Griffin–Lim (Griffin and Lim, 1984), alternates between the time and frequency domains, keeping the given magnitudes and re-estimating the phase; it needs no training, but its phase is only approximate and the result has audible artifacts. Neural vocoders learn the mapping from data.
This gives the two routes of the note. Text-to-speech generates a mel spectrogram and hands it to a vocoder. Music generation learns a discrete code of the waveform itself, as VQGAN did for images, and generates the code.
The text-to-speech pipeline#
A text-to-speech (TTS) system turns written text into a waveform in stages, each a conditional model.
- Text normalization writes out what is not spelled as it is spoken: numbers, dates, abbreviations, symbols. “Dr. Smith paid £5 on 3 May” must become words before anything can be pronounced. LJ Speech ships each clip’s text twice, as written and in a normalized form with numbers, ordinals and monetary units written out as words.
- Grapheme-to-phoneme conversion (G2P) maps letters to phonemes, for example in the International Phonetic Alphabet. English spelling is ambiguous: “read” has two pronunciations, and “though”, “through” and “tough” spell the ending “ough” with three different vowels. A rule-based phonemizer such as eSpeak, or a learned G2P model, removes this burden from the acoustic model.
- Linguistic and phonetic analysis adds what the phonemes do not say: stress, phrase boundaries, intonation. In neural systems this is mostly implicit in the acoustic model.
- The acoustic model maps the phoneme sequence to a mel spectrogram.
- The vocoder maps the mel spectrogram to a waveform.
The acoustic model faces the central difficulty of TTS: alignment. The input has tens of phonemes, the output hundreds of frames, and how many frames each phoneme lasts is not given by the data. Tacotron 2 (Shen et al., 2018) decodes frames autoregressively and learns an attention over the input tokens that decides, frame by frame, which of them is being spoken; a WaveNet vocoder then produces the waveform. Generation is sequential, and attention errors make it skip or repeat words, especially on long or repetitive inputs (Kim et al., 2020, §1). FastSpeech (Ren et al., 2019) generates all frames in parallel: a length regulator repeats each phoneme’s hidden vector as many times as its predicted duration. Its duration targets, however, come from the attention of a pretrained autoregressive teacher, so the parallel model still depends on an external aligner.
Vocoders span the families of the course. WaveNet is autoregressive over samples. WaveGlow (Prenger, Valle and Catanzaro, 2019) is a normalizing flow from Gaussian noise to the waveform, conditioned on the mel spectrogram and trained by maximum likelihood. GAN vocoders are the fastest: HiFi-GAN (Kong, Kim and Bae, 2020) trains a convolutional generator against a multi-scale discriminator and a multi-period discriminator, whose sub-discriminators look at every -th sample for to catch the periodic structure of voiced speech, together with an loss on mel spectrograms and a feature-matching loss. On LJ Speech its listeners’ mean opinion score, 4.36, approaches the 4.45 of the recordings, at 167.9 times faster than real time on one V100 GPU. Multi-band MelGAN (Yang et al., 2020) is a lighter GAN vocoder of the same kind, and LPCNet (Valin and Skoglund, 2019) combines classical linear prediction with a small recurrent network, cheap enough for phones and embedded devices.
The pipeline can also collapse into one model. VITS (Kim, Kong and Son, 2021) is a conditional VAE whose prior is a normalizing flow conditioned on the phonemes and whose decoder is a HiFi-GAN generator trained adversarially; it outputs the waveform directly. Speaker identity is one more condition. A multi-speaker model either learns an embedding per speaker ID, as VITS does for the 109 speakers of the VCTK corpus, or reads a speaker embedding computed by a separate speaker encoder from a reference recording. YourTTS (Casanova et al., 2022) builds on VITS with such an encoder, so a short recording of a voice unseen in training is enough to synthesize new text in it.
Glow-TTS: a flow with a text-conditioned prior#
Glow-TTS (Kim et al., 2020) is a parallel acoustic model that learns its own alignment. It combines two ideas of the course: an exact likelihood from a normalizing flow, and a search over alignments by dynamic programming.
The likelihood#
The decoder is an invertible flow from a latent sequence , , to the mel spectrogram. For a fixed alignment of latent frames to text tokens, defined below, the change of variables gives
The decoder does not see the text. The text enters through the prior: a text encoder reads the phonemes and outputs a mean and standard deviations for every token . The alignment says which token each latent frame belongs to, and the prior is a product of Gaussians:
A person reads text in order without skipping words, so is required to be monotonic (it never goes back) and surjective (every token gets at least one frame).
Maximizing over the parameters and the alignment jointly is intractable, so training alternates. Given , find the most probable alignment ; given , take a gradient step on . Because and the log-determinant do not depend on , the first step only has to maximize the prior term. This is Viterbi training: it maximizes , the likelihood under the single best alignment, found by the search below. A marginal likelihood of the text alone, , would need a model of alignments and a sum over all of them.
Monotonic alignment search#
There are monotonic surjective alignments, one for each choice of the frames at which a new token starts. For about 50 phonemes and 430 frames, five seconds of speech, that is . Monotonic alignment search (MAS) finds the best one by dynamic programming. Let be the largest log-likelihood of the first frames aligned to the first tokens with frame on token . Monotonicity and surjectivity leave frame only two options, token or token , so
The table has cells, 21,500 in the example above. The alignment is read off backwards: start at and at each earlier frame take whichever of the two predecessors has the larger . The paper reports under 20 ms per iteration on a CPU, less than 2% of training time, and MAS is not needed at inference.
Worked example. Take three tokens with one-dimensional means and , the value the paper fixes during training, and six latent frames . With , , and every alignment uses each frame exactly once, so maximizing is minimizing the summed squared distance , with :
| token 1, | 0.04 | 0.13 | 5.89 | 6.70 | 20.39 | 37.20 |
| token 2, | — | 2.93 | 0.29 | 1.50 | 4.39 | 8.80 |
| token 3, | — | — | 5.49 | 9.90 | 1.59 | 1.60 |
Backtracking from the corner, 1.60, picks the bold cells: , durations , total cost 1.60, and a prior log-likelihood of . Frame is closer to (squared distance 0.81) than to (1.21). Assigning every frame to its nearest mean gives with a smaller total, 1.20, but it returns from token 2 to token 1, which a reader never does. MAS pays 1.60 for the best alignment that is allowed.
Durations and sampling#
At inference there is no mel spectrogram to align, so the alignment must be predicted. MAS provides the training targets: the duration of token is the number of frames aligned to it, , in the example. A duration predictor , two convolutional layers on top of the encoder output , is trained with a squared error on log durations,
where the stop-gradient keeps this loss from changing the encoder, which the likelihood trains.
Synthesis is then parallel. The encoder gives ; the predictor gives durations, which are rounded up and expand the means and standard deviations into a frame sequence, as FastSpeech’s length regulator does; the latent is sampled as with ; and one pass of the decoder gives . The temperature scales the standard deviations of the prior. The paper’s experiments fix (Kim et al., 2020, §4), and so do the authors’ released configuration and the default of Coqui TTS (mean_only): the encoder predicts only the means, the latent is , and is the standard deviation used at sampling, as in eq. 8 of the paper. Different noise gives different stress and intonation of the same sentence, changing alone shifts the pitch while keeping a similar intonation, and multiplying all durations by a constant changes the speaking rate; the paper shows factors from 0.5 to 1.25. Listeners rated best.
Inside the decoder#
The decoder is a Glow-style stack (flow architectures). Pairs of consecutive 80-band frames are first squeezed into single 160-channel frames, halving the length. Each of 12 blocks then applies an ActNorm layer, an invertible convolution and an affine coupling layer whose scale and shift come from a WaveNet-like convolutional network, as in WaveGlow. The convolution is made cheaper: the 160 channels are split into 40 groups of four, mixed by one shared matrix, so its log-determinant is times the number of squeezed frames times of one matrix. The encoder is a Transformer encoder with relative position representations, 6 blocks of width 192. The whole model has 28.6 million parameters, fewer than FastSpeech’s 30.1 million.
On LJ Speech (13,100 clips, about 24 hours), with WaveGlow as the vocoder, listeners gave Glow-TTS a mean opinion score of 4.01 against 3.88 for Tacotron 2. The recordings scored 4.54, and the recordings converted to mel spectrograms and back by WaveGlow 4.19. That is the reconstruction baseline of this vocoder in this test: the vocoder’s fidelity is a practical bottleneck for any acoustic model that feeds it, but a score measured on reconstructed recordings is not a proven maximum over every spectrogram an acoustic model might produce, and like every listening score it carries uncertainty from the listeners and the sentences. Glow-TTS generated mel spectrograms 15.7 times faster than Tacotron 2, in an almost constant 40 ms regardless of length; for one minute of speech the whole synthesis took 1.5 seconds, 96% of it in the vocoder. On long sentences the character error rate of Tacotron 2 rose beyond about 260 characters while Glow-TTS stayed robust, because a hard monotonic alignment cannot skip or repeat. How such listening scores are collected and compared is the subject of the human evaluation note.
Neural audio codecs: sound as tokens#
Music needs the full bandwidth and many overlapping instruments, and an autoregressive transformer wants discrete tokens. The image answer carries over: train an autoencoder with a discrete bottleneck, here on the waveform, and model its codes. Thirty seconds of music at 32 kHz is 960,000 samples; the codec has to shrink that by orders of magnitude while keeping the sound.
EnCodec#
EnCodec (Défossez et al., 2023) follows SoundStream (Zeghidour et al., 2022). The encoder is a one-dimensional convolutional network: a first convolution with 32 channels, then four blocks of a residual unit and a strided convolution with strides 2, 4, 5 and 8, doubling the channels at every downsampling, then a two-layer LSTM and a final convolution to channels. The total stride is samples, so 24 kHz audio gives 75 latent frames per second and 48 kHz audio 150. The decoder mirrors the encoder with transposed convolutions. Between them, a residual vector quantizer turns each frame into codes.
The losses are those of the VQGAN family, adapted to sound. Reconstruction is measured by an distance on the waveform and by and distances between 64-band mel spectrograms at seven resolutions, with windows of to samples. A multi-scale STFT discriminator, five convolutional networks of the same structure on spectrograms with windows of 2048 down to 128 samples, adds a hinge adversarial loss and a feature-matching loss. The quantizer adds a commitment loss. A loss balancer normalizes the gradient of each loss with respect to the output by its running norm, so that each loss contributes a share of the total gradient proportional to its weight, whatever its natural scale; the weights are 0.1 for time, 1 for frequency, 3 for adversarial and 3 for feature matching.
One model serves several bitrates: in training, each batch keeps a randomly chosen number of codebooks, 2, 4, 8, 16 or 32 at 24 kHz. An optional small transformer predicts the codes for entropy coding and saves up to 40% more. In listening tests of the streamable models (MUSHRA, scores from 0 to 100) at 6 kbps, EnCodec scored 83.1 on clean speech and 92.9 on music against 30.1 and 20.6 for the Opus codec at the same bitrate. The model inside MusicGen is a 32 kHz mono EnCodec with stride 640, so 50 frames per second, and four codebooks of 2048 entries (Copet et al., 2023, §3.1).
Residual vector quantization#
A VQ-VAE replaces each encoder vector by the nearest entry of one codebook. Residual vector quantization (RVQ) quantizes what that leaves, again and again. For a frame ,
and the decoder receives the sum of the chosen vectors,
The sum telescopes, so the quantization error is exactly the last residual. The code of the frame is the list of indices, and stage only has to describe what stages missed: its codebook is trained on residuals, which are smaller than the frames. With this is the VQ-VAE, and training is the same: the straight-through estimator across the argmin, a commitment term per stage, , and codebooks updated as moving averages of the vectors assigned to them, with unused entries replaced by vectors from the current batch.
Residual quantization: three codebooks of four vectors
Worked example. The figure follows one vector of a toy cloud through three codebooks of four entries, each fitted by k-means to the residuals of the previous stages (values rounded to two decimals). The vector , with , is nearest to entry 2 of the first codebook, , which leaves with . The second codebook picks entry 1, , leaving and 0.51. The third picks entry 4, , leaving and 0.11. The code is , six bits, and the decoder reconstructs . Over all 160 points the mean squared error per coordinate falls from 1.396 (the variance of the cloud) to 0.394, 0.137 and 0.051: each stage removes 63 to 72% of what is left.
Why not one large codebook? SoundStream’s example makes the case (Zeghidour et al., 2022, §III-C). At 6 kbps and 75 frames per second each frame gets bits. A single codebook would need entries; eight residual stages of entries spend the same 80 bits with 8192 stored vectors and 8192 distance computations per frame. A single codebook is not worse per bit: the possible sums of an RVQ form one particular codebook of that size, searched greedily, so the best codebook of size is at least as good. The toy cloud shows the gap. With 2000 training and 2000 test points from the same distribution (test variance 1.525 per coordinate):
| Bits per point | RVQ: stages × entries | Test error | One codebook: entries | Test error |
|---|---|---|---|---|
| 2 | 1 × 4 | 0.447 | 4 | 0.447 |
| 4 | 2 × 4 | 0.165 | 16 | 0.139 |
| 6 | 3 × 4 | 0.066 | 64 | 0.044 |
RVQ pays some error per bit for a codebook that grows linearly in the number of bits instead of exponentially. It gains two more properties. The first codes carry the most information, so the streams are ordered from coarse to fine. And training with a random number of stages per example, which SoundStream calls quantizer dropout, gives one model for many bitrates, since dropping the last stages only removes refinements.
How many bits#
A codec with codebooks of entries at frames per second spends
| Codec | Sample rate | Stride | Frames per second | Bits per frame | Bitrate | ||
|---|---|---|---|---|---|---|---|
| SoundStream, 6 kbps | 24 kHz | 320 | 75 | 8 | 1024 | 80 | 6 kbps |
| EnCodec, 24 kHz | 24 kHz | 320 | 75 | 2 to 32 | 1024 | 20 to 320 | 1.5 to 24 kbps |
| EnCodec, 48 kHz stereo | 48 kHz | 320 | 150 | 2 to 16 | 1024 | 20 to 160 | 3 to 24 kbps |
| EnCodec in MusicGen | 32 kHz | 640 | 50 | 4 | 2048 | 44 | 2.2 kbps |
For MusicGen’s codec, bits per second, against for 16-bit samples: 233 times less. As a sequence, one second is 200 codes instead of 32,000 samples. A transformer that emits one frame of four codes per step, as MusicGen does, needs 50 steps per second, 640 times fewer than a sample-level model.
MusicGen: one transformer over parallel streams#
MusicGen (Copet et al., 2023) generates the four code streams of that codec with a single autoregressive transformer decoder, conditioned on a text description and optionally on a melody, and decodes the codes with EnCodec. Earlier systems cascaded several models over such streams: MusicLM (Agostinelli et al., 2023) models semantic and acoustic tokens with a hierarchy of transformers, and VALL-E (Wang et al., 2023), a speech model, generates the first codebook autoregressively and the rest with a second, non-autoregressive model. MusicGen’s question is how to lay out parallel streams so that one model can predict them.
Interleaving the codebooks#
The exact answer is to flatten the codes into one sequence, frame by frame and codebook by codebook within a frame: . The chain rule then factorizes the joint distribution exactly, as for pixels, but the sequence has steps, 6000 for 30 seconds, and the gain of the low frame rate is partly lost.
The cheap answer predicts several codes in one step from the same past. Predicting all codes of frame together means modelling
which is exact only if the codes of a frame are independent given the past. In RVQ they are not: stage encodes exactly what the stages before it missed. The paper describes all such choices as a pattern: a sequence of sets that partition the cells , with each codebook at most once per set. At step the model predicts all cells of in parallel from the cells of . Four patterns:
- Flattening, one cell per step: .
- Parallel, : , and the codes of a frame are chosen independently of each other.
- Coarse first, all of codebook 1, then codebooks 2 to in parallel frame by frame: . This is the VALL-E arrangement in a single model.
- Delay, (Copet et al., 2023, eq. 6): codebook is shifted by steps, so .
Four ways to lay four code streams out as generation steps
In the delay pattern the code is predicted at step , after the codes of codebooks of the same frame, which come at steps . It therefore sees the coarser codes of its own frame, the dependency RVQ creates, at almost the cost of the parallel pattern. What it does not see are the finer codes of the latest frames: codebook 1 of frame is predicted in the same step as codebook 2 of frame , codebook 3 of frame and codebook 4 of frame . The ablation of the paper (Table 4, a 300-million-parameter model, 30-second excerpts) measures the trade-off with the Fréchet audio distance (FAD), the FID of audio computed on embeddings of the VGGish audio classifier (Kilgour et al., 2018). Flattening scores 0.86 with 6000 steps, delay 0.96 with 1500, coarse first 1.98 with 3000, and parallel 2.58 with 1500. Listeners rated flattening and delay equally, 79.7, and parallel lower, 72.2. The delay pattern buys nearly the quality of the exact factorization at a quarter of its steps, and MusicGen uses it.
The transformer and its objective#
At step the input is the sum of embeddings of size , the width of the transformer, one from each codebook’s own table of entries; a codebook that is absent from contributes a special empty token. A sinusoidal encoding of is added. Each of layers has causal self-attention over the earlier steps, cross-attention to the conditioning, and a feed-forward block from width to and back, with layer normalization before each block. The output feeds linear heads, one per codebook, each giving logits for that codebook’s cell in . Training minimizes the cross-entropy of every code given the steps before it,
where is the conditioning. The models have 300 million parameters (, 16 heads, 24 layers), 1.5 billion (1536, 24, 48) and 3.3 billion (2048, 32, 48). They were trained on 30-second crops of 20,000 hours of licensed music (10,000 high-quality tracks and 390,000 instrument-only tracks from stock collections), downmixed to mono at 32 kHz, for one million steps with AdamW and batches of 192.
Text conditioning#
A description such as ”90s rock song with a guitar riff” is encoded by a pretrained T5 encoder (Raffel et al., 2020), kept frozen in the released models, and projected linearly to the width of the decoder: a sequence of vectors , one per token of the description. Every decoder layer reads it through cross-attention: queries from the audio steps, keys and values from the text, as the U-Net of latent diffusion does. The paper also tried FLAN-T5 and CLAP, a joint text–audio embedding. T5 and FLAN-T5 performed alike (FAD 3.12 and 3.36 on MusicCaps), CLAP worse (4.16). Training descriptions are augmented: with probability 0.25 metadata such as genre, key and tempo is appended, the description itself is then dropped with probability 0.5, and words are dropped with probability 0.3.
Classifier-free guidance on logits#
As in latent diffusion, the condition is dropped during training, here with probability 0.2, so one network learns both and ; in the released implementations the null condition is a zero text encoding. At sampling time, for every code, the two sets of logits are extrapolated with a guidance scale :
Logits are log-probabilities up to a constant per distribution, and . Hence , and the softmax removes the constant:
This is the tilt that the guided score has at each noise level in diffusion, and here it is exact for one step: given the codes before it, each code is drawn from the tilted conditional. Over a whole sequence the sampled distribution is the product of these tilts, each normalized separately, which in general is not the tilt of the whole sequence normalized once, just as guided diffusion does not in general sample the tilted endpoint distribution. Writing by Bayes’ rule gives : the unconditional distribution reweighted by an implicit classifier raised to the power . MusicGen samples with .
Worked example. Take three codes with and . With the unnormalized weights are , and , which normalize to . The code that the condition favours more than the prior does takes almost all the mass, and the entropy falls from 1.49 to 0.50 bits: guidance makes samples follow the text more closely and vary less. Each step costs two forward passes, which are run as one batch.
Melody conditioning#
Text describes style but not a tune. MusicGen can also follow the melody of a reference recording through its chromagram: the energy in each of the 12 pitch classes (C, C♯, …, B, all octaves together) over time. The reference is first separated with Demucs (Défossez et al., 2019) and its drums and bass are dropped, because they dominate the chromagram. The chromagram is computed with windows of samples and a hop of (0.128 s, about 7.8 frames per second), and only the strongest pitch class of each frame is kept. That information bottleneck matters: with the full chromagram the model learned to reconstruct the reference instead of composing. The quantized chromagram is given as a prefix to the decoder input instead of through cross-attention; the released melody model puts the text encoding in the same prefix. No labelled melody data is needed. For the 1.5-billion model, the cosine similarity between the chromagrams of the reference and the output rose from 0.10 without the melody condition to 0.66 with it, and listeners’ melody-match ratings from 64.4 to 72.9 (Table 2).
Continuing a recording#
The codec also works in the other direction. The first seconds of a recording are encoded into codes, laid out by the delay pattern, and given as the beginning of the sequence; the model continues it, with or without a text description, and EnCodec decodes prompt and continuation together. This is the image completion of ImageGPT, done with sound. The limits are those of the training setup: positions were trained on 30-second crops, 1500 frames, and the prompt counts towards them.
Sampling and results#
Codes are sampled with top- filtering, of the 2048 codes, at temperature 1, after guidance. On the MusicCaps benchmark the 3.3-billion model had the best overall quality in the listening test, 84.8 out of 100 against 80.5 for MusicLM, and the 1.5-billion model the best match to the text, 83.7 (Table 1). By FAD the 300-million model, 3.1, beat MusicLM, 4.0, but not the diffusion model Noise2Music, 2.1. Scale helps the text more than the sound: on the authors’ test set, the overall quality peaked at 1.5 billion parameters (81.9 against 78.3 and 79.2), while the text match improved steadily (82.5, 82.9, 83.5; Table 5).
What changed#
| Image transformers (previous note) | Glow-TTS | MusicGen | |
|---|---|---|---|
| Generated signal | image | mel spectrogram of speech | music waveform at 32 kHz |
| Representation | grid of codes from one codebook | continuous frames, per second | 4 parallel RVQ streams, 50 frames per second |
| Generator | causal transformer, one token per step | normalizing flow, all frames in one pass | causal transformer, one frame step per pass |
| Likelihood | exact over tokens | exact over mel frames, under the best alignment | exact, with codes of one step modelled as independent |
| Conditioning | text tokens in the sequence or an encoder | prior means from a text encoder, durations from a predictor | frozen T5 by cross-attention; chroma prefix; audio prefix |
| Alignment to the text | none needed | monotonic alignment search | none: attention decides |
| Steering | top-, top-, guidance, reranking | prior temperature, duration scale | top- with , guidance with |
| From codes to signal | VQGAN decoder | separate vocoder | EnCodec decoder |
Limitations#
- The vocoder is a bottleneck. Recordings passed through mel spectrograms and back scored 4.19 against 4.54 for the originals; in practice a two-stage system is limited by its second stage, and the reconstruction score is the usual reference, not a proven maximum (how such scores are compared).
- One rhythm per sentence. Glow-TTS predicts durations deterministically, so a sentence is always spoken with the same timing; only intonation varies with the noise. VITS adds a stochastic duration predictor for this reason. Viterbi training also learns from the best alignment only.
- The codec is a bottleneck. As the reconstruction FID of VQGAN is a practical reference for its image transformer, the reconstruction quality of EnCodec at 2.2 kbps limits MusicGen in practice.
- The factorization is approximate. Codes predicted in the same step are assumed independent given the past; the delay pattern narrows the gap to exact flattening (FAD 0.96 against 0.86) but does not close it.
- Length. Training on 30-second crops limits generation to 30 seconds; longer pieces are built by repeated continuation, without a model of their global form.
- Sequential sampling. MusicGen needs 50 decoder passes per second of audio, each over a doubled batch with guidance.
- Control and data. Text gives coarse control, mainly through the guidance scale. The training music is mostly western-style, with Dance/EDM the largest genre. Voice cloning from a short recording makes impersonation easy, and speech corpora with few speakers make those voices easy to overuse.
Summary#
- Audio is long: 22,050 to 48,000 samples per second. Speech systems shorten it with a mel spectrogram, about 6900 numbers per second of speech, and a vocoder restores the phase; music systems learn a discrete code of the waveform.
- The TTS pipeline is text normalization, grapheme-to-phoneme conversion, an acoustic model and a vocoder. Its core difficulty is the alignment between tens of phonemes and hundreds of frames.
- Glow-TTS is a normalizing flow from mel frames to a Gaussian prior whose means come from a text encoder. Monotonic alignment search finds the most likely monotonic alignment by dynamic programming in ; a duration predictor replaces it at inference, and the flow generates all frames in one pass.
- Neural codecs such as EnCodec are VQ-VAEs trained with GAN losses on waveforms. Residual vector quantization codes each frame with codebooks, each quantizing the residual of the previous ones; the error is the last residual, and the bitrate is , 2.2 kbps for MusicGen’s codec.
- MusicGen predicts the four code streams with one transformer. The delay pattern shifts codebook by steps, so each code sees the coarser codes of its own frame, at steps instead of .
- Text enters through a frozen T5 encoder and cross-attention, a melody through an argmax chromagram prefix, a recording through its codes as a prefix. Classifier-free guidance on logits samples each code from given the codes before it, with and top- 250.
Notebook#
The audio generation notebook of the HSE-LAMBDA Deep Generative Models repository runs text-to-speech with the Coqui TTS library and music generation with MusicGen in Hugging Face Transformers (cell numbers count every cell, markdown included, from 1).
- Cells 1–2: the TTS pipeline. Contents, and the four stages: text preprocessing with normalization and G2P, linguistic and phonetic analysis, an acoustic model (Tacotron, FastSpeech or VITS) and a vocoder (WaveGlow, HiFi-GAN or LPCNet).
- Cells 3–5: setup. Installs
transformers,datasets[audio]and Coqui’sTTSpackage, and the eSpeak phonemizer, which Coqui uses for G2P in English. - Cells 6–9: pretrained inference.
tts --list_modelsprints Coqui’s model registry. Cell 8 synthesizes “hello world” withtts_models/en/ljspeech/glow-tts, a Glow-TTS model trained on LJ Speech, which the registry pairs with a multi-band MelGAN vocoder by default; cell 9 plays the result. - Cells 10–14: speaker IDs. A single-speaker model has one voice; a multi-speaker model takes a speaker as a condition.
--list_speaker_idxslists the speakers oftts_models/en/vctk/vits, an end-to-end VITS model trained on VCTK, and cell 13 synthesizes a sentence as speakerp341. - Cells 15–18: voice cloning. Cell 16 downloads a speaker encoder, its configuration and one LJ Speech clip. Cell 17 runs YourTTS (
tts_models/multilingual/multi-dataset/your_tts) with--speaker_wavset to that clip and--language_idx en: the speaker encoder turns the clip into an embedding that conditions the synthesis. - Cells 19–22: data. LJ Speech is downloaded and unpacked into
tts_train_dir, andBaseDatasetConfiguses theljspeechformatter onmetadata.csv; the formatter reads the normalized text column. - Cells 23–25: the training configuration.
GlowTTSConfigwith batch size 32 (16 for evaluation), 4 data-loader workers, evaluation on, test sentences synthesized from the first epoch (test_delay_epochs=-1), 100 epochs, thephoneme_cleanerstext cleaner (number and abbreviation expansion), phonemes foren-uswith a phoneme cache, a log line every 25 steps, mixed precision and a checkpoint every 1000 steps. The model itself keeps the library defaults: 12 flow blocks of width 192, a six-layer relative-position Transformer encoder with two heads, a prior with as in the paper (mean_only=True), 10 steps of data-dependent ActNorm initialization, and RAdam at learning rate with Noam warm-up over 4000 steps. - Cells 26–28: the audio processor.
AudioProcessor.init_from_configwith the default audio settings: 22,050 Hz, a window and FFT of 1024 samples, a hop of 256, 80 mel bands from 0 Hz to the Nyquist frequency, log magnitudes normalized to , and Griffin–Lim with 60 iterations for inversion. These are the settings of the worked numbers in Sound as a signal. Cell 27 pinsnumpy==1.21.0(see the issues below). - Cells 29–30: the tokenizer.
TTSTokenizer.init_from_configbuilds the IPA phoneme vocabulary and the eSpeak phonemizer and returns the updated configuration. - Cells 31–32: the split.
load_tts_samplesholds out the default 1% for evaluation, 131 of the 13,100 clips. Samples are dictionaries withtext,audio_file,speaker_nameandroot_path; the markdown of cell 31 still describes them as lists. - Cells 33–34: the model.
GlowTTS(config, ap, tokenizer, speaker_manager=None), a single-speaker model. - Cells 35–38: the one-batch test. The markdown proposes overfitting a single batch,
train_samples[:batch_size], with “TrainingArgs”. Cell 36 buildsTrainerArgs(shuffle=False, steps_per_epoch=1, epochs=100, output_path="output/", lr=1e-4, save_step=100, save_optimizer_state=True)and aTrainerontrain_samples[:1]andeval_samples[:1]; cell 37 callstrainer.fit(), and cell 38 opens TensorBoard ontts_train_dir. - Cells 39–44: testing. The markdown says that the overfitted model memorizes its one sentence. Cell 41 collects checkpoint and configuration paths with
globbut does not use them. Cell 43 synthesizes “This is the test script for the GlowTTS model” from a hard-coded checkpoint,/content/tts_train_dir/run-February-28-2025_01+53PM-0000000/best_model_1624.pth, and cell 42 offers a 20-epoch checkpoint behind an empty link. Without--vocoder_paththettscommand inverts the mel spectrogram with Griffin–Lim, so the quality of this test is limited by the phase reconstruction however well the model is trained. The sampling temperature is the configuration’sinference_noise_scale, whichGlowTTSConfigdeclares twice, 0.33 and then 0.0; the second declaration wins, so the trained model synthesizes from the prior means, . - Cells 45–46: MusicGen in theory. The three parts (text encoder, autoregressive decoder, EnCodec), EnCodec’s encoder, quantizer and decoder, the count of 4 codebooks × 50 frames = 200 tokens per second against 32,000 samples, the RVQ recursion and the sum , the transformer with code embeddings, positions, self- and cross-attention, the cross-entropy objective, the interleaving patterns and a list of the design choices.
- Cells 47–52: loading.
facebook/musicgen-small, the 300-million model (a comment lists medium 1.5B, melody 1.5B and large 3.3B), moved to the GPU when one is present. - Cells 53–54: the generation configuration.
model.generation_configholdsdo_sample=True,guidance_scale=3.0,max_length=1500(30 seconds) and start and padding tokens 2048, one past the last code. - Cells 55–61: unconditional generation.
get_unconditional_inputs(num_samples=1)supplies a zero text encoding and guidance 1;generate(..., do_sample=True, max_new_tokens=256); the audio is played at the codec’s 32,000 Hz and saved withscipy.io.wavfile.write; cell 61 computes the duration as256 / frame_rate= 5.12 s. - Cells 62–66: text-conditional generation. The processor tokenizes two prompts, a romantic ballad with acoustic guitar and an 80s synthwave track, with padding, and
generate(..., do_sample=True, guidance_scale=3, max_new_tokens=256)produces both; cell 66 explains the guidance scale: values above 1 switch classifier-free guidance on, larger values follow the text more closely at some cost in quality, and 3 is the recommended default. - Cells 67–68: audio-prompted generation. The first clip of a streamed copy of GTZAN (999 clips stored at 32 kHz, the rate the processor requires) is cut to its first half, about 15 seconds, and encoded together with the text “add heavy drums”;
generatecontinues it with guidance 3 for 256 steps. The returned audio contains the prompt followed by the continuation. - Cell 69: conclusion.
Saved outputs. None: no cell of the notebook has been run, so it documents procedures, and there are no audio samples, losses or timings to quote.
Notebook issues.
TrainerArgsdoes not accept these arguments. In Coqui’strainerpackageTrainerArgsis a dataclass with fields such asrestore_path,overfit_batchandsmall_run; it has noshuffle,steps_per_epoch,epochs,output_path,lr,save_steporsave_optimizer_state, so cell 36 stops with aTypeError.epochs,lr,save_stepandoutput_pathare fields of the model configuration (GlowTTSConfiginherits them), and the other three exist nowhere. A working version sets them on the configuration and callsTrainerArgs(), orTrainerArgs(overfit_batch=True), which trains on a single batch, as the markdown intends.- One sample, not one batch.
train_samples[:1]trains on a single clip; the markdown’strain_samples[:batch_size]would give a batch of 32. - NumPy 1.21.0. Cell 27 pins a version with wheels only for Python 3.7 to 3.9, and Coqui’s
TTS0.22.0 itself requiresnumpy==1.22.0on Python 3.10 andnumpy>=1.24.3above, so the pin either fails to build or conflicts with the package. The originalTTSpackage supports Python 3.9 to 3.11 only and is no longer released; on newer Python the maintained forkcoqui-ttsinstalls the sameTTSmodule andttscommand. - The voice-cloning encoder. YourTTS ships with its own speaker encoder and uses it when only
--speaker_wavis given; cell 17’s--encoder_pathreplaces it with the separately downloaded encoder of cell 16. (--encoder_configworks as an abbreviation of--encoder_config_path.) - VITS is not an acoustic model. Cell 2 lists VITS among models that predict a mel spectrogram; VITS outputs the waveform directly.
- Two of the four patterns are described wrongly. Cell 46 calls flattening “all tokens from codebook 1, then all tokens from codebook 2”; the paper’s flattening interleaves the codebooks within each frame, as described above. The “VALL-E pattern” of the first version of the paper (renamed “coarse first” in the final one) generates codebook 1 for all frames and then the others in parallel, steps; it is not a variant of the parallel pattern with offsets.
- Other inaccuracies in cell 46. The released MusicGen models encode text with T5; BART is not used; its codec is the 32 kHz EnCodec (48 kHz is the stereo model of the EnCodec paper); EnCodec’s encoder is convolutional with an LSTM, and a transformer appears only in its optional entropy coder. RVQ is not more accurate than a single codebook at the same bitrate; its advantage is a codebook that can be stored and searched, as above.
- Top- differs from the paper. The generation configuration sets no
top_k, so Transformers falls back to its default of 50 codes, while the paper and the original implementation sample from the top 250. Passingtop_k=250togeneratereproduces the paper’s setting. - The duration is slightly shorter. With the start token and the delay pattern, 256 steps hold complete frames, 5.06 s, not the 5.12 s of cell 61.
- “add heavy drums” is a description. MusicGen was trained on descriptions of the music it hears, not on editing instructions, so the prompt asks for music with heavy drums rather than for an edit of the clip.
The course in one paragraph#
The six families of the course answer the same question, how to train a generator when is unknown, in six ways. VAEs bound the likelihood with an encoder. GANs avoid the likelihood and train against a discriminator; the same adversarial losses translate images between domains. Normalizing flows compute the likelihood exactly with invertible layers. Energy-based models let any network define a density up to its normalizing constant and pay with Markov chains in training and sampling. Diffusion models bound the likelihood again, with a fixed encoder, the noising chain, so that the bound becomes a regression on noise, equivalently on the score. Autoregressive models compute it exactly as a product of conditionals and pay at sampling time. The largest models combine the families: a discrete or continuous autoencoder compresses the image or the sound, and a diffusion model or an autoregressive transformer generates in its latent space. All of them are judged by the same metrics, from Inception Score to precision and recall and human judgement, and all rest on the KL divergence and its relatives.
References#
- J. Kim, S. Kim, J. Kong, S. Yoon. Glow-TTS: A Generative Flow for Text-to-Speech via Monotonic Alignment Search. NeurIPS, 2020. Monotonic alignment search in §3.2 and Algorithm 1; hyperparameters in Appendix A.2.
- J. Copet, F. Kreuk, I. Gat, T. Remez, D. Kant, G. Synnaeve, Y. Adi, A. Défossez. Simple and Controllable Music Generation. NeurIPS, 2023. MusicGen; codebook patterns in §2.2, setup in §3.1, ablations in §4.4 and Appendix A.
- A. Défossez, J. Copet, G. Synnaeve, Y. Adi. High Fidelity Neural Audio Compression. Transactions on Machine Learning Research, 2023. EnCodec.
- N. Zeghidour, A. Luebs, A. Omran, J. Skoglund, M. Tagliasacchi. SoundStream: An End-to-End Neural Audio Codec. IEEE/ACM Transactions on Audio, Speech, and Language Processing, 30, 2022. Residual vector quantization and quantizer dropout in §III-C.
- J. Kong, J. Kim, J. Bae. HiFi-GAN: Generative Adversarial Networks for Efficient and High Fidelity Speech Synthesis. NeurIPS, 2020.
- R. Prenger, R. Valle, B. Catanzaro. WaveGlow: A Flow-based Generative Network for Speech Synthesis. ICASSP, 2019.
- A. van den Oord, S. Dieleman, H. Zen, K. Simonyan, O. Vinyals, A. Graves, N. Kalchbrenner, A. Senior, K. Kavukcuoglu. WaveNet: A Generative Model for Raw Audio. arXiv, 2016.
- J. Shen et al. Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions. ICASSP, 2018. Tacotron 2.
- Y. Ren, Y. Ruan, X. Tan, T. Qin, S. Zhao, Z. Zhao, T.-Y. Liu. FastSpeech: Fast, Robust and Controllable Text to Speech. NeurIPS, 2019.
- G. Yang, S. Yang, K. Liu, P. Fang, W. Chen, L. Xie. Multi-band MelGAN: Faster Waveform Generation for High-Quality Text-to-Speech. arXiv, 2020.
- J.-M. Valin, J. Skoglund. LPCNet: Improving Neural Speech Synthesis Through Linear Prediction. ICASSP, 2019.
- J. Kim, J. Kong, J. Son. Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech. ICML, 2021. VITS.
- E. Casanova, J. Weber, C. Shulby, A. Candido Junior, E. Gölge, M. A. Ponti. YourTTS: Towards Zero-Shot Multi-Speaker TTS and Zero-Shot Voice Conversion for everyone. ICML, 2022.
- D. Griffin, J. Lim. Signal Estimation from Modified Short-Time Fourier Transform. IEEE Transactions on Acoustics, Speech, and Signal Processing, 32(2), 1984.
- K. Ito, L. Johnson. The LJ Speech Dataset. 2017.
- C. Wang et al. Neural Codec Language Models are Zero-Shot Text to Speech Synthesizers. arXiv, 2023. VALL-E.
- A. Agostinelli et al. MusicLM: Generating Music From Text. arXiv, 2023.
- C. Raffel, N. Shazeer, A. Roberts, K. Lee, S. Narang, M. Matena, Y. Zhou, W. Li, P. J. Liu. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. JMLR, 21(140), 2020. T5.
- K. Kilgour, M. Zuluaga, D. Roblek, M. Sharifi. Fréchet Audio Distance: A Metric for Evaluating Music Enhancement Algorithms. arXiv, 2018.
- A. Défossez, N. Usunier, L. Bottou, F. Bach. Music Source Separation in the Waveform Domain. arXiv, 2019. Demucs.
- J. Ho, T. Salimans. Classifier-Free Diffusion Guidance. NeurIPS Workshop on Deep Generative Models, 2021.