Video and audio generation

How image generators gain a time axis: video as space-time patches of a causal video VAE's latent, full attention and what a clip costs, conditioning and long-video drift; audio as spectrograms and neural-codec tokens (residual vector quantisation), codec language models and flow-matching speech; how both are evaluated. A real video VAE round trip, three neural codecs at every bitrate and the token arithmetic of eight video models, measured on an Apple M1 Pro. A child of Topic: generative-and-multimodal. Data as of October 2026. Reading: 31 min, plus 17 in closed details.

The idea in one screen

A video or audio generator is an image generator with a time axis, and almost every design choice exists to make that axis affordable: a causal video VAE folds 4 frames into one latent frame so that a 5 s clip becomes about 33,000 space-time tokens for a flow-matching transformer, and a neural codec turns each second of sound into 100 to 600 discrete tokens for a language model, or into a short continuous latent for flow.

You need: the image denoiser this page extends (patchify, DiT, adaLN, MMDiT, 2-D RoPE ids, FLOPs per pass) on Latent diffusion and diffusion transformers; the objectives and samplers on Diffusion from zero and Flow matching; VAEs, VQ and residual quantisation of images (RQ-VAE) on Autoencoders and VAEs. One network that reads and writes text, images and speech is Native multimodal and any-to-any models. Release dates, licences and status of every model named here are on the root's Model map tab (Topic: generative-and-multimodal), including Sora's discontinuation in 2026 (app closed 2026-04-26, API scheduled to end 2026-09-24, from secondary reports).

Same four moves for both media: compress, cut into tokens, generate, decode

Video: Wan 2.1's default clip through its VAE and 1 × 2 × 2 patches (sections 1 to 4). Audio: the running sentence through EnCodec 24 kHz at 6 kbps (sections 6 to 8). Highlighted: what the generator actually sees, the number every cost on this page follows from. All counts derived from the configs.

Causal video VAE
a VAE with 3-D convolutions that only look backwards in time; frame 1 alone, then each group of 4 (or 8) frames becomes one latent frame.
Space-time patch
one token: a small block of the latent across space and time (1 × 2 × 2 latent cells in Wan).
Full against factorised attention
every token attends to every token in the clip, against attention within a frame followed by attention across frames at one position.
Exposure bias, drift
a model trained on real frames conditions on its own imperfect ones when extending a video, and errors pile up.
Mel spectrogram
sound as an image: log power in frequency bands spaced like human hearing, one column every 10 to 20 ms.
Vocoder
a network that turns a spectrogram back into a waveform (it must invent the phase).
Neural codec, RVQ
an autoencoder for sound whose bottleneck is a chain of small codebooks, each quantising what the previous ones missed (residual vector quantisation).
Quantiser dropout
training with a random number of codebooks, so any prefix of the chain decodes (one model, many bitrates).
Semantic tokens
codes that carry what is said rather than how it sounds (Mimi distils a speech model into its first codebook).
Delay pattern
codebook k shifted k − 1 steps, so one transformer emits every codebook of a frame in order, one step per frame.

The running examples. Video: the topic's public-domain test image p01_cat (scikit-image's "chelsea", CC0) turned into two 17-frame 256 × 256 clips by sliding a crop across it, slowly (2 pixels per frame) and fast (14 pixels per frame), sent through Wan 2.1's video VAE (126.9M parameters, Apache 2.0) on the CPU, plus the configs of seven open video denoisers. Audio: one LibriSpeech sentence ("I hope he doesn't work too hard said Shaggy", 3.67 s, utterance 1272-135031-0008, CC BY 4.0) and a 3.5 s synthesised music phrase, through three open neural codecs, EnCodec 24 kHz, DAC 44.1 kHz and Mimi, at every number of codebooks. Everything measured ran on an Apple M1 Pro CPU; files and scripts are in this page's src/.

Video against audio in one table (reference)
VideoSpeech, music, sound
Raw size5 s of 480 × 832 at 16 fps: 81 frames, 97 million numbers3.67 s at 24 kHz: 88,080 numbers (samples)
CompressorCausal video VAE: 8 × 8 in space, 4 in time, 16 channels (Wan 2.1)Neural codec: 75 frames a second, 1 to 32 codebooks of 1,024 (EnCodec); or a mel spectrogram, or a continuous audio VAE
What the generator sees32,760 tokens for that clip (Wan 2.1 1.3B, 1 × 2 × 2 patches): tokens per second of video600 tokens a second at 6 kbps (EnCodec, 8 codebooks); 100 a second for Mimi at 1.1 kbps
GeneratorA transformer denoiser trained with flow matching (Wan, HunyuanVideo, LTX, Movie Gen) or diffusion (CogVideoX)A language model over codec tokens (AudioLM, VALL-E, MusicGen, Moshi) or flow / diffusion over mel or latents (F5-TTS, Stable Audio)
What failsMotion and time: identity drift, objects appearing or vanishing, broken physics, quality falling past the trained lengthMetallic or muffled timbre at low bitrates, mispronounced or skipped words, voice drift in long takes
How it is judgedHuman preference (arenas, A/B tests), VBench; FVD with careMUSHRA or MOS listening tests; word error rate and speaker similarity for speech; FAD, CLAP score

Raw video: 81 × 480 × 832 × 3 = 97,044,480 numbers. Token counts from the configs and diffusers v0.41.0 pipeline defaults (section 1); codec rates from the codec configs (section 7).

1. Video as space-time latents

The problem. Wan 2.1's default clip (480 × 832 pixels, 81 frames, about 5 s at 16 frames per second) is 97 million numbers, and neighbouring frames are almost the same picture. An image VAE applied to every frame (8 × 8 smaller in space) still leaves 81 latent frames; with 2 × 2 patches that is 81 × 30 × 52 = 126,360 tokens, most of them repeating the frame before. Attention cost grows with the square of the token count, so redundancy across time is the first thing to remove.

