TAI BUI
Back to curriculum
LearnPython

Flamingo and Gated Cross-Attention for Few-Shot VLMs

Flamingo (DeepMind, 2022) showed two things before anyone else. One model could process arbitrarily interleaved images, video, and text. And a VLM could learn in context: give it three (image, caption) examples and it captions a new image with no gradient step. The mechanism is a set of gated cross-attention layers inserted between a frozen LLM's existing layers, with a learned tanh gate that starts at zero so the text capability is intact at initialization. The Perceiver resampler and gated cross-attention are the ancestors of Gemini's interleaved inputs and Idefics2's visual tokens.

TIME: ~120 minutesPREREQUISITES: Phase 12 · 03 (BLIP-2 Q-Former)

Learning Objectives

  • Explain how gated cross-attention preserves a frozen LLM's text capability at initialization via tanh(gate) = 0.
  • Walk through a Perceiver resampler: N image patches → K fixed "latent" queries via cross-attention.
  • Describe how Flamingo handles interleaved image-text sequences with causal masking that respects image placement.
  • Reproduce a few-shot multimodal prompt structure (3 image-caption examples then a query image).

The Problem

BLIP-2 feeds 32 visual tokens into a frozen LLM's input layer. That works for one image per prompt. Now try interleaving many images with text: "here is image A, caption it; here is image B, caption it; now here is image C, caption it." The LLM's self-attention would have to handle image tokens and text tokens in a single stream, and deciding which positions can attend to which images gets fussy.

Flamingo's answer is to leave the LLM's input stream alone. Insert extra cross-attention layers between existing LLM blocks. Text tokens still flow through the LLM's causal self-attention as usual, and every few blocks they also cross-attend to image features through a new gated layer. The gate starts at zero, so at step zero the new layers are no-ops and the model behaves like the pretrained LLM. As training progresses the gate opens and visual information starts flowing.

The second question Flamingo had to answer: how do you handle a variable number of images (0, 1, or many) per prompt? A Perceiver resampler, a small cross-attention module, takes whatever number of patches you have and produces a fixed number of visual latent tokens. The LLM's cross-attention layer sees the same shape however many images are in the prompt.

Warm-up0/3
1. In BLIP-2, how does the Q-Former connect a frozen image encoder to a frozen LLM?Warm-up
A row of four boxes: image, frozen image encoder, a dashed box reading Q-Former with a question mark, and a frozen LLM, with arrows left to right.
Typed schematic, not captured.
2. Where do BLIP-2's visual tokens enter the frozen LLM?Warm-up
A box of Q-Former visual tokens above a row of six boxes: input layer, block 1, block 2, an ellipsis, block N and softmax. A dashed outline around the whole row is marked with a question about where the tokens enter.
Typed schematic, not captured.
3. In cross-attention, where do the queries and the keys/values come from?Warm-up
Two token sequences, sequence 1 with tokens a1 to a3 and sequence 2 with tokens b1 to b4, above an attention layer with three dashed slots asking where the queries, keys and values come from.
Typed schematic. The tokens are placeholders.
Check: The Problem0/1
1. Why does Flamingo leave the LLM's input stream alone and add cross-attention layers between blocks?Explain
Flamingo's layout: a text input stream passes through an LLM block, an added cross-attention layer fed from above by image features for images A, B and C, and a second LLM block. A line gives the prompt order.
Typed schematic. Arrows show the direction the data flows.

The Concept

The frozen LLM

Flamingo starts with a frozen Chinchilla 70B LLM. None of the 70B weights change, and the existing text self-attention and FFN run as they did before.

Perceiver resampler

For each image in the prompt, the ViT produces N patch tokens. The Perceiver resampler has K fixed learnable latents (Flamingo uses K=64). Each resampler block has two sub-steps:

  1. Cross-attention: the K latents attend over the N patch tokens (Q from latents, K/V from patches).
  2. Self-attention + FFN within the latents.

After 6 resampler blocks, the output is K=64 visual tokens of dim 1024, whatever the ViT's patch count. A 224x224 image (196 patches) and a 480x480 image (900 patches) both exit as 64 resampler tokens.

For video, the resampler is applied temporally: each frame's patches produce 64 latents, and a temporal positional encoding lets the model distinguish t=0 from t=N. The full video becomes T * 64 visual tokens.

Gated cross-attention

Between every M layers of the frozen LLM (Flamingo uses M=4), insert a new gated cross-attention block:

