Lecture guides›
✎

Lecture guide: Alignment: multimodality#

Lecturer: course staff · Course: Stanford CS336 Language Modeling from Scratch, Spring 2026, lecture 17 · Length: 1:18:00 Video: watch on YouTube Chapters that cite this lecture: 12. Alignment and Multimodality

In one sentence: Percy Liang explains how a transformer built for text comes to see: CLIP and SigLIP turn images into vectors with meaning, LLaVA and the Qwen vision-language models stitch such encoders onto a language model, and Chameleon shows what happens when images become tokens like any other.

Before you watch#

The lecture assumes the transformer and the tokenizer of the early lectures and RoPE from the architecture lecture; little else from the course is needed, though it refers back to the systems lectures, critical batch size and data mixtures; it sits a little apart from the reinforcement learning around it. It is about getting images into a model, with generation only at the end. The video has no chapter marks. The chapter Alignment and Multimodality follows it section by section.

The lecture, part by part#

0:00–4:00 Tokens beyond text#

Liang had one lecture left for this stretch of the course and chose multimodality, because every major model now has it. It is an overview of a subject that could fill a course. Language models are already general, mapping any text to any text, in any language, code, poetry, even DNA. The world holds text, images, audio and video, and the north star is an omni model that takes any combination of these and produces any combination: a question about an image and a video, a generated image, audio turned into an image. The course stops short of that and covers the pieces that let a model ingest images. The starting point is awkward but real: transformers work, and despite every effort to replace them they remain the best thing at scale in all modalities. Transformers speak tokens, discrete ones or, in an extended sense, continuous ones, the embeddings of tokens; a token stands for a semantic unit of information. Subwords qualify; a pixel does not. So images and audio must be turned into tokens of one kind or the other. Text needed this too, in the tokenizer of the first lecture, and byte-pair encoding was tolerable. For other modalities the equivalent has to be worked out. In this book: Alignment and Multimodality › Part two: the core idea of multimodality.

4:00–8:00 CLIP (2021): contrastive language-image pretraining#

Two questions follow: how non-text data goes into a transformer, and how it comes out; the lecture is about the first. Back to 2021. CLIP is the foundation of most modern vision-language models. Language had entered the foundation-model era, while vision still rested on heavily annotated data sets of ImageNet's kind, on models such as ResNet, and data augmentation. Researchers at OpenAI asked whether the mass of images with captions could be used as scraped text is used: noisy, but enough scale makes something useful of it. CLIP, contrastive language-image pretraining, takes image-text pairs, 32,000 to fix ideas. Each image goes through an image encoder into a vector, each text through a text encoder. The objective: the dot product of a matched image and text is much larger than that of the image with any other text, and, conversely, larger than that of the text with any other image. That is 2n softmax classification problems over an n by n matrix. The code matches: two matrices of embeddings, rows normalized, a dot product with a temperature, and cross-entropy; a multi-class classification whose examples are arranged in a grid. In this book: Alignment and Multimodality › 1. CLIP: learning what images mean from their captions.

8:00–16:00 Building CLIP: data, crops and encoders#

The paper says little about the data: queries were searched online and pairs mined, 400 million of them, never released. OpenCLIP replicated the idea and released LAION-5B, five billion images with descriptions, filtered with CLIP itself before training the new model, a bootstrapping that at least leaves a model whose data and code can be inspected. Images arrive at arbitrary sizes and networks prefer fixed ones, so CLIP resizes until the shorter side is 336 pixels, or 224, and crops a square from the center: a heuristic that suited ImageNet-style classification, where the object sits in the middle and only background is lost. Asked why pairs rather than images alone: learning from augmented copies of an image, as SimCLR does, captures low-level detail but cannot carry one kind of dog over to another; text supplies higher-level semantics. For the encoder CLIP tried ResNets and the newly published vision transformer, and the transformer won, so CLIP today means the ViT version. A vision transformer cuts the image into patches, 16 by 16 in the original, 14 by 14 in CLIP; each patch is a token; positional embeddings are added; a standard transformer follows. The encoder outputs a sequence of vectors, and CLIP does a little better than averaging them: attention pooling uses the global average as a query over the positions' keys and values. The best model was ViT-L/14, a large transformer of about 24 layers by his estimate over 14 by 14 RGB patches, trained first at a lower resolution for speed and at 336 only toward the end. Asked about two-dimensional positional embeddings: CLIP tried them against one-dimensional ones and found little difference for classification; fancier ones come later. In this book: Alignment and Multimodality › 1. CLIP: learning what images mean from their captions.

