Codec language models
A codec language model is a language model whose tokens are pieces of sound. It writes audio the way a text model writes a sentence. It predicts the next token from the ones before it, appends it, and repeats. The tokens come from a neural audio codec, a network that turns a waveform into a short grid of integers and turns the grid back into sound (§37.3). Models built this way clone a voice from three seconds of audio, read text aloud, compose music, and speak inside voice assistants.
Here is the grid in plain words. The codec cuts audio into short frames, of them per second. It describes each frame with integers called codes, , one per level . Each code names one of the vectors in its level's codebook, a learned table. The levels come from residual quantization. Level 1 picks the codebook vector closest to the encoder's vector for the frame. Level 2 picks the vector closest to what level 1 missed, and level 3 corrects what the first two missed. So level 1 is a coarse description of the frame, and each later level is a finer correction. The codec's decoder adds up the chosen vectors of each frame and turns the result back into a waveform.
The obvious plan is the one that worked for text. Write the codes out in one row, frame by frame, and within a frame from level 1 to level . Train a decoder-only Transformer, the model of Chapter 6, to predict the next code of the row. Then prompt it with a few seconds of audio and sample. Two things go wrong.
The first is length. EnCodec, a widely used codec (Défossez et al. 2022), runs at frames per second with levels in its 6 kbps setting. Its row holds tokens per second, so a 30-second clip is 18,000 tokens, and the cost of attention grows with the square of the length (§4.7). The second problem is worse. A team at Google trained exactly this model while building AudioLM (Borsos et al. 2022) and prompted it with 4 seconds of speech. The continuations kept the speaker's voice and the recording conditions, but the words were babble.
So a codec language model must answer two questions that a text model never faces. What should it generate first? And in what order should it generate the codes of each frame? This section answers both. We build the hierarchy that writes the content before the sound, and voice cloning as the continuation of a prompt. We compare the orders in which a frame's codes can be generated, with an exact rule for when an order is correct, and we build the faster designs that real-time and production systems use. We end with what is specific to audio when sampling (loops that never end) and when post-training (rewards that are easy to game).
Speech changes slowly in what it says and fast in how it sounds
Speech carries two kinds of information, and they change at very different rates. What is said, the sequence of words and speech sounds, changes slowly. A reader of audiobooks says about 15 characters per second, the rate of the LJSpeech dataset of §37.1. English speech can be written with only 3 to 4 text tokens per second (Défossez et al. 2024). How it sounds, meaning the exact voice, the room, the breath, and the fine detail of the spectrum, changes fast and takes most of the bits. That is why EnCodec needs 600 tokens per second.
§37.3 gave each kind of information its own kind of token.
A model that predicts everything in one row spends almost all its steps on the fast part. Meanwhile the slow part, which a listener calls the content, must stay consistent across thousands of positions. The fix is to generate the slow part first and then fill in the fast part conditioned on it. Every design in this section is a version of that idea, and "why semantic tokens first?" is a standard interview question.
Four orders for the codes of a frame
The second question is the order of the codes inside a frame. The chain rule of probability allows any order, as long as each code is predicted from all the codes generated before it. A model may also write several codes in one step, which is faster, but then those codes cannot see each other. Here are the four orders that matter, on a grid small enough to draw.
The cell counts the steps for real codecs and clip lengths. The frames column is also the number of steps of any model that writes a whole frame at once. The delay column is the frames plus . The codecs are EnCodec at 24 kHz, the 32 kHz EnCodec of the music model MusicGen, SoundStream (the codec of AudioLM), and Mimi, the 12.5 Hz codec of the Moshi dialogue model (§37.3).
Flattening five minutes of Mimi codes takes 30,000 steps, and the delay order takes 3,757. Each sequential step is one more forward pass that the listener waits for, which is why the order of the codes is a design decision and not a detail.
Phonetic units alone lose the voice
An early language model of speech threw the fast part away entirely. Clustering the features of a self-supervised speech model gives discrete units that track phones (§35.5). Generative spoken language modeling built a whole pipeline on such units, with no text anywhere (Lakhotia et al. 2021).
GSLM produces speech-like continuations from raw audio alone, which was a real result. But its units were chosen to be phonetic, and a phonetic code is by design almost independent of who is speaking. So the decoder has to invent a voice.
The way to measure this is speaker similarity. A speaker-verification model maps each recording to an embedding vector, and the similarity of two recordings is the cosine of their embeddings (§35.6, made precise in §37.6). Two different real recordings of one speaker score 0.754 with the verification model the VALL-E authors used. GSLM's output scored 0.126 against its prompt (Wang et al. 2023, Table 2). A follow-up restored part of the identity by adding a separate low-rate code for pitch and a vector for the speaker. Its authors noted that the three streams together form a codec at 365 bits per second (Polyak et al. 2021).
The lesson is the one AudioLM drew. Semantic units alone lose the voice, and acoustic tokens alone lose the words. A model needs both, with the content first.
AudioLM writes the content first, then the coarse sound, then the fine sound
AudioLM (Borsos et al. 2022) runs two tokenizers on the same 16 kHz audio.
- Its semantic tokens come from w2v-BERT, a self-supervised speech model trained to predict masked parts of its input (§35.5). AudioLM clusters the features of the seventh layer of its masked-prediction module into k-means clusters, at 25 tokens per second.
- Its acoustic tokens come from SoundStream (Zeghidour et al. 2021), the first codec of the kind in §37.3. Its encoder downsamples by strides , so one frame is samples and there are frames per second. Each frame has 12 levels of 1,024 codes, which is 600 tokens and 6,000 bits per second.
Two measurements from §37.3 justify having two tokenizers. The ABX error is the chance that a recording of one phone lands closer to a recording of a different phone than to another recording of its own, so lower means more phonetic. ViSQOL estimates perceived quality on a 1 to 5 scale by comparing the rebuilt audio with the original. In AudioLM's Table I the semantic tokens, at 250 bits per second, have ABX errors of 6.7 percent within speakers and 7.6 percent across speakers, but audio rebuilt from them scores a ViSQOL of only 1.1. SoundStream's codes at 2 kbps rebuild to 3.3 and have ABX errors of 22.4 and 28.7 percent. Neither token type is good at both jobs.
So AudioLM generates both, one after the other. Write for semantic token and for the acoustic code of frame at level .
In plain words, first decide what is said, as a slow sequence of phone-like tokens. Then decide how it sounds, first the coarse acoustics conditioned on the content, then the fine acoustics conditioned on the coarse ones. Each assumption says that what a stage needs was already summarized by the stage before it.
The first assumption is reasonable because of what the tokens mean. Which phone comes next depends on the words so far, not on the exact timbre they were spoken with. The second is the residual hierarchy again. Levels 5 to 12 encode corrections of corrections, local detail that the coarse codes have already placed.
The stages also cut the sequence lengths. Stage 1 runs at 25 tokens per second, and stage 2 at . Stage 3 runs at , but only inside 3-second chunks. AudioLM samples with temperatures 0.6, 0.8, and 0.6 for the three stages. Prompted with 3 seconds of an unseen speaker, it continues in that speaker's voice with coherent content, which GSLM could not do.
A text-to-speech system needs only one more piece, a model from text to semantic tokens. SPEAR-TTS (Kharitonov et al. 2023) added exactly that. It splits text to speech into "reading", from text to semantic tokens, and "speaking", from semantic to acoustic tokens. The speaking stage needs only audio to train. With this split, SPEAR-TTS reported a character error rate competitive with the best systems of its time from only 15 minutes of paired text and speech. VALL-E, next, took the other route and skipped semantic tokens entirely.
VALL-E clones a voice by continuing a prompt
VALL-E (Wang et al. 2023) treats text to speech as language modeling over EnCodec codes at 6 kbps, with 24 kHz audio, , and levels of codes. It is a zero-shot system, which means it speaks in a voice it never saw in training, with no fine-tuning. It conditions on two things. One is the phonemes of the text, the symbols for its speech sounds that the front end of §37.1 produces. The other is an acoustic prompt, the codes of a short recording of the target voice, frames long, where is the set of code values. From them it generates the code matrix of the new utterance. Column of the matrix is level over time.
VALL-E uses two kinds of model. An autoregressive (AR) model writes one position per step, each conditioned on the positions before it. A non-autoregressive (NAR) model writes many positions in one step.
In plain words, the AR model writes the coarse code sequence one frame at a time, and with it the timing and the length of the utterance. The NAR model then fills in the seven finer levels, one whole level per pass. Each pass looks at everything coarser and at the full prompt. Both models see the prompt's codes, and that is how the voice gets in.
The split follows the codec. Level 1 carries most of the information, including much of the speaker identity. It is also the only level whose length must be decided. An AR model decides length naturally, by emitting an end token. A separate length predictor would have to know how fast each unseen speaker talks. The finer levels inherit their length from level 1, so they can be predicted in parallel. The authors note that this takes the cost of the remaining levels from steps to .
Training is plain language modeling. VALL-E was trained on LibriLight, 60,000 hours of English audiobooks from about 7,000 speakers, transcribed into phonemes by a speech recognizer, in random crops of 10 to 20 seconds. The AR model is never shown a separate prompt in training. Every prefix of a training sequence is a prompt for the rest of it. This is in-context learning in the sense of §6.8, where a model infers a task from its context and continues it with no weight update. Here the prompt is evidence about the speaker and the channel, and the best continuation is the one that fits that evidence. The NAR model's prompt in training is a random 3-second segment of the same utterance.
Decoding matters as much as modeling. VALL-E samples the AR stage, because the authors saw beam search drive the model into an infinite loop, and because sampling gives varied outputs for the same input. The NAR stages are greedy, taking the most probable code at each frame. Loops come back later in the section.
To read the results you need one more metric. The word error rate (WER) runs a speech recognizer on the generated audio and counts the words it gets wrong against the input text, the substitutions, deletions, and insertions, divided by the number of words in the text (§36.1). Lower is better.
VALL-E's training sequences and loss masks
VALL-E's AR model reads phonemes and audio codes. The paper gives each its own embedding table. An equivalent layout, used here, is one shared vocabulary in which the two ranges of ids do not overlap. Phoneme ids run from to . The end-of-text token is . Level-1 code has id . The end-of-audio token is . Write three functions.
valle_ar_example(phones, codes1, V_text, K)builds the training sequence [phonemes, end of text, offset codes, end of audio]. It returns(inputs, targets, loss_mask).inputsis the sequence without its last token, andtargetsis the sequence without its first token.loss_maskis 1 exactly where the target is an audio code or the end of audio, and 0 elsewhere.valle_ar_prompt(prompt_phones, phones, prompt_codes1, V_text, K)returns the inference prefix [prompt phonemes, new phonemes, end of text, offset prompt codes], which the model then continues.valle_nar_input(prompt_C, C, q, E)builds the NAR model's input for one level. Its arguments are the prompt codes of shape(n_q, T_p), the target codes of shape(n_q, T), the 0-indexed levelq >= 1to predict, and per-level embedding tablesEof shape(n_q, K, d). It returns the input matrix of shape(T_p + T, d)and a loss mask. Each prompt row sums the embeddings of all levels. Each target row sums the embeddings of levels0toq - 1. Every level is looked up in its own table, and the mask is 1 on the target rows. Leave the phonemes out of this function.
One sentence, end to end, as codec tokens
Here is one sentence followed through every stage of VALL-E, with the shape and the count at each step. It is the sentence that §37.1 followed to a mel spectrogram, Dr. Smith paid $5., so the two routes can be compared. There the front end turned it into the words "doctor smith paid five dollars" and 20 phonemes, and the predicted durations gave 1.81 seconds of speech.
The widget follows the sentence through this route, level-1 codes first and then the seven finer levels, on the same time axis as the mel route of §37.1. Switch routes to compare the two.
The cell runs the same pipeline with stand-ins for the two trained models, so every array has its real shape. A trained AR model would sample each code from its prediction given the prefix. A trained NAR model would take the most probable code for each frame.
Interleaving patterns describe every order in one language
VALL-E's split is one answer to the question of order. MusicGen, a text-to-music model from Meta (Copet et al. 2023), turned the question into a family of answers with one language for all of them. An interleaving pattern says which codes of the grid are predicted at each step, and so which earlier codes each prediction may look at. We call the order of the flattened row, frame by frame and coarse to fine within a frame, the frame-major order.
The delay pattern is the one MusicGen used, and it is easiest to see as a shift. Write the grid with one row per level. Slide row to the right by positions and pad the gaps. Every column of the shifted grid is now one step. Column holds level 1 of frame , level 2 of frame , and so on. So the codes predicted together always come from different frames.
The cell prints, for a grid of 4 frames and 3 levels, the step at which each code is produced. The code counts levels and frames from 0, as the exercises do.
The diagonal stripes of the delay pattern are visible in the printout. So is the price of VALL-E's pattern, whose last two steps each produce a whole level of all frames.
Delay and undelay
Write delay(codes, pad), which maps a code grid of shape (n_q, T) to the delayed grid of shape (n_q, T + n_q - 1). In the delayed grid, level q (0-indexed) is shifted right by q columns, and every empty position holds pad. Column s of the delayed grid is what a delay-pattern model predicts at step s. Then write undelay(delayed), which inverts it. Keep the dtype of the input.
When a pattern is exact
Every pattern except flattening draws some codes together, and codes drawn together cannot see each other. How much does that cost? The answer is exact, and it needs two quantities from §0.5. The entropy of a random code is its average surprise, , in nats when the log is natural. The KL divergence is the average extra surprise of using a model when the data come from . It is never negative, and it is zero only when .
Suppose a model is trained with a pattern by maximum likelihood, each code in scored against its true value given the codes of earlier steps. Write for the codes in . The expected cross-entropy is smallest at the true distribution, so the best such model outputs the true conditional of each single code . Now sample from those exact conditionals step by step, drawing the codes of one step independently of each other. Call the distribution of the result ,
In plain words, is the best that any model trained with this pattern can do. The question is how far it is from the truth .
The answer uses the total correlation of a set of codes, the information they carry about each other. It is the sum of their separate entropies minus their joint entropy, so it is zero exactly when they are independent. Two codes that are always equal fair coins have separate entropies of each and a joint entropy of , so their total correlation is . §34.4 used the same quantity to price one parallel step of masked image generation. The answer for a whole pattern adds up its steps.
∂ Proof of the pattern theorem
By the chain rule over steps, . Dividing by and taking logs,
Take the expectation under , one step at a time. Given a context , the codes are distributed as , whose marginals are the . So the bracket's expectation is , the total correlation. Averaging over contexts gives the identity.
Each term is the KL divergence between a joint distribution and the product of its marginals. So it is nonnegative, and it is zero exactly when the codes of the step are conditionally independent, which gives statement 1. For statement 2, a step with one code has total correlation zero for every . If a step holds two codes , take a in which and are equal fair coins independent of everything else. Their total correlation is , so the pattern is inexact for that . ∎
In plain words, a pattern costs exactly the information that codes drawn in the same step carry about each other, given what came before, summed over the steps. Flattening pays nothing, because it never draws two codes together. Every other pattern is a bet that the codes it draws together are close to independent given what it has already seen.
MusicGen's authors state one direction for the parallel pattern, that it is a proper model only if the codes of each frame are conditionally independent given the past. The theorem adds the converse and covers every pattern. Note also what the theorem does not require. A pattern need not follow the frame-major order to be exact. Coarse first with draws one code per step, so it is exact, even though each level-1 code is predicted before the level-2 codes of all earlier frames. It is the chain rule in a different order.
The theorem tells us where each pattern places its bet.
- Parallel draws all levels of a frame together. Residual quantization makes them strongly dependent, since level is by construction a correction of the levels below it.
- Coarse first, with three or more levels, draws levels 2 to of a frame together, the same dependence one level up.
- Delay draws codes of different frames together, and each code sees every coarser code of its own frame. Its only bet is that codes of nearby frames are nearly independent given everything drawn in earlier steps.
- VALL-E's NAR passes draw one level of all frames together, given every coarser level of every frame, including future frames. The bet is that fine codes are local detail once the coarse codes are fixed. SoundStorm, later in the section, makes the same bet.
The next cell measures these bets exactly in a toy world of codes. It has 3 frames, 3 levels, and 3 codes per level, small enough that the joint distribution over all grids fits in a table. Level 1 (index 0 in the code) is a sticky chain over time, with a weak link to the previous frame's level 2. Level 2 depends strongly on level 1 of its own frame and weakly on its own previous value. Level 3 depends strongly on level 2 and weakly on level 1. For each pattern, the cell computes from the exact conditionals and its KL divergence from .
The widget draws the grid for 8 frames and 4 levels, counted from 0 at the bottom. Press Generate to watch a pattern write its codes step by step. Click a code to see three things. They are the codes the model has already seen when it predicts that code, the frame-major predecessors it has not seen, and the codes drawn in the same step. In the delay pattern, click a code high in the grid. It sees the coarse codes of later frames, a lookahead that the frame-major order never gives.
The theorem predicts the ranking that MusicGen measured on real music.
An interviewer who asks "why does the delay pattern work?" wants this argument. The codes it draws together come from different frames, and each of them already sees the coarser codes of its own frame.
Which predictions does each pattern starve?
Write pattern(name, T, n_q) for the names "flatten", "parallel", "delay", "coarse_first", and "valle". It returns a list of steps, each a list of (t, q) with frames and levels 0-indexed, following the table above. Assume n_q >= 2.
Then write missing_dependencies(steps). It returns a dict that maps every code (t, q) to the set of its frame-major predecessors that are not in a strictly earlier step. A code's frame-major predecessors are all codes of earlier frames and the coarser codes of its own frame. Codes in the same step cannot see each other. A missing dependency is not an error by itself, since coarse first with two levels misses some and is exact. But it shows where a pattern places its independence bets.
Two Transformers, one for time and one for depth
Delay is inexact, and flattening is exact but slow. A third design keeps the exactness and most of the speed. It gives the two axes of the grid two different models, a large one that steps through time and a small one that steps through the levels of a frame. The idea comes from image generation, the RQ-Transformer of Lee et al. (2022), and audio models used it before Moshi did. We follow the form written down for Moshi (Défossez et al. 2024), a dialogue model that §37.5 builds on this design.
In plain words, the big model reads the history once per frame and summarizes it in . A linear layer reads the first code off that summary. The small model then spells out the frame's other codes from coarse to fine. Each code sees the summary and the codes already chosen in its frame.
This is the flattened chain rule with no independence bet, so by the theorem it is exact. What changes is the cost. The large model runs steps instead of . Its KV cache, the stored keys and values of past positions (§6.5), holds positions instead of . The small model runs steps per frame over a sequence never longer than , so its cache is thrown away after every frame.
Moshi adds one refinement, the delay pattern's idea applied inside the frame. Mimi's first level is semantic and the other seven are acoustic (§37.3). Moshi shifts the acoustic levels by an acoustic delay of frames. With Mimi's codes written , the step's codes are and for . With of 1 or 2, the authors report that quality "greatly improves". The reason is that the large temporal model, rather than the small depth model, now sees a frame's semantic code before it has to describe that frame's sound.
Later systems use the same split. Qwen3-TTS (Hu et al. 2026) predicts the first of its 16 levels at 12.5 Hz with the large backbone and the other 15 with a small multi-token prediction module in the depth role. MOSS-TTS (Gong et al. 2026) offers both a delay-pattern model and one with a small autoregressive module inside each frame.
The reference block builds both pieces at toy size. The first is a VALL-E style AR model. It is a causal Transformer over [phonemes, end of text, level-1 codes, end of audio] whose loss is masked to the audio targets, the layout of Exercise 37.4a. The second predicts the 4 levels of one frame from a context vector, level 0 with a linear layer and levels 1 to 3 with a small causal depth Transformer. A check confirms that the prediction for level cannot see the code of level .
Filling the grid in parallel
An autoregressive model over frames still takes one step per frame. Masked parallel decoding removes that too. §34.4 built it for images (Chang et al. 2022), and here is its rule in brief. Start with every position masked. A bidirectional model predicts every masked position at once. The predictions it is most confident about, those with the highest probability, are kept, and the rest are masked again. After iteration of , the number of positions still masked is out of . This cosine schedule commits few tokens in the first iterations, while little of the grid is known, and many at the end.
SoundStorm (Borsos et al. 2023) applies this rule to AudioLM's acoustic stages. For each 50 Hz frame, its input is the sum of two kinds of embedding. One is the embedding of the conditioning semantic token, repeated from 25 Hz to 50 Hz. The others are the embeddings of the frame's 12 acoustic codes. So the bidirectional model attends over frames rather than codes, and its sequence does not grow with . The model is a 350 M Conformer, a Transformer with convolution layers added. It decodes one level at a time, coarse to fine. Within a level it runs the confidence-based schedule over the frames, with a greedy choice in the last iteration of each level.
Training mirrors decoding. For each example it draws a prompt boundary, a level to train, and a masking ratio from the cosine schedule. Frames before the boundary are a voice prompt and are never masked. At level , each later frame is masked with that probability. Every finer level is masked on all later frames, and the coarser levels stay visible. The loss is the cross-entropy on the masked tokens of level only.
The schedule of levels is the theorem again. Codes of level 1 depend on each other strongly, so they get many small steps. Given all of level 1, the finer codes are close to conditionally independent local detail, so one parallel step per level loses little.
SoundStorm's training mask and decoding passes
Write soundstorm_mask(T, n_q, t_p, q, frame_mask), which returns two boolean arrays of shape (n_q, T), masked and loss. Frames 0 to t_p - 1 are the prompt and are never masked. At level q (0-indexed), a frame t >= t_p is masked when frame_mask[t] is true. Every finer level is masked on all frames t >= t_p, and coarser levels are not masked. The loss covers exactly the masked tokens of level q.
Then write soundstorm_schedule(T, iters), where iters[l] is the number of decoding iterations of level l. Levels are decoded in order. Within a level with I iterations, the number still masked after iteration i is . The small constant guards against rounding, so that the count is 0 after the last iteration. Return a list with one (level, n_committed) pair per forward pass, where n_committed is the number of tokens that pass unmasks.
Hybrids put a language model on the content and a flow on the sound
Many of the strongest text-to-speech systems of 2025 and 2026 take the slow-then-fast idea to its end. A language model generates a single stream of semantic tokens, one at a time. A separate continuous generator then turns them into sound. Usually it is flow matching (§33.6, used for TTS in §37.1), which learns a velocity field that carries noise to data along straight paths. Sometimes it is diffusion.
CosyVoice (Du et al. 2024) is the cleanest example, in four parts.
- Its tokens are supervised semantic tokens. They are made by inserting a vector quantizer into the encoder of a multilingual speech recognizer (§37.3), so they keep what recognition needs.
- An LLM maps text to these tokens.
- A conditional flow-matching model maps the tokens, a speaker embedding (an x-vector, §35.6), and the prompt's mel spectrogram to a mel spectrogram.
- A neural vocoder, HiFi-GAN (§37.2), makes the waveform.
CosyVoice 2 (Du et al. 2024) made the LM a pretrained text LLM, Qwen2.5-0.5B, with no separate text encoder and no speaker embedding in the LM. Its tokens come from finite scalar quantization, which rounds each coordinate of a short vector to one of a few levels, at 25 tokens per second. Its flow-matching decoder is chunk-aware and causal, so it can stream. Its mel spectrogram runs at 50 frames per second for 24 kHz audio, so each speech token covers two mel frames. The flow takes 10 function evaluations, 10 forward passes of its network per chunk. CosyVoice 3 (Du et al. 2025) scaled the data from ten thousand to one million hours and the model to 1.5 B parameters.
Why do hybrids work so well? Each half does what it is good at. The slow, discrete part (which words, with what timing, with what prosody) is a long-range sequence problem. Autoregressive LMs are strong there, and the text knowledge of a pretrained LLM transfers. The fast, continuous part is local and high-dimensional. Autoregression over its codes would be slow and would compound errors, while a parallel generator that sees whole chunks is fast and accurate. The hybrid also lets the acoustic stage condition directly on the prompt's spectrogram, so the voice does not have to be squeezed through the semantic tokens.
VibeVoice (Peng et al. 2025) goes one step further and makes the tokens continuous. Its tokenizer compresses 24 kHz audio 3,200 times, to 7.5 latent frames per second. A Qwen2.5 LLM, with 1.5 B or 7 B parameters, reads text and past latents. Its hidden state at each step conditions a small diffusion head of 4 layers that generates the next continuous latent, which the authors call next-token diffusion. The low frame rate is what makes long audio fit. Ninety minutes at 7.5 Hz is frames, inside its 64K context, and the model generates up to 90 minutes with up to 4 speakers.
Streaming text in, speech out
A voice assistant does not have the whole sentence when it starts speaking, because the text LLM is still writing it. CosyVoice 2 handles this inside the LM's own sequence, by alternating short runs of text and speech.
In plain words, the model reads a little text and speaks a little. Whenever it has spoken its share, it says "more text, please" with the filling token. When no more text will come, the turn-of-speech token switches it to plain continuation until it ends.
The ratio keeps the text ahead of the speech. At 25 speech tokens per second and roughly 3 to 4 text tokens per second of English speech, a sentence needs about 6 to 8 speech tokens per text token. That is more than . So each block of text covers more audio than the model speaks before it reads the next block, and the model never has to speak words it has not read.
The bi-streaming sequence
The setup defines the special tokens SOS = "S", TURN = "T", EOS = "E", FILL = "F", and IGNORE = None, a target that carries no loss. Write bistream(text, speech, N=5, M=15), returning (inputs, targets), two lists of equal length.
The full sequence is S, then blocks of N text tokens each followed by the next M speech tokens until the text runs out, then T, the remaining speech, and E. inputs is the full sequence without its last token. targets[k] is the next token of the full sequence, with two exceptions. It is FILL when the next token is text and the current one is speech. It is IGNORE when the next token is text and the current one is not speech. You may assume there are at least M speech tokens for every text block.
Music, and guidance on token logits
MusicGen (Copet et al. 2023) is a single-stage codec LM for music. It models the 4 levels of a 32 kHz EnCodec at 50 Hz with the delay pattern. It reads the text caption through a pretrained text encoder, T5-base, and cross-attention, and it can also follow a melody. The models have 300 M, 1.5 B, and 3.3 B parameters. They were trained on 20,000 hours of licensed music and sample with top-k 250 at temperature 1.
The melody conditioning needs no labels. A chromagram of a reference track gives the energy of each of the 12 pitch classes (C, C sharp, D, and so on) in every frame. MusicGen keeps only the dominant pitch class per frame. The authors added this bottleneck because the raw chromagram let the model copy the reference.
Like image token models, MusicGen uses classifier-free guidance on its logits, a way to make a model follow its condition more strongly than it learned to. During training the text condition is dropped with probability 0.2. So one network learns both the conditional logits , given the caption, and the unconditional logits , given no caption. At each step it samples from
In plain words, start from the logits the model would use with no caption, and move times as far as the caption pushes them. With this lands on the conditional logits, which is plain conditional sampling. With it goes twice as far again, past what the caption alone would do.
§34.4 worked out what this rule does. Write and for the softmax of the two logit vectors. Guidance samples each token from the renormalized product , the per-token version of the Bayes argument for diffusion guidance in §33.5. That holds token by token, not for the whole sequence, because each step's normalizer depends on the prefix. The rule must combine logits or log-probabilities, never probabilities, which can turn negative. And it runs the model twice per step, with and without the caption, which doubles the batch and the KV cache but not the number of steps. The same guidance also helps text LLMs (Sanchez et al. 2023). The cell shows its effect on one codebook's distribution.
The caption alone raises the odds of the 64 favored codes by a factor of and moves their share from 0.029 to 0.076. Guidance with raises the odds by , to a share of 0.377, and lowers the entropy from 9.55 to 8.73 bits. That is the familiar trade of diversity for adherence to the text.
The reference call through Hugging Face transformers is a few lines. At 50 frames per second, 256 new tokens is about 5 seconds of audio.
Sampling audio tokens without loops
Everything in §6.4 applies to audio tokens. Temperature divides the logits before the softmax. Top-k keeps the most probable tokens before sampling. Top-p, or nucleus sampling, keeps the smallest set of most probable tokens whose total probability reaches , called the nucleus. What is specific to audio is how decoding fails.
- Loops. The model repeats a few codes, heard as a stuck syllable, a buzz, or endless silence. VALL-E saw beam search fall into infinite loops, and VALL-E 2 reported the same for nucleus sampling with a small top-p.
- Stopping errors. The end token comes too early, which cuts the sentence, or never comes, which runs on into babble.
- Hallucinated content. Words are skipped, repeated, or added. This is the codec LM's version of the attention failures of Tacotron in §37.1.
Loops have a mechanism. In text LMs, Xu et al. (2022) found a self-reinforcement effect. The more times a sentence has been repeated in the context, the more probable the model makes the next repetition. An audio code that repeats has the same pull, and a run of silence or of one steady sound is the easiest pattern to continue. Once the probability of repeating reaches the top-p threshold, the nucleus contains only the repeated code, and no amount of sampling can leave. Sampling from the full distribution escapes. But on every step it also lets in the long tail of unlikely codes, which costs quality.
The cell runs a toy codec LM over 16 codes for 300 steps at several values of top-p. Its probability of repeating grows with the length of the current run, from 0.6 when the last code has just appeared to 0.9 once it has appeared four times in a row. Of the remaining probability, 0.4 goes to one "next sound" code and 0.6 is spread evenly over the other 14 codes. A tail draw is a code whose probability was below 0.05.
VALL-E 2's fix is to truncate as usual and to watch for repetition.
In plain words, sample carefully from the head of the distribution as long as the output is varied. The moment the chosen code already fills more than a tenth of the last ten slots, take one draw from the whole distribution instead. Its small chance of a different code is what ends the loop.
RAS changes the output only on steps that repeat. On varied speech it is plain nucleus sampling, and its cost is one extra draw, negligible next to a forward pass. It is what let VALL-E 2 decode with a very small top-p, even 0. The authors identify that as the key to a word error rate below that of the ground-truth recordings. One detail matters if you implement it from the paper. Its Algorithm 1 writes the sum from , which would count the candidate itself, while dividing by . With that version falls back whenever the candidate appears even once in the window. We count only the preceding codes. That matches the division, and the paper's prose, which speaks of the candidate's ratio in the preceding codes.
The widget's toy model caps its repeat probability at 0.85 on the sticky preset. The line under the strip is the model's chance of repeating the last code, and the dashed line is top-p. The widget opens with RAS off at top-p 0.8. Within a few codes the line climbs to the dashed line, and the strip becomes one long outlined loop, because the nucleus holds only the repeated code. Turn RAS on and the loops end, since every fallback leaves with probability at least 0.15. Then switch RAS off and set top-p to 1. The runs look much the same, and the tail draws go up.
That is the whole effect of RAS. On repetitive stretches it samples exactly like the full distribution, so its loops last as long as those of top-p 1. Everywhere else it keeps the nucleus. On the very sticky preset, where the model repeats with probability 0.97, every sampler leaves long runs, because each draw escapes only 3 percent of the time. The fix there is a better model, not a better sampler.
Repetition-aware sampling
Write ras_sample(probs, history, rng, top_p=0.8, window=10, threshold=0.1), returning (token, fell_back). The setup provides nucleus_probs, which applies top-p with the threshold rule of §6.4.
- Draw a candidate with
rng.choice(K, p=nucleus_probs(probs, top_p)), whereK = len(probs). - Compute its repetition ratio, the number of matches among the last
windowcodes ofhistory, divided bywindoweven when the history is shorter than the window. - If the ratio exceeds
threshold, return a fresh drawrng.choice(K, p=probs)from the full distribution andTrue. Otherwise return the candidate andFalse.
Use rng for every draw and draw nothing else, so that without a fallback the result equals plain nucleus sampling under the same seed.
Stopping, and controlling duration
An autoregressive codec LM decides the length of an utterance by when it emits its end token. That is flexible but not controllable, and dubbing and video need an exact duration. IndexTTS2 (Zhou et al. 2025) adds a mode in which the number of tokens to generate is given explicitly, next to a free mode. MOSS-TTS offers token-level duration control. Non-autoregressive systems, MaskGCT and the flow-matching models of §37.1, set the length directly. That gives control for free and moves the problem to estimating a good length.
In free mode, stopping errors are usually treated in two ways. One is a length prior at inference, which refuses an end token far before the length the text implies and forces one far after it. The other is the post-training rewards of the next section, since a cut sentence raises the word error rate.
Post-training with rewards a computer can score
Speech generation has unusually cheap automatic judges. A speech recognizer gives a word error rate against the input text (§36.1). A speaker-verification model gives the similarity to the prompt voice (§35.6). An emotion classifier says whether the requested emotion came out. A MOS predictor estimates the mean opinion score, the 1 to 5 naturalness rating that listeners would give (§37.6).
Each judge can serve as a reward for the methods of Chapter 15 to Chapter 18. The codec LM is the policy , and a frozen copy of it is the reference that a KL penalty keeps the policy close to. Three methods recur.
- DPO (§17.2) fits preference pairs directly, with no reward model and no sampling during training.
- GRPO (§18.4) samples a group of outputs for the same input and scores each by its reward relative to the group's mean.
- GSPO, in the same section, is GRPO with one importance ratio per sequence instead of one per token.
The same report documents the failure. To reach a lower WER, the RL model tended to speak more slowly and pronounce more clearly, at a cost in naturalness. The authors had already observed that a lower WER usually means more "standardized" speech that is easier for the recognizer. Such speech keeps less of the prompt's accent and expressiveness, and listeners judge it less similar to the prompt. This is reward overoptimization (§16.5) in its speech form. The proxy measures how well one recognizer understands the speech. The goal is natural speech in a particular voice. Pushing on the proxy moves the output away from the goal in directions the proxy cannot see.
Every cheap judge can be gamed in its own way. A WER reward pays for slow, over-articulated, accent-free speech. A similarity reward can be raised by copying the prompt's room and noise along with the voice. A MOS predictor rewards whatever acoustic features it happens to have learned to like. Practical recipes therefore combine several rewards and keep a KL penalty to the reference model. They gate every release on human listening tests against the reference model, with accent and prosody checks on expressive prompts. The box gives the recipes of 2025 and 2026, and a way to spend the same judges at inference instead.
Where text to speech stands in 2026
The list below dates the main text-to-speech systems of 2025 and 2026 and says how each is built. Each one combines designs from this section, a language model over tokens, a flow or diffusion stage, a low frame rate, or post-training with rewards.
The benchmark in that list, Seed-TTS-Eval, was released with the Seed-TTS report and scores a system by its error rate and its speaker similarity (SIM) on fixed English and Mandarin test sets.
Two lessons follow for reading such tables. Synthetic speech can score a higher similarity to the prompt than a different real recording of the same speaker does. It copies the prompt's speaking style and recording conditions, which the other recording does not share. And numbers from different evaluation setups are not comparable, a point §37.6 develops.
Where codec language models break
The table puts the families of this section side by side, with the number of sequential model calls for frames of codes.
| Family | Examples | Sequential calls | Streams natively | Typical failure | Duration | Voice or style from |
|---|---|---|---|---|---|---|
| Flattened AR codec LM | AudioLM's acoustic stages | yes | slow, long contexts | end token | prompt continuation | |
| AR plus NAR | VALL-E, VALL-E 2 | level 1 only | loops in the AR stage | end token | prompt continuation | |
| Delay pattern | MusicGen | yes | inexact within-step draws | chosen number of steps | text, melody, continuation | |
| Temporal plus depth | Moshi, Qwen3-TTS 12.5 Hz | large plus small | yes | AR failures | end token | prompt or speaker embedding |
| Masked parallel | SoundStorm, MaskGCT | fixed, 27 for 30 s in SoundStorm | no | needs the total length | set in advance | prompt infilling |
| Hybrid LM plus flow or diffusion | CosyVoice, Seed-TTS | LM tokens plus flow steps per chunk | with chunk-aware flow | LM hallucination | end token | prompt plus embedding |
| Continuous AR | VibeVoice | , each with a diffusion head | yes | long-form drift | end token | prompt |
| Flow-matching NAR | F5-TTS (§37.1) | fixed ODE steps | no | length estimate | set in advance | infilling |
Read more
- Borsos et al. (2022). AudioLM: a Language Modeling Approach to Audio Generation. Section III gives the token analysis, the babbling experiment, and the three-stage hierarchy.
- Wang et al. (2023). Neural Codec Language Models are Zero-Shot Text to Speech Synthesizers. VALL-E. Section 4 defines the AR and NAR models and the prompting, and Table 2 gives the results.
- Chen et al. (2024). VALL-E 2: Neural Codec Language Models are Human Parity Zero-Shot Text to Speech Synthesizers. Algorithm 1 is repetition-aware sampling, and the introduction defines what the authors mean by human parity.
- Copet et al. (2023). Simple and Controllable Music Generation. MusicGen. Section 2.2 introduces codebook patterns and exactness, and Table 4 compares them.
- Défossez et al. (2024). Moshi: a speech-text foundation model for real-time dialogue. Section 3.4.1 writes the RQ-Transformer and the acoustic delay for audio.
- Borsos et al. (2023). SoundStorm: Efficient Parallel Audio Generation. Level-by-level masked decoding of RVQ codes, with its training mask and the 27-pass count.
- Du et al. (2024). CosyVoice 2: Scalable Streaming Speech Synthesis with Large Language Models. The hybrid LM plus chunk-aware flow matching, and the bi-streaming interleave.
- Anastassiou et al. (2024). Seed-TTS: A Family of High-Quality Versatile Speech Generation Models. The evaluation protocol behind Seed-TTS-Eval, RL on WER and similarity, and the reward hacking it caused.