Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

~11 min readDeepMind · 2022

Flamingo,
explained.

You have a brilliant language model and a brilliant vision model, each trained at enormous cost. How do you make them talk — without retraining either? Flamingo's answer is a bridge: freeze both, compress each image into a handful of tokens, and thread them into the language model through new attention layers that start switched off so they can't break what already works. The result learned new vision-language tasks from a few examples in the prompt, the way GPT-3 learned text tasks. Here's the connector, and the gate that makes it safe.

The delta

What changes against CLIP: the model can talk about the image

Rung 1 puts images and text in one space, which supports matching and retrieval and not generation — it can tell you which of several captions fits, and it cannot write one. What you want is a language model that can see, and the obvious route is to train one on images and text together from scratch, which is enormously expensive and risks a model worse at language than the language models already available.

The change is to keep the language model frozen and add sight around it, which preserves everything it knows at zero risk. Two mechanisms make that work. A resampler maps however many visual features an image or a run of video frames produces down to a fixed, small number of tokens, so visual input has a constant cost regardless of resolution or frame count. And cross-attention layers are inserted between the frozen model's existing layers so it can read those tokens.

The detail worth carrying up the ladder is how those inserted layers avoid damaging the model they are inserted into. Each is wrapped in a gate initialised at exactly zero, so at the start of training the inserted layer contributes nothing and the network computes bit-for-bit what the original language model computed. Vision is then faded in as the gate opens, rather than arriving as a perturbation that has to be recovered from. Training on interleaved image-and-text documents rather than isolated pairs is what then gives it few-shot behaviour: show it two labelled examples and a third image, and it continues the pattern.

01

Bridging two frozen models

By 2022 the field had superb pretrained pieces: vision encoders like CLIP that turn images into rich features, and large language models fluent in text. The obvious goal was a model that could do both — read an image and reason about it in words. The expensive way is to train one giant multimodal model from scratch. Flamingo took the cheap, elegant route: keep both pretrained models frozen and train only a small connector between them.

Freezing is the whole strategy. It preserves the language model's hard-won abilities and the vision encoder's perception, and it makes training far cheaper — only the bridge learns. But it raises two engineering questions. Vision encoders emit a variable, often large number of features per image (and far more per video); how do you feed that into a language model expecting a tidy token stream? And how do you inject visual information into a frozen model without disrupting the delicate weights that make it work? Flamingo answers both.

The one-sentence version

Freeze a vision encoder and a language model; compress each image to a few tokens with a resampler, and inject them through cross-attention layers that start switched off so the language model is never broken.

02

The Perceiver Resampler

The first component solves the variable-size problem. A vision encoder might produce hundreds of feature vectors for one image, thousands for a video — and that count changes with resolution and length. The Perceiver Resampler maps any such set to a fixed, small number of latent tokens. It does this with cross-attention: a fixed set of learned query vectors (say 64 of them) attend to the visual features and absorb them, producing exactly 64 output tokens no matter how many features came in.

Because M is fixed, the cost of everything downstream — feeding vision into the language model — is constant, independent of image resolution or video length. A 576-feature image and a 2,304-feature one both become 64 tokens; the language model sees the same tidy, bounded input either way. The runnable version below confirms the fixed output and the constant downstream cost.

03

Gated cross-attention

Now the delicate part: inject those visual tokens into a frozen language model without wrecking it. Flamingo interleaves new gated cross-attention layers between the language model's existing (frozen) layers. Each new layer lets the text tokens attend to the visual tokens — but its output is multiplied by a learnable tanh(α) gate, with α initialized to zero:

output = text + tanh(α) · cross-attention(text → vision) ,   αinit = 0

At initialization tanh(0) = 0, so the cross-attention contributes exactly nothing and the model is bit-for-bit the original language model — untouched, unbroken. As training proceeds, the gates α gradually open, smoothly letting visual information flow in. This zero-init trick is what makes adding a modality to a frozen model safe: you begin from a known-good model and only ever add, never disrupt. The runnable version below shows the gate starting at 0 and opening.

04

Interleaved training