16:00–22:00 What CLIP learned, and zero-shot ImageNet#

The text encoder is a GPT-2-style transformer; with a beginning token in front and an end token appended, the top-layer activation at the end token represents the sequence. Training takes a batch, encodes everything and applies the 2n cross-entropy losses. The headline result that excited people in 2021: zero-shot CLIP beat a ResNet trained on the 1.2 million labeled images of ImageNet, labels that cost many hours of Mechanical Turk work, by using web data instead. Zero-shot means taking the dot product of the image with the text of each label and keeping the highest. Asked whether other dogs in the batch confuse it: the process is noisy, but on average the other images are not always dogs, and the captions themselves are extremely noisy, since a caption does not necessarily name what is obvious in the picture; heavy filtering is needed, and it is interesting that it works. CLIP's authors also tried predicting the caption from the image, as a bag of words or with a language model, and found that a stronger model did worse, or less efficiently: for a rough representation of an image, measured by ImageNet accuracy, the exact order of the caption's tokens does not matter. What was learned: CLIP encodes an image's semantics, because text talks about semantics; its design choices come from image classification, so it is not fine-grained; and it is a robust starting point. In this book: Alignment and Multimodality › 1. CLIP: learning what images mean from their captions · Alignment and Multimodality › What the practitioners say.

22:00–28:00 SigLIP: a sigmoid loss and separable training#

One technical flaw of CLIP: it needs very large batches, around 30,000; a batch of one or even ten does not work; and the softmax spans the whole batch, so training does not decompose the way language-model training does, where sequences run in parallel and aggregate at the end. SigLIP, from Google, fixes that flaw and should be read as an improved CLIP: sigmoid loss for language-image pretraining. Where CLIP is multi-class classification of a pair against all alternatives, SigLIP asks of each image-text pair only whether it is aligned: binary classification, the diagonal of the matrix positive and everything else negative. The algorithm normalizes the embeddings, takes the dot product as before, forms labels of plus one on the diagonal and minus one elsewhere, and applies a log-sigmoid. Asked about sampling strategies: the first paper used the same plain matrix, though contrastive methods sometimes need balanced or hard negatives. The data came from WebLI, billions of pairs from the web, with OCR on images containing text as a further source of pairs, some filtering, and several languages. The point of the paper is efficiency: days of training on hundreds of chips for CLIP against days on a few tens for SigLIP, although CLIP's code was probably never tuned for throughput. The newer chips are not faster one by one; more of them fit in a pod, and they are linked better. The parallelization resembles data parallelism: each device holds a subset of the pairs and computes the losses on them, then the text embeddings are passed around, one device receiving the next block and scoring those negatives, until every off-diagonal block is covered. The gain is that the loss no longer depends on the batch size, where in CLIP a different batch is a different loss; batches below 16,000 work, with more variance but the same expected loss, and larger batches do not help: the critical batch size was about 32,000. In this book: Alignment and Multimodality › 2. SigLIP: the same idea with a cheaper loss.

28:00–34:00 LLaVA (2023): stitching a vision encoder to a language model#