x_after_llm_block = llm_block(x_before)
cross = cross_attn(x_after, resampler_output)
gated = tanh(alpha) * cross + x_after
x_before_next_block = gated
  • alpha is a learnable scalar initialized to zero.
  • tanh(0) = 0, so at init the gated branch contributes zero.
  • As alpha moves away from zero, the cross-attention contribution grows smoothly.
  • Because of the residual connection, even a wide-open gate does not overwrite the LLM's text representation. It adds visual information on top.

This is the design choice that matters most in Flamingo. Visual conditioning is additive, gated, and zero at initialization, so on text-only inputs a Flamingo at step 0 behaves like Chinchilla 70B.

Masked cross-attention for interleaved inputs

In a prompt like " caption A caption B ?", each text token should only see images that came before it in the sequence. The cross-attention mask enforces this: the text token at position t attends only to resampler tokens of image i_t, the most recent image before position t. "Sees only the last preceding image" and "sees all preceding images" are both valid choices, and Flamingo chose the former.

In-context few-shot learning

A Flamingo prompt looks like:

<image1> A photo of a cat. <image2> A photo of a dog. <image3> A photo of a

The model sees the completion pattern and outputs "bird" (or whatever image3 shows), with no gradient steps. The frozen LLM's in-context learning carries through the gated cross-attention. That is the punchline of the paper.

Training data

Flamingo trained on three datasets:

  1. MultiModal MassiveWeb (M3W): 43M web pages with interleaved images and text, in reading order.
  2. Image-Text Pairs (ALIGN + LTIP): 4.4B pairs.
  3. Video-Text Pairs (VTP): 27M short video clips.

OBELICS (2023) is an open reproduction of the interleaved web corpus, which Idefics, Idefics2, and most open "Flamingo-like" models train on.

OpenFlamingo and Otter

OpenFlamingo (2023) is the open reproduction. The architecture is the same (Perceiver resampler + gated cross-attention on a frozen LLaMA or MPT), with checkpoints at 3B, 4B, and 9B. Quality lags Flamingo because of the smaller base LLM and less data.

Otter (2023) builds on OpenFlamingo with instruction tuning on MIMIC-IT (a dataset of multimodal instructions), which shows gated cross-attention works for instruction following too.

The descendants

  • Idefics / Idefics2 / Idefics3: Hugging Face's gated cross-attention lineage, getting simpler over time. Idefics2 dropped the resampler for direct patch tokens with adaptive pooling.
  • Flamingo-to-Chameleon transition: by 2024 many teams had moved to early fusion (Lesson 12.11). Flamingo-style gated cross-attention still shows up in production where the backbone has to stay frozen.
  • Gemini's interleaved input: conceptually inherits Flamingo's interleaved-format flexibility, though the mechanism is proprietary.

Comparison to BLIP-2

BLIP-2Flamingo
Visual bridgeQ-Former once at inputGated cross-attention at every M layers
Visual tokens32 per image64 per image per cross-attn layer
Frozen LLMYesYes
Few-shot in-contextWeakStrong, the paper's centerpiece
Interleaved inputsNo native supportYes, the design target
Training data130M pairs1.3B pairs + 43M interleaved pages
Parameter count188M trained~10B trained (cross-attn layers)
ComputeDays on 8 A100sWeeks on thousands of TPUv4

Pick BLIP-2 for single-image VQA on a budget. Pick Flamingo/Idefics2 for interleaved, few-shot, or multi-image reasoning.

