Stanford CS336
Language Modeling from Scratch Lecture 17: Multimodal Models

From Vision-Language Encoders to Omni Architectures
Autumn 2026

From Language Models to Omni Models

Text Language Model (So Far) Text Text Images Video Audio Omni Model Shared Transformer Backbone (any-to-any reasoning) Text Images Video Audio Understanding Generation

Core constraint: Transformers operate on sequences of tokens, so every modality must be converted into tokens.

The Core Interface: Turning Signals into Tokens

Two guiding questions for this lecture:
1. How do we encode non-text inputs into a Transformer (understanding)?
2. How do we output non-text modalities from a Transformer (generation)?

We start with vision encoders, then inject them into LLMs, and finally examine unified discrete tokenization.

Three Architectural Paradigms for Multimodality

1. Modular VLM LLaVA, Qwen-VL series Continuous Vision Encoder Projector / Adapter LLM Backbone Text Output Only 2. Early-Fusion Discrete Chameleon (VQ-VAE) VQ-VAE + BPE Tokenizer Unified Autoregressive Transformer Text + Image Token IDs → VQ-VAE Decoder → Pixels 3. Continuous + Diffusion Current omni direction Continuous Encoders Multimodal Transformer (shared reasoning core) Text LM Head Diffusion Decoder

Notice the central tension: continuous features excel at comprehension, while generation requires reconstructing fine-grained details.

Encoding Images: From Labels to Web Captions (CLIP)

Supervising vision with natural language gives open-vocabulary semantics instead of a fixed class list.

Vision Transformer (ViT) Image Tokenization

Raw Image arbitrary W × H resize + crop 336 × 336 px 14 × 14 patches × 3 ch Linear Patch Embedding + 2D pos. emb. 24 × 24 = 576 tokens ViT-L Transformer bidirectional attn Attention Pooling Q = global avg 1 image vector

Later VLMs drop the final pooling step and feed the full spatial grid of ViT patch embeddings into the LLM.

CLIP: Dual-Encoder Contrastive Alignment

Text Encoder (GPT-2, 63M, 12L) T1 T2 T3 TN Image Encoder (ViT) I1 I2 I3 IN I₁ · T₁ neg neg neg neg I₂ · T₂ neg neg neg neg I₃ · T₃ neg neg neg neg Iₙ · Tₙ Maximize diagonal; push down N² − N off-diagonals
  • Sample a large batch of $N$ aligned (image, text) pairs (e.g., $N = 32{,}768$)
  • Text encoder: GPT-2 Transformer (63M params, 12 layers)
    • Encodes [BOS] ... [EOS]
    • Returns top-layer [EOS] activation
  • Symmetric objective:
    • Row-wise: each image picks its true caption over $N - 1$ distractors
    • Column-wise: each caption picks its true image over $N - 1$ distractors

CLIP Objective: Symmetric Cross-Entropy

Given $L_2$-normalized embeddings $\hat{v}_i, \hat{t}_j \in \mathbb{R}^d$ and learnable scale $\tau = e^{t}$, form similarity logits $S_{ij} = \tau\, \hat{v}_i^\top \hat{t}_j$:

$$\mathcal{L}_{\text{CLIP}} = -\frac{1}{2N}\sum_{i=1}^{N} \left[\log \frac{e^{S_{ii}}}{\sum_{j=1}^N e^{S_{ij}}} + \log \frac{e^{S_{ii}}}{\sum_{j=1}^N e^{S_{ji}}}\right]$$

I_e = F.normalize(image_encoder(I) @ W_i, dim=-1)  # [N, d]
T_e = F.normalize(text_encoder(T)  @ W_t, dim=-1)  # [N, d]

logits = (I_e @ T_e.T) * torch.exp(t)              # [N, N]
labels = torch.arange(N)
loss_i = F.cross_entropy(logits,   labels)         # image -> text
loss_t = F.cross_entropy(logits.T, labels)         # text  -> image
loss   = 0.5 * (loss_i + loss_t)

Every row and column requires a softmax over the entire batch of $N$ examples — coupling loss quality directly to batch size.

CLIP: Why Contrastive Ranking Wins — and Its Limits

CLIP gave multimodal models their semantic backbone, motivating fixes for both its loss (SigLIP) and resolution (AnyRes, dynamic ViT).

