Lecture 22 · Multimodal Models

Deep Unsupervised Learning · Lecture 22。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 12a · Thu 4/11/2024 · Multi-Modal Models (slides 1–48 of the L12 deck; the deck’s last part, parallelization, is Lecture 23). It covers:

  • Bidirectional models: CLIP’s capabilities (zero-shot classification, re-ranking, Dream Fields, VQGAN-CLIP guidance, pretrained encoders, CLIPort) and M3AE.
  • Encoder–decoder models: Flamingo, PaLI and its successors (PaLI-X, PaLI-3).
  • Decoder-only models: Frozen, MiniGPT-4 / LLaVA (1.5, 1.6), GPT-4V, Gemini 1.5.
  • Multimodal generation: text → image / video / audio, CoDi (any-to-any), Emu vs LaVIT (continuous vs quantized visual tokens), Video-LaVIT, the Large World Model.

Basis: The slides are mostly figures from the papers; these notes explain each design from its paper. The code then rebuilds the central mechanisms at toy scale, on ShapeWorld images, captions, and questions whose answers follow exactly from the image:

  • a language model pretrained on text only;
  • frozen vision encoders from Lectures 13–15;
  • LLaVA-, Flamingo- and Frozen-style connectors;
  • visual instruction tuning;
  • discrete vs continuous visual tokens;
  • one token stream for every direction.

Code: code/lecture22/ (4 scripts + vlm.py; PyTorch on CPU; reuses Lecture 4’s text → image model, Lecture 13’s MAE, Lecture 14’s SimCLR and Lecture 15’s CLIP; the first run trains ~45 small models in about 2 CPU-hours (independent, so they parallelize), later runs take minutes) Reading time: 3 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Families. Place a multimodal model in one of the three families (bidirectional, encoder–decoder, decoder-only) and say what each is good for.
  2. CLIP as a component. Use CLIP as a judge (zero-shot, re-ranking) and as a guide, and explain why guiding pixels with CLIP produces adversarial images.
  3. Connectors. Explain the ways to connect a pretrained vision encoder to a pretrained language model: a projection into the LM’s input (LLaVA), gated cross-attention with a resampler (Flamingo), a trained encoder with a frozen LM (Frozen). Say what each trains and what can go wrong (soft-prompt interference, forgetting).
  4. Instruction tuning. Explain why visual instruction tuning needs little data, and what the vision encoder’s pretraining contributes.
  5. Generation. Explain why generating images as discrete tokens (softmax) samples sharp, valid images while regressing continuous embeddings averages them, and how any-to-any models put everything into one token stream.

0.2 Prerequisites and scope

AssumedIntroduced hereElsewhere
Lecture 4 (Transformers, homework 1 Q6: one stream of text and image tokens)connectors: projection, cross-attention, resamplerLecture 17 (video tokens and generation)
Lectures 13–15 (MAE, SimCLR, CLIP, SigLIP, LiT)visual instruction tuning, soft prompts, forgettingLecture 23 (parallel training of such models)
Lecture 16 (LLMs, scaling)M3AE; discrete vs continuous visual tokens; any-to-any streams

The slides’ product descriptions (GPT-4V, Gemini 1.5) are summarized as the slides give them. What is known about these closed models is limited, and the slides say so.

0.3 Map

§1  what multimodal models are for
§2  bidirectional models: CLIP as a judge and a guide; M3AE               ← code 01
§3  encoder-decoder models: Flamingo, PaLI                                ← code 02
§4  decoder-only models: Frozen, LLaVA, GPT-4V, Gemini                    ← code 02
§5  visual instruction tuning: why so little data                         ← code 03
§6  multimodal generation: discrete vs continuous tokens; any-to-any      ← code 04
§7 summary   §8 pitfalls   §9 exercises   §10 further reading   §11 next lecture

0.4 The toy world of the code