Check: The Concept0/27
1. What is a Perceiver resampler?Define
A box of ViT patch tokens, an arrow into a box labelled Perceiver resampler, and an arrow out to a box labelled visual tokens. Nothing inside the resampler is drawn.
Typed schematic. Names only.
2. What is gated cross-attention?Define
A frozen LLM block, then a block titled gated cross-attention with a dashed inside question mark and visual tokens from the resampler entering from above, then another frozen LLM block.
Typed schematic. One gated block is drawn between two LLM blocks.
3. What is an interleaved input?Define
A web page sketch with five stacked blocks: paragraph, photo, paragraph, photo, paragraph. An arrow leads to a dashed box asking what the model reads.
Typed schematic of a page layout.
4. What does it mean that Flamingo uses a frozen LLM?Define
A Flamingo sketch: image features go to a Perceiver resampler and then to gated cross-attention layers, which feed a box for the text LLM. Text tokens enter that box and text comes out. The LLM box is dashed and reads weights during training with a question mark.
Typed schematic. Arrows show the direction the data flows.
5. What is few-shot prompting for a model like Flamingo?Define
Three cards on the left: example 1 and example 2, each a photo plus an answer, and a new task with a photo and an unknown answer. An arrow leads to a Flamingo box and a dashed question about how the examples are used.
Typed schematic. The photos and answers are placeholders.
6. What is OBELICS?Define
A card reading OBELICS (2023) with the citation Laurençon et al., arXiv:2306.16527, and an arrow to a dashed box asking what OBELICS is. A line notes the paper is listed under Further Reading.
Typed card. Nothing here describes the dataset itself.
7. What role does Chinchilla play in Flamingo?Define
Five name cards from the lesson: ViT, Perceiver resampler, gated cross-attention layers, text tokens, and a dashed Chinchilla card reading role in Flamingo with a question mark. No roles are given for the others.
Typed cards. Roles are left out on purpose.
8. What is the gate schedule?Define
Empty axes for training step and alpha with a dashed box in the middle reading alpha over time with a question mark.
Typed sketch. The axes carry no numbers.
9. How often does Flamingo insert a gated cross-attention block into the frozen LLM?Define
A row of nine blocks numbered 1 to 9 with a circled question mark in each of the eight gaps, and a line asking where Flamingo puts its gated cross-attention blocks.
Typed schematic. The count of nine blocks is illustrative.
10. Which checkpoint sizes does OpenFlamingo ship, and how does its quality compare with Flamingo?Define
A card reading OpenFlamingo (2023), an open reproduction of Flamingo with the same architecture, above two dashed boxes asking about checkpoint sizes and about quality next to Flamingo.
Typed card from the Concept section.
11. Which three datasets did Flamingo train on?Define
Three dashed boxes labelled dataset 1, dataset 2 and dataset 3, each with an arrow into a Flamingo box.
Typed schematic. The stem says Flamingo trained on three datasets.
12. What does Otter add on top of OpenFlamingo?Define
Three boxes in a row: Flamingo, OpenFlamingo on a frozen LLaMA or MPT, and a dashed box reading Otter adds with a question mark.
Typed schematic. Otter (2023) builds on OpenFlamingo (2023).
13. Which statement about the Flamingo lineage is accurate?Define
A family tree of names: Flamingo points to OpenFlamingo, which points to Otter, and to Idefics, which points to Idefics2 and then Idefics3.
Typed schematic. Solid arrows: built from or follows. Idefics is Hugging Face's lineage.
14. The Perceiver resampler receives a variable number of ViT patches per image. What does it output?Explain
Three patch grids of different sizes labelled 36, 196 and 900 patches, an arrow to a Perceiver resampler box, and an arrow to a dashed box reading output with a question mark.
Typed schematic. Grid cells stand for patches.
15. You add gated cross-attention layers to a frozen LLM and run a text-only prompt before any training. What do you expect?Explain
A text-only prompt box with arrows to two models, the original frozen LLM and an LLM with new gated layers before any training, each leading to an output box. The first output is a reference and the second is a dashed box with a question mark.
Typed schematic. No prompt text or outputs are shown.
16. Why does a wide-open gate not overwrite the LLM's text representation?Explain
x_after, the text representation, goes into a block titled gated cross-attention with the gate wide open and tanh(alpha) close to 1, while visual tokens enter from above. The output is a dashed box with a question mark.
Typed schematic.
17. In '<image A> caption A <image B> caption B <image C> ?', which images can a text token cross-attend to under Flamingo's masking?Explain
A prompt drawn as six boxes in order: image A, caption A, image B, caption B, image C and a highlighted question token. A dashed box asks which images that token can cross-attend to.
Typed schematic. Boxes stand for the prompt's images and text.
18. How does Flamingo's resampler handle video?Explain
Four frames labelled frame 1 to frame 4, an arrow to a resampler box, and an arrow to a dashed box reading output with a question mark, above a line asking how the resampler treats the clip.
Typed schematic. Four frames are drawn for illustration.
19. Why is few-shot in-context learning called the centerpiece of the Flamingo paper?Explain
A one-row table: few-shot in-context learning is weak for BLIP-2 and strong, the paper's centerpiece, for Flamingo. A dashed box asks why Flamingo is strong at it.
Typed from the Comparison to BLIP-2 table.
20. Following the lesson's pattern, how is a 3-shot captioning prompt laid out?Apply
Seven boxes in no particular order: caption 2, image 3, caption 1, query image, image 1, caption 3 and image 2, above a dashed bar asking what the prompt looks like left to right.
Typed schematic. The pieces are placeholders, listed in no particular order.
21. A 10-frame video goes through the resampler with K=64 latents per frame. How many visual tokens result?Apply
Ten numbered frame boxes with an arrow to a resampler box reading K equals 64 latents per frame, and an arrow to a dashed box reading visual tokens with a question mark.
Typed schematic. Numbers are the stem's.
22. A prompt has three 480x480 images (900 patches each). The text token '?' after the third image cross-attends. How many resampler tokens can it see?Apply
Three image boxes, each 480x480 with 900 patches, followed by a highlighted question token, and a dashed bar asking how many resampler tokens the question token can see.
Typed schematic. Boxes stand for the prompt's images and the final text token.
23. A team inserts gated cross-attention into a frozen LLM but starts alpha at a large random value. Text-only output is already degraded at step 0. Which property did they lose?Analyze
Two cards: the pretrained LLM with a text-only baseline, and the team's model at step 0 with alpha initialised to a large random value. A red line says the team's text-only output is degraded, and a dashed bar asks which property the team lost.
Typed schematic. The setup is the stem's.
24. A teammate edits the mask so that t1a sees IMG0 as well as IMG1 (all preceding images). Which description fits?Analyze
The sequence IMG0, t0a, t0b, IMG1, t1a as five boxes with t1a highlighted and two arcs from t1a to IMG1 and to IMG0, labelled as the teammate's edit. A dashed bar asks what kind of change this is.
Typed schematic. Arcs show which images t1a may attend to after the edit.
25. Team A must label single product photos on a small GPU budget. Team B needs a model to reason over five screenshots interleaved with chat text. Which pairing fits?Design
Two team cards. Team A labels single product photos on a small GPU budget and shows one photo box. Team B reasons over five screenshots interleaved with chat text and shows five screenshot boxes. A dashed bar asks for the pairing of models to teams.
Typed schematic. Boxes stand for photos and screenshots.
26. You must add vision to a frozen 70B LLM, keep its text-only quality intact, and support prompts with anywhere from 0 to 10 images. Which design fits?Design
A frozen 70B LLM card that must keep its text-only quality, next to three example prompts holding 0, 3 and 10 image boxes, and a dashed bar asking which design fits.
Typed schematic. Three example prompts are drawn: 0, 3 and 10 images.
27. You want each text token to reason over all earlier images in a multi-image prompt. What is the smallest change in the Flamingo-style design?Design
A prompt drawn as six boxes: IMG0, t0a, IMG1, t1a, IMG2 and a highlighted t2a, with three dashed arcs from t2a to the three earlier images, and a dashed bar asking for the smallest change in the design.
Typed schematic. Dashed arcs show the visibility the team wants.