SigLIP: Pairwise Sigmoid Loss

$$\mathcal{L}_{\text{SigLIP}} = -\frac{1}{N}\sum_{i=1}^{N}\sum_{j=1}^{N} \log \frac{1}{1 + \exp\!\bigl(-z_{ij}\,(\tau\,\hat{v}_i^\top \hat{t}_j + b)\bigr)}$$

Removing batch-wide softmax breaks the strict coupling between the loss function and global batch size.

SigLIP: Implementation & Chunked Parallelism

z_img = F.normalize(img_enc(I), dim=-1)
z_txt = F.normalize(txt_enc(T), dim=-1)

# [N, N] pairwise scores
logits = (z_img @ z_txt.T) * t + b

# +1 on diagonal, -1 off-diagonal
labels = 2 * torch.eye(N) - 1

loss = -F.logsigmoid(
    labels * logits
).sum() / N
  • Each device holds a shard of image and text embeddings
  • Pairwise losses sum additively across shards — no global softmax denominators needed
Chunked Ring Evaluation (3 Devices) Step 1 (local + pos) Dev 0 I₀ · T₀ᵀ Dev 1 I₁ · T₁ᵀ Dev 2 I₂ · T₂ᵀ rotate text chunks Tₖ Step 2 (negatives) I₀ · T₁ᵀ I₁ · T₂ᵀ I₂ · T₀ᵀ Step 3 (negatives) I₀ · T₂ᵀ I₁ · T₀ᵀ I₂ · T₁ᵀ Never materializes full N × N matrix

SigLIP: WebLI Data & Batch-Size Scaling

Better data (OCR + quality filtering) plus a simpler, chunkable loss made SigLIP and SigLIP-2 the standard VLM vision encoders.

Vision Encoders: CLIP vs. SigLIP / SigLIP-2

DimensionCLIP (2021 baseline)SigLIP / SigLIP-2 (2023–2025)
ObjectiveSymmetric $N$-way softmax cross-entropyPairwise binary sigmoid loss (learnable $\tau, b$)
Global syncFull-batch softmax over all $N$ examplesAdditive per-chunk loss; no full $N\times N$ gather
Batch sizeNeeds very large batches (e.g., 32,768)Beats CLIP below 16K; scales to 1M (32K sufficient)
Pretraining data400M private pairs (OpenCLIP: LAION-5B)WebLI: $O(\text{B})$ pairs, auto-OCR, top 10%, 100 langs
VLM usageEarly VLMs (LLaVA, Qwen-VL)Modern VLMs (LLaVA-OneVision, Qwen3-VL)

LLaVA: Injecting Vision into an LLM (2023 Baseline)

Image Xv CLIP ViT-L/14 (frozen encoder) Linear Proj. W Hv = W · Zv Text Instruction Xq → Token Embeddings Hq Vicuna LM (LLaMA fine-tuned on ShareGPT) Xa

Historical baseline (2023): proved simple projection + instruction data suffices to unlock visual reasoning in an LLM.

LLaVA: Synthetic Instruction Data & 2-Stage Training

MS COCO Annotations bounding boxes + Mechanical Turk captions Prompt Text-Only GPT-4 generate visual Q&A, descriptions, and multi-turn conversations Pair with Original Images 158K multimodal examples for visual instruction tuning
Training StageVision EncoderProjector $W$Language ModelPurpose
Stage 1 (Alignment)FrozenTrainFrozenAlign visual features to LM space without wrecking LM weights
Stage 2 (Fine-tuning)FrozenTrainTrainEnd-to-end multimodal instruction following

Bootstrapping multimodal data from text annotations + a strong LLM became a standard recipe across open VLMs.

The Resolution Bottleneck & AnyRes

High-Res Image e.g. wide chart / OCR Base global a × b encoder-sized tiles Encode each tile with ViT → Concatenate Too many tokens? Bilinear interpolation pool
  • Fixed $336 \times 336$ resizing and center-cropping destroys fine details needed for OCR, documents, and diagrams
  • AnyRes (introduced in LLaVA 1.5, extended in LLaVA-OneVision):
    • Split the image into $a \times b$ crops matching the vision encoder's native resolution
    • Encode each crop plus a global overview, then concatenate tokens
    • If total token count exceeds budget, downsample spatial grids via bilinear interpolation