CLIP and SigLIP map an image of fixed size, 336 by 336 say, to a vector with some semantics. Vision-language models inject such vectors into a language model. Two families follow, LLaVA and Qwen, close in outline and different in detail; the work is closer to mid-training or post-training than to training from scratch, since an existing encoder and an existing language model are stitched together. LLaVA appeared in 2023, when the closed GPT-4 was showing visual reasoning; LLaVA managed some too, not as well, but it was an open model and people could look under the hood. Its pieces: CLIP as the vision encoder; Vicuna as the text decoder, the first Llama model fine-tuned on conversations that people had shared from ChatGPT; and data synthesized from MS COCO, where crowd workers had captioned images and drawn bounding boxes: GPT-4 received the captions, or the objects detected, with a request for conversations, detailed descriptions or complex reasoning, 158,000 examples in all. The model sends each image through CLIP ViT-L/14; the resulting vector does not live in the text's space, so a matrix W maps it into the space of the text embeddings; text uses its ordinary embeddings; and the concatenated sequence of vectors passes through a standard transformer. Images are turned into text-like tokens so that the pretrained language model can be reused. Training has two stages. In the first, the alignment stage, the vision encoder and the language model are frozen and only W is trained, because a random W produces nothing resembling a language token. In this book: Alignment and Multimodality › 3. The standard recipe: encoder, projector, language model.

34:00–40:00 From LLaVA to LLaVA-OneVision (2024): any resolution#

In the second stage, the vision encoder stays frozen and W and the language model are fine-tuned on image plus text to text. LLaVA's paper gives an example: asked what is unusual in a picture, the model answers that ironing on the back of a minivan is unusual, and it mentions the oddity even when the user does not ask about oddities, as GPT-4 did and other models of the time did not. A series followed, LLaVA-1.5 and LLaVA-NeXT, and LLaVA-OneVision of 2024 collects their ideas: the same recipe with more ambition, covering several images and video, a video being a sequence of sampled frames. The vision encoder became SigLIP, the text decoder Qwen 2, then probably the best language model available, and the projector, the part that turns the encoder's output into the language model's input, became a two-layer network instead of a linear projection: parts upgraded in a stable system. Data processing drove one idea. OCR needs fine detail, or a J reads as an I, and a document cropped to 336 by 336 cannot be read. AnyRes, introduced in LLaVA-1.5, cuts the image into pieces at the encoder's resolution, encodes each and concatenates the vectors: rather than downsampling the whole image, the model looks at its parts. Images or videos of very high resolution yield too many tokens and are then downsampled. The idea is adaptive, and that suits the transformer, which already copes with sentences of any length; images of any resolution are the same kind of freedom. In practice a page is encoded once downsampled, and once as crops at the encoder's resolution, all concatenated, with the number of patches reduced by interpolation when there are too many. In this book: Alignment and Multimodality › 3. The standard recipe: encoder, projector, language model · Alignment and Multimodality › 4. Resolution.

40:00–46:00 Balancing images and video; targeted data and its transfer#

Several images and video are all reducible to images, yet the authors put a thumb on the scale so that the modalities stay comparable, because a long video would otherwise dominate the data with repetitive frames. A single image is encoded as the downsampled whole plus up to nine crops; several images at base resolution only, seen from afar; video at lower resolution or with fewer tokens per frame, up to 32 frames, since context length runs out, and handling long context is a large part of multimodality. The data is described as high quality and in quantity, which Liang reads as targeted: task-based, visual question answering, questions about tables, the territory of post-training. The work is also unabashedly distilling GPT-4, which is what one does without an annotation budget. Training now has three stages instead of two: the projector alone for alignment; a stage on high-quality data focused on knowledge; and a stage on the full model with examples like the downstream tasks. He is not sure there is a principle behind the split. The interesting finding is transfer between modalities. Data on diagrams and charts exists only for single images, yet the model answers questions about a table and a chart shown together. Single-image OCR combined with relational reasoning over several images yields descriptions of sets of screenshots, which powers GUI agents. Visual prompting, a circle marking the region to act on, exists only for single images and carries over to video, as when a user asks about a player highlighted across many frames. Enough targeted tasks, and the models generalize, which is reassuring. LLaVA is one of the few lines that releases its data as well as its weights. In this book: Alignment and Multimodality › 4. Resolution · Alignment and Multimodality › What the practitioners say.