ingredientwhat it is
ImagesLecture 13’s 10,000 training and 2,000 test ShapeWorld images (two panels, a shape in each).
Captions16 words: “a huge ring at the middle center and a big ring at the middle center.”
Questions8 templates whose answers follow exactly from the caption: the kind, size and place of each shape, “are the two shapes the same?”, “which shape is bigger?”.
Language modelA 0.46M-parameter decoder-only Transformer pretrained on text only: captions of other random images, and reading comprehension “⟨bos⟩ caption ⟨sep⟩ question answer”. It never sees an image.
Vision encodersFrozen towers from earlier lectures: CLIP (Lecture 15), SimCLR (Lecture 14), MAE (Lecture 13), plus an untrained network and raw pixel patches as controls.

1. What multimodal models are for

A multimodal model takes in (or produces) several modalities: images, video, text, audio. The slides name two hoped-for outcomes:

  1. Multimodal understanding: answering questions about images, captioning, following instructions that refer to pictures.
  2. Better unimodal understanding: for example, image features that improve because language was involved in training.

The slides sort models into three families by how the modalities meet:

familyhow the modalities meetexamples
Bidirectionalencoders that look at both modalities at once or map them into one space; no text generationCLIP, SigLIP, M3AE
Encoder–decoderan encoder of images (+ text) feeds a text decoderFlamingo, PaLI
Decoder-onlyimages become tokens (or embeddings) in the input of a decoder-only LMFrozen, LLaVA, GPT-4V, Gemini

A fourth topic is generation of non-text modalities from the same models.


2. Bidirectional models: CLIP as a component, and M3AE

2.1 What CLIP is used for (slides 4–9)

Lecture 15 trained CLIP: two encoders and a contrastive loss that puts matching images and captions close in one space. The slides list what that enables:

  • Zero-shot classification: compare an image with prompts like “a photo of a {class}”. Lecture 15 reached 99.1% on ShapeWorld kinds with prompt ensembles.
  • Re-ranking: generate NN images from a text-to-image model and keep the one with the highest CLIP score. DALL·E did this.
  • Guidance: push a generator toward a high CLIP score with gradients. Examples are VQGAN-CLIP (optimize the VQGAN latent) and Dream Fields (optimize a NeRF, Lecture 25). The slides add that this works for diffusion models too, and better.
  • Pretrained encoders: Stable Diffusion’s text encoder is CLIP’s; CLIPort uses CLIP features for robot manipulation. They generalize better to unseen concepts.

Re-ranking, measured (script 01, Part 1). Lecture 4’s text → image Transformer drew 8 images for each of 300 test captions. Lecture 15’s CLIP scored each image against its caption:

image keptvalidmatches its caption
one sample88.0%78.7%
highest CLIP score of 899.7%99.7%
lowest CLIP score of 862.3%21.7%
oracle (any of the 8 matches)100%100%

CLIP’s cosine score is 0.957 for matching pairs and 0.752 for generated images that do not match. A judge that never touches the generator turned 79% into 99.7%. This is “generate, then verify” (Lecture 16’s verifiers for text).

Guidance by pixel optimization (Part 2). Start from a gray image and run Adam on the pixel logits to maximize the CLIP score of a caption (64 captions, 400 steps):

optimizationCLIP score (gray image)after rounding to 0/1validink
plain0.8870.5580%49%
with random shifts0.7780.6150%49%
the true images—0.954100%22%

The optimizer raises the score a long way, from near zero to 0.887, but never produces the described image. It finds a gray, half-inked pattern that excites the right features. Rounding to a real binary image destroys most of the score.

Random shifts during optimization make the pattern more robust; this is the augmentation trick of practical CLIP guidance. They do not make it valid.

This is the adversarial-example problem of Lecture 10: a classifier’s gradient points toward whatever raises its score, not toward the data. Guidance works when a generator keeps the image on the data manifold, which is why VQGAN-CLIP optimizes the generator’s latent rather than pixels.