A causal video VAE. The image VAE (Autoencoders and VAEs) with 3-D convolutions, so it also shrinks the time axis: every open model on this page compresses time by 4 (or 6, or 8) as well as space by 8 (or 16, or 32). Two details recur:

  • Causal in time. The encoder's convolutions only look at the current and earlier frames (all the padding goes at the start of the time axis, CogVideoX, Sec 2.1), so the latent of frame group t never depends on later frames. One model then encodes an image (a 1-frame video), and a decoder can stream.
  • The first frame alone. Wan's VAE encodes frame 1 on its own and then each further group of 4 frames into one latent frame, carrying a cache of features from earlier groups. So a clip must have 4k + 1 frames, and 81 frames become 1 + 80 / 4 = 21 latent frames. Wan's paper: "the first frame is only spatially compressed to better handle the image data" (Wan 2025, Sec 4.1).
The encode loop in diffusers (real code)

diffusers v0.41.0 models/autoencoders/autoencoder_kl_wan.py, lines : the encode loop. The first call sees only frame 0; each later call sees 4 frames plus the cached features of everything before.

Then patches. The denoiser cuts the latent into space-time patches: Wan, HunyuanVideo and Movie Gen use 1 × 2 × 2 (one latent frame, 2 × 2 latent pixels), so each token stands for 4 × 16 × 16 = 1,024 pixels across 4 frames. Sora's report: "spacetime patches which act as transformer tokens. This scheme works for images too since images are just videos with a single frame" (OpenAI, Feb 2024, archived) vendor. With time compression ct, space compression cs and patch size p, a clip of F frames at H × W becomes

tokens = (1 + (F − 1) / ct) × H / (cs p) × W / (cs p)

For Wan 2.1's default: 21 × 30 × 52 = 32,760, about a quarter of the per-frame count. The pipeline computes the first factor the same way (num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1, pipeline_wan.py:341).

  1. The clip. Wan 2.1's default: 81 frames of 480 × 832 pixels, about 5 s at 16 frames a second, 81 × 480 × 832 × 3 = 97,044,480 numbers. The disc moving across the frames is an illustration: neighbouring frames are almost the same picture.
  2. Group the frames in time. The causal VAE encodes frame 0 alone (purple), then every 4 frames into one latent frame (blue and orange in turn), each group seeing only cached features of earlier frames: 1 + 80 / 4 = 21 latent frames. An image VAE has no time axis and keeps all 81, however similar each is to the last.
  3. Shrink each latent frame in space. 8 times per side: 480 × 832 becomes 60 × 104, with 16 channels per position, a 21 × 60 × 104 × 16 latent of 2,096,640 numbers, 46 times fewer than the pixels. (From here the plates are drawn larger than to scale.)
  4. Cut into patches. The denoiser groups 2 × 2 latent positions into one token (orange): 30 × 52 = 1,560 tokens per latent frame.
  5. One sequence, three compressors. 21 × 1,560 = 32,760 tokens, so full attention forms 1,073 million pairs per head per layer. The same clip through an image VAE per frame is 81 × 1,560 = 126,360 tokens; through LTX-Video's 32 × 32 × 8 VAE it is 11 × 15 × 26 = 4,290 (LTX packs 4 × 4 pixel patches into the VAE input and keeps 128 channels to hold the detail, so its denoiser uses 1 × 1 patches). Columns to scale; every count from the configs.

What temporal compression costs, measured. Both 17-frame clips through Wan 2.1's VAE become a latent of 16 × 5 × 32 × 32 (5 = 1 + 16 / 4), 48 times fewer numbers, then are decoded and compared frame by frame with PSNR (peak signal-to-noise ratio in decibels; higher is closer, every 6 dB halves the typical error).

Frame 0, encoded alone, comes back at dB in both clips. With slow motion the other frames stay close (mean dB): four nearly identical frames share one latent frame cheaply. With fast motion every later frame drops to about dB on average, rippling with the group size of 4: one latent frame has to describe four quite different pictures with the same 16 channels. That is why fast motion is where video generators blur first. The PSNRs transfer to any hardware (same weights, float32); the timings in the closed block at the end do not.

The video VAEs of eight models, with published ratios recomputed (reference table)

"Ratio" is how many input numbers (3 colours × pixels × frames) each latent number replaces; "pixels per token" includes the denoiser's patch. Read from seven open configs and Movie Gen's paper.

Every combination of size, frames and model: the Space-time patch calculator. VAE losses, KL and quantised latents: Autoencoders and VAEs.

Fast motion is what the video VAE loses: PSNR drops after frame 0 and ripples with period 4

Original, reconstruction, and their difference (amplified 4 times) at frame 0
PSNR per frame (dB), both clips; the chosen clip highlighted

2. Attention across space and time

The problem. Each token must see the rest of its frame (to draw a coherent picture) and the same object in other frames (to move smoothly). Full 3-D attention lets every token attend to every other token in the clip, at a cost that grows with the square of the token count N: for Wan 2.1 1.3B's default clip, N = 32,760, so one layer forms N2 = 1.07 billion query-key pairs per head.

The older answer: factorise. Factorised attention splits one layer into spatial attention (within its own latent frame) followed by temporal attention (the same position in the other frames). Video Diffusion Models did this inside a U-Net: "we insert a temporal attention block that performs attention over the first axis" with the spatial axes treated as batch (Ho et al. 2022); Latte compared four ways of splitting the two inside a video DiT, and alternating spatial and temporal blocks "performs the best" (a plot, not a table: Ma et al. 2024, Fig 5). With f latent frames of s tokens, the pairs fall from (fs)2 to fs2 + sf2: about 21 times fewer for Wan's default clip.

The current answer: full attention. Every open model from 2024 on uses it (CogVideoX, HunyuanVideo, Mochi, LTX-Video, Wan, Movie Gen). CogVideoX's argument: separated attention "requires extensive implicit transmission of visual information" (Yang et al. 2024, Sec 2.2): an object moving diagonally is at a different position in the next frame, so a temporal layer that looks only at the same position cannot follow it directly. Full attention became affordable because the VAE took most of the tokens out (section 1) and FlashAttention-style kernels never store the N2 matrix; the price is compute, and section 4 shows attention becomes the largest term.

  1. The query. A small latent clip (6 latent frames of 6 × 10 tokens, an illustrative size) with a disc moving diagonally across it. The query token sits on the disc in frame 2.
  2. Full 3-D attention. The query reads every token in every frame (keys), the disc included wherever it has moved (the streams): one layer, one hop. At Wan 2.1 1.3B's default clip that is all 32,760 tokens.
  3. Factorised, layer 1: spatial. Attention only within its own latent frame: 1,560 keys at Wan's size.
  4. Factorised, layer 2: temporal. Only the same position in every other frame: 21 keys. The disc has moved away, so these keys mostly show background.
  5. Diagonal motion takes two hops. For the query to read the disc in frame 4, a spatial layer in frame 4 first carries the disc's content to the query's position there, then a temporal layer brings it to the query (the stream runs from the disc to the query): relayed, not direct.
  6. What each costs. Every token does this. At Wan's default clip full attention forms N2 = 1,073 million query-key pairs per head per layer, factorised attention 21 × 1,5602 + 1,560 × 212 = 52 million, 20.7 times fewer (columns to scale).