LLaVA-OneVision: Unifying Image, Multi-Image & Video

Single Image Higher resolution AnyRes multi-tile grid Multiple Images Base resolution each 1 base crop per image Video Lower res per frame bilinearly pooled frames

Unifying representation length prevents one modality from starving or overwhelming the context window.

Data Curation, Curriculum & Cross-Modal Transfer

Key takeaway: once the vision-language interface is shared, skills learned in one visual regime transfer to others.

Qwen-VL (2023): Compression Adapter & Spatial Grounding

StageData & ResolutionVisionAdapterLM
Stage 1Large-scale, lower-quality web pairsTrainTrainFrozen
Stage 2Higher-quality task-specific data + higher resolutionTrainTrainTrain
Stage 3Instruction tuning dataFrozenTrainTrain

Unfreezing the vision encoder in Stages 1–2 improves visual alignment, but a fixed 256-token bottleneck still limits fine-grained reading.

Qwen2-VL (2024): Native Dynamic Resolution

Small Native Aspect Dynamic ViT (675M) init from DFN 14 × 14 patches no forced square crop 2 × 2 Spatial Merge → 4× fewer visual tokens Qwen2 LM variable-length visual token stream

Multimodal Rotary Position Embedding (MRoPE)

Decomposing RoPE into (t, h, w) Coordinates Temporal (t) Height (h) Width (w) Text tokens: (0,0,0) (1,1,1) (2,2,2) ... t = h = w ⇒ identical to standard 1D RoPE Image tokens: (3,0,0) (3,0,1) ... (3,h,w) Constant t; (h, w) tracks exact 2D patch grid coordinates Video frames: (t, h, w) increments t per frame Unifies 1D text, 2D images, and 3D space-time video
  • Standard 1D RoPE flattens 2D patch grids into a line, making vertical neighbors look arbitrarily far apart
  • MRoPE (Qwen2-VL) partitions rotary embedding channels across three axes: temporal $t$, height $h$, and width $w$
  • Text tokens set $t = h = w$, preserving exact backward compatibility with pretrained text-only RoPE

Next: how Qwen3-VL fixes a subtle frequency-band flaw in MRoPE and deepens visual-language fusion.

Qwen3-VL (Late 2025): Refining the Modular VLM

Illustrates the mature open VLM recipe: surgical architectural fixes combined with massive data engineering and scale.

Interleaved MRoPE & Explicit Video Timestamps

← High frequency (fine local detail) Low frequency (long-range) → Block MRoPE (Qwen2-VL) t t t t w w w w h h h h Each axis is trapped in a narrow band of rotary frequencies Interleaved (Qwen3-VL) t w h t w h t w h t w h All three axes (t, w, h) span both high- and low-frequency bands

DeepStack: Cross-Layer Visual Feature Injection

SigLIP-2 Vision Encoder Early ViT Layers Mid ViT Layers Top ViT Layers LLM Decoder Layers LLM Layer 0 (in) LLM Layer k₁ LLM Layer k₂ Proj 0 Proj 1 Proj 2 Multi-level visual features injected across depth
  • Standard VLMs inject visual tokens only at LLM Layer 0, forcing the final ViT layer to summarize everything
  • DeepStack fuses intermediate visual encoder representations into multiple LLM layers
  • Preserves both fine-grained low-level cues (edges, OCR characters) and high-level semantics without inflating context length

Loss Balancing & Staged Pretraining (Qwen3-VL)

4-Stage Pretraining Post-Training Stage 0 Train adapter align vision & LM Stage 1 All params 8K context Stage 2 All params 32K context Stage 3 All params 256K context 1. Long-CoT SFT 2. Distillation 3. RL

Progressive context extension (8K → 32K → 256K) mirrors text-LLM training while scaling cleanly to long videos and documents.

Evolution of the Modular VLM Template

Model Vision Encoder Resolution Adapter Pos. / Backbone
LLaVA
(2023 baseline)
CLIP ViT-L/14 Fixed 336×336 crop Linear $W$ 1D RoPE / Vicuna (LLaMA)
Qwen-VL
(2023 baseline)
OpenCLIP ViT/14 Fixed crop, higher in Stage 2 1-layer cross-attn → 256 tokens 2D pos in adapter; <box>, <ref>
LLaVA-OneVision
(2024)
SigLIP (2-layer grid) AnyRes tiles + bilinear pool 2-layer MLP Qwen-2 72B (img / multi / vid)
Qwen2-VL
(2024)
675M ViT (DFN init) Native dynamic + 2×2 merge Patch merger MRoPE / Qwen2 (vid 2 fps, ≤16K)
Qwen3-VL
(late 2025)
SigLIP-2 Native dynamic + timestamps DeepStack (multi-layer) Interleaved MRoPE / Qwen-3 MoE (235B-A22B, 256K)