2.2 M3AE: one encoder over both modalities (slides 10–13)

M3AE (Geng et al., 2022) is a masked autoencoder whose single Transformer encoder reads image patches and text tokens together. It masks a large fraction of both (75% of the patches, 50% of the words in the paper’s setting) and reconstructs the pixels and the words. There is no contrastive loss and no paired-batch negatives, so the method also learns from image-only or text-only data. Its representations transfer well, and the paper reports that its image features benefit from the language.

Measured (Part 3). One Transformer, trained with and without the caption’s words in its input (4,000 steps each). Image-only features at test time, probed with Lecture 13’s protocol:

modelpixel lossleft shapeleft sizetop/bottomsame kind10 labels/class
M3AE (patches + words)0.19097.1%99.8%99.7%56.2%75.8%
MAE (patches only)0.24696.4%98.3%99.7%54.1%74.2%
  • The words help reconstruction: pixel loss 0.190 vs 0.246. The caption says what is hidden.
  • They give a small but consistent gain in the image-only probes: +0.7 to +2.1 points. That is “better unimodal understanding”, modestly, on a world where pixels alone already determine every caption.
  • The CLIP tower is still the best feature extractor for kinds (100%; 95.1% with 10 labels per class). Lecture 15 showed why: it was trained to align with exactly these words.

3. Encoder–decoder models: Flamingo and PaLI

3.1 Flamingo (slides 15–19)

Flamingo (Alayrac et al., 2022) connects a frozen vision encoder (an NFNet trained contrastively) and a frozen Chinchilla language model with two new trainable parts:

  1. A Perceiver resampler. A fixed number of learned latent queries (64) cross-attend to the visual features and return a fixed-size set of visual tokens, whatever the image or video size.
  2. Gated cross-attention layers. One is inserted before each (or every few) frozen LM block: h←h+tanh⁡(α) CrossAttn(h,visual tokens),h←h+tanh⁡(β) FFW(h),h \leftarrow h + \tanh(\alpha)\,\mathrm{CrossAttn}(h, \text{visual tokens}), \qquad h \leftarrow h + \tanh(\beta)\,\mathrm{FFW}(h), with α=β=0\alpha = \beta = 0 at initialization. At the start, the model is the pretrained LM. The gates open as training shows that the images help.

Flamingo trains on interleaved image–text web pages (M3W), image–text pairs and video–text pairs, with masking so that each text token attends only to the image just before it. The result is an in-context few-shot learner: show a few (image, answer) examples in the prompt and it answers for a new image, without fine-tuning.

3.2 PaLI and successors (slides 20–22)

PaLI (Chen et al., 2022) is an encoder–decoder in the T5 style:

  • a large ViT (ViT-e, 4B parameters) encodes the image into tokens;
  • an mT5 encoder–decoder takes those tokens plus a text prompt and generates text;
  • it is trained on a mixture of tasks (captioning, VQA, OCR, multilingual) in many languages.

Its lesson is to scale the vision side together with the language side.

  • PaLI-X: scales further, with a mixture of objectives and extra OCR training of the vision encoder.
  • PaLI-3: switches to a SigLIP encoder (Lecture 15) and comes close to PaLI-X at a tenth of the size (5B vs 55B parameters). The quality of the vision encoder’s pretraining matters.

3.3 The connectors, measured (script 02)

The text-only LM (Part 1) codes captions in 12.08 bits; the exact entropy is 11.97. It answers all 8 question types correctly (100%) when it reads a caption. That reading skill is what a multimodal model should be able to reuse.

Stage 1: alignment on 10,000 (image, caption) pairs with Lecture 15’s frozen CLIP image tower. The tower’s 3 × 6 feature map gives 18 visual tokens.