46:00–52:00 Qwen-VL and Qwen2-VL: cross-attention, dynamic resolution, M-RoPE#

Qwen began training multimodal models in 2023. Qwen-VL follows the pattern: OpenCLIP's ViT as the vision encoder, and, as the adapter, one layer of cross-attention with two-dimensional positional embeddings that maps an image to a fixed 256 tokens, not very dynamic, though neither was the encoder. Special tokens mark an image, a bounding box and a description. Training has three stages: a first stage called pretraining, though nothing is trained from scratch, on large-scale, low-quality data, 1.4 billion examples, with the language model frozen and the vision encoder and adapter trained, which differs from LLaVA; a second on higher-quality, task-specific data, visual question answering and charts among them, training every parameter; and a third of instruction tuning with the vision encoder frozen and the adapter and language model trained. The examples include Chinese, code, grounding, with bounding boxes for characters found in an image, output as boxes and not as a picture, and OCR: the aim is a model that subsumes a language model. Qwen2-VL upgrades it: a larger vision encoder and, the main change, dynamic resolution. A large picture may map to 11,000 tokens, a tiny equation to eight. It is AnyRes again, each 224 by 224 patch encoded by the ViT, which is OpenCLIP's, fine-tuned, and every two by two patches compressed into one, so that each ends as 66 tokens; video is sampled at two frames per second and capped at 16,000 tokens. Qwen2-VL also changed the positional embeddings, with multimodal RoPE. RoPE makes the inner product of two vectors depend only on their distance, measured in one dimension by the number of tokens between them. The multimodal version is the same in three dimensions, height, width and time: every patch position is a triple of coordinates, and RoPE is computed for each dimension and the results concatenated. In this book: Alignment and Multimodality › 5. The Qwen vision-language line.

52:00–58:00 Qwen3-VL: interleaved frequencies, timestamps, DeepStack#

That multimodal RoPE is a straightforward idea, though Qwen 3 later shows it to be a bit suboptimal. The language model was initialized from Qwen, training had three stages as before, and the model showed video understanding, mathematics, code and function calling. Qwen3-VL, from the previous year, keeps the diagram and changes what bears on quality. It builds on the Qwen 3 models, dense and mixture-of-experts, which are very strong; it supports contexts up to 256,000 tokens, which long video needs. Its vision encoder is SigLIP 2, an improved SigLIP with an identical architecture, made to be backward compatible. Its RoPE was improved: the earlier version gave the first block of dimensions to time, the next to width, the next to height, and since each dimension represents a frequency, that left one axis all low frequencies and another all high; the dimensions are now interleaved so that every axis sees both. Video timestamps became explicit tokens, where time had been implicit in position: a token for zero seconds and so on, which the model can refer to directly, as in "after two seconds". The per-token loss is normalized by the square root of the example's length, so that long video examples do not dominate short single-image ones; Liang says the details are not too clear but believes that is the mechanism. And the adapter changed: DeepStack, from the DeepSeek team, takes the stack of embeddings the vision encoder computes and adds them straight into the language model's residual stream, a deeper fusion than an encoder treated as a black box that outputs a sequence of vectors. Pretraining now has four stages and post-training three. In this book: Alignment and Multimodality › 5. The Qwen vision-language line.

58:00–66:00 Results, and questions on training multimodal models#