To get few-shot multimodal ability, Flamingo trains on interleaved image-and-text sequences — web pages and documents where images and words are naturally mixed, images appearing inline with the text about them. The model learns to predict the text given the interspersed images, with attention masking so each text span cross-attends only to the most recent image that precedes it.

Flamingo, assembled
Vision encoderFrozen. Turns each image into a set of features.
Perceiver ResamplerTrained. Compresses features → fixed latent tokens.
Gated cross-attnTrained. Injects visual tokens into the LM; tanh gate starts at 0.
Language modelFrozen. Generates text, now conditioned on vision.

Training on interleaved data is what teaches Flamingo to handle a prompt like "here's an image and its caption; here's a second; now caption this third image" — the multimodal analogue of in-context few-shot prompting. The same interleaving that appears in training appears at inference as the prompt format.

How it works

How Flamingo reads interleaved images and text

Flamingo maps any interleaved run of images, videos and text to text. Two frozen pretrained networks do most of the work, the trainable parts sit between them, and a mask decides which picture each word may look at, which is the detail most descriptions of Flamingo leave out.

Image 1 Image 2 Image 3 resampler 64 tokens 64 tokens 64 tokens Two cats. A dog. Output: cross-attn self-attention sees image 1 only sees image 2 only sees image 3 only Gated block between frozen LM layers h ← h + tanh(α) · xattn(h, image φ(ℓ)) h ← h + tanh(α′) · ffw(h) At init α = α′ = 0: exactly the frozen LM
The per-image mask: each word's cross-attention reads only the latest image's 64 tokens. Earlier images arrive indirectly, through self-attention over the text that followed them.
  1. Freeze a vision encoder. An NFNet-F6 image encoder is pretrained contrastively on image–text pairs, CLIP-style, then frozen. Its final feature grid is flattened into a set of vectors. For video, frames are sampled at one per second, encoded independently, tagged with learned temporal embeddings and flattened into one set.
  2. Resample to 64 tokens. In the Perceiver Resampler, 64 learned latent queries cross-attend to the visual features through a few Transformer layers. Unusually, the keys and values are built from the visual features concatenated with the latents themselves, which the authors found worked slightly better. The output is 64 visual tokens per image or per video clip.
  3. Mark the images in the text. An <image> tag replaces each image at its position in the text, and an end-of-chunk token is added before every image and at the end of the document.
  4. Give each word one image. For each text token ℓ, φ(ℓ) is the index of the last image that appears before it, and the cross-attention mask lets token ℓ read only that image's 64 tokens; text before the first image reads none. Earlier images still reach later words, indirectly, through the language model's own self-attention over the text that followed them.
  5. Insert gated blocks. New GATED XATTN-DENSE blocks sit between the frozen language-model layers: a cross-attention sublayer, with queries from the text and keys and values from the visual tokens, then a feed-forward sublayer, each added residually after multiplication by tanh of its own learned scalar, which starts at 0. Flamingo-3B adds a block before every layer, Flamingo-9B every fourth layer and Flamingo-80B every seventh.
  6. Choose the language models. Frozen Chinchilla models of 1.4B, 7B and 70B parameters give Flamingo-3B, -9B and -80B. "Small connector" is relative: in Flamingo-80B the new gated layers come to about 10B trainable parameters, plus a resampler of about 194M.
  7. Train on a weighted mixture. M3W, text and images extracted from about 43 million web pages, sampled as 256-token chunks with at most 5 images; ALIGN, 1.8 billion images with alt text; LTIP, 312 million images with longer descriptions; and VTP, 27 million short videos with descriptions, about 22 seconds long on average. The loss is a weighted sum of each dataset's next-token loss on the text, with gradients from all four accumulated in every update.
  8. Prompt it at test time. A prompt is a few support examples, each an image followed by its text (a caption, or a question and its answer), then the query image. Open-ended answers come from beam search; multiple-choice tasks are scored by each option's log-likelihood. Support examples can be picked with RICES, which retrieves the pool examples whose images look most like the query.
The math

Flamingo's likelihood, gates and per-image mask