recipetrained paramscaption exactslotszero-shot VQA (describe, then answer)VQA, answer directlyreads (true caption given)
LLaVA: linear projector, LM frozen7,9683.9%70.2%46.9%38.6%65.1%
LLaVA-1.5: MLP projector, LM frozen17,2806.6%73.0%55.6%38.9%72.1%
Frozen: trainable encoder, LM frozen100,64011.4%79.4%58.6%44.0%76.4%
Flamingo: resampler + gated cross-attention, LM frozen680,168100%100%0.0%6.8%0.0%
same, + interleaved caption–question text680,168100%100%98.4%52.6%98.4%
linear projector, LM unfrozen466,848100%100%56.9%30.0%56.9%
same, + interleaved caption–question text466,848100%100%96.8%51.4%96.8%

“Slots” means the 8 informative caption words are right. “Describe, then answer” means generate a caption, then answer by reading it, which needs no question–answer training with images at all.

Four lessons, each a real phenomenon of the full-size systems:

  1. A frozen small LM is hard to steer with a prefix. A linear projector gets 70% of the caption words right but only 3.9% of the whole captions. Its 18 visual tokens act as a soft prompt: they sit no closer to any word embedding than words sit to each other (cosine 0.27 vs 0.22; Part 4).
    • Real LLaVA works with a frozen 7B LM in stage 1, because a big LM is far more steerable.
    • Even so, the soft prompt disturbs the frozen LM’s reading. Given the true caption after the image, it answers 65% instead of 100%. The prefix steers everything that follows, not just the caption.
  2. Flamingo’s cross-attention layers caption perfectly, but trained on captions alone they override the frozen LM. It no longer reads (0%), and zero-shot VQA collapses to 0%.
    • The tanh gates start closed, but nothing stops them from opening wide when the only training signal is captioning.
    • Adding interleaved text, here caption–question–answer sequences next to their images, keeps the reading skill (98.4%). Flamingo’s diverse interleaved training data plays this role.
  3. Unfreezing the LM gives perfect captions and forgetting (57%). Mixing in text the LM must still read fixes it (97%). This is the standard cure for catastrophic forgetting: keep the old task in the data mix.
  4. Answering directly (“⟨bos⟩ ⟨sep⟩ question” with no description first) stays at 30–53% for every recipe. Stage 1 never showed the model that format with an image. That is what stage 2 is for (§5).

4. Decoder-only models: Frozen, LLaVA, GPT-4V, Gemini

Frozen (Tsimpoukelli et al., 2021; slides 24–25).

  • Design: keep a pretrained LM entirely frozen and train only a vision encoder whose outputs are fed as a prefix of 2 embeddings, trained on captioning.
  • Result: the frozen LM’s in-context learning carries over. With a few (image, text) examples in the prompt, it can name new objects or answer questions — the first demonstration that a frozen LM can be given eyes.
  • In our table: the Frozen-style recipe trains 100k parameters and beats a linear projector on frozen CLIP features (11.4% vs 3.9% exact captions). Here the trainable encoder adapts to what the frozen LM can use.

MiniGPT-4 and LLaVA (slides 26–31).

  • MiniGPT-4 connects a frozen Vicuna LM to a frozen BLIP-2 visual encoder (ViT + Q-Former) with one linear layer.
  • LLaVA (Liu et al., 2023) has two stages:
    1. Alignment. Freeze the vision encoder (CLIP ViT-L) and the LM, and train only a projection on ~600K image–caption pairs, so that visual features land where the LM can use them.
    2. Visual instruction tuning. Keep the vision encoder frozen and fine-tune the LM + projection on ~158K multimodal instruction examples. GPT-4, given captions and bounding boxes as text, wrote conversations, detailed descriptions and reasoning questions about the images.
  • Later versions:
    • LLaVA-1.5: 336-pixel inputs, an MLP projector, better VQA data in the mix.
    • LLaVA-1.6: higher resolution via “AnyRes”, tiling the image into crops plus a global view.