Positions in 3-D. Most of these models use 3-D RoPE: the head's channels are split into three groups, each rotated by one coordinate (frame, row, column). HunyuanVideo splits a 128-wide head 16 / 56 / 56 (rope_axes_dim), Wan 44 / 42 / 42 (h_dim = w_dim = 2 * (attention_head_dim // 6), transformer_wan.py:368). Movie Gen is the exception: "factorized learnable positional embedding" (Polyak et al. 2024, Sec 3.1.3). How the ids are built and why rotation gives relative positions: Latent diffusion and diffusion transformers (section 7) and Positional Encodings.

DiT, adaLN-Zero, MMDiT and double and single stream blocks: Latent diffusion and diffusion transformers; attention kernels: Writing kernels: ... FlashAttention.

3. Conditioning: text, a first frame, sound

A video denoiser takes three kinds of condition, and each enters at a different place in the sequence: text through attention, an image as latent frame 0, sound as a second stream aligned in time.

  1. The noisy video latent. What the denoiser works on: Wan 2.1 1.3B's default clip as 21 latent frames, 32,760 tokens, pure noise at the start of sampling.
  2. Text, through attention. Two designs, both from image models (the boxes: 512 umT5 tokens, one per 16). Cross-attention to the text encoder's output in every block (Wan with umT5, LTX-Video with T5; LTX reports cross-attention beat joint attention for them, Sec 2.3), or joint attention over text and video tokens together, MMDiT-style (CogVideoX, HunyuanVideo's dual-stream then single-stream blocks, Mochi's asymmetric streams with a visual stream "nearly 4 times" the text stream's parameters, Mochi card). The text encoders keep growing: T5 (CogVideoX, LTX, Mochi), a multimodal LLM (HunyuanVideo), Qwen2.5-VL (HunyuanVideo 1.5), Gemma 3 12B (LTX-2).
  3. A first frame. Image to video is the same model with the first frame given: the causal VAE encodes it alone (section 1), and its latent replaces or conditions the first latent frame (LTX-Video gives conditioning tokens a small timestep, Sec 2.4). This is the second reason the first frame is encoded on its own.
  4. Sound, as a second stream. Audio with video (Veo 3, LTX-2, Sora 2) adds an audio latent stream with its own 1-D positions and cross-attention between the streams; LTX-2 uses only the time component of RoPE in that cross-attention so sound aligns with frames (Sec 3.1.1) vendor. (One audio segment per latent frame in the figure is illustrative.)

The levers the open models pulled. All of them are a latent transformer with full attention and flow matching (CogVideoX: diffusion with v-prediction); they differ in where they spend tokens and parameters.

  • Compress harder (LTX-Video, 2024): a 32 × 32 × 8 VAE with 128 channels ("1:192", "a pixels-to-tokens ratio of 1:8192") leaves so few tokens that a 1.9B model runs "faster-than-real-time": "2 seconds to generate 121 frames at 768x512 pixels and 20 diffusion steps on an Nvidia H100 GPU" (Sec 1) vendor. The price is fine detail, so its decoder also performs the last denoising step.
  • Split denoising by noise level (Wan 2.2, 2025): two 14B experts, "a high-noise expert for the early stages ... and a low-noise expert for the later stages" (27B total, 14B active per step), plus a 5B model on a 4 × 16 × 16 VAE (card).
  • Sparse attention (HunyuanVideo 1.5, 2025): 8.3B, a 16 × 16 × 4 VAE with 32 channels and no extra patching, sparse "SSTA" attention 1.87 times faster than FlashAttention-3 end to end for 10 s at 720p (card) vendor.
  • Scale the context (Movie Gen, Meta, 2024, weights not released): a 30B flow-matching transformer with "a maximum context length of 73K video tokens, corresponding to a generated video of 16 seconds at 16 frames-per-second" (abstract), the most detailed public recipe.

The arc in one line: factorised U-Nets (2022) to diffusion transformers on space-time patches (2024) to flow-matching transformers that also make sound (2025 to 2026). Closed models disclose almost nothing: Sora's report says "Model and implementation details are not included in this report"; Veo 3's model card says "latent diffusion ... applied to the temporal audio latents, and the spatio-temporal video latents", trained on TPUs with JAX (model card) vendor.

Eight video models in one table (from configs, pipeline defaults and papers)