Use It

code/main.py runs three demos:

  1. A Perceiver resampler on 36, 196, and 900 random patch tokens, each reduced to 8 latents with pure Python cross-attention. The output shape is the same for all three.
  2. A gated cross-attention step with alpha = 0, where the output equals the input (LLM unchanged), then alpha = 2.0, where the visual contribution is mixed in (tanh(2.0) is about 0.96).
  3. An interleaved-mask builder that produces the 2D attention mask for a sequence of images and text, where each text token sees only the most recent preceding image.
Check: Use It0/6
1. In demo 1, patch tokens of dimension 16 go through the resampler with num_latents=8. What does it return for 500 patches?Apply
A code panel with a list of 500 patches of dimension 16, a call to perceiver_resampler with num_latents 8 and num_blocks 2, and a final line asking what the number of latents and their dimension are.
Adapted from demo 1 in main.py (500 patches instead of 36, 196 and 900). Typed, not run.
2. In demo 2, the gated step runs with alpha=0.0. What does the max delta against the input come out as?Apply
A code panel creating 5 text hidden states and 8 visual tokens of dimension 16, calling gated_cross_attention_step with alpha 0.0, and a last line asking for the max delta of the output against text_hidden.
Adapted from demo 2 in main.py. Typed, not run.
3. In demo 2, alpha is changed to 2.0. How much of the cross-attention output is added to the input?Apply
A code panel creating 5 text hidden states and 8 visual tokens of dimension 16, calling gated_cross_attention_step with alpha 2.0, and a last line asking what share of the cross-attention output is added.
Adapted from demo 2 in main.py. Typed, not run.
4. In demo 3, the sequence is IMG0, t0a, t0b, IMG1, t1a, t1b, t1c, IMG2, t2a. Which mask entries are True in the row for t1b?Apply
The sequence IMG0, t0a, t0b, IMG1, t1a, t1b, t1c, IMG2, t2a as nine boxes with t1b highlighted, above an empty grid with rows for the six text tokens and columns IMG0, IMG1 and IMG2, with the t1b row outlined.
Typed schematic. Rows are text tokens, columns are image tokens.
5. With the code in demo 3, the sequence is ['t0', 'IMG0', 't1']. What does the row for t0 contain?Apply
Three boxes for the sequence t0, IMG0, t1 with t0 highlighted, above an empty grid with rows t0 and t1 and one column IMG0, the t0 row outlined, and a line asking what the row for t0 contains.
Typed schematic. Rows are text tokens, the column is the image token.
6. A reader runs demo 1 and says the resampler clearly learns to compress 900 patches into 8 useful latents. What is wrong with that?Analyze
A quoted claim, the resampler learns to compress 900 patches into 8 useful latents, above a code panel that makes 900 patches of dimension 16 and calls perceiver_resampler with 8 latents, and a dashed bar asking what is wrong with the claim.
Adapted from demo 1 in main.py. Typed, not run.