GPT-4V (slides 32–36). The architecture is not public. The slides infer from the pricing that a low-resolution image costs 85 tokens and a 512 × 512 image 255 tokens (85 + 170), and that larger images are tiled into 512 × 512 tiles. This suggests a fixed token budget per tile, as in LLaVA-1.6’s tiling. The capabilities shown are a visual knowledge bank, OCR, and code from sketches, along with mistakes (“not always correct”).

Gemini 1.5 (slides 37–40). Also not public. The slides suggest discrete (VQ-like) image encodings and a CoCa-like combination of captioning and contrastive objectives. They show long-context retrieval of a “needle” in hours of video. Multimodal input then becomes a question of context length (Lecture 16’s RingAttention; §6’s LWM).


5. Visual instruction tuning: why so little data? (script 03)

Stage 2 trains on NN (image, question, answer) examples and evaluates direct answers on 1,000 test images × 8 questions:

recipe250 examples1,0004,00016,000
LLaVA: stage-1 projector, then LM + projector62.7%77.9%94.4%97.4%
no stage 1: fresh projector, LM + projector58.1%81.0%93.9%96.3%
LM frozen: only the projector learns58.9%70.0%77.8%80.2%
from scratch: random LM + conv encoder on pixels48.8%64.3%83.9%94.3%

Pretrained parts make instruction data go far. At 250 examples the LLaVA recipe answers 63%, the model from scratch 49%. At 4,000 examples it is 94% vs 84%.

  • The text-pretrained LM already knows how to answer each question from a description.
  • The frozen CLIP tower already makes kind, size and position explicit.
  • The instruction data only has to connect the two.

With enough data, the model from scratch catches up (94% at 16,000), as one would expect when the task itself is small.

Three further observations:

  • Stage 1 helped a little at 250 examples (62.7% vs 58.1%) and not at all at 1,000 (77.9% vs 81.0%). With a small LM and a task this narrow, the projector learns fast either way.
  • Fine-tuning the LM matters. A frozen LM with only the projector plateaus at 80%. It cannot learn to answer directly from visual tokens through a soft prompt alone, as §3.3 suggested.
  • The vision encoder matters most for what it was trained to see (LLaVA recipe, 4,000 examples, per question type):
frozen encodermeanleft kindright kindleft placeright placebigger?
CLIP image tower94.4%98%98%95%94%83%
SimCLR91.5%98%94%89%79%91%
MAE85.9%90%88%85%85%81%
raw 3 × 3 pixel patches74.6%80%75%75%73%71%
untrained network66.9%58%54%80%76%72%

CLIP was trained against these very words and wins. Its 3 × 6 grid of features also keeps the position.

New questions without examples. We trained on six question types only (4,000 examples) and asked the two held-out ones:

recipe“are the two shapes the same?”“which shape is bigger?”
always answer the most common answer56%38%
LLaVA recipe72%44%
from scratch0%0%

The model trained from scratch never produces a valid answer to a question it was not trained on. The text-pretrained LM transfers part of its reading skill to images without a single example. This is the generalization to unseen instructions that makes LLM-based VLMs useful, here only partial, at 0.46M parameters.


6. Multimodal generation (slides 42–48)

The slides list the generation landscape:

  • Text → image: Stable Diffusion, Parti, Imagen.
  • Text → video: Imagen Video, Make-a-Video, Phenaki, Stable Video Diffusion.
  • Text → video + audio: VideoPoet.

Four designs connect generation with the LLMs of this lecture:

  • CoDi (any-to-any; Tang et al., 2023): diffusion models for each modality whose latent spaces are aligned (CLIP-style), so they can be composed. Any subset of input modalities can condition any subset of outputs.
  • Emu (Sun et al., 2023): an LLM regresses continuous visual embeddings (with an ℓ2\ell_2 loss) in its output stream; a diffusion decoder turns them into images.
  • LaVIT (Jin et al., 2023): images become discrete visual tokens, with a dynamic number per image, predicted by the LLM with a softmax exactly like words. Video-LaVIT splits video into keyframe tokens and motion tokens (Lecture 17’s codecs).
  • LWM, the Large World Model (Liu et al., 2024): one autoregressive Transformer over text, image and video tokens with a million-token context (RingAttention, Lecture 16).