Clear trend: fixed crops and fixed-length resamplers gave way to native dynamic resolution, 3D rotary positions, and MoE backbones.

Late-2026 Backbones Powering Multimodal Systems

Low active-parameter MoE and sparse 1M-context attention directly relieve the visual token-length bottleneck.

Towards Omni Models: Generating Non-Text Modalities

Chameleon (2024): maps text and images into one discrete vocabulary to model both with next-token prediction.

Discretizing Images with a VQ-VAE Tokenizer

Image x 512 × 512 Encoder continuous ze(x) Vector Quantization k = argminj ‖ze − ej‖2 Codebook: 8,192 entries 1,024 discrete token IDs Decoder from quantized zq Recon. x̂ min ‖x − x̂‖ Trained end-to-end via reconstruction loss

Chameleon: Early-Fusion Autoregressive Training

Draw a cat: <img> v_4102 ... v_0819 </img> Here is... Single Autoregressive Transformer Standard next-token cross-entropy over interleaved text and image IDs

Why Mixed-Modal Early Fusion Is Unstable

Text Tokens Lower entropy Image VQ Tokens Higher entropy Shared Layer Competition uncontrolled activation norm growth + softmax logit drift Training Divergence attention entropy collapse and loss spikes at scale

Stabilizing Early Fusion: QK-Norm & z-Loss

$$\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{\text{Norm}(Q)\,\text{Norm}(K)^\top}{\sqrt{d_k}}\right)V$$

$$\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{CE}} + \lambda\,(\log Z)^2$$

Together, QK-Norm and z-loss stabilized Chameleon across trillions of mixed-modal tokens.

Continuous Encoders vs. Discrete Visual Tokenizers

PropertyContinuous Encoders
(CLIP / SigLIP / SigLIP-2)
Discrete Tokenizers
(VQ-VAE / Chameleon)
Token typeContinuous ViT patch vectorsDiscrete codebook IDs (e.g., 8,192)
Fine-grained detail & OCRHigh — preserves subtle visual detailDegraded — discretization loses fine detail (e.g., small text / OCR)
Image generationNot native (needs external decoder)Native — single autoregressive LM head
Training stabilityMature staged alignmentHarder — entropy mismatch needs QK-Norm + z-loss
Architectural simplicityRequires encoder + adapter + decoderElegant — pure next-token modeling

Chameleon proved unified discrete autoregression works, but discretization still lags continuous encoders on visual comprehension.

Comprehension vs. Generation: The Fundamental Tension

Understanding wants high-level semantics (invariant to pixel noise) Generation wants fine-grained details (textures, edges, layout) Prevailing Omni Architecture Continuous Encoders Multimodal Transformer Diffusion Decoders Decouples semantic reading from pixel synthesis
  • Comprehension and generation place opposing demands on visual representations
  • Contrastive encoders discard pixel-level details to isolate semantics; reconstruction tokenizers preserve pixels at the cost of weaker semantics and OCR
  • Dominant practical synthesis: continuous encoders + Transformer + diffusion decoders

Four Practical Levers in Multimodal Training

  1. Data curation & synthesis dominate quality:
    • OCR-enriched web filtering (WebLI), LLM-synthesized conversations & CoT (LLaVA, OneVision, Qwen3-VL), and easy-to-hard curricula
  2. Resolution & token budgeting:
    • Native dynamic resolution, $2 \times 2$ spatial merging, and modality-aware frame budgets keep image/video lengths manageable
  3. Cross-modal stability & loss weighting:
    • Square-root-normalized per-token loss balances low-density video against text; QK-Norm and z-loss prevent mixed-modal divergence
  4. Spatial-temporal alignment across depth:
    • Interleaved MRoPE, explicit timestamp tokens, and DeepStack cross-layer fusion preserve 3D visual structure inside deep LMs

Recap: Multimodal Models