p(y | x) = ∏ℓ=1…L p(yℓ | y<ℓ, x≤ℓ)
h ← h + tanh(α) · Attn(Q = h, K = V = Rφ(ℓ))
h ← h + tanh(α′) · FFW(h)
L = Σm λm · Lm, Lm = average over dataset Dm of −Σℓ log p(yℓ | y<ℓ, x≤ℓ)
  • yℓ — the ℓ-th text token; only text is ever predicted, never images
  • x≤ℓ — the images and videos that appear before token ℓ in the sequence
  • φ(ℓ) — the index of the last image before ℓ, or 0 if there is none; Rφ(ℓ) is that image's 64 resampler tokens
  • α, α′ — one learned scalar for each sublayer of each inserted block, both initialized at 0
  • λm — the weight of dataset m among M3W, ALIGN, LTIP and VTP

At α = α′ = 0, tanh(0) = 0 and both new sublayers add nothing, so p(y | x) is exactly the frozen language model's probability for the text. Gradients still flow: the derivative of tanh at 0 is 1, so at the first step the gate scalars receive gradient while the cross-attention weights behind them receive none. Large |α| saturates tanh at ±1, so a gate can pass its sublayer's full output but never amplify it. And although each cross-attention reads only Rφ(ℓ), the likelihood still conditions on every earlier image, which reaches token ℓ through self-attention.

The evidence

Flamingo's 16 benchmarks and its ablations

All three sizes were tested on 16 image and video benchmarks covering captioning, visual question answering, dialogue and classification, prompted with 0 to 32 examples and fine-tuned only where stated. Design choices were made on 5 development benchmarks (COCO, OK-VQA, VQAv2, MSVD-QA, VATEX); the other 11 were never used for design decisions, so they give unbiased few-shot estimates. The largest run used 1,536 TPU chips for 15 days.

Result (Flamingo-80B)Value
Benchmarks with a new few-shot state of the art16 of 16
Benchmarks where 32 examples beat the fine-tuned state of the art6, with about 1,000 times less task-specific data
Fine-tuned, new state of the art on 5 moreVQAv2, VATEX, VizWiz, MSRVTT-QA, HatefulMemes
Images per sequenceat most 5 in training, up to 32 shots at test time

The ablations train Flamingo-3B variants and report one overall score across the development benchmarks; the full model scores 70.7.

ChangeOverall score
Remove the interleaved M3W data53.4
Remove the image–text pairs60.9
Train the LM from scratch / fine-tune the pretrained LM57.8 / 62.7
Single cross-attention layer in the middle of the LM59.8
Round-robin over datasets instead of accumulating gradients62.9
CLIP ViT-L/14 instead of NFNet-F664.9
Remove the tanh gating66.5
MLP / plain Transformer instead of the Perceiver Resampler66.6 / 66.7

The interleaved web data matters most; without it the model loses the largest share of its score in the whole study. Without the zero-initialized gate, training became unstable. Unfreezing the language model hurt whether it was fine-tuned or trained from scratch, which the paper ties to catastrophic forgetting of its pretraining. A separate test of the mask itself found that attending only to the most recent image scored 7.2% better overall than attending to all previous images.

Since then

What the authors admit, and what happened next

Freezing the language model is the design and also the limit: its knowledge is frozen too, so the system cannot learn anything that requires changing what the model knows, only how it is conditioned. The connector is also heavy — a resampler plus cross-attention layers threaded through the whole stack is a substantial amount of new machinery to train and to serve.

The interleaved training data was proprietary, which made the result difficult to reproduce and is a large part of why rung 3's much simpler approach was the one that spread.

How it held up: the strategy won and the specific connector did not. Freeze a capable language model, attach a comparatively small bridge from another modality, and train the bridge — that is how essentially every multimodal model is built. And the zero-initialised gate is the single most reusable trick here: adding a component that begins as an exact no-op, so initialisation cannot hurt, appears again in adapter-based fine-tuning on the post-training ladder and is worth reaching for whenever you extend a network you do not want to break.

SOLVE IT YOURSELF

Fixed tokens, and a gate that opens