Discrete vs continuous, measured (script 04, Part 1). The same Transformer generates the 18 4 × 4 patches of an image from its caption, with three output types:

visual tokensvalidmatches captiondistinct of 4 samples
discrete patch ids, softmax (LaVIT-style)87.8%86.7%3.54
continuous patches, squared error (Emu-style)0.3%0.3%1.00
continuous patches, independent pixels3.8%3.6%3.96

A caption leaves the exact position of each shape open.

  • Regression predicts the conditional mean of the next patch: a blur of all possible positions. Thresholded, it becomes empty or broken shapes, and it is deterministic (1 distinct image of 4).
  • Independent pixel probabilities sample, but they sample pixels independently, which sprinkles noise.
  • A softmax over patch ids represents the joint distribution of a patch’s pixels and samples coherent, valid patches.

This is why LaVIT quantizes, and why Emu needs a diffusion decoder after its regression. Regressing an embedding is acceptable only if a generative decoder resolves the remaining uncertainty.

One stream for every direction (Part 2). One model was trained on text → image, image → text and image + question → answer in a single token stream. Compared with three specialists of the same architecture and the same number of updates per task:

modeltext → image: matches captionimage → text: exact captionVQA (8 types)
one model, all three tasks92.8% (valid 93.3%)100.0%95.7%
specialist: text → image90.5% (valid 91.1%)——
specialist: image → text—100.0%—
specialist: image + question → answer——92.5%

The generalist did not lose anything by sharing. It is slightly better at generation (+2.3 points) and at answering (+3.2), with every task getting the same number of training examples. Captioning is perfect for both.

The tasks share what matters: which patches make which shape, and which words describe it. Each task’s data trains the common parts for the others. The exception is “are the two shapes the same?” (66% vs the specialist’s 82%), the one question that needs a comparison rather than a lookup.

This is the bet behind LWM- and Gemini-style models, at toy scale: once everything is a token, one model per modality pair is unnecessary.


7. Summary

  1. Multimodal models connect modalities by a shared embedding space (CLIP, SigLIP), a joint encoder (M3AE), an encoder feeding a decoder (Flamingo, PaLI), or visual tokens inside a decoder-only LM (Frozen, LLaVA, GPT-4V, Gemini).
  2. CLIP as a judge is powerful: re-ranking 8 samples raised caption-faithful images from 79% to 99.7%. CLIP as a guide on pixels makes adversarial patterns: 0% valid, even below the real images’ score. Guide a generator instead. M3AE’s words lowered the pixel loss and nudged image features up by 1–2 points.
  3. Connecting a frozen LM is delicate.
    • A linear prefix into a small frozen LM is a soft prompt: it captions poorly and disturbs the LM’s reading (65%).
    • Flamingo-style gated cross-attention captions perfectly, but trained on captions alone it erases the LM’s reading (0%). Interleaved text data keeps it (98%).
    • Unfreezing the LM forgets in the same way and is fixed the same way.
  4. Visual instruction tuning needs little data because the parts are pretrained. With 250 examples: 63% vs 49% from scratch; with 4,000: 94% vs 84%. The best frozen encoder is the one trained against the same words (CLIP 94%, SimCLR 92%, MAE 86%, pixels 75%). The LM’s reading skill transfers partially to question types never trained with images (72% / 44% vs 0% from scratch).
  5. For generation, discrete visual tokens with a softmax sample valid images (87%). Regressing continuous patches averages over the uncertainty (0.3%). One token stream can carry every direction. Here it even helped: one model for three tasks generated (92.8% vs 90.5%) and answered (95.7% vs 92.5%) better than specialists given the same data.

