Act IV · Generation and Perception
Part 23 of 31Every Sense Is a Token
How do text, sound and pictures all become tokens that one transformer can read?
The part opens with a sentence, a picture and a voice turned into one stream of tokens, and with four histories on one time axis: listening from Audrey in 1952 to Whisper, speaking from the Voder of 1939 to Qwen3-TTS, text from Shannon's letters to byte-pair encoding, and pictures from captioning to CLIP. Text comes first: BPE is a greedy compressor in which a merge found n times saves n symbols, Kudo's unigram model puts a probability on every cut, and bits per character let tokenizers be compared on the novels. Bytes and entropy patches remove the tokenizer. Pictures and sound need learned codes: a VQ codebook trained with the straight-through estimator can leave codes dead, which restarts and FSQ's fixed grid address in different ways. For sound, aliasing is derived and measured on tones sampled at 8 kHz, and a residual codec of the series' own codes speech spectrograms at 400 to 3,200 bits a second. The part turns to recognition: CTC sums over every alignment with the forward recursion of Part 7, and a small CTC recognizer is set against Whisper. It ends with CLIP's contrastive loss as a bound on mutual information, the connectors of vision-language models, and omni models that listen and speak at once.
What you need. Logarithms, sines and cosines; bits and cross-entropy from Part 1 and the forward algorithm of Part 7.
- Mathematics and history
- BPE, byte-level models, VQ and FSQ, RVQ, audio and CTC, CLIP vs SigLIP, VLMs, omni models
- Models, data
- Whisper, Qwen3-TTS (the narrator)
What you will be able to do
Undergraduate
- Run byte-pair encoding by hand on a short phrase and count the symbols each merge saves.
- Compute where a tone above the Nyquist frequency appears after sampling, and convert bits per token to bits per character.
Master's
- Compute a word's probability under a unigram tokenizer with the forward algorithm, and its best cut with Viterbi.
- Write the VQ-VAE losses with the straight-through estimator, and count the codes and bits of an FSQ grid and of residual stages.
- Derive CTC's forward recursion on the 2L + 1 extended states and say why a repeated letter needs a blank.
Research
- Derive InfoNCE's optimal critic and the bound log N - L <= I(X; Y), and explain why a batch of N cannot certify more than log N.
- Compare CLIP's softmax loss with SigLIP's sigmoid loss as estimators, and state how each depends on the batch size.
Engineering
- Choose a vocabulary size and tokenizer for a corpus, and compare models with different tokenizers in bits per character on the same text.
- Budget a speech or vision front end in tokens per second, bits per second and word error rate.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 20 min · Master's 49 min · Research 53 min · Engineering 36 min.
- 0One sequenceUndergraduate2 min
- 1How we got hereUndergraduate2 min
- 2Merges as compressionUndergraduate3 min
- 3A probability for every cutMaster's3 min
- 4What a token is worthMaster's
- 5Bytes and patchesUndergraduate4 min
- 6Learning a codebookMaster's3 min
- 7Codes without a codebookMaster's3 min
- 8Sampling soundUndergraduate3 min
- 9Neural codecsEngineering4 min
- 10From Audrey to hidden Markov modelsUndergraduate3 min
- 11Connectionist temporal classificationMaster's4 min
- 12Listening at scaleEngineering3 min
- 13SpeakingEngineering3 min
- 14Matching pictures and wordsResearch4 min
- 15Models that seeEngineering3 min
- 16Every sense at onceEngineering4 min
- Recap, problems, and what comes nextAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
One sequenceUndergraduate2 min
A transformer reads a sequence of tokens. So how does a model look at a picture, or listen to a voice? Everything is turned into tokens first: text into pieces of words, a picture into codes for its patches, sound into codes for slices of time. Then it's all one sequence, and one model can read it, and write it.
Every sense poses the same questions. What should a token be? How many does a sentence, a picture or a second of speech need? And how are the codes learned? We'll follow seventy years of answers: a machine that recognized ten spoken digits in 1952, the statistical recognizers that followed, byte-pair encoding, CTC, WaveNet, CLIP and Whisper, up to models that listen while they speak. This part will demonstrate small versions: tokenizers, codebooks, a speech codec, a speech recognizer, and a model that matches pictures with captions.
This is Part 23 of AI, Built. In this part: tokenizers for text, and what a token is worth in bits; vector quantization, its codebooks and how they fail; sampling, spectra and neural audio codecs; listening, from templates to CTC and Whisper; speaking, up to modern codec language models including Qwen3-TTS; and matching pictures with words, from CLIP to models that see, hear and talk.
1How we got hereUndergraduate2 min
Machines were listening long before they could read. In 1952 Bell Labs built Audrey, a rack of electronics that recognized the ten digits spoken by one person, ninety-seven to ninety-nine times in a hundred. In the 1970s recognizers learned to stretch time to match a template, and then, at IBM and Carnegie Mellon, to treat speech as a hidden Markov model, Part 7's statistics, which ruled for thirty years. Neural networks took over the sound model in 2012, and in 2022 Whisper transcribed nearly a hundred languages. Speaking went the same way: from the Voder, played on a keyboard at the 1939 World's Fair, to formant synthesizers and spliced recordings, and in 2016 to WaveNet, a network that writes sound one sample at a time.
Then speech became language modeling: Tacotron, then in 2023 VALL-E, which writes a voice as codes the way a language model writes words. Text needed units of its own. Word models choked on words they had never seen, and characters made sequences long. In 1994 Philip Gage published a way to compress files by replacing common pairs of bytes; in 2016 it became the standard way to cut text into tokens, and versions over bytes and over probabilities followed. Pictures met words around 2014, when networks learned to caption photographs; in 2021 CLIP learned from four hundred million captioned pictures off the web, and by 2023 a vision encoder bolted onto a language model could talk about an image.
In the last few years the threads met. Once speech, pictures and text are all tokens, one transformer can read and write them all: GPT-4o in 2024, Moshi, Qwen's omni models. This part builds that idea from the bottom up: what a token is and what it is worth, how codes are learned, how sound and pictures become sequences, and how the senses are matched.
2Merges as compressionUndergraduate3 min
A tokenizer decides what a model's units are. Whole words? In two million characters of our novels there are 21,374 different words, and still 5.3 percent of the words in the scoreboard's passage never appear among them. A model of words has nothing to say about those. Single characters never run out, but a sentence becomes a long sequence, and attention's cost grows with the square of its length. Byte-pair encoding finds the units in between.
In 1994 Philip Gage described a way to compress a file: find the pair of bytes that occurs most often, replace it everywhere with one new symbol, and repeat. In 2016 Rico Sennrich, Barry Haddow and Alexandra Birch used it to cut words for machine translation. Start from single characters, merge the commonest neighbouring pair, and repeat. Here are the first merges on our novels: a space and a t, h and e, then the starts and ends of words, and soon whole words. Each new symbol is a token.
Why is this compression? Each time the merged pair occurs, two symbols become one, so a merge that applies n times shortens the text by exactly n. After k merges the text is its original length minus the sum of actual replacements. BPE greedily ranks pair counts, including overlaps. In aaaa, aa occurs three times but allows only two replacements, so the most frequent pair need not give the largest saving. On our novels the first merge alone saves symbols, and after merges the text is percent of its length in characters. The savings shrink as the merges get rarer.
The more merges, the bigger the tokens. Here's one sentence, cut into characters, then after 500, 2,000 and 8,000 merges. With 8,000 merges a token covers 3.9 characters of the passage on average, so a transformer sees the same text in a fraction of the steps. BERT's tokenizer, WordPiece, merges by a different rule: the pair whose parts rarely occur apart, the merge that most raises the text's likelihood. Its first merges on our novels are rare pairs that always come together. Real vocabularies run from fifty thousand tokens in GPT-2 to over a quarter of a million in Gemma 3.
3A probability for every cutMaster's3 min
Byte-pair encoding cuts each word one way, fixed by the order of its merges. In 2018 Taku Kudo proposed a model instead. A vocabulary of pieces, each with a probability. A cut of a word into pieces scores the product of their probabilities, and the word's probability is the sum over every cut. Here are a few ways to write armchair with the pieces our model learned. The tokenizer keeps the most probable cut.
Every cut of a word is a path through a lattice. Put a node between each pair of letters, and an arc for every piece in the vocabulary. A cut is a path from the first node to the last. The sum over all cuts is computed left to right: the probability of reaching node j adds up every arc that ends there, from every earlier node, the forward algorithm of Part 7's hidden Markov models. Replace the sum with a maximum and you get the best cut. Run it backward as well, and you get how often each piece is expected to be used: what training needs.
Training starts from far too many pieces: the most frequent substrings of the text, 27,517 of them after the first round. Then expectation-maximization, Part 7's EM: compute how often each piece is expected to be used, summed over every cut of every word, and set each probability in proportion. Then prune: for each piece, measure how much the likelihood would fall without it, keep the three quarters that matter most and every single letter, and repeat. Here is the model's own measure of the novels, in bits per character, as the vocabulary shrinks: smaller vocabularies cost bits, 0.55 of them from the first round down to 4,096 pieces.
How different are the two? At pieces each, on the scoreboard's passage, : characters a token for BPE, for the unigram model, and percent of the words have different token counts. The unigram model can also sample cuts instead of taking the best, so a model in training sees the same word written several ways; Kudo called it subword regularization. His SentencePiece library runs either method on raw text, with the space as just another symbol, and it cut the text for T5, the first two Llamas and Gemma.
4What a token is worthMaster's
We compare five original tokenizer configurations at three seeds each. These are newly completed QA candidates, not recovered historical results. The original training schedules are preserved. Their measured work and revised compute estimates differ, so this is a descriptive comparison, not an equal-compute race.
Bits per token uses different units for different tokenizers. For a common text suffix, add the negative log probabilities along each tokenizer's canonical token path, then divide by the exact number of Unicode characters in that suffix. Dividing both numerator and denominator by the same number of scored tokens gives bits per token divided by characters per scored token. This is one token path, not a marginal likelihood summed over every possible tokenization.
The scored passage suffix is identical across all five tokenizers. A shared prefix ends at a token boundary for every encoding and at a strict UTF-8 boundary. That prefix conditions the predictions but is excluded from the score. These rows show the actual number of scored tokens at seed zero. The numerical conversion uses the four-thousand-and-ninety-six-piece BPE model and exactly this same suffix.
The Transformer body has three layers, width ninety-six and a context of one hundred and twenty-eight tokens. Embeddings, output heads and total parameter counts differ. Subword heads contain one additional unknown-token class beyond their nominal pieces. The unknown counts here describe the encoded full training corpus, not how many unknown targets were encountered during the sampled updates. Original lossy training encodings are preserved.
Completed updates determine the number of training target tokens. We also tally the original source bytes covered by the sampled target windows, counting repeated exposures again. This is neither a unique-coverage count nor a passage-density estimate of characters read. CPU and wall times are measured around the training loop and include validation and checkpoint overhead. Each entry shows the three-seed mean and recorded range.
These are estimates of matrix operations, not measured hardware FLOPs or CPU seconds. The triangular and dense attention conventions give different estimates while keeping the same completed original update schedules. They exclude normalization, rotary position operations, softmax, optimizer work, validation and kernel overhead. The displayed cost per token comes directly from the accepted estimator, not from dividing a reference budget by rounded steps.
All fifteen learning curves are shown, including every recorded finite validation point. The horizontal axis uses the triangular matrix-operation estimate. The vertical axis is a diagnostic proxy: sampled validation bits per token divided by the validation corpus's average characters per token. The windows differ across tokenizers. These curves are not exact common-suffix character scores, and their range is chosen from all displayed data rather than clipping high values.
Final scores use exact common suffixes for both the passage and the full validation text. Every row shows the mean and observed minimum to maximum over seeds zero, one and two. A lower recorded score describes this cohort and these runs. Three-seed ranges are not confidence intervals or a significance test. Different vocabulary sizes, initializations, sampled windows and compute prevent an isolated causal claim about the tokenizer.
Tokenization changes the sequence length, the text represented in a fixed token window, the model's embedding and output size, and the distribution of training targets. Those effects interact. These original-schedule runs do not isolate them. The separately studied lossless UTF-8 fallback candidate is outside these fifteen canonical cases. Keep the measured outcomes, diagnostic proxies and scientific limitations together.
This byte-model example uses seed zero at temperature zero point eight. The prompt is the model's first eight passage tokens; the displayed generated text is a continuation only, appended once. The excerpt is illustrative, not a generation-quality benchmark. Byte output is decoded as UTF-8 with replacement, so a replacement character is a decoding result, not the model's unknown-token class.
This BPE example also uses seed zero and temperature zero point eight, but eight BPE prompt tokens cover different text from eight byte tokens. The prompts are not matched. Subword output uses the original decoder, which displays an unknown class as a question mark. Prompt and continuation are shown separately so the prompt cannot be duplicated. Truncated excerpts are marked, while the accepted output remains unchanged.
5Bytes and patchesUndergraduate4 min
Tokenizers fail in their own ways. A character the vocabulary never saw becomes unknown. Letters hidden inside one token are hard to count or spell. And a vocabulary learned mostly on English cuts other languages into more tokens, so they cost more. GPT-2's fix, in 2019, was to run BPE on bytes. Any text is a sequence of bytes in UTF-8, one to four per character, with only 256 possible values, so with the bytes as the starting alphabet nothing is ever unknown.
Could a model skip the tokenizer and read bytes? Google's ByT5, in 2021, did exactly that, at the price of sequences several times longer than BPE's. In 2023 Meta's MegaByte grouped the bytes into fixed patches: a big transformer looks at the patches, and a small one writes the bytes inside each. But a fixed patch spends as much on the end of a predictable word as on its surprising start. In December 2024 Meta's Byte Latent Transformer let the data decide. Here we illustrate the idea, rather than train a BLT: force the initial patch, then start a new one at each byte whose conditional entropy is greater than the threshold. Here, the same bytes become fixed patches, with a possibly shorter final patch, or entropy patches.
For this QA candidate, our byte model completed one thousand training steps with seed zero. This does not establish acceptance of chapter four's fifteen-run experiment. The initial byte has no prediction score and starts a forced patch. Each bar is conditional entropy: uncertainty about the next byte, in bits. Each dot is observed surprise: minus log two of the probability assigned to the byte that arrived. These quantities differ: a confident prediction can be wrong. Uncertainty may fall inside familiar words, but this is measured, not guaranteed. Apart from the forced initial patch, start a new patch at every byte where entropy is greater than the threshold, including consecutive bytes above it. This is a threshold test, not just an upward crossing.
How well do the patches follow the surprise? Mean length divides all passage bytes by all units, including the forced initial unit. Start shares and surprise shares use scored bytes only; the initial unscored byte is excluded. Choose the sampled threshold whose measured mean length is nearest to BPE's: approximately bytes per patch, compared with per BPE token. These lengths need not be equal. percent of scored bytes start a patch, and carry percent of scored surprise. For BPE, percent of scored bytes start a token and carry percent of scored surprise. This pilot measures boundary placement, not trained BLT quality. Separately, the BLT paper reported byte patches matching tokenized models at controlled compute, up to eight billion parameters.
6Learning a codebookMaster's3 min
Text comes in pieces; pictures and sound are continuous. To make tokens of them we need a vocabulary of shapes: a codebook. Cut every letter picture into four by four patches and find sixteen typical ones by k-means: start with sixteen guesses, give each patch to its nearest guess, move each guess to the average of its patches, and repeat. Now a picture is a sequence of numbers from zero to fifteen: each patch is replaced by its nearest code. With more codes the copy comes closer; the numbers are the error per pixel, on evaluation patches, for and codes. These patches were sampled from the same pool as fitting patches, so this is not a disjoint held-out test.
In a real model the codebook is learned with the encoder and decoder, as in Part 20's VQ-VAE, and that hits a snag. Each encoder output z is replaced by its nearest code. Picking the nearest is a jump, with no gradient. The fix is the straight-through trick: forward, use the code; backward, pretend nothing happened, and hand the code's gradient straight to z. Two more terms keep things together: one pulls each chosen code toward the outputs that chose it; the other, the commitment loss, weighted by beta, keeps each output near the code it was snapped to. And here is the weakness: a code that nobody picks gets no gradient at all. It never moves, and it is never picked.
We trained a small VQ autoencoder on the letters: each letter becomes a five by five grid of codes from a book of , the same budget of steps and three seeds for every variant. With the textbook recipe, on held-out letters, on average over the seeds. A popular repair updates each code as a running average of the outputs that chose it, an exponential moving average, which is k-means done online. Here : codes in use. and restart any code unused for fifty steps at a random output of the batch: codes in use.
A fairer measure than counting codes is perplexity: the number of equally used codes that would carry the same information. Plain VQ reaches 67, EMA 56, and EMA with restarts 194. The reconstructions: EMA with restarts rebuilds the held-out letters best, at 4.6 thousandths per pixel. Restarts are standard in audio codecs; the other cure is to get rid of the learned codebook altogether, the subject of the next chapter.
7Codes without a codebookMaster's3 min
In 2023 Fabian Mentzer and colleagues at Google asked whether the codebook needs learning at all. Finite scalar quantization: map the encoder's output to a few numbers, squash each into a fixed range, and round it to one of a few levels. For four levels an offset keeps the rounded values at minus two, minus one, zero and one. The codebook is just the grid of all the combinations: with four numbers of four levels each, 256 codes, eight bits, the same as our VQ. Rounding has no gradient either, so the straight-through trick again. But the grid itself cannot drift away: no code is learned. Some grid points can still go unused.
Months later, Lijun Yu and colleagues pushed it to the limit for their video tokenizer, MAGVIT-v2: lookup-free quantization. Keep only each number's sign. With d numbers there are two to the d codes, the corners of a cube, and a vocabulary of a quarter of a million costs no table at all. To make the codes earn their keep they add an entropy term: each output should be confidently near one corner, while across the batch all the corners are used.
All five, at 256 codes, the same network, the same steps and three seeds. Perplexity: for FSQ, for LFQ, for plain VQ. ; . On error, comes first at thousandths, then at , and last at . The Google team's point was not that FSQ wins outright, but that it matches VQ without any of VQ's repairs.
One more trick, the one sound codecs rely on: quantize in stages. The first stage codes the patch roughly; the second codes what the first missed; then a third, and a fourth. The patch is rebuilt as the sum. At equal bits, here is our comparison on evaluation patches sampled from the same pool as the fitting patches. But residual stages keep going where one codebook can't: sixteen bits would need a table of 65,536 entries, and four stages of 16 reach with 64. That is residual vector quantization, inside nearly every neural audio codec.
8Sampling soundUndergraduate3 min
A microphone measures air pressure, and a computer keeps a sample of it at regular ticks. How fast is fast enough? Take a pure tone of frequency f, sampled f s times a second. Add f s to the frequency, and at every sample the phase gains a whole number of turns, so the samples don't change at all. And because cosine is even, f s minus f gives the same samples as f. So the samples can only tell apart frequencies between zero and half the sampling rate. A seven kilohertz tone sampled eight thousand times a second lands exactly on a one kilohertz tone. The converse is the sampling theorem of Nyquist and Shannon: a signal band-limited strictly below half the rate is fixed exactly by its samples.
We can check it numerically. Sample tones of one, three, five and seven kilohertz eight thousand times a second, and find the peak of each one's spectrum: 1.00, 3.00, 3.00, 1.00 kilohertz. Above four kilohertz, every frequency folds back into the band below, a zigzag: aliasing.
Speech shows why this matters. In this sentence from a held-out Kokoro voice, 4 percent of the energy lies above two kilohertz. Keep every fourth sample, four thousand a second, and that energy doesn't vanish; it folds down into the band that's left: by our measure, 5 percent of what remains below two kilohertz is folded energy. Filter first, then keep every fourth, and the band below two kilohertz is clean. So every sampling rate is a decision about what to keep: eight kilohertz for the telephone, sixteen for Whisper, twenty-four for most audio codecs.
A wave is hard to read, so speech models look at its spectrum, slice by slice. Cut the signal into windows of 25 milliseconds, one every 10, taper each with a Hann window and take its Fourier transform: the short-time Fourier transform, a picture of frequency against time. The ear hears pitch roughly by ratios, so the frequencies are pooled into bands evenly spaced on the mel scale: narrow below a kilohertz, wider above. Take the logarithm of each band's energy, keep the top eight decades, and you have exactly what Whisper hears: 80 log-mel bands every 10 milliseconds. Our own implementation agrees with the transformers library's to within ten to the minus 5.
9Neural codecsEngineering4 min
For most of a century digital sound meant samples: the telephone's 64 thousand bits a second, a CD's 1.4 million. In 2021 Neil Zeghidour and colleagues at Google learned a codec end to end. SoundStream's encoder turns the wave into seventy-five vectors a second, residual vector quantization turns each into a handful of code numbers, and a decoder turns codes back into a wave, all trained together, with a spectral loss and a GAN's judge. They also dropped quantizer stages at random during training, so one model works at every bitrate. Meta's EnCodec, in 2022, runs from 1.5 to 24 kilobits a second. The tokenizers of today's speech models go lower still: one or two kilobits.
We built a small one, with one simplification. Teaching a network to make a wave takes far more compute than this computer has, so ours codes the picture Whisper reads, the log-mel spectrogram of chapter eight, and leaves turning a picture back into sound to a vocoder. A strided convolution takes the picture's 100 frames a second down to 50. Each frame passes through up to eight residual stages of 256 codes, eight bits each, so a stage costs 400 bits a second. Stages are dropped at random in training, so the same model runs at 400, 800, 1600 or 3,200 bits a second. It has 1.3 million parameters and trained for 1,500 steps on 6 minutes of Kokoro speech in ten voices, with a plain loss: the average error in the rebuilt picture. Here it learns to rebuild a sentence from a voice it never heard.
How good is it? Here is the held-out sentence rebuilt at each bitrate: one stage keeps the rough shape, eight keep much more of the detail. A blunt but fair test: Whisper reads such pictures directly, so can it still understand ours? On 12 held-out sentences, Whisper's word error rate falls from 30 percent at 400 bits a second to 15 percent at 3,200, against 12 percent on the original picture; two seeds. At 3,200 bits a second the codes are 80 times smaller than the picture stored as 32-bit numbers, and 80 times smaller than the samples themselves. A real codec must also make the wave, with a GAN's judge, far more data and far more steps; ours only has to show the trade.
Speech tokens come in two kinds. A codec's acoustic tokens carry how the speech sounds: the voice, the room, the detail. Our codec uses its stages : perplexities from to of 256. Semantic tokens carry what is said, and they come from a self-supervised speech model, the kind Part 24 builds, clustered into codes. In 2022 Google's AudioLM generated speech by writing semantic tokens first and acoustic tokens after them. Then the two were merged into one codec: Kyutai's Mimi teaches its first codebook to match the self-supervised model WavLM, and keeps seven acoustic stages beside it, at 12.5 frames a second and 1.1 kilobits. Qwen3-TTS's published tokenizer also uses a semantic first codebook, with fifteen acoustic codebooks beside it.
10From Audrey to hidden Markov modelsUndergraduate3 min
Speech recognition began with digits. In 1952 three engineers at Bell Labs built Audrey. It split the sound into two frequency bands, tracked each band's frequency by counting how often the signal crossed zero, and compared the pattern with a stored one for each of the ten digits. For the speaker it was tuned to, it was right ninety-seven to ninety-nine times in a hundred; for anyone else it had to be adjusted. We built the same idea: ten templates from one Kokoro voice, one take of each digit, and each new word goes to the nearest template. The same voice, saying the digits again a little faster: 90 percent right. Eleven other voices: 63 percent. The problem of speech recognition was never the words. It was the voices.
People say the same word fast or slow, stretching some sounds and not others, so squeezing every word to one length is crude. In 1968 Taras Vintsyuk in Kyiv, and in 1978 Hiroaki Sakoe and Seibi Chiba at NEC, aligned the two by dynamic programming: dynamic time warping. The cheapest alignment to each pair of frames extends the cheapest alignment to one of three neighbours. Here is the path that matches a new take of seven to the template. Warping helps: 100 percent for the same voice, 74 for the others. And with templates from ten voices, two voices it has never heard get 95 percent. More examples beat cleverer matching, a lesson the field would learn again and again.
Classical speech recognition represents speech as short frames of acoustic features. This illustrative left-to-right hidden Markov model has acoustic states, often subphone states, rather than one state for each letter or each whole phone. A path can remain in a state or move forward. A Gaussian mixture gives a probability density for a frame's feature vector. These little curves show just one illustrative feature coordinate, not fitted speech. EM, often Baum-Welch for an HMM, estimates parameters with hidden paths. Viterbi searches for a single best state path. For fixed observed features X, the word sequence maximizes its acoustic likelihood times its language-model prior. The likelihood sums over hidden state paths. Replacing that sum with a best-path approximation can change the winning word sequence. A 2012 joint review collected earlier gains from deep neural acoustic models. Those DNN-HMM hybrids retained HMM timing: network state posteriors were divided by state priors to form acoustic likelihood scores. Next, CTC trains a direct labelling network by summing alignments. It was not the first method to train with hidden alignments.
11Connectionist temporal classificationMaster's4 min
A recognizer hears a hundred frames of sound for a dozen letters, and training data says only what was said, not when. Many neural-HMM systems used frame targets from an earlier aligner, while HMM training itself could use hidden alignments. In 2006 Alex Graves, Santiago Fernández, Faustino Gomez and Jürgen Schmidhuber introduced CTC to train a direct labelling network without frame targets. The network outputs, for every frame, a probability for each letter and for one extra symbol, a blank. Any path through the frames becomes text by merging repeated symbols and then dropping the blanks. A blank is also how a real double letter survives: without one between them, the two e's of three merge into one. The probability of the text is the sum over every path that becomes it.
There are exponentially many paths, but the sum is cheap. Write the transcript with a blank before, between and after its letters: two L plus one states, in order. A path at state s at time t was, one frame earlier, at s, or at the state just before. And it may also skip a blank, jumping from two states back, unless that would merge two equal letters. Multiply by the network's probability for the symbol at s. The paths that end on the last letter or the final blank add up to the transcript's probability. It is the forward algorithm of Part 7's hidden Markov models, with the transcript as the chain of states, and minus its logarithm is a loss whose gradient comes from the same recursion run backward.
We trained a small recognizer this way: 162 thousand parameters in seven convolutions, on digit strings spoken by ten Kokoro voices, three seeds. Here is what it hears in a string from a voice it never heard, as training goes on. At first every frame is a blur. Then the blank takes over, the cheapest way to be right about most frames. Then letters appear between the blanks: at the end the blank wins 59 percent of the frames, and a letter lasts 4.5 frames on average, CTC's famously peaky alignments. The greedy reading below takes the likeliest symbol at each frame, then merges and drops.
And here is the lattice itself, computed from the trained network: the states of the transcript down the side, the frames across. The brightness is how likely each state is at each frame, from the forward and backward passes together; the white line is the single best path. The forward algorithm's total, in natural log, agrees with PyTorch's own CTC log probability, the negative of its unreduced loss. Averaged over three seeds: ; . In 2014 Baidu's Deep Speech trained CTC on thousands of hours and did without the old pipeline. CTC treats each frame's letter as independent of the others, so later systems, RNN transducers and attention-based recognizers, let each letter depend on the ones before.
12Listening at scaleEngineering3 min
After Deep Speech, two roads led to the recognizers we use today. One was self-supervision. Facebook's wav2vec 2.0, in 2020, hid stretches of speech from its own transformer and learned to pick the true hidden frame out of distractors, Part 24's contrastive loss applied to sound. Pretrained on 53,000 unlabelled hours, fine-tuned on ten minutes of transcribed speech, and decoded with an external Transformer language model, the large model reported 4.8 and 8.2 percent word errors on LibriSpeech's clean and other test sets. The other road was weak supervision. In 2022 OpenAI's Whisper was trained on 680,000 hours of audio paired with transcripts found on the web, imperfect ones and all, one model that transcribes, translates into English, names the language and predicts segment timestamps, in nearly a hundred languages.
Whisper is a plain encoder-decoder transformer, the shape of Part 14's translation model. Its input is chapter eight's picture: 80 log-mel bands every ten milliseconds, always thirty seconds long, padded with silence. The encoder reads it; the decoder writes the transcript one token at a time, with GPT-2's byte-level BPE, attending back to the sound. Special tokens at the start say what to do: here, start of transcript, no timestamps. A recognizer has become a language model that listens. We ran the base English model, base.en, million parameters, from the Hugging Face cache.
How does it do on our voices? On sentences from the two held-out Kokoro voices, it gets percent of the words wrong. On the digit strings, percent, counting its numerals as words, against for our CTC recognizer, trained on nothing but digits: . Look at its mistakes: where the sound leaves room, the decoder, a language model, writes what it finds likelier, a plural, a number in figures, two words run together.
Recognizers kept growing and getting faster: Whisper large-v3 in 2023, and a turbo version that cut its decoder from 32 layers to 4. In January 2026 Alibaba's Qwen3-ASR, built on an omni model, covered 52 languages and dialects.
13SpeakingEngineering3 min
Speaking is the inverse problem, and it is older than listening. In 1939 Bell Labs showed the Voder at the World's Fair: an operator played speech on keys and a pedal. The idea behind it is the voice as a source and a filter: the vocal folds buzz, and the throat and mouth shape the buzz with resonances, the formants. In 1980 Dennis Klatt's formant synthesizer computed those resonances from rules; the voice Stephen Hawking used grew out of his work. The robotic edge went away when synthesizers started reusing real recordings: in unit selection, a speaker reads for hours, and the system splices together the pieces that join best. In the 2000s statistical models, hidden Markov models again, predicted the spectrum instead, smooth but muffled.
In 2016 DeepMind's WaveNet threw out the vocoder's rules and generated the wave itself, one sample at a time. It is a language model whose tokens are samples: each predicted from all the ones before, sixteen thousand a second, each sample squashed onto 256 levels by a logarithmic mu-law curve, so the vocabulary is small. To see far enough into the past, its convolutions skip by one, two, four and eight samples, doubling the reach with each layer. Listeners preferred it to the best systems of the day, but it was very slow. Google's Tacotron 2 split the job: a sequence-to-sequence network turns text into a mel spectrogram, and WaveNet turns that into sound. Listeners scored it 4.53 out of 5; real recordings scored 4.58.
Then speech synthesis became language modelling, with chapter nine's codec tokens as the words. Microsoft's VALL-E, in January 2023, takes the text and three seconds of someone's voice, written as EnCodec tokens. A transformer continues the voice prompt, writing the first codebook frame by frame; a second one fills in the finer codebooks all at once, and the codec's decoder makes the wave. Trained on sixty thousand hours, it could speak in a voice it had heard for three seconds, the trick that made voice cloning cheap, and that every speech model since has had to reckon with.
One modern codec language model is Qwen3-TTS. This model, from Alibaba in January 2026, was trained on over five million hours of speech in ten languages. Its tokenizer is a codec like Mimi: 12.5 frames a second, sixteen codebooks of 2,048, the first taught by a self-supervised model to carry what is said, the other fifteen how it sounds. Its transformer writes the first codebook of each frame and a small module predicts the other fifteen. The report gives first-packet latency around a tenth of a second in its streaming setup. Three seconds of reference speech can condition voice cloning. From the Voder's keys to here took eighty-seven years.
14Matching pictures and wordsResearch4 min
Pictures met words in two ways. Around 2014 networks learned to caption photos, a vision network feeding a language model that wrote a sentence. In 2021 OpenAI's CLIP did something simpler. Two encoders, one for pictures and one for text, trained on four hundred million pictures with their captions from the web, so that matching pairs get similar vectors. It could then classify pictures it was never trained to classify: write each class as a caption, and pick the closest. On ImageNet that scored 76 percent, without a single one of its labels. We trained a small pair on our letters, with captions like bold serif A. Here's a batch: every picture scored against every caption, and the bright diagonal is the right pairs.
Part 24 develops the information bound behind this loss. Here is a proof from the critic's side. Draw a candidate set, choose a slot uniformly, then draw a picture conditioned on that slot's caption. The loss asks the picture to find its partner. The best possible score is the log of how much more likely the caption is given the picture than on its own. Randomize the partner's slot. The chain rule for KL divergence splits the mutual information into log N minus the optimal loss, plus a nonnegative divergence. Any other critic has at least the optimal loss, which proves the bound for the population expectation. The candidate law Q N can be independent marginal draws, or uniform distinct captions as in our experiment: every slot still has the same caption marginal. Our measured values have sampling error, so they are estimates of that population bound. With , and candidates, three seeds, that score grows from nats to . The uniform seen-caption entropy is nats. At the same candidates, models trained on batches of and of score and .
Here is that table while the two encoders learn. At the start every score is noise. Each batch pulls the matching pairs' vectors together and pushes the others apart, and the diagonal lights up; pairs that share a letter or a style stay partly lit, because they really are alike. Now the test CLIP was famous for. We hid of the captions, every picture of bold mono Q and the like, from training altogether. Asked to choose among all captions, those pictures find their exact caption percent of the time, .
In 2023 Xiaohua Zhai and colleagues at Google changed one thing. CLIP's loss is a softmax over the batch: each picture's score depends on every other caption in it, so the whole batch must be gathered on every chip. SigLIP asks each picture-caption pair a yes-or-no question instead, with a sigmoid and a learned bias. No batch-wide sum, so it scales to enormous batches, and they found it better at small ones. We ran both at three batch sizes, on the same budget of pairs, three seeds each. On the unseen captions, the seeds overlap at the smallest batch, and they overlap at the largest: 53 against 50 percent at 16, 55 against 57 at 256, CLIP first. At scale, SigLIP's encoders became the eyes of many open vision-language models.
15Models that seeEngineering3 min
CLIP matches pictures with captions, but it can't answer a question about a picture. For that, connect a vision encoder to a language model. DeepMind's Flamingo, in 2022, squeezed each picture into 64 tokens and added new cross-attention layers to a frozen language model. Salesforce's BLIP-2 sent 32 learned queries to a frozen image encoder. And in April 2023 LLaVA showed how little it takes: a single linear map turns each of CLIP's patch vectors into a vector in the language model's word space, and the picture is just more tokens at the start of the prompt. Train the map on captions, then fine-tune on 158 thousand examples of chat about pictures that GPT-4 wrote from their captions. Nearly every open vision-language model since has this shape.
Early models resized every picture to one small square, 224 or 336 pixels on a side. That's fine for a dog, fatal for a receipt. Our letter-reading CLIP shows the effect: shrink its twenty-pixel letters and blow them back up. At ten pixels it still reads 88 percent of the letters; at five, 42. In 2024 Qwen2-VL stopped resizing to a square. A picture keeps roughly its own size and shape, is cut into 14-pixel patches, and every two by two patches become one token, so a small icon costs a few dozen tokens and a big screenshot over a thousand. These counts come from the published code.
A picture's tokens are a grid, not a line, and positions should say so. Qwen2-VL's answer, M-RoPE, gives every token three coordinates: time, row and column. Text tokens use the same number three times, so for text it is ordinary RoPE from Part 13. A picture's tokens share one time and take their own rows and columns, and the text after it carries on past the largest number used. The rotary dimensions are split three ways, each part rotated by one coordinate, so attention can tell neighbours in the picture from neighbours in the sentence. Video adds frames in time; Qwen2.5-VL tied that axis to real seconds, and Qwen3-VL spread the three across the frequencies.
The connector recipe bolts a vision encoder onto a model that learned language alone. The newer recipe trains on mixed sequences from the start, early fusion. In 2024 Meta's Chameleon wrote pictures as VQ tokens in the same vocabulary as words, Part 22's image tokens. In February 2026 Alibaba's Qwen3.5 was trained from the start on text and picture tokens together; by its model card it matches its text-only predecessor on text and beats the dedicated vision-language models on pictures. Seeing is no longer an add-on.
16Every sense at onceEngineering4 min
A text-based voice assistant can use a cascade: a recognizer turned your speech into text, a language model wrote a reply, and a synthesizer read it out. Stages can stream partial results, but text alone cannot carry every detail of the original voice: the tone, the laugh, and the hesitation may be lost. In May 2024 OpenAI's GPT-4o put it all in one network trained end to end on text, pictures and sound, answering speech in as little as 232 milliseconds, 320 on average, about as fast as people take turns.
GPT-4o still took turns. Conversation doesn't: people interrupt, overlap and murmur mm-hm while the other one talks. In September 2024 Kyutai's Moshi modelled two streams of sound at once, the user's and its own, eighty milliseconds at a time, so it is always listening, even while it speaks. Alongside its own speech it writes the words it is saying, slightly ahead of the sound, an inner monologue that keeps the speech on track. Its latency: 160 milliseconds in theory, about 200 in practice.
Alibaba's open omni models split the work in two. A Thinker, a language model, reads one sequence of text, picture and sound tokens, with rotary positions aligned by time, and writes text. A smaller Talker writes speech codes as it goes, and a decoder turns them into sound; in Qwen3-Omni, twelve and a half frames a second through a small convolutional decoder. In Qwen2.5-Omni the Talker read the Thinker's hidden states; in Qwen3-Omni it reads only the words and the sound and picture features, so tools and safety filters can step in on the text before it is spoken. Qwen3-Omni, in September 2025, made both halves mixtures of experts and released the weights; Qwen3.5-Omni, in April 2026, holds more than ten hours of audio in one context. And NVIDIA's PersonaPlex, in January 2026, carried full-duplex talk forward with a voice and a role to play.
In the end, every sense is a stream of tokens, and what differs is how many. The words of speech come at about tokens a second, by Whisper's own tokenizer on our voices. The same speech as Mimi's codes is 100 a second. Qwen3-TTS's published configuration has codebook indices a second, and a single high-definition frame of video is tokens. A minute of conversation is tokens per stream at Mimi's rate, so much of the engineering in these models is in spending fewer: lower frame rates, fewer codebooks, smaller pictures where they will do.
Qwen3-TTS's published codec configuration uses twelve point five frames per second and sixteen codebooks. Each frame carries one index from each codebook, giving a nominal rate of two hundred codebook indices per second. These are not two hundred text tokens per second, and this arithmetic is not a measurement of an executed narrator.
Recap, problems, and what comes nextAll tracks3 min
Let's take stock. Byte-pair encoding cuts text by merging the commonest pairs, a greedy compressor; the unigram model puts a probability on every cut. Our bits-per-Unicode-character scores use the same text suffix and one canonical token path. These three-seed runs used unequal compute, so the bars describe this cohort rather than isolate a tokenizer effect. Entropy patches mark high conditional uncertainty; the initial byte is unscored, not zero entropy. Pictures and sound become tokens through codebooks, which can collapse; restarts or fixed grids address different failure modes. Our residual codec codes speech spectrograms at 400 to 3,200 bits a second; making a wave would still need a vocoder. Sampling folds what is too fast back into the band; spectra and the mel scale are what recognizers hear. CTC learns to transcribe without alignments by summing over a lattice, Whisper learns from the web, and speech synthesis became language modelling over codec tokens. Contrastive training puts pictures and words in one space, and with everything as tokens, one model can see, listen and speak at once.
All of this comes back. The self-supervised speech and image encoders that semantic tokens and vision-language models are built on are the next part, Part 24. Reasoning models think in tokens, in Part 28. Robots and world models write actions and video frames as tokens, in Part 29. What the tokens come to mean inside a model is Part 30. And the quirks of tokenizers in benchmarks, and voices cloned from three seconds of speech, come back in the last part, on trust.
Here are six problems, from counting merges to the information a batch can certify. Pause here, and work through them; full solutions are in this part's notes.
Next time: where encoders like wav2vec 2.0 and DINO come from, when nobody labels anything. Two views of one input are pulled together in contrastive learning, while other inputs are pushed apart. We'll also see self-distillation and other ways to learn from data alone: learning without labels, Part 24.
Jurafsky and Martin's Speech and Language Processing is the place to go deeper: tokenization, recognition and synthesis are all in it. Thanks for watching, and see you in Part 24.
These three panels summarize newly completed QA measurements. The BPE curve counts remaining symbols at every fifty merges, not file size. The language-model bars show three-seed mean bits per Unicode character on the same text suffix along one canonical token path, for five configurations, with each observed seed range. The original schedules used unequal compute, so this is a descriptive comparison, not an isolated tokenizer effect. The entropy panel uses the accepted seed-zero byte-model entropy. A cross marks the initial unscored byte in its original position; it is not zero entropy. The threshold marks high conditional uncertainty, not the surprise of the observed byte.
Where it goes next. The self-supervised speech and image encoders that semantic tokens and vision-language models are built on are Part 24. Reasoning models think in tokens in Part 28, robots and world models write actions and video frames as tokens in Part 29, and what the tokens come to mean inside a model is Part 30. Tokenizer quirks in benchmarks and cloned voices return in Part 31.
Key results
The part's results in one place, for revision.
Try it
Lab 23 · CTC: every alignment at once
For random frame-by-frame probabilities over {blank, a, b}, compute p(y | x) by the forward recursion on the 2L + 1 extended states, compare it with a brute-force sum over all 3^T paths, and check that the gradient the series' autodiff sends back to the logits is the lattice's posterior occupancy minus the softmax.
python -m videos.ai.labs 23
needs numpy, scipy, matplotlib · download lab23.py ·
source on GitHubp('ab' | x): brute force over 729 paths 0.045678 forward recursion 0.045678
p('aa' | x): brute force over 729 paths 0.027610 forward recursion 0.027610
p('bab' | x): brute force over 729 paths 0.142014 forward recursion 0.142014
p('a' | x): brute force over 729 paths 0.020301 forward recursion 0.020301
paths of 3 frames that collapse to 'ab' 5 (aab, abb, -ab, a-b, ab-)
paths of 2 frames that collapse to 'aa' 0 (a repeated letter needs a blank between)
gradient: autodiff against occupancy - softmax largest difference 2.2e-16
p('ab' | x) before and after 60 steps on the logits 0.0457 to 0.9485 best path '-aaabb'
The forward recursion adds up every alignment in T(2L + 1) steps instead of 3^T, and its gradient tells each frame which symbol it should have voted for: the alignment is learned, never labelled.
The code (145 lines; it asserts its own result)
"""Lab 23: sum over every CTC alignment by the forward recursion, and check it against brute force and autodiff."""
import itertools
import numpy as np
from videos.coursekit import labs
from explainer.ai.autodiff import Tensor, log_softmax
TITLE = "CTC: every alignment at once"
GOAL = ("For random frame-by-frame probabilities over {blank, a, b}, compute p(y | x) by the forward recursion on the "
"2L + 1 extended states, compare it with a brute-force sum over all 3^T paths, and check that the gradient the "
"series' autodiff sends back to the logits is the lattice's posterior occupancy minus the softmax.")
TASKS = [
"Set T = 2 and ask for 'aa'. What does the recursion return, and which missing path explains it?",
"Replace the sum in the recursion by a maximum (Viterbi) and compare the best path's share of p(y | x) before and after training the logits.",
"Take 200 gradient steps on the logits for 'ab' with T = 12 and plot where the blanks end up.",
]
BLANK = 0
NAMES = "-ab"
def collapse(path):
"""CTC's map B: merge repeats, then drop blanks."""
out, prev = [], None
for k in path:
if k != prev and k != BLANK:
out.append(k)
prev = k
return tuple(out)
def extended(y):
ext = [BLANK]
for k in y:
ext += [k, BLANK]
return ext
def forward(logp, y):
"""p(y | x) as a Tensor, and the forward variables alpha (T x (2L+1)), from log-probabilities (T x K)."""
ext, T = extended(y), logp.data.shape[0]
p, zero = logp.exp(), Tensor(0.0)
alpha = [[p[0, ext[s]] if s < 2 else zero for s in range(len(ext))]]
for t in range(1, T):
row = []
for s in range(len(ext)):
reach = alpha[-1][s] + (alpha[-1][s - 1] if s >= 1 else zero)
if s >= 2 and ext[s] != BLANK and ext[s] != ext[s - 2]:
reach = reach + alpha[-1][s - 2] # skip the blank, unless it separates a repeated letter
row.append(reach * p[t, ext[s]])
alpha.append(row)
total = alpha[-1][-1] + alpha[-1][-2]
return total, np.array([[float(a.data) for a in row] for row in alpha])
def backward_vars(prob, y):
ext = extended(y)
T, S = prob.shape[0], len(ext)
beta = np.zeros((T, S))
beta[-1, -1] = beta[-1, -2] = 1.0
for t in range(T - 2, -1, -1):
for s in range(S):
b = beta[t + 1, s] * prob[t + 1, ext[s]]
if s + 1 < S:
b += beta[t + 1, s + 1] * prob[t + 1, ext[s + 1]]
if s + 2 < S and ext[s + 2] != BLANK and ext[s + 2] != ext[s]:
b += beta[t + 1, s + 2] * prob[t + 1, ext[s + 2]]
beta[t, s] = b
return beta
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
T, K = 6, 3
logits = Tensor(rng.standard_normal((T, K)), requires_grad=True)
prob = np.exp(log_softmax(logits).data)
paths = list(itertools.product(range(K), repeat=T))
weight = np.array([np.prod(prob[np.arange(T), list(pth)]) for pth in paths])
labels = [collapse(pth) for pth in paths]
worst = 0.0
for y in [(1, 2), (1, 1), (2, 1, 2), (1,)]:
brute = weight[[lab_ == y for lab_ in labels]].sum()
fwd = float(forward(log_softmax(logits), y)[0].data)
worst = max(worst, abs(brute - fwd))
lab.row(f"p('{''.join(NAMES[k] for k in y)}' | x): brute force over {len(paths)} paths", f"{brute:.6f} forward recursion {fwd:.6f}")
assert worst < 1e-12, "the recursion is the sum over paths"
assert abs(weight.sum() - 1) < 1e-12
# counting: with every probability 1 the recursion counts the paths (Problem 5: five paths for 'ab' at T = 3)
count = round(float(forward(Tensor(np.zeros((3, K))), (1, 2))[0].data))
count_aa = round(float(forward(Tensor(np.zeros((2, K))), (1, 1))[0].data))
lab.row("paths of 3 frames that collapse to 'ab'", f"{count} (aab, abb, -ab, a-b, ab-)")
lab.row("paths of 2 frames that collapse to 'aa'", f"{count_aa} (a repeated letter needs a blank between)")
assert count == 5 and count_aa == 0
# the gradient: d log p(y|x) / d logit[t, k] = occupancy of symbol k at frame t - softmax[t, k]
y = (1, 2)
total, alpha = forward(log_softmax(logits), y)
logp = total.log()
logp.backward()
beta, ext = backward_vars(prob, y), extended(y)
gamma = alpha * beta / np.exp(float(logp.data)) # the posterior over extended states, frame by frame
occ = np.zeros((T, K))
for s, k in enumerate(ext):
occ[:, k] += gamma[:, s]
grad_gap = np.abs(logits.grad - (occ - prob)).max()
lab.row("gradient: autodiff against occupancy - softmax", f"largest difference {grad_gap:.1e}")
assert np.allclose(gamma.sum(1), 1) and grad_gap < 1e-10, "the CTC gradient is occupancy minus softmax"
# gradient ascent on the logits: the model learns an alignment nobody gave it
history = [float(np.exp(logp.data))]
for _ in range(60):
logits.data += 1.0 * logits.grad
logits.grad[:] = 0
total, alpha = forward(log_softmax(logits), y)
logp = total.log()
logp.backward()
history.append(float(np.exp(logp.data)))
prob2 = np.exp(log_softmax(logits).data)
gamma2 = alpha * backward_vars(prob2, y) / history[-1]
best = "".join(NAMES[k] for k in prob2.argmax(1))
lab.row("p('ab' | x) before and after 60 steps on the logits", f"{history[0]:.4f} to {history[-1]:.4f} best path '{best}'")
lab.note = ("The forward recursion adds up every alignment in T(2L + 1) steps instead of 3^T, and its gradient "
"tells each frame which symbol it should have voted for: the alignment is learned, never labelled.")
assert all(b > a - 1e-12 for a, b in zip(history, history[1:])) and history[-1] > 0.9, "ascent raises p(y | x)"
assert collapse(prob2.argmax(1)) == y, "the best path collapses to the label"
fig, ax = labs.figure(2, size=(11, 4.2))
for a, g, title in ((ax[0], gamma, "Posterior over the lattice, random logits"), (ax[1], gamma2, "After 60 gradient steps")):
im = a.imshow(g.T, origin="lower", aspect="auto", cmap="magma", vmin=0, vmax=1)
a.set_yticks(range(len(ext)), [("blank" if k == BLANK else NAMES[k]) for k in ext])
a.set_xticks(range(T), [str(t + 1) for t in range(T)])
a.set(title=title, xlabel="frame", ylabel="extended state of 'ab'")
a.grid(False)
for t in range(T):
for s in range(len(ext)):
if g[t, s] > 0.005:
a.text(t, s, f"{g[t, s]:.2f}", ha="center", va="center", fontsize=8, color=labs.INK if g[t, s] < 0.8 else labs.BG)
fig.colorbar(im, ax=ax[1], label="probability of being in the state")
lab.fig = fig
return lab
Now change it
- Set T = 2 and ask for 'aa'. What does the recursion return, and which missing path explains it?
- Replace the sum in the recursion by a maximum (Viterbi) and compare the best path's share of p(y | x) before and after training the logits.
- Take 200 gradient steps on the logits for 'ab' with T = 12 and plot where the blanks end up.
Problems, with solutions
Try each problem before opening its solution.
-
Show that a BPE merge of a pair found n times (without overlaps) shortens the text by exactly n symbols. In "aaaa", how often does the pair (a, a) occur, and how many merges does it allow?
Solution
Replacing one occurrence of (a, b) by the single symbol ab turns two symbols into one, so n separate occurrences save n symbols. In "aaaa" the pair (a, a) sits at three overlapping positions, but merging left to right gives "aa aa": two merges, saving two symbols, not three. That is why
learn_bpehere records the actual savings next to the (overlapping) pair counts it ranks by, and checks that the merged text's length equals L₀ minus the savings. -
One model pays 9.6 bits per token with 3.2 characters a token; another pays 2.9 bits per byte on the same ASCII text. Which is better per character? Show that per-character perplexity is per-token perplexity to the power 1/(characters per token).
Solution
The first: 9.6 / 3.2 = 3.0 bits per character. The second: on ASCII text a byte is a character, so 2.9 bits per character; it is better. Perplexity per character is 2^(bits per character) = 2^(bits per token / characters per token) = (2^(bits per token))^(1/characters per token).
-
How many codes do FSQ levels (8, 5, 5, 5) give, and how many bits? What bitrate do 8 residual stages of 1,024 codes give at 75 frames a second?
Solution
8 · 5 · 5 · 5 = 1,000 codes, log₂ 1000 ≈ 9.97 bits. 8 stages × log₂ 1024 = 10 bits × 75 frames/s = 6,000 bits/s: EnCodec's 6 kbps setting.
-
Show that cos(2πft) and cos(2π(f_s − f)t) agree at every t = n/f_s. Sampled at 16 kHz, where does a 9 kHz tone appear?
Solution
At t = n/f_s, cos(2π(f_s − f)n/f_s) = cos(2πn − 2πfn/f_s) = cos(2πfn/f_s), by periodicity and evenness. At 16 kHz the Nyquist frequency is 8 kHz, and 9 kHz folds to 16 − 9 = 7 kHz.
-
List every path of T = 3 frames over {a, b, ∅} that collapses to "ab", and check the count with the forward recursion. Why must every path for "aa" contain a blank?
Solution
aab, abb, ∅ab, a∅b, ab∅: five paths. With all probabilities 1 the recursion counts paths: on the states (∅, a, ∅, b, ∅), α₁ = (1, 1, 0, 0, 0); α₂ = (1, 2, 1, 1, 0) (b may be reached from a, skipping the blank, since b ≠ a); α₃(b) = α₂(b) + α₂(∅) + α₂(a) = 1 + 1 + 2 = 4 and α₃(final ∅) = α₂(final ∅) + α₂(b) = 0 + 1 = 1; total 5. For "aa", two adjacent a's merge into one, so the skip from the first a to the second is forbidden: every path passes through the blank between them.
-
Show that f*(x, y) = log[p(y | x)/p(y)] minimizes InfoNCE, and that log N − L ≤ log N for any critic. How much information can a batch of 256 certify?
Solution
The loss is the cross-entropy of guessing which of the N captions is the partner. Given x and the N captions, the true posterior that slot k holds the partner is p(y_k | x) Π_{j≠k} p(y_j) divided by its sum over k, that is, [p(y_k | x)/p(y_k)] / Σ_l [p(y_l | x)/p(y_l)], a softmax of f* = log p(y | x)/p(y) (plus anything depending on x alone). A cross-entropy is smallest at the true posterior, so f* is optimal for every N. A cross-entropy of a discrete guess is never negative, so log N − L ≤ log N. With N = 256 the most it can certify is log 256 ≈ 5.55 nats = 8 bits.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| byte-pair encoding (BPE), merge | 字节对编码(BPE),合并 |
| word type, out-of-vocabulary word | 词型,未登录词 |
| WordPiece | WordPiece |
| unigram language model (tokenizer) | 一元语言模型(分词器) |
| cut (segmentation) of a word, lattice | 切分,格(网格) |
| subword regularization, SentencePiece | 子词正则化,SentencePiece |
| byte-level BPE, UTF-8 | 字节级BPE,UTF-8 |
| tokenizer-free model, patch, entropy patching | 无分词器模型,块,按熵分块 |
| Byte Latent Transformer (BLT) | 字节潜变量Transformer(BLT) |
| codebook, dead code, codebook collapse | 码本,死码,码本坍缩 |
| straight-through estimator, stop-gradient | 直通估计器,停止梯度 |
| codebook loss, commitment loss | 码本损失,承诺损失 |
| exponential moving average (EMA) codebook | 指数移动平均(EMA)码本 |
| dead-code restart | 死码重启 |
| finite scalar quantization (FSQ) | 有限标量量化(FSQ) |
| lookup-free quantization (LFQ), entropy term | 免查表量化(LFQ),熵项 |
| residual vector quantization (RVQ), stage | 残差向量量化(RVQ),级 |
| quantizer dropout | 量化器丢弃 |
| sampling rate, Nyquist frequency, sampling theorem | 采样率,奈奎斯特频率,采样定理 |
| aliasing, anti-aliasing filter, decimation | 混叠,抗混叠滤波器,抽取(降采样) |
| short-time Fourier transform (STFT), spectrogram | 短时傅里叶变换(STFT),频谱图 |
| mel scale, mel filterbank, log-mel spectrogram | 梅尔刻度,梅尔滤波器组,对数梅尔频谱 |
| neural audio codec, bitrate (kbps) | 神经音频编解码器,码率(kbps) |
| semantic tokens, acoustic tokens | 语义词元,声学词元 |
| template matching, dynamic time warping (DTW) | 模板匹配,动态时间规整(DTW) |
| acoustic model, Gaussian mixture | 声学模型,高斯混合 |
| word error rate (WER) | 词错误率(WER) |
| connectionist temporal classification (CTC), blank | 连接时序分类(CTC),空白符 |
| collapse map, alignment, posterior occupancy | 折叠映射,对齐,后验占有率 |
| RNN transducer, listen-attend-spell | RNN转录器,听-注意-拼写 |
| weak supervision | 弱监督 |
| forced aligner | 强制对齐器 |
| source–filter model, formant | 源-滤波器模型,共振峰 |
| formant synthesis, unit selection, statistical parametric synthesis | 共振峰合成,单元选择,统计参数合成 |
| vocoder, μ-law | 声码器,μ律 |
| dilated causal convolution | 扩张因果卷积 |
| codec language model, voice cloning | 编解码器语言模型,声音克隆 |
| multi-token prediction (MTP), first-packet latency | 多词元预测(MTP),首包延迟 |
| critic, density ratio | 打分函数(评判函数),密度比 |
| zero-shot retrieval | 零样本检索 |
| sigmoid loss (SigLIP) | sigmoid损失(SigLIP) |
| vision-language model, connector, Perceiver resampler, Q-Former | 视觉语言模型,连接器,感知重采样器,Q-Former |
| dynamic resolution, M-RoPE | 动态分辨率,多模态旋转位置编码(M-RoPE) |
| early fusion | 早期融合 |
| cascade, full duplex, inner monologue | 级联,全双工,内心独白 |
| Thinker, Talker | 思考者(Thinker),说话者(Talker) |
Sources
Books. D. Jurafsky & J. H. Martin, Speech and Language Processing, 3rd ed. draft (tokenization, ASR, TTS); L. Rabiner & B.-H. Juang, Fundamentals of Speech Recognition (1993); P. Taylor, Text-to-Speech Synthesis (2009).
Text. P. Gage, "A New Algorithm for Data Compression", C Users Journal (1994); M. Schuster & K. Nakajima, "Japanese and Korean Voice Search" (ICASSP 2012); R. Sennrich, B. Haddow & A. Birch, "Neural Machine Translation of Rare Words with Subword Units" (ACL 2016); T. Kudo, "Subword Regularization" (ACL 2018); T. Kudo & J. Richardson, "SentencePiece" (EMNLP 2018); A. Radford et al., "Language Models are Unsupervised Multitask Learners" (GPT-2, 2019); L. Xue et al., "ByT5" (2021); L. Yu et al., "MegaByte" (2023); A. Pagnoni et al., "Byte Latent Transformer: Patches Scale Better Than Tokens" (arXiv 2412.09871, 2024); Llama 3 (Meta, 2024), Gemma 3 (Google, 2025) vocabulary sizes from their reports.
Codebooks. A. van den Oord, O. Vinyals & K. Kavukcuoglu, "Neural Discrete Representation Learning" (VQ-VAE, 2017); A. Razavi, A. van den Oord & O. Vinyals, VQ-VAE-2 (2019); F. Mentzer, D. Minnen, E. Agustsson & M. Tschannen, "Finite Scalar Quantization" (2023); L. Yu et al., "Language Model Beats Diffusion: Tokenizer is Key to Visual Generation" (MAGVIT-v2, LFQ, 2023).
Sound. H. Nyquist (1928); C. E. Shannon, "Communication in the Presence of Noise" (1949); N. Zeghidour et al., "SoundStream" (2021); A. Défossez et al., "High Fidelity Neural Audio Compression" (EnCodec, 2022); Z. Borsos et al., "AudioLM" (2022); A. Défossez et al., "Moshi: a speech-text foundation model for real-time dialogue" (arXiv 2410.00037, 2024; Mimi: 24 kHz, 12.5 Hz, 8 codebooks of 2,048, 1.1 kbps, WavLM distilled into the first; 160/200 ms).
Recognition. K. H. Davis, R. Biddulph & S. Balashek, "Automatic Recognition of Spoken Digits", JASA 24, 637 (1952); T. Vintsyuk (1968); H. Sakoe & S. Chiba (1978); J. Baker, "The DRAGON System" (1975); F. Jelinek (1976); L. Rabiner, "A Tutorial on Hidden Markov Models" (1989); G. Hinton et al., "Deep Neural Networks for Acoustic Modeling in Speech Recognition" (2012); A. Graves, S. Fernández, F. Gomez & J. Schmidhuber, "Connectionist Temporal Classification" (ICML 2006); A. Hannun et al., "Deep Speech" (2014); A. Baevski et al., "wav2vec 2.0" (2020); A. Radford et al., "Robust Speech Recognition via Large-Scale Weak Supervision" (Whisper, 2022); Qwen Team, "Qwen3-ASR Technical Report" (arXiv 2601.21337, 2026).
Synthesis. H. Dudley, the Voder (1939); D. Klatt, "Software for a Cascade/Parallel Formant Synthesizer" (1980); A. Hunt & A. Black, "Unit Selection in a Concatenative Speech Synthesis System" (1996); A. van den Oord et al., "WaveNet" (2016); J. Shen et al., "Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions" (Tacotron 2, 2017); C. Wang et al., "Neural Codec Language Models are Zero-Shot Text to Speech Synthesizers" (VALL-E, 2023); Qwen Team, "Qwen3-TTS Technical Report" (arXiv 2601.15621, 2026: 12.5 Hz, 16 codebooks of 2,048, WavLM-taught semantic codebook, MTP, 97/101 ms first packet, over 5 million hours, 10 languages); G. E. Peterson & H. L. Barney (1952), the formants drawn.
Pictures and words. O. Vinyals et al., "Show and Tell" (2015); A. Radford et al., "Learning Transferable Visual
Models From Natural Language Supervision" (CLIP, 2021); X. Zhai et al., "Sigmoid Loss for Language Image
Pre-Training" (SigLIP, 2023); M. Tschannen et al., SigLIP 2 (2025); J.-B. Alayrac et al., "Flamingo" (2022); J. Li et
al., "BLIP-2" (2023); H. Liu, C. Li, Q. Wu & Y. J. Lee, "Visual Instruction Tuning" (LLaVA, 2023); P. Wang et al.,
"Qwen2-VL" (2024; dynamic resolution: transformers' smart_resize, copied); Qwen Team, Qwen2.5-VL (2025), Qwen3-VL
(arXiv 2511.21631, 2025); Chameleon Team, "Chameleon" (2024); Qwen3.5-397B-A17B model card (February 2026).
Omni. OpenAI, "Hello GPT-4o" (May 2024: 232 ms minimum, 320 ms average audio response); OpenAI, "Introducing gpt-realtime" (August 2025); Qwen Team, Qwen2.5-Omni (2025), "Qwen3-Omni Technical Report" (arXiv 2509.17765, 2025: Thinker–Talker MoE, 234 ms, 119/19/10 languages, Apache 2.0; the Talker no longer reads the Thinker's text representations), "Qwen3.5-Omni Technical Report" (arXiv 2604.15804, 2026); R. Roy et al., "PersonaPlex" (arXiv 2602.06053, 2026).
About this partfrom its README
Part 23 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus). How text, sound and pictures become sequences of tokens, how the codes are learned, how speech is recognized and synthesized, and how pictures and words are matched, from Bell Labs' Audrey (1952) to the omni models of 2026. A hook, sixteen chapters and an outro, about 55 minutes, in English and Chinese. Some scenes require separately accepted cached measurements and model assets; published figures are cited. A fresh checkout does not by itself establish that all experiments were run or that production inputs are present.
What is computed and builtOriginal reported results (not reverified here)
QA interpretation (2026-11-02): the numbers below are the original reported outcomes, not new measurements on the QA host. The k-means fitting and evaluation patches are sampled independently from the same pool and may overlap; those errors are RMSE on evaluation patches, not a disjoint held-out result. The saved CLIP information scores use uniform distinct captions sampled without replacement. The population information bound remains valid for that candidate law (see below), but the finite empirical scores have sampling error. A disjoint patch split is a separate experiment, requiring restored inputs, independent review and measured impact before replacing any original outcome.
For the information proof, let Q_N be the candidate-caption law, let I be an independent uniform slot, and draw X conditional on Y_I. Every candidate slot has the same caption marginal. Relative to p_X Q_N Uniform(I), the joint KL divergence is I(X;Y). The KL chain rule splits this into the KL of the unlabelled candidate mixture and log N minus the optimal classification loss. The former is nonnegative, and every critic's cross-entropy is at least the optimal loss. This proves log N minus L <= I(X;Y) without replacing a random sum by its expectation inside a logarithm. It covers both iid candidates and uniform distinct candidates.
Measured by compute.py on this machine (CPU only, one torch thread, seeded); the video reads every number from the
cache, so a rerun elsewhere may differ in the last digits.
- BPE on 2 million characters of the novels: 21,374 word types; 5.3% of the test passage's words never seen. Characters a token on the passage: 2.43 (500 merges), 3.14 (2,000), 3.93 (8,000); the first merge saves 48,515 symbols and 8,000 merges leave 23.4% of the length. The series' own byte-level tokenizer: 3.23 characters a token.
- Unigram LM vs BPE, characters a token: 2.64 vs 2.74 at 1,024 pieces, 3.46 vs 3.54 at 4,096; 22% and 15% of the passage's words have different token counts (this metric does not count equal-length alternative segmentations).
- Bits per character of the same transformer (3 layers, width 96) at equal FLOPs, three seeds: bytes 2.46, BPE-1,024 2.28, unigram-1,024 2.26, BPE-4,096 2.36, unigram-4,096 2.26.
- Entropy patches at BPE's length (3.54 bytes): 28% of bytes start a patch and carry 46% of the surprise; BPE's token starts carry 24%.
- Codebooks on letter pictures (k-means), error per pixel: 0.148 / 0.110 / 0.083 / 0.061 for 16 / 64 / 256 / 1,024 codes; residual stages of 16: 0.149, 0.117, 0.097, 0.083.
- VQ autoencoders, 256 codes, three seeds (codes used, perplexity, error ×10⁻³): VQ 86, 67, 6.20; EMA 76, 56, 6.47; EMA with dead-code restarts 255, 194, 4.62; FSQ (4·4·4·4) 186, 121, 5.32; LFQ (8 bits) 74, 60, 14.98.
- Sampling: tones of 1, 3, 5, 7 kHz sampled at 8 kHz peak at 1, 3, 3, 1 kHz; 4.4% of a sentence's energy lies above 2 kHz, and 4.8% of what remains below 2 kHz after naive decimation is folded energy. Our log-mel matches the transformers extractor to 1.5 × 10⁻⁵.
- Audrey replica (ten digit templates from one voice): same voice 90% (stretched) / 100% (time warping); eleven other voices 63% / 74%; templates from ten voices on two new voices 95%.
- Log-mel codec (1.3 M parameters, 1,500 steps, 6 minutes of speech, two seeds): log-mel error 0.13 / 0.11 / 0.11 / 0.10 at 400 / 800 / 1,600 / 3,200 bits a second; Whisper's word error on 12 held-out sentences 30% / 17% / 15% / 15%, against 12% on the original pictures; stage perplexities 166–227 of 256. (A first attempt, an 8-channel waveform codec trained for 3,000 steps, learned only the average spectrum: Whisper's word error stayed above 100%. That is why the chapter codes the picture.)
- CTC digit recognizer (162 thousand parameters, 2,500 steps, three seeds): word error 33.1%, 32.5%, 68.8% on two held-out voices; 4.6%, 8.8%, 15.0% on training voices. The forward algorithm's total matches PyTorch's CTC loss.
- Whisper base.en (72.6 M parameters): word error 7.9% on 24 held-out sentences, 5.0% on 40 digit strings.
- Qwen3-TTS tokenizer: the narrator's 16.6 s reference clip as 208 frames × 16 codes (2,200 bits a second); encoded and decoded, log-mel distance 0.066, and Whisper's transcript is unchanged. The narrator saying this part's title: 43 frames, transcribed correctly.
- CLIP vs SigLIP on 520 letter captions (15% held out, 384 thousand pairs, three seeds): exact unseen captions found 46–58% (CLIP) and 47–62% (SigLIP) across batch sizes, ranges overlapping. InfoNCE's log N − L for the batch-256 CLIP at N = 16 / 64 / 256: 2.62 / 3.69 / 4.46 nats, under H(caption) = 6.09.
- Visual tokens (Qwen2-VL's
smart_resize, 28-pixel cells after merging): 64, 256, 1,196, 1,222, 1,230, 1,230 for the six test images.
Compute: about four hours of one CPU thread on a busy machine in all (the language models 87 minutes, speech synthesis 36, CLIP 26, the codec 26, CTC 25, VQ 19, the narrator's codes 17, the rest under 4 each).
Chapter notes
- Hook: one sequence. Text, a picture and a voice (a held-out Kokoro voice's log-mel spectrogram) become one stream of tokens; the questions of the part; objectives.
- 1. How we got here. Four threads on one time axis: listening (Audrey 1952, time warping, HMMs, CTC, deep acoustic models, Deep Speech, wav2vec 2.0, Whisper), speaking (the Voder 1939, formant synthesis, unit selection, WaveNet, Tacotron, VALL-E, Qwen3-TTS), text (Shannon's letters, Gage's byte pairs 1994, WordPiece, BPE for translation, SentencePiece, byte-level BPE, entropy patches) and pictures (captioning, VQ-VAE, CLIP, Flamingo, LLaVA, early fusion), meeting in GPT-4o, Moshi and the Qwen omni models.
- 2. Merges as compression. Words run out (word types in two million characters of the novels; the share of the passage's words never seen); characters make sequences long. Gage's algorithm and Sennrich, Haddow & Birch's BPE, replayed on a phrase; why it compresses (a merge found n times saves n symbols; L_k = L_0 − Σ n_i; greedy); the length of the text against the number of merges; one sentence at 0 to 8,000 merges; WordPiece's likelihood rule and its first merges; vocabulary sizes of GPT-2, Llama 3, GPT-4o, Gemma 3.
- 3. A probability for every cut. Kudo's unigram language model: P(x) = Σ over cuts Π p(pieces); the lattice of a word, the forward algorithm, Viterbi, expected counts; training by EM and pruning, replayed (bits per character as the vocabulary shrinks); BPE and the unigram model side by side; sampled cuts (subword regularization); SentencePiece.
- 4. What a token is worth. Bits per character = bits per token / characters per token, derived; five tokenizers (bytes; BPE and unigram at 1,024 and 4,096 pieces), the same small transformer (explainer.lm.pocket), unequal original compute schedules, three seeds: learning curves against compute, bits per character on the scoreboard's passage with the spread; why vocabulary size trades text per FLOP against the output layer; samples from two of the models.
- 5. Bytes and patches. Tokenizer failure modes; UTF-8 and GPT-2's byte-level BPE; the series' own byte-level BPE (explainer/ai/novels.py) on the passage; ByT5, MegaByte, the Byte Latent Transformer; our byte model's next-byte entropy along a line of the passage, a threshold, the patches; the share of surprise on a patch's first byte against BPE's token starts, at equal average length.
- 6. Learning a codebook. k-means codebooks of 4 × 4 letter patches; the straight-through estimator, the codebook and commitment losses (VQ-VAE); dead codes; a VQ autoencoder trained three ways (plain, EMA, EMA with data initialization and dead-code restarts), three seeds: codes in use through training, the usage histogram, perplexity and error.
- 7. Codes without a codebook. FSQ (bound, round, a fixed grid of Π L_i codes), LFQ (signs, 2^d codes, the entropy term); all five quantizers at 256 codes, three seeds; residual stages against one codebook at equal bits.
- 8. Sampling sound. Aliasing derived (cos(2π(f + k f_s)n/f_s) = cos(2πfn/f_s); evenness), the sampling theorem; tones sampled at 8 kHz and their measured spectral peaks; the folding curve; speech decimated with and without a filter; the STFT, Slaney's mel filters, Whisper's log-mel front end, our implementation checked against transformers'.
- 9. Neural codecs. From PCM to SoundStream and EnCodec (residual VQ, quantizer dropout); our codec, a small cousin that codes Whisper's log-mel picture instead of the wave (a strided convolution to 50 frames a second, 8 stages × 256 codes, quantizer dropout, EMA codebooks with restarts; turning the picture back into sound would need a vocoder, the expensive part), trained on Kokoro speech, its training replayed on a held-out voice; spectrograms and Whisper's word error rate, reading the rebuilt pictures directly, at 400 to 3,200 bits a second, two seeds; semantic and acoustic tokens (AudioLM, Mimi, Qwen3-TTS's tokenizer); our stages' perplexities.
- 10. From Audrey to hidden Markov models. Audrey (Davis, Biddulph & Balashek 1952); a template recognizer of our own (one Kokoro voice's digits) on the same voice and eleven others; dynamic time warping (Vintsyuk 1968; Sakoe & Chiba 1978) with an alignment path; templates from ten voices on two new ones; HMMs with Gaussian mixtures, the noisy channel argmax P(sound|W)P(W); 2012's deep acoustic models.
- 11. Connectionist temporal classification. The alignment problem; the blank and the collapse map; p(y|x) as a sum over paths; the forward recursion on 2L+1 states, derived (Part 7's forward algorithm); a small CTC recognizer (seven convolutions, dilated, 20 ms frames) trained on Kokoro digit strings, three seeds, its posteriors replayed through training; the lattice's posterior occupancy and best path from the trained network, its total checked against PyTorch's CTC loss; word error rates on held-out and training voices; Deep Speech, RNN-T, attention.
- 12. Listening at scale. wav2vec 2.0 and Whisper; Whisper base.en on the held-out voices: its input, its token stream, its word error rates on sentences and digit strings against our CTC model, its mistakes; large-v3, turbo, Qwen3-ASR, and how this series' narration is checked and aligned (tools/tts_server.py).
- 13. Speaking. The source–filter model and formants, the Voder, Klatt, unit selection, HMM synthesis; WaveNet (an autoregressive model of samples, μ-law, dilated causal convolutions); Tacotron 2; VALL-E (codec tokens, a 3-second prompt); Qwen3-TTS, the narrator: its tokenizer (12.5 Hz, 16 codebooks of 2,048, semantic + acoustic), its multi-token prediction, and an optional narrator-code experiment currently marked as not run unless a verified result is supplied.
- 14. Matching pictures and words. Captioning and CLIP; our letters-and-captions model; InfoNCE as a lower bound on the mutual information, derived from the optimal critic (Part 24 derives it another way); the estimate against log N at batch sizes 16, 64, 256; training replayed; zero-shot retrieval of captions never seen in training; SigLIP's sigmoid loss against CLIP's softmax at three batch sizes, equal pairs, three seeds.
- 15. Models that see. Flamingo, BLIP-2, LLaVA (connectors); resolution (our CLIP reading shrunken letters) and Qwen2-VL's dynamic resolution (token counts from the published rule); M-RoPE position ids, computed; Qwen2.5-VL and Qwen3-VL; early fusion (Chameleon, Qwen3.5).
- 16. Every sense at once. Cascades and GPT-4o; full duplex (Moshi: two streams, the inner monologue); Thinker and Talker (Qwen2.5-Omni, Qwen3-Omni, Qwen3.5-Omni), PersonaPlex; tokens a second for each sense.
- Outro. Recap tiles from this part's results, where it comes back, six problems, next time (Part 24), references.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- BPE (merges as compression); unigram LM.
- Byte-level and tokenizer-free: BLT, entropy patching.
- Tokenization and bits per character.
- VQ: straight-through, commitment, collapse, EMA; FSQ/LFQ; RVQ.
- Audio: Nyquist derived, STFT, mel; codecs (SoundStream, EnCodec, Mimi); semantic vs acoustic tokens.
- ASR: Whisper; CTC derived (the HMM forward algorithm).
- TTS: Qwen3-TTS, the narrator.
- Full duplex (Moshi).
- CLIP: InfoNCE as an MI bound; SigLIP.
- VLMs: connectors, dynamic resolution, M-RoPE.
- Omni models (Thinker–Talker).
中文讲义
本讲的中文部分(与英文版对应)。
习题
- 证明:一个出现n次(互不重叠)的字节对,合并一次能让文本恰好缩短n个符号。在“aaaa”里,字节对(a, a)出现几次?能合并几次?
- 一个模型每个词元花9.6比特,平均每个词元3.2个字符;另一个在同一段ASCII文本上每字节花2.9比特。按每字符算哪个更好?证明每字符困惑度等于每词元困惑度的(1/每词元字符数)次方。
- FSQ的等级取(8, 5, 5, 5),一共有多少个码,几比特?8级残差量化、每级1024个码、每秒75帧,码率是多少?
- 证明cos(2πft)和cos(2π(f_s − f)t)在每个t = n/f_s上取值相同。以16 kHz采样时,9 kHz的音调会出现在哪里?
- 列出在{a, b, ∅}上长为T = 3、折叠后得到“ab”的所有路径,并用前向递推核对数目。为什么“aa”的每条路径都必须经过一个空白符?
- 证明f*(x, y) = log[p(y | x)/p(y)]使InfoNCE最小,并证明对任何打分函数都有log N − L ≤ log N。一个256的批次最多能证实多少信息?
解答
1. 把一次(a, b)换成一个符号ab,两个符号变成一个,所以n次互不重叠的出现省下n个符号。“aaaa”里(a, a)出现在三个互相重叠的位置,但从左到右合并得到“aa aa”:两次合并,省两个符号,而不是三个。所以这里的learn_bpe在用来排序的(含重叠的)字节对计数旁边,还记下实际省下的符号数,并核对合并后的文本长度正好等于L₀减去省下的总数。
2. 第一个:9.6 / 3.2 = 每字符3.0比特。第二个:ASCII文本里一个字节就是一个字符,所以每字符2.9比特,它更好。每字符困惑度是2的(每字符比特数)次方,等于2的(每词元比特数 / 每词元字符数)次方,也就是每词元困惑度的(1/每词元字符数)次方。
3. 8 · 5 · 5 · 5 = 1000个码,log₂ 1000 ≈ 9.97比特。8级 × log₂ 1024 = 10比特,乘以每秒75帧,是每秒6000比特:正是EnCodec的6 kbps档。
4. 在t = n/f_s处,cos(2π(f_s − f)n/f_s) = cos(2πn − 2πfn/f_s) = cos(2πfn/f_s),用到余弦的周期性和偶性。16 kHz采样的奈奎斯特频率是8 kHz,9 kHz会折叠到16 − 9 = 7 kHz。
5. aab,abb,∅ab,a∅b,ab∅:共五条。把所有概率都取1,递推就在数路径:在状态(∅, a, ∅, b, ∅)上,α₁ = (1, 1, 0, 0, 0);α₂ = (1, 2, 1, 1, 0)(b可以跳过空白、直接从a到达,因为b ≠ a);α₃(b) = α₂(b) + α₂(∅) + α₂(a) = 1 + 1 + 2 = 4,α₃(末尾∅) = α₂(末尾∅) + α₂(b) = 0 + 1 = 1;合计5。对“aa”,相邻的两个a会合并成一个,所以不允许从第一个a跳到第二个a:每条路径都要经过它们之间的空白符。
6. 这个损失是猜N个说明里哪一个是配对的交叉熵。给定x和N个说明,第k个位置是配对的真实后验概率,正比于p(y_k | x) Π_{j≠k} p(y_j),即[p(y_k | x)/p(y_k)] / Σ_l [p(y_l | x)/p(y_l)],正是f* = log p(y | x)/p(y)(再加任何只依赖x的项)的softmax。交叉熵在真实后验处最小,所以f*对任何N都是最优的。离散猜测的交叉熵永远不为负,所以log N − L ≤ log N。N = 256时,最多能证实log 256 ≈ 5.55奈特,即8比特。
Build the film
python -m videos.ai.ai23.compute # the part's numbers, into .cache/ai23
python tools/build.py ai23 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai23 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai23. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
Before production, run python tools/check_part23_qa_inputs.py from the repository root. It checks for five
separately accepted cache JSON files. The standard compute registry does not create those files automatically.
Presence alone does not validate their contents or any companion arrays. Missing originals must be restored or
independently generated and accepted; model assets, audio, and full playback still need their own checks.
python tools/make.py ai23 # compute, then the narrated cut in English and Chinese
python -m videos.ai.ai23.compute # just the numbers (Part 1's novels, Part 21's letters)
python -m videos.ai.ai23.compute --force codec # recompute one item
AI23_SCALE=0.05 python -m videos.ai.ai23.compute # reduced-scale computation, into .cache/ai23_quick/
python tools/build.py ai23 -q l # a 480p preview
The original full run took about four hours on a busy 4-core machine, on one torch thread (AI23_THREADS); actual
time and memory depend on the machine and available inputs. Synthesized speech is saved voice by voice
(.cache/ai23/speech/), the language models checkpoint every 100 steps and the codec every 500. Multi-run items
save completed runs, but not every individual training run has a mid-run checkpoint: an interruption can require
restarting the current run. Equal numbers of image-caption pairs do not imply equal compute across batch sizes or
loss functions. It needs Kokoro-82M (a dependency of the repo; the eleven extra voices, about 0.5 MB each, download on first
use) and Whisper base.en (about 290 MB, downloaded by transformers on first use). The narrator's codes need
.venv-tts with qwen_tts and the Qwen3-TTS-12Hz-1.7B-Base model in the Hugging Face cache. The narrator-code
experiment is optional and requires explicit AI23_NARRATOR_EXECUTE=1; it is not a scene dependency. If explicitly
running that experiment, AI23_NARRATOR_GENERATE=0 skips synthesizing a new sentence.