Flamingo's two ideas are each a couple of lines. The Perceiver Resampler outputs a fixed number of tokens no matter the input size — a 576-feature image and a 2,304-feature one both become 64 tokens (9× and 36× compression), so the downstream cross-attention cost is identical either way. And the gated cross-attention uses tanh(α) with α starting at 0, so at init the visual contribution is exactly zero and the frozen language model is preserved — then grows as α opens. Change the feature counts or the gate value and watch it hold.

YOUR TASK

Write the body of gated_output. Everything else in the file is already written; this is the function the paper is about. Press ▶ Run to check it against the 5 assertions below — they start red.

WHAT IT HAS TO SATISFY — 5 ASSERTIONS
  1. The resampler output is a fixed M regardless of N
  2. The compression ratio is N/M
  3. Downstream cross-attn cost is fixed (uses M, not N)
  4. The tanh gate at init (alpha=0) contributes nothing
  5. The gated contribution grows with alpha
CPython · WebAssembly
06

The template it set

Flamingo's architecture — freeze strong pretrained encoders, train a lightweight connector — became a dominant template for visual language models. The specific pieces recur throughout the field: resampler-style compression of visual tokens (and its cousins, like Q-Former in BLIP-2), and lightweight connectors that graft vision onto a frozen or lightly-tuned LLM (as in CLIP-plus-projector systems). The zero-initialized gate — adding a new capability by starting from a no-op — shows up wherever you want to extend a pretrained model safely.

Its deeper lesson is about composition. Rather than train one monolithic model to do everything, Flamingo showed you can take excellent specialist models and stitch them together with a small learned interface, inheriting both their strengths at a fraction of the cost. As pretrained components proliferate, that compositional approach — bridge, don't rebuild — has only grown more central to how multimodal systems are built.

Worth knowing

The Perceiver Resampler is a descendant of the Perceiver architecture, whose whole idea is to map arbitrarily large inputs onto a fixed-size latent array via cross-attention — decoupling model cost from input size, the same trick Flamingo uses for vision.

Questions

Questions people ask about Flamingo

How does the Flamingo Perceiver Resampler work?

The Perceiver Resampler turns a variable number of visual features into exactly 64 tokens. Flamingo's frozen NFNet-F6 encoder produces a grid of features for each image; for video, frames are sampled at one per second, encoded separately, given learned temporal embeddings and flattened into one set. A fixed set of 64 learned latent vectors then cross-attends to those features through a few Transformer layers, with keys and values built from the visual features concatenated with the latents themselves, which the authors found worked slightly better. The output is 64 tokens per image or per clip, whatever the resolution or frame count. In the ablations it beat both an MLP and a plain Transformer used in its place.

How is Flamingo different from BLIP-2?

Both keep a pretrained image encoder and a pretrained language model frozen, but they connect them differently. Flamingo inserts new gated cross-attention layers inside the language model, so text can attend to visual tokens at many depths, and it trains on interleaved web pages, which is what gives it few-shot prompting with several images. BLIP-2, from Salesforce in 2023, adds no layers to the language model: a Q-Former with 32 learned queries is first trained on image–text objectives, then its outputs are projected and placed in front of the text as soft prompts. BLIP-2 reports beating Flamingo-80B by 8.7% on zero-shot VQAv2 with 54 times fewer trainable parameters, but shows no in-context learning, which its authors attribute to training on single image–text pairs.

Why does each text token in Flamingo attend to only one image?

In Flamingo's cross-attention layers, a text token reads only the visual tokens of the last image that appears before it, and text before the first image reads none. Earlier images are not lost, because the language model's own self-attention can reach the text that followed them. The authors tested the alternative directly: attending to all previous images scored 7.2% worse overall than attending to the most recent one. The rule also explains how a model trained on sequences of at most 5 images handles prompts with 32: each cross-attention always sees exactly one image's 64 tokens, so the number of images in a prompt never changes the shape of what the new layers read.

Why is Flamingo's tanh gate initialized at zero?