Ship It

This lesson produces outputs/skill-gated-bridge-diagnostic.md. Given an open VLM's config (resampler Y/N, cross-attn frequency, gate scheme), it identifies the Flamingo lineage elements and explains the freezing strategy. It helps when a fine-tune has degraded text performance, where the likely cause is a gate that got too wide too fast.

Check: Ship It0/1
1. After fine-tuning an open Flamingo-style VLM, its text-only quality dropped. Where should you look first?Analyze
A flow of three boxes: an open Flamingo-style VLM, fine-tune, and text-only quality marked as dropped, above a dashed bar asking where to look first.
Typed schematic. Nothing is measured here.
Author's Note

I'd run main.py and read the second demo before anything else. With alpha=0.0 it prints a max delta of 0.000000 against the input, which is the argument for the gate in one line. With alpha=2.0 the average delta is nonzero, because the cross-attention output is added at about 0.96 of its full weight.

I'd also keep the toy in proportion. Nothing trains here. The resampler draws its latents as fresh random vectors on each call, runs 2 blocks of plain cross-attention with a residual, and has no projections, no self-attention, and no FFN. So the 36, 196, and 900 patch runs all coming out as 8 latents shows why the output size is fixed, and says nothing about what a trained resampler learns. The gate is only checked at two fixed values of alpha, which means the schedule for how fast it opens is not in the code. When a fine-tune loses text quality, that schedule is where I'd look first.

The mask is the piece I'd poke at. Changing the rule from the last preceding image to all preceding images is a small edit to which entries get set to True, and I'd try both on the 9-token demo sequence before reading the paper's argument for its choice.

Exercises

  1. Compute Flamingo-9B's visual parameter count: 9B LLM + 1.4B gated cross-attention layers + 64M resampler. What fraction of total params is trained?

  2. Implement the gated residual y = tanh(alpha) * cross + x in PyTorch. Show experimentally that with alpha=0, y==x exactly at init.

  3. Read OpenFlamingo Section 3.2 (arXiv:2308.01390) on how they handle multiple images in a batch when each prompt has a different image count. Describe the padding strategy.

  4. Why does Flamingo's cross-attention mask let a text token attend to only the most recent preceding image rather than all preceding images? Read the Flamingo paper Section 2.4 and explain the tradeoff.

  5. In-context few-shot: construct a prompt with 4 examples of "image → color of main object" for a new Flamingo variant. Describe the expected accuracy pattern as you vary the number of examples from 0 to 8.

Key Terms

TermWhat people sayWhat it actually means
Perceiver resampler"Fixed-latent cross-attention"Module that produces K fixed tokens from a variable number of input patches
Gated cross-attention"Tanh-gated bridge"Residual layer y = tanh(alpha)*cross + x, learnable alpha, init 0
Interleaved input"Mixed sequence"Prompt format with images and text mixed freely in reading order
Frozen LLM"No LLM gradients"The text LLM's weights do not update; only resampler + cross-attn layers train
Few-shot"In-context examples"Give a few (image, answer) pairs in the prompt; model generalizes without finetuning
OBELICS"Interleaved web corpus"Open dataset of 141M web pages with images and text in reading order
Chinchilla"70B frozen base"Flamingo's frozen text LLM, from DeepMind's Chinchilla paper
Gate schedule"How alpha moves"The rate at which the cross-attention gate opens during training
Cross-attn frequency"Every M layers"How often a gated cross-attention block is inserted; Flamingo uses M=4
OpenFlamingo"Open reproduction"MosaicML/LAION open checkpoint at 3-9B; architecture-identical to Flamingo

Further Reading

Code

Ships With