Pretraining first trains the adapter, as all these models do, then runs three stages on longer and longer sequences, 8,000, 32,000 and 256,000 tokens, with most tokens in the second and third; post-training combines knowledge distillation, supervised fine-tuning on long chains of thought and a little reinforcement learning. By now it is a systems paper with many details left out here. The results: against the closed Gemini, GPT-5 and Opus 4.1, the Qwen models are quite strong, bold marking the best number in a row. The questions: these models do not generate images or video; all the multimodality is on the input side, and the output is always text, supervised at every token except under RL, so the description's quality is whatever the data set holds. Is training multimodal models harder? On the systems side certainly not easier: the data sets are larger, and even loading video can be a bottleneck, where loading text was too cheap to discuss, so loading must run asynchronously with computation. On the algorithmic side video has more tokens, which is one reason for the normalization, though one can also downweight a source in the mixture, and text tokens are still so plentiful that multimodal tokens do not vastly outnumber them. How does one know when alignment is finished? The language model is frozen and the adapter trained for a chosen token budget; there is no adaptive threshold. Are the vision encoders smaller? Yes: the encoder does a local job, understanding a small patch, with little knowledge or reasoning in it, so the capabilities stay in the language model; the projector is smaller by far and the ViT usually has fewer than a billion parameters. In this book: Alignment and Multimodality › 5. The Qwen vision-language line · Alignment and Multimodality › What the practitioners say.

66:00–72:00 Chameleon (2024): everything a discrete token#

From Qwen-VL to Qwen3-VL a great deal of data work happened with few details published; the LLaVA papers and AI2's Molmo report, which the lecture skips, say more. The changes were scaling up, more curated data, long context and sharper image processing, with the framework unchanged. Chameleon, from Meta in 2024, departs from it. The models so far inject vectors and, being language models, generate only text; one remedy is to bolt a diffusion head onto a vision-language model. Chameleon instead maps everything into discrete tokens, which appeals to Liang as a language person: images are analyzed and generated the same way, as tokens. Given the prompt that one is bored and would like to see birds, it answers with text, then images, then more text and images, interleaved. It is the omni model's vision, text and images in one space, achieved by making everything look like text. The tool is the vector-quantized variational autoencoder, an idea from 2017: an image is encoded into a continuous vector that is rounded to the nearest entry of a learned codebook, 8,000 prototypical vectors for patches, and a decoder reconstructs the image from the codes; training minimizes reconstruction loss, with extra terms for the rounding that the lecture has no time for. A 512 by 512 image becomes 1,024 tokens from that vocabulary. A new tokenizer is trained for the mixed data. Training is then ordinary language-model training, with no adapter and no vision encoder to tune, the attraction of the method; it has two stages, the bulk on unsupervised text and text-image data, then a mix of high-quality data. In this book: Alignment and Multimodality › 6. Generation.

72:00–1:18:00 Why it was hard, and what the field settled on#

Chameleon has problems. Training was unstable, because text and image tokens behave very differently even in one space, and calling an image a discrete token does not hide it: the next text token has fairly low entropy, most words being predictable, while an image token has very high entropy, which exact shade of blue. The mixture made parameter norms grow and losses unstable, which QK-norm and a z-loss mitigated by controlling the norms. The elegance of one model treating all modalities alike did not make it as performant, and discretization loses information: very small print becomes unreadable, as with OCR. Balancing modalities is tricky in general and worse here. Vector-quantized autoencoders were popular for a while, above all for image generation, since a transformer must generate discrete things; then diffusion models became viable for generation and this approach receded. Liang's reflections: frontier models are expected to be multimodal, natively so, or omni; Gemini and GPT are said to be and are, with no details of how; his guess is a continuous encoder, to lose no information, with diffusion for generation. The fundamental challenge is handling non-text modalities, with a symmetry between understanding one and generating one, and there is no universal encoder: CLIP needed only high-level semantics for classification and could use small vectors, while OCR or image generation needs fine detail, at which diffusion excels by optimizing high-frequency information. Video carries a lower information density than text and must not overwhelm it. The current best practice, in his view: continuous encoders, CLIP-like ideas now five years old, transformers, and diffusion for generation, which he did not talk about. There is no homework on this; he encourages students to train such a model for themselves. In this book: Alignment and Multimodality › What the practitioners say · Alignment and Multimodality › Key takeaways.

What to take away#

Sources#