8. Common pitfalls

  1. Optimizing pixels against CLIP and expecting an image. You get an adversarial pattern; guide a generator’s latent instead.
  2. Assuming a frozen LM stays intact. A trained prefix (soft prompt) or cross-attention layers change what the LM does on everything that follows. Measure the old skills, not only the new one.
  3. Aligning on captions only. Whatever is trainable, the model forgets what the data do not exercise. Keep text-only or interleaved data in the mix.
  4. Comparing encoders on one task. An encoder’s pretraining decides what is linearly available. CLIP’s grid kept positions here; a globally pooled feature would not.
  5. Regressing visual tokens with an ℓ2\ell_2 loss when the condition leaves the image uncertain. You get the mean: blurry, invalid, deterministic.
  6. Reading closed-model architectures off marketing material. The slides’ GPT-4V token counts come from pricing, an inference, not a specification.

9. Exercises

Exercise 1 (gates at zero — derivation). Show that a Flamingo layer h←h+tanh⁡(α) XAttn(h,v)h \leftarrow h + \tanh(\alpha)\,\mathrm{XAttn}(h, v) with α=0\alpha = 0 leaves the LM’s output unchanged, and that the gradient with respect to α\alpha at 0 is ⟨∂L/∂h,XAttn(h,v)⟩\langle \partial L/\partial h, \mathrm{XAttn}(h, v)\rangle. What does this mean for the start of training?

Answer

Unchanged output. tanh⁡(0)=0\tanh(0) = 0, so hh is unchanged and the network computes the pretrained LM exactly, for every input.

Gradient. ∂L/∂α=⟨∂L/∂h′,XAttn(h,v)⟩⋅(1−tanh⁡2(0))=⟨∂L/∂h′,XAttn(h,v)⟩\partial L/\partial \alpha = \langle \partial L/\partial h', \mathrm{XAttn}(h, v)\rangle \cdot (1 - \tanh^2(0)) = \langle \partial L/\partial h', \mathrm{XAttn}(h, v)\rangle, which is nonzero whenever the cross-attention output correlates with the direction that lowers the loss.

At the start of training:

  • Training starts from the LM’s own behaviour: no initial damage from random new layers.
  • The gate opens only as far as the visual pathway helps.
  • The cross-attention weights themselves still receive gradients, scaled by tanh⁡(α)\tanh(\alpha), which is small at first. Their own bias and α\alpha move first.

Exercise 2 (regression gives the mean — derivation). A caption allows a shape at 4 possible positions, equally likely. Show that the squared-error-optimal prediction of a pixel is the probability that it is inked. Explain why thresholding at 0.5 can erase the shape.

Answer

The minimizer of E[(x−x^)2]\mathbb{E}[(x - \hat{x})^2] is x^=E[x]\hat{x} = \mathbb{E}[x], here P(pixel inked∣caption)P(\text{pixel inked} \mid \text{caption}). A pixel inked under only one of the 4 positions has expected value 1/4 < 0.5 and is thresholded to 0. Only pixels covered under at least 3 of the 4 positions survive, so a small shape whose positions do not overlap disappears completely. Script 04: 0.3% valid images.

Exercise 3 (soft prompts — derivation). In a pre-LayerNorm Transformer, explain why the norm of a prefix embedding does not determine its influence, while its direction does.

Answer

Every block first applies LayerNorm to its input. That rescales each token’s vector to zero mean and unit variance (times learned gains), so the queries, keys and values computed from a prefix token depend only on its normalized direction. The first block’s computation is invariant to the prefix’s scale.

The scale reappears only in the residual stream: the prefix vector is added to the block’s outputs at its own position. That changes the relative size of the residual and the update for later blocks. Script 02’s visual tokens had 1/16 of a word embedding’s norm and still steered the LM strongly.

Exercise 4 (stage 2 data efficiency). In script 03, give the LLaVA recipe 250 examples of questions 1–6 only and test all 8. Predict the held-out accuracy relative to the 4,000-example run.