Parameters: counted from each config on the meta device (diffusers 0.41.0, no weights), except Movie Gen (stated). Default clip: diffusers v0.41.0 pipeline defaults or the model card; tokens from the formula in section 1 (Movie Gen's 8 × 8 × 8 VAE has no separate first frame). Release dates, licences and status: the root's Model map tab.

Per-model notes: data, speed and win-rate claims (vendor figures)
  • Movie Gen: O(100M) video-text pairs and O(1B) images; training on "up to 6,144 H100 GPUs"; stages of 256 px text-to-image, then 256 px and 768 px joint image and video. Its human evaluation reports a net win rate (wins minus losses) on overall quality of 8.23% against Sora, "within 1-2" standard deviations of ±5.07, and 3.87% against Kling 1.5, "on par" (Table 6) vendor.
  • CogVideoX (Zhipu, 2024): a causal 3-D VAE, v-prediction with zero terminal SNR, an "expert transformer" with separate adaptive LayerNorms for text and video tokens; about 35M clips and 2B images. On an H800 the 5B model takes 113 s for 6 s at 480 × 720 with 50 steps (Table 7) vendor.
  • HunyuanVideo (Tencent, 2024): 13B, dual-stream then single-stream blocks like FLUX, a multimodal LLM as text encoder; its VAE reaches 35.39 dB PSNR on the MCL-JCV video set against 33.22 for CogVideoX 1.5's (Table 1) vendor. HunyuanVideo 1.5 trained on about 800M video segments.
  • Wan 2.1 (Alibaba, 2025): 1.3B and 14B DiTs with cross-attention to umT5, the 1.3B "requiring only 8.19 GB VRAM"; VBench total 86.22% for 14B against 84.28% for Sora (Table 4) vendor.
  • LTX-2 (2026) generates video and synchronised audio in one model; its own paper gives 14B + 5B in the abstract, 13B + 3B in the conclusion and 19B in Table 1 (the checkpoints are named 19b) (arXiv 2601.03233).
  • Sora: it "is a diffusion transformer" trained to predict "clean" patches, on re-captioned videos at native aspect ratios, generating up to a minute vendor. Veo 3 through the Gemini API serves 8 s at 24 fps, 720p or 1080p.

4. What one clip costs

The arithmetic. One denoiser pass over N video tokens costs about

FLOPs per pass ≈ 2 P N + 4 L N2 D

where P is the parameter count (every weight used once per token: one multiply and one add), L the number of blocks and D the attention width (query-key scores plus the weighted sum of values, each N2D multiply-adds per layer). A clip costs that times the sampling steps times the passes per step (2 with classifier-free guidance). The first term grows with the clip's length, the second with its square. The image version, fitted to eleven image denoisers, is on Latent diffusion and diffusion transformers (section 9).

Predict, then drag: Wan 2.1 1.3B, same resolution, clip doubled from 81 to 161 frames (10 s). Tokens grow by about 2. By how much does the self-attention compute of one denoiser pass grow?

Checked against a real count. Wan 2.1 1.3B's config instantiated on the meta device (no weights) and run once at its default clip under PyTorch's FLOP counter: TFLOP, of which TFLOP () are the attention matrix products. The formula gives TFLOP (): it charges all 1.42B parameters to every video token, including the text cross-attention's key and value projections that act on the 512 text tokens only, and it leaves out cross-attention's scores. So attention is about two thirds of the compute even at 480p and 5 s; at HunyuanVideo's 720p and 129 frames the formula puts it at .

Predict: which costs more per denoiser pass with Wan 2.1 1.3B, 720p for 5 s (81 frames) or 480p for 10 s (161 frames)?

Where else the time goes, and the levers. The text encoder runs once and the VAE decoder once per clip, but a video decoder is heavy: in the measured run of section 1, decoding 17 small frames took longer than encoding them. The published speed-ups attack each factor: fewer steps by distillation (CausVid distils 50 steps to 4; HunyuanVideo 1.5 ships 8 or 12 step variants), fewer tokens by a stronger VAE (LTX-Video, Wan 2.2's 5B model), cheaper attention by sparsity (HunyuanVideo 1.5's SSTA, 1.87 times end to end, vendor), and lower resolution plus a separate upsampler (Movie Gen to 1080p, HunyuanVideo 1.5's few-step super-resolution).

Cost of eight models at their defaults, and whether published speeds add up (derived)

Derived from configs and defaults with the formula above (not run here: the weights are not needed for counting). "Per clip" multiplies by the default steps and passes; HunyuanVideo embeds guidance in the model, so one pass per step.

Do published speeds agree? (derived)

Any model, resolution, duration and step count: the Space-time patch calculator. Serving costs and batching: Topic: inference-and-serving.

Duration is the expensive axis: attention grows with its square and overtakes everything else

One pass, to scale against 20 s: linear layers 2 P N and self-attention 4 L N2 D

5. Keeping a video consistent, and making it longer

The problem. Inside one clip, full attention keeps things consistent: every frame sees every other. The failures are temporal: identity drift (a face or a shirt slowly changing), objects that appear or vanish, physics that does not hold. Sora's own report: it "does not accurately model the physics of many basic interactions, like glass shattering", and shows "incoherencies that develop in long duration samples or spontaneous appearances of objects" (OpenAI, Feb 2024, archived) vendor. Independent physics tests agree: on Physics-IQ "the best model scoring 29.5%" where real videos score 100 (Motamed et al. 2025) independent; on VideoPhy the best model, CogVideoX-5B, follows both the caption and physical laws in 39.6% of cases (Bansal et al. 2024) independent.

Why length is hard. Models train on clips of 5 to 16 s because tokens, and attention with their square, grow with duration (section 4). A longer video needs a bigger window (Movie Gen trained to 16 s; LTX-2 reaches 20 s with audio) or generation in pieces, each conditioned on the frames before. That works like a language model writing text, with the same weakness: the model trained on clean real frames now conditions on its own imperfect ones, errors accumulate, and quality drifts (exposure bias; FramePack calls the result "drifting").

  • Per-frame noise. Diffusion Forcing gives every frame its own noise level during training, so at sampling time later frames can be noisier than earlier ones; it rolls out "with lengths past the training horizon, where baselines diverge" (Chen et al. 2024). MAGI-1 generates "in chunks of 24 frames, where each chunk attends to all previously denoised chunks", denoising several chunks at once at rising noise levels (Sand AI 2025).
  • Causal students. CausVid distils a bidirectional model into a few-step causal one that streams with a KV cache: "an initial latency of only 1.3 seconds, after which frames are generated continuously ... at approximately 9.4 FPS" (Yin et al. 2024) vendor. Self Forcing trains on its own rollouts to close the train-test gap: "real-time video generation at 17 FPS with sub-second latency on a single H100 GPU"; in its Table 1 the many-step Wan2.1 1.3B it starts from runs at 0.78 FPS with 103 s latency (Huang et al. 2025) vendor.
  • Compressed context. FramePack encodes older frames with fewer tokens so the context stays bounded however long the video, and samples in an order that limits drift (Zhang and Agrawala 2025).

How to check. Generate past the training length and plot a per-frame quality score and an identity score (similarity of a face or object embedding to frame 1) against time: drift shows as a slope. VBench-Long and the "dynamic degree" dimension exist because a frozen video scores well on many per-frame metrics (section 9).

Three noise schedules over a long video: the rising-noise one streams and can still correct course

Each row is one denoising step, each column one chunk of frames; darker means noisier. Illustration of the published schemes (no run here).

6. Sound as data: waveforms and spectrograms

The problem. Audio is a waveform: air pressure measured tens of thousands of times a second (the sample rate: 16 kHz for speech recognition, 24 kHz for most speech generation, 44.1 or 48 kHz for music). The Shaggy sentence is 3.67 s, so 58,720 samples at 16 kHz or 88,080 at 24 kHz; ten seconds of speech is 240,000 numbers, against a few dozen text tokens for the same words. Nothing can attend over that directly.

The spectrogram. Cut the waveform into short overlapping windows, take each window's Fourier transform, keep the magnitude, pool the frequencies into bands spaced like human hearing (the mel scale: fine at low frequencies, coarse at high), and take the log. Whisper: "an 80-channel log-magnitude Mel spectrogram representation is computed on 25-millisecond windows with a stride of 10 milliseconds" (Radford et al. 2022, Sec 2.2); large-v3 uses 128 bins. The result is an image, 80 numbers per 10 ms, about 30 times shorter than the 16 kHz waveform.

The catch: phase. A magnitude spectrogram throws away each frequency's phase, so it cannot be played back directly. A vocoder turns a spectrogram back into a waveform; HiFi-GAN "uses a mel-spectrogram as input and upsamples it through transposed convolutions until the length of the output sequence matches the temporal resolution of raw waveforms", reaching MOS 4.36 against 4.45 for the real recordings, "167.9 times faster than real-time on a single V100 GPU" (Kong et al. 2020) vendor. Because phase is free, a vocoder's output can sound right while matching the original waveform poorly sample by sample, which is why waveform error (SNR) is a poor quality measure for generated audio (section 7).

From spectrograms to today's two representations. Text-to-speech from 2017 to 2022 predicted a mel spectrogram and called a vocoder (Tacotron 2: 80 mel channels, 12.5 ms hop, WaveNet vocoder). Today two representations dominate: discrete codec tokens (section 7), which turn audio into a language-model problem, and continuous latents from an audio VAE (Stable Audio Open: 64 numbers per frame at 21.5 frames a second for 44.1 kHz stereo, Evans et al. 2024), which turn it into a diffusion problem, exactly like an image VAE.

The same 3.67 s as 88,080 samples and as an image of frequency against time

Log-mel spectrogram of the speech clip

Top: the waveform at 24 kHz drawn as its minimum and maximum in every 10 ms. Below: 64 mel bands from 0 to 12 kHz (bottom to top) at 20 ms steps, brightness = log power over 70 dB, computed on this page's data (codec/make_assets.py). The source is a 16 kHz recording, so it holds nothing above 8 kHz (the top eighth of the bands holds only faint energy leaked by the resampler, 37 dB below the total).

7. Neural audio codecs and residual vector quantisation

What a neural codec is. An autoencoder for sound with a discrete bottleneck. A convolutional encoder strides through the waveform (EnCodec: 320 samples per step, so 24,000 / 320 = 75 frames a second, each a 128-number vector); a quantiser replaces each vector with codebook indices; a decoder turns the indices back into a waveform. It is trained with reconstruction losses on waveform and mel spectrograms plus adversarial losses from discriminators that look at the spectrogram at several scales, which is what makes it sound natural rather than merely close (SoundStream 2021, EnCodec 2022, DAC 2023, Mimi 2024).

Why residual quantisation. One codebook of 1,024 gives each frame log2(1,024) = 10 bits; spending 80 bits a frame (6 kbps) with one codebook would need 280 entries. Residual vector quantisation (RVQ) chains several small codebooks: the first quantises the vector, the second quantises what the first missed, and so on, so 8 codebooks of 1,024 give 80 bits with 8,192 stored vectors. Bits per codebook per second in EnCodec's code: bw_per_q = math.log2(self.codebook_size) * self.frame_rate = 10 × 75 = 750 bit/s, so 1.5 kbps is 2 codebooks and 24 kbps is 32. The image version (RQ-VAE) and VQ training tricks are on Autoencoders and VAEs.

The RVQ loop as transformers runs it for EnCodec (real code)

transformers v5.20.1 models/encodec/modeling_encodec.py, lines . Each stage picks the nearest codebook vector (Euclidean distance, line ) and subtracts it; the bitrate formula is line .

Bitrate scalability for free. During training the number of codebooks is drawn at random per example (quantiser dropout, introduced with SoundStream), so the decoder learns to work from any prefix of the chain. That is why one model serves 1.5 to 24 kbps, and why a token generator can predict the first codebooks first: they carry the most.

  1. One frame, one vector. EnCodec's encoder strides 320 samples (13.3 ms at 24 kHz) into one 128-number vector, 75 a second; the Shaggy sentence is 276 frames.
  2. Codebook 1: the nearest of 1,024 entries. Each frame's vector is replaced by the index of its nearest codebook vector, 10 bits (the sentence's first frame takes entry 475). That alone leaves only 3.93% of the vectors' energy unexplained, over all 276 frames: 0.75 kbps, 75 tokens a second.
  3. Codebook 2 quantises what is left. The residual (vector minus its entry) goes to a second codebook of 1,024: 3.01% left at 1.5 kbps. The columns are now drawn 25 times taller.
  4. Codebooks 3 to 8. Each stage quantises the previous stage's residual: 1.07% left at 8 codebooks, 6 kbps and 600 tokens a second, the setting VALL-E used.
  5. Codebooks 9 to 32. Diminishing returns are built in: a later stage only fixes what earlier stages missed, and 24 more codebooks take it to 0.062% at 24 kbps (2,400 tokens a second).
  6. What you hear. Spectral error of the decoded sentence (defined below): 0.42 with one codebook, 0.32 with two, 0.22 with eight, 0.15 with 32; Opus, the standard non-neural codec, scores 0.43 at 6 kbps and 0.21 at 12 kbps.

mel_l1 (spectral error) is the mean absolute difference of log10 mel power (80 bands, floored 60 dB below the clip's peak): 0.1 is about 1 dB of average spectral error. resid is the share of the encoder vector's energy that the first k codebooks leave unexplained. Measured on Apple M1 Pro CPU (PyTorch 2.14.1, transformers 5.20.1, 4 threads).

  • Neural beats classical at equal bits, on this metric. At 6 kbps EnCodec's spectral error is against Opus's ; Opus needs 12 kbps to reach . EnCodec's own listening test agrees: on clean speech MUSHRA 83.1 at 6 kbps against 76.5 for Opus at 12 kbps and 30.1 for Opus at 6 kbps (Table 1) vendor.
  • Do not judge by waveform error. SNR at 24 kbps is only dB for EnCodec, below Opus at 12 kbps ( dB), although EnCodec's spectrogram is closer: an adversarially trained decoder reproduces how it sounds, not the exact phase.
  • Music is harder, and the codec matters. On the synthesised phrase EnCodec at 24 kbps stays at while DAC's 9 codebooks (7.75 kbps, 44.1 kHz) reach . DAC looks codes up in an 8-dimensional projection with L2-normalised (cosine) matching (Kumar et al. 2023); measured here, its full 1,024-dimensional latent is not approached as stages are added (unexplained share after one stage, after nine): each stage fixes only the part of the residual its projection sees, which is the part the decoder uses.
  • Fast enough for anything. Decoding the 3.67 s sentence took s for EnCodec and s for DAC on the laptop CPU.
The run that produced these numbers (real code and output)

The heart of codec/run_codecs.py and lines of its output.

Semantic tokens. A codec trained only to reconstruct sound has no reason to put what is said into its first codebook rather than the voice's timbre or the room. Mimi (Kyutai's codec for Moshi) runs at only 12.5 frames a second with codebooks of 2,048 and distils a speech model into its first codebook: "we distill semantic information from a self-supervised model (WavLM ...) into the first level of the RVQ", using "a plain VQ and ... an RVQ with 7 levels in parallel" (Défossez et al. 2024, Sec 3.3). At 8 codebooks that is 1.1 kbps and 100 tokens a second, rated MUSHRA 81.0 against 74.3 for SpeechTokenizer at 4 kbps (Table 4) vendor. Measured here, Mimi's first codebook alone gives a smeared spectrogram (error ; listen in the RVQ codec explorer): it carries content, not timbre; 8 codebooks reach at 1.1 kbps, close to EnCodec at 1.5 kbps () with two thirds of the tokens per second (100 against 150).

Predict: a speech language model must generate 10 s of audio. How many tokens is that with EnCodec at 6 kbps, and with Mimi at 8 codebooks?

Every codec, bitrate and clip, with players and the token rates of nine codec settings: the RVQ codec explorer.

Each extra codebook fixes less: the same sentence through 1 to 32 EnCodec codebooks, against Opus (measured)

EnCodec 24 kHz, decoded from the first k codebooks of one encoding. Left: the log-mel spectrogram of the reconstruction above the original; right: spectral error against bitrate. The counters add how much of the encoder's vector the first k stages leave unexplained. Toggle to Opus, the standard non-neural codec, at about the same bitrate; the controls set k.

Reconstruction spectrogram
Original:
Original spectrogram

8. Generating audio: token language models and flow

Route 1: a language model over codec tokens. Once audio is tokens, generating it is next-token prediction, and everything known about language models applies (prompts, sampling temperature, KV caches, streaming). The difficulty is that each frame has several codebooks, so the question is in what order to predict them.

  • AudioLM (Google, 2022) used a hierarchy: first semantic tokens (k-means clusters of a speech model's features at 25 a second) for long-range structure, then the first 4 SoundStream codebooks, then the remaining 8, each by its own 0.3B decoder; listeners told its continuations from real speech 51.2% of the time, "not statistically significantly different" from chance (Borsos et al. 2022) vendor.
  • VALL-E (Microsoft, 2023) made text-to-speech a language-model task: phonemes plus a "3-second enrolled recording" of a voice in, EnCodec tokens out (8 codebooks at 6 kbps). The first codebook is predicted autoregressively, codebooks 2 to 8 by a second, non-autoregressive model, all trained on 60K hours of audiobooks (Wang et al. 2023).
  • MusicGen (Meta, 2023) predicts all 4 codebooks with one transformer using a delay pattern (Fig. 5, steps 2 to 4): "This translates 30 seconds of audio into 1500 autoregressive steps" (50 frames a second; Copet et al. 2023); trained on 20K hours of licensed music; weights CC-BY-NC.
  1. The token grid. 4 codebooks (rows, the coarse first codebook at the front) by frames (columns), as MusicGen has it at 50 frames a second; each slot is one token to generate. A column's height will be the step at which its token is generated.
  2. Flatten. One token per step, frame by frame: exact, since each token sees every earlier one, the coarser codebooks of its own frame included (the stream), but 4 steps per frame: 24 steps for 6 frames, 200 a second.
  3. Parallel. All 4 codebooks of a frame in one step: 50 steps a second, but the 4 tokens of a frame are predicted independently of each other (no stream between the levels).
  4. Delay. Codebook k is shifted k − 1 steps: still one step per frame (plus 3 at the end), and each fine codebook is generated after the coarser codebooks of the same frame, from earlier steps. MusicGen: 30 s of audio in 1,500 steps.

Moshi (Kyutai, 2024) is full duplex: it "always listens and always generates sound", modelling its own Mimi tokens and the user's as parallel streams plus a text stream it writes as an "inner monologue", 17 tokens per 80 ms step (1 text + 8 + 8). A 7B temporal transformer runs once per step and a small depth transformer generates the codebooks within the step; "a theoretical latency of 160ms, 200ms in practice" (Défossez et al. 2024) vendor. Mimi's 12.5 frames a second are what make one big forward pass per 80 ms affordable.

Moshi listens and speaks at once: 17 tokens per 80 ms step, one big pass per step

Rows are token streams, columns are 80 ms steps (Mimi's 12.5 frames a second). The temporal transformer reads everything up to the previous step once per step; the depth transformer then emits this step's own tokens one after another, text first. In the current step (outlined) the user's codes have just been heard (solid) and Moshi's are still to be generated (faint). Structure from the Moshi paper; token counts from the Mimi config. The same frame set against a three-model cascade, the native-or-pipeline question: Native multimodal and any-to-any models, section 9.

Route 2: flow or diffusion over continuous audio. The image recipe, applied to a spectrogram or an audio latent. F5-TTS trains a DiT with flow matching to fill in masked mel frames; the text is "simply padded with filler tokens to the same length as input speech", with no duration model or aligner; 336M parameters, about 95K hours of speech, "an inference RTF of 0.15" (real-time factor: 10 s of speech in 1.5 s, on an RTX 3090 at 16 steps) (Chen et al. 2024) vendor. Stable Audio Open generates "variable-length (up to 47s) stereo audio at 44.1kHz" with a 156M VAE, a 109M T5 text encoder and a 1,057M DiT, trained on Creative Commons recordings; it cannot produce intelligible speech or lyrics (Evans et al. 2024).

F5-TTS needs no aligner: text padded to the length of the audio, the missing frames filled by flow

Training: a random span of the mel frames is masked and the model learns the flow that fills it, seeing the rest of the audio and the whole padded text. Inference: the prompt recording is the unmasked part, its transcript plus the new text is padded with filler tokens, and the total length must be chosen before sampling (the "fixed or estimated length" weakness in the table below). Frame counts illustrative.

Codec tokens + language modelContinuous latent or mel + flow / diffusion
ExamplesAudioLM, VALL-E, MusicGen, Bark, Moshi, CSM, DiaF5-TTS, Stable Audio Open, Movie Gen Audio, LTX-2's audio stream, Veo 3 ("temporal audio latents")
StrengthStreaming, prompting and in-context voice cloning, one model with text (any-to-any)Parallel generation of the whole clip, fewer steps, no quantisation loss, easy joint generation with video latents
WeaknessHundreds of tokens per second; errors accumulate in long takes; quality capped by the codecFixed or estimated length, harder to stream, no KV-cache reuse

Small and fast. Not every speech model is large: Kokoro-82M (StyleTTS 2 with an ISTFTNet decoder, Apache 2.0) and Chatterbox Turbo (350M, MIT; the narration engine of this knowledge base's explainer videos) run comfortably on a laptop.

One network for text, images and speech: Native multimodal and any-to-any models; flow matching itself: Flow matching.

9. How video and audio are evaluated

Human judgement is still the reference for both media; every automatic number measures one slice of quality and has a known blind spot. The Fréchet scores (FVD, FAD), their sample-count and preprocessing traps and the evidence on how well they track people are taught once, on Evaluating generative models (its section 9); this table keeps what is specific to each medium.

MeasureWhat it doesBlind spot
FVDThe Fréchet distance on features of I3D, an action-recognition network, so each clip is scored as a whole (Unterthiner et al. 2018)Mostly scores single frames: a motionless video can score well (content bias, Ge et al. 2024) independent
VBench16 dimensions (subject consistency, motion smoothness, temporal flickering, dynamic degree, spatial relationship and others), each scored by its own model (Huang et al. 2023); its total is what Wan's 86.22% refers toEach dimension inherits its scoring model's errors; a total hides which dimension moved
Human A/B, arenasMovie Gen, finding that FVD did not track human scores, evaluated with human A/B tests on its public 1003-prompt Movie Gen Video Bench; blind pairwise arenas (the Artificial Analysis Video Arena, Elo from human votes) are the closest thing to an independent rankingArenas move weekly, so this page does not copy them; vendor A/B tests choose their own prompts
MOS, MUSHRAListening tests: MOS (mean opinion score, 1 to 5) for speech naturalness; MUSHRA (0 to 100, with a hidden reference and low-pass anchors) for codecs, as in the EnCodec and Mimi tables of section 7Slow and costly to run
WER, speaker similarityFor speech generation: word error rate of an ASR model on the output (VALL-E used HuBERT-Large, F5-TTS Whisper-large-v3) and speaker similarity between output and prompt from a speaker-verification network (WavLM-based in both)Say nothing about prosody or naturalness
FAD, CLAP scoreFAD (Fréchet Audio Distance) is the Fréchet recipe on VGGish audio embeddings (Kilgour et al. 2018); CLAP score measures text-audio agreement with a contrastive audio-text model, the audio cousin of CLIPScoreModerate agreement with listeners; both depend on the feature network

The two numbers measured on this page (spectral error and SNR) are sanity checks of a codec on one clip, not quality scores.

FID, KID, CLIPScore, preference models, FVD and FAD with their pitfalls: Evaluating generative models; video benchmarks for VLMs: Long-context and multimodal benchmarks.

Depth: mistakes, what was measured, interview rehearsal

Common mistakes, with the real errors (9 items)

A frame count that is not 4k + 1 (or 8k + 1)

A causal video VAE needs the first frame plus whole groups. diffusers does not fail, it changes your request: . Ask for 80 frames from Wan and you get 81; from LTX-Video (8 per group) the rule is 8k + 1. Check the frame count of the output, and pick 4k + 1 yourself.

A size the latent grid cannot divide

Height and width must be multiples of the VAE factor times the patch: (Wan, 8 × 2), and 32 for LTX-Video. 720p is 1280 × 720 for Wan 2.1 (720 / 16 = 45) but 1280 × 704 for Wan 2.2's 5B model, whose VAE plus patch divides by 32.

Feeding audio at the wrong sample rate

Measured: the 16 kHz LibriSpeech samples passed straight to EnCodec 24 kHz encode and decode without error, and come out as s instead of s, 1.5 times faster and higher: . The feature extractor would have stopped it: . Resample first (this page uses scipy.signal.resample_poly), and assert the rate wherever audio enters a model.

Asking a codec for a bitrate or depth it does not have

Real errors from this page's run: and . Bitrate is codebooks × frames per second × bits per code, so only a few values exist per model.

Judging a codec or vocoder by waveform error

Measured: EnCodec at 24 kbps has a lower SNR than Opus at 12 kbps on the same sentence but a closer spectrogram, and its own listening test ranks it far above (section 7). Adversarially trained decoders do not reproduce phase. Use mel distance for quick checks, MUSHRA or MOS for decisions.

Counting cost in frames or parameters instead of tokens

Wan 2.2's 5B model makes 720p clips with fewer tokens (27,280 for 121 frames) than Wan 2.1's 1.3B makes at 480p and 81 frames (32,760), because its VAE plus patch is 32 × 32 in space. And attention is about two thirds of the compute at these sizes, so doubling the duration roughly quadruples it. Count tokens with the formula in section 1, then FLOPs (section 4).

Trusting a headline compression ratio

Mochi's card says its VAE "causally compresses videos to a 128x smaller size, with an 8x8 spatial and a 6x temporal compression to a 12-channel latent space"; those factors give 3 × 8 × 8 × 6 / 12 = 96, not 128 (the card does not show its arithmetic). LTX-Video's "1:192" and Wan 2.2's "64" do reproduce (section 1, closed table). Recompute from the factors.

Comparing FVD across settings, or trusting it alone

FVD depends on frame count, resolution, the feature network and the number of samples, and it rewards good single frames over motion: a frozen video can score well (section 9). Compare only at identical settings, add a motion measure (VBench's dynamic degree), and run a human or arena comparison for decisions.

Building on a closed model as if it will stay

Sora's app closed in April 2026 and its API was scheduled to end in September 2026 (secondary reports; the root's Model map tracks status). Keep an open fallback and your own evaluation set, so switching is a measured decision.

What was measured here, and what transfers (provenance)

Measured on Apple M1 Pro, all on the CPU (float32, 4 threads, no GPU lock needed): the three codecs at every depth on two clips, the Opus baselines (libopus through PyAV), Wan 2.1's VAE on two 17-frame clips, the FLOP count of Wan 2.1 1.3B on meta tensors, and parameter counts of seven configs. Wan's VAE took s to encode and s to decode 17 frames at 256 × 256, with peak memory GB, over this topic's 6 GB guideline, so a rerun should use smaller clips or the VAE's tiling.

Transfers exactly: codes, reconstructions and their spectral errors and SNRs (same weights, float32; a GPU may differ in the last digits), PSNR per frame, parameter and FLOP counts, token counts. Does not transfer: the timings (a laptop CPU, one clip at a time). The listening players use 32 kbps MP3 copies (the page has no network and must stay small), which add their own coding on top; every number was computed on the decoders' raw output. Not run here: any video denoiser (the smallest, Wan 2.1 1.3B, generates one 480p clip in minutes on a large GPU and would teach less than the arithmetic), and any speech or music generator.

Interview rehearsal (10 questions with answers)

Why compress time in the VAE rather than just using bigger patches in the transformer?

Both cut tokens, but the VAE is trained to reconstruct, so it learns what to keep (a moving edge) and what to drop (a static background repeated over 4 frames); a bigger patch is a fixed linear projection that loses detail uniformly. Latte found tubelet-style patches "notably" worse than per-frame patches; LTX-Video moved patching into the VAE for the same reason.

Full 3-D attention or factorised spatial and temporal attention?

Factorised is about 20 times cheaper at Wan's default size but a token can only see its own frame or its own position over time, so diagonal motion must be relayed through layers. Full attention sees everything and is what every 2024 to 2026 open model uses; it is affordable because the VAE leaves tens of thousands of tokens, not hundreds of thousands, and FlashAttention avoids storing N2. Above that, sparse or sliding-tile attention (HunyuanVideo 1.5) is the middle ground.

Why is the first frame encoded on its own?

So that an image is a valid 1-frame video (joint image and video training, and image-to-video conditioning on a clean first latent), and so the encoder can be causal: each later group of 4 frames is encoded with a cache of features from earlier frames only. Hence 4k + 1 frames.

How many tokens is 10 s of 720p video for Wan 2.1 14B, and what does it do to attention?

161 frames at 16 fps become 1 + 160 / 4 = 41 latent frames of 90 × 160, patched 2 × 2: 41 × 45 × 80 = 147,600 tokens, against 75,600 for 5 s. Tokens about double, attention FLOPs about quadruple (3.8 times).

Why residual VQ rather than one big codebook?

Bits add up across stages while storage adds linearly: 8 codebooks of 1,024 give 80 bits per frame with 8,192 vectors, where one codebook would need 280. Quantiser dropout makes every prefix decodable, so one model gives many bitrates and a generator can predict coarse codebooks first.

Codec language model or flow matching for text-to-speech?

Tokens and a language model when you need streaming, voice cloning by prompt, or one model shared with text (dialogue agents, any-to-any). Flow or diffusion over mel or latents when you can generate the whole utterance at once and want speed and robustness (F5-TTS: RTF 0.15, no aligner). The deciding factors are usually latency, length control and how the model is served.

Why can a codec with worse SNR sound better?

SNR compares waveforms sample by sample, so any phase shift counts as error; hearing is mostly insensitive to phase. Neural codecs are trained with spectral and adversarial losses that reward sounding right, so their waveforms differ while their spectrograms match.

Design: a text-to-video API must return 5 s of 720p in under a minute on one datacenter GPU. Sketch the model and the arithmetic.

Work backwards from tokens. At Wan 2.1 14B's design (8 × 8 × 4 VAE, 2 × 2 patches) 5 s at 720p is 75,600 tokens and about 6,800 TFLOP per pass, so 50 steps with guidance is about 680,000 TFLOP: far beyond a minute on any single GPU. Levers in order of size: a stronger VAE (32 × 32 in space, as Wan 2.2 5B or LTX: 4 to 10 times fewer tokens, quadratic gain in attention); a smaller denoiser (2 to 5B); step and guidance distillation (50 × 2 passes down to 4 to 8 single passes); sparse attention; generate at 480p and upsample. Verify with the calculator, then measure: a published check is LTX-Video's 2 s for 121 frames at 768 × 512 on an H100 with a 1.9B model and 1:8192 compression.

Design: a real-time voice agent with sub-300 ms response. What audio representation and model?

A causal codec with a low frame rate and semantic first codebook (Mimi: 12.5 Hz, 80 ms frames, 8 codebooks), a model that runs once per frame and generates the codebooks within the frame with a small depth model, full duplex so it can listen while speaking, and text tokens predicted alongside audio for content. Moshi's budget: 80 ms frame plus 80 ms acoustic delay = 160 ms theoretical, 200 ms measured on an L4. A cascade (ASR, LLM, TTS) is simpler to build but adds each stage's latency and loses tone.

How would you get a 1-minute video from a model trained on 5 s clips?

Extend in chunks conditioned on previous frames, and fight drift: train with per-frame noise levels (Diffusion Forcing) or on your own rollouts (Self Forcing), compress old context (FramePack), keep identity anchors (a reference image or keyframes generated first and filled in between). Check with a per-frame identity score over time.