Each inserted cross-attention and feed-forward sublayer is multiplied by tanh of a learned scalar that starts at 0. At initialization the product is zero, so the network computes exactly what the frozen language model computes, and training begins from a model that already writes fluent text. As the scalar moves away from zero, the visual signal is blended in gradually instead of arriving as a large random perturbation. The ablation shows it matters: removing the gating lowered Flamingo-3B's overall score from 70.7 to 66.5, and the authors report that training without it was unstable. Each gate is a single number per sublayer, so the safety it buys costs essentially no parameters.

What data was Flamingo trained on?

A weighted mixture of four datasets. M3W was built from the HTML of about 43 million web pages, keeping text and images in their original order; each training sample is a 256-token chunk with up to 5 images. ALIGN contributes 1.8 billion images with alt text, LTIP 312 million images with longer descriptions, and VTP 27 million short videos, about 22 seconds long on average, with sentence descriptions. The loss is a weighted sum of each dataset's next-token loss on the text, with gradients from all four accumulated in every update. M3W was the most important ingredient: without it the overall ablation score fell from 70.7 to 53.4. M3W, LTIP and VTP were not publicly released, which made the result hard to reproduce.

How does Flamingo do few-shot prompting, and what is RICES?

A Flamingo prompt is a short run of support examples, each an image followed by its text, such as a caption or a question with its answer, and then the query image followed by an open prefix for the model to complete. Open-ended answers are generated with beam search; for multiple-choice tasks each option is scored by its log-likelihood. RICES, retrieval-based in-context example selection, chooses the support examples by visual similarity: features from the frozen vision encoder are compared with the query image's, the closest examples in the pool are retrieved, and they are ordered so the most similar one sits right before the query. Flamingo was evaluated with up to 32 shots.

Check yourself

4 questions to test what you just read

Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.

A 4-shot prompt contains five images. How many visual tokens does it hold in total, and how many can one token of the answer cross-attend to?

Show answer

5 × 64 = 320 visual tokens in the prompt, but each answer token's cross-attention reads only 64: those of the query image, the last one before it. The other 256 reach the answer only indirectly, through the frozen language model's self-attention over the text that followed each support image.

Predict Flamingo-80B's output on a text-only document at the very first training step, compared with the 70B Chinchilla it was built from. Which parameters get gradient at that step?

Show answer

The outputs are identical, because every inserted sublayer is multiplied by tanh(0) = 0. At that step only the gate scalars receive gradient, since the derivative of tanh at 0 is 1; the cross-attention and feed-forward weights behind each gate get none, because their output is multiplied by zero. Once the gates move, the new layers start learning.

A 30-second video sampled at one frame per second goes in, then a single photo. How many visual tokens does each become after the Perceiver Resampler?

Show answer

64 each. The 30 frames are encoded separately, given learned temporal embeddings and flattened into one feature set before resampling, so the clip costs the same 64 tokens as the photo. The price is that all of the clip's temporal detail has to fit into those 64 latents.

Flamingo trained on sequences with at most 5 images, yet kept improving up to 32 shots. How does the single-image mask make that possible?

Show answer

Each text token's cross-attention always reads exactly one image's 64 tokens, so the new layers see inputs of the same size whether the prompt holds 5 images or 32. The number of images only lengthens the text sequence, which the frozen language model already handles. A mask over all previous images would hand the new layers inputs larger than anything seen in training.

Where this sits

One model, many senses

Joining text to images, audio, video and finally to a robot arm. Starts with the contrastive objective the whole field standardised on.

  1. 1CLIP2021
  2. 2Flamingo2022
  3. 3LLaVA2023
  4. 4wav2vec 2.02020
  5. 5Whisper2022
  6. 6V-JEPA2024
  7. 7RT-22023
  8. 8Genie2024

All 110 papers, in 19 ladders →

Flamingo: a Visual Language Model for Few-Shot Learning · Alayrac, Donahue, Luc, Miech, et al. · DeepMind · NeurIPS 2022 · read the original paper on arXiv → · Vibe Engines · 2026
Finished this one? 0 / 110 Paper Breakdowns done
NextLLaVA Next on the “One model, many senses” ladder · rung 3 of 8

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Paper Breakdowns