Answer

(Run it.) Expect lower accuracy on the held-out questions than with 4,000 examples, because the model learns less about where to look in the visual tokens. Expect it still above the from-scratch model’s 0%, since the answer format and the reading skill come from text pretraining.

Exercise 5 (GPT-4V’s token count). Using the slides’ inference (85 tokens base + 170 per 512 × 512 tile), how many tokens does a 1024 × 1536 image cost? How does that compare with LLaVA-1.5 (576 visual tokens at 336 px)?

Answer

The image is 2×3=62 \times 3 = 6 tiles: 85+6×170=1,10585 + 6 \times 170 = 1{,}105 tokens. LLaVA-1.5 uses a fixed 576 tokens (a 24 × 24 grid of ViT patches) at 336 × 336, so a large image is down-sampled.

Tiling keeps detail (OCR!) at the cost of more tokens. LLaVA-1.6’s AnyRes tiling makes the same trade.

Exercise 6 (coding). Train the Flamingo-style connector of script 02 with the gated feed-forward branch removed (only gated cross-attention). Does it still erase the LM’s reading skill when trained on captions alone?

Answer

(Run it; during development, a cross-attention-only version still reached 92% exact captions and its zero-shot VQA collapsed to 0–33% by question type.) The interference does not come from the feed-forward branch alone. Any trainable path that injects image information at every text position can override reading when the only training signal is captioning.


10. Further reading

From the slides

  • A. Radford et al. Learning Transferable Visual Models From Natural Language Supervision (CLIP), ICML 2021.
  • X. Geng et al. Multimodal Masked Autoencoders Learn Transferable Representations (M3AE), 2022.
  • A. Jain et al. Zero-Shot Text-Guided Object Generation with Dream Fields, CVPR 2022; K. Crowson et al. VQGAN-CLIP, ECCV 2022; M. Shridhar et al. CLIPort, CoRL 2022.
  • J.-B. Alayrac et al. Flamingo: a Visual Language Model for Few-Shot Learning, NeurIPS 2022.
  • M. Tsimpoukelli et al. Multimodal Few-Shot Learning with Frozen Language Models, NeurIPS 2021.
  • X. Chen et al. PaLI (2022), PaLI-X (2023), PaLI-3 (2023).
  • D. Zhu et al. MiniGPT-4, 2023; H. Liu et al. Visual Instruction Tuning (LLaVA), NeurIPS 2023; Improved Baselines with Visual Instruction Tuning (LLaVA-1.5), 2023.
  • Gemini Team. Gemini 1.5: Unlocking Multimodal Understanding Across Millions of Tokens of Context, 2024.
  • Z. Tang et al. Any-to-Any Generation via Composable Diffusion (CoDi), NeurIPS 2023; Q. Sun et al. Generative Pretraining in Multimodality (Emu), 2023; Y. Jin et al. LaVIT (2023), Video-LaVIT (2024); H. Liu et al. World Model on Million-Length Video and Language with RingAttention (LWM), 2024.

Added by these notes

  • J. Li et al. BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and LLMs, ICML 2023 (the Q-Former).
  • J. Yu et al. CoCa: Contrastive Captioners are Image-Text Foundation Models, 2022.
  • B. Lester, R. Al-Rfou, N. Constant. The Power of Scale for Parameter-Efficient Prompt Tuning, EMNLP 2021 (soft prompts work better as the LM grows — the frozen-LM result of §3.3 at small scale).
  • R. Bavishi et al. Fuyu-8B (2023): raw image patches straight into a decoder (our “raw pixel patches” encoder).

11. Next lecture

Lecture 23 is the second half of the same session: parallelization, i.e. how models like these are trained across thousands of chips. It covers hardware, collectives, sharding matmuls and layers, and data, tensor and fully sharded data parallelism.

← 返回课程目录