Search

Search papers and lessons

Flamingo: a Visual Language Model for Few-Shot Learning

Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc et al. · 2022

Flamingo joins a frozen language model to a frozen image encoder with new gated cross-attention layers, so one model can learn a vision task from a few image-and-text examples in its prompt.

On this page

  • Colour = topic mix
  • Neural network basics
  • Calculus
  • Discrete math
  • Linear algebra
  • Probability
  • Architectures
  • ReadReady to readNot yet

TL;DR

Flamingo is a family of vision-language models that can learn a new visual task from a few examples placed in the prompt, with no weight updates. It keeps a strong pretrained image encoder and a strong pretrained language model frozen, and trains only new layers that let the language model read images. Its largest version, built on a 70-billion-parameter language model, beats models fine-tuned on far more task data on several benchmarks, using only 32 examples.

Builds on: Vision-Language Model, In-Context Learning, Perceiver Transformer, Language Model · Leads to: later models that feed images to a frozen language model through inserted attention layers, and prompting with interleaved images and text.

Why it mattered

Before Flamingo, the strongest vision-language systems were of two kinds. Contrastive models such as CLIP could match images to text labels without training on each task, but they could not write free-form answers. Generative models could write captions, but they usually had to be fine-tuned on thousands of labelled examples for each new task.

Flamingo showed a single model that does both: it writes open-ended answers to questions about images and video, and it adapts to a new task from a handful of examples in its prompt. The paper reports new few-shot results on a wide range of tasks, including visual question answering, captioning, multiple-choice questions, and video question answering. Its design of inserting new layers into a frozen language model became a common reference point for later multimodal systems. The paper has been cited more than 7,000 times on Semantic Scholar.

The problem

The few-shot ability of large language models came from training on large text corpora and then prompting with examples, as in GPT-3. Vision had no equivalent. A vision model would need its input and output shapes changed for each task, and each change usually meant fine-tuning on a labelled dataset.

Three things had to be solved to get in-context learning for images:

  • The model must accept a prompt where images and text are mixed in any order, such as an example image, its answer, another image, and then a query.
  • Images and videos differ in size. The model needs a fixed number of visual inputs, however large the image or however long the video.
  • Training the whole system from scratch would throw away the knowledge in strong pretrained models. The design has to keep those models useful.

Flamingo's architecture is a response to these three points.

How it works

Here is the path of one prompt through the model, in the order the computation runs.

  1. Encode the images. Each image, or each video frame sampled at 1 frame per second, goes through a frozen vision encoder. The encoder is a Normalizer-Free ResNet (NFNet), pretrained with a contrastive loss on the paper's own image and text pairs. It outputs a grid of features, which is flattened into a sequence.
  2. Compress to a fixed size. The Perceiver Resampler takes that feature sequence, whatever its length, and produces 64 visual tokens. It does this with a small set of learned query vectors that attend to the features, as in the Perceiver Transformer.
  3. Read the text with images in place. The prompt is text with images inserted where they belong, and each image is followed by an end-of-chunk token. For example, a prompt written as <image> then text, then <EOC>, then another <image> gives the model two images, each with its place in the sequence.
  4. Attend to the right image. A text token attends only to the 64 visual tokens of the most recent image before it. It still sees earlier images indirectly through the language model's own self-attention.
  5. Condition the frozen language model. Between the frozen layers of a pretrained language model, Flamingo inserts new gated cross-attention layers. These take the visual tokens as keys and values, and the text as queries. Each new layer's output is multiplied by a learned scalar, initialised to zero, before it is added back, so the model starts out behaving exactly like the original language model.
  6. Predict the next token. The language model outputs a distribution over the next text token, as in any Autoregressive Model.
  7. Adapt by prompting. For a new task, the prompt holds a few example image and text pairs, then the query image and the start of its answer. Open-ended answers are decoded with Beam Search. Multiple-choice answers are scored by their likelihood under the model.

A tiny trace of step 4 and step 7. Suppose the prompt is one example image of a cat, with the answer "a cat", and then a second image, with the answer left blank. The text after the second image attends only to the second image's 64 visual tokens. The language model's own history still holds the first example, so it can copy the pattern and write a short caption for the second image in the same style.

The structure in one picture:

flowchart LR
  A[Images and video] --> B[Frozen vision encoder]
  B --> C[Perceiver Resampler: 64 tokens per image]
  T[Interleaved text prompt] --> D[Frozen language model layers]
  C --> E[Gated cross-attention layers, trained]
  D --> E
  E --> D
  D --> F[Next-token distribution]

The math

Step 6 in symbols: the likelihood the model learns

Let the text be yy, split into LL tokens y1,…,yLy_1, \ldots, y_L, and let xx be the interleaved images and videos. The model assigns probability to the text one token at a time:

p(y∣x)=∏ℓ=1Lp(yℓ∣y<ℓ,x≤ℓ).p(y \mid x) = \prod_{\ell=1}^{L} p\big(y_\ell \mid y_{\lt \ell}, x_{\leq \ell}\big).

Here y<ℓy_{\lt \ell} are the tokens before position ℓ\ell, and x≤ℓx_{\leq \ell} are the images that appear before token ℓ\ell in the sequence. Training minimises the negative log of this, which is the usual language-modelling loss, with the images as extra conditioning.

Step 2 in symbols: the resampler

Let FF be the variable-length matrix of image features. The resampler has K=64K = 64 learned latent queries QQ. It computes attention from the queries to the features,

Attn(Q,F)=softmax ⁣(QWq(FWk)⊤d)FWv,\mathrm{Attn}(Q, F) = \mathrm{softmax}\!\left(\frac{Q W_q (F W_k)^{\top}}{\sqrt{d}}\right) F W_v,

Here FF has nn rows, one per feature vector, and nn can be any number. QQ is the K×dK \times d matrix of learned queries. WqW_q, WkW_k and WvW_v are learned matrices that project the queries and features into a common width dd, and softmax turns each row of scores into weights that sum to 1.

So the output has shape K×dK \times d, however many feature rows FF has. This is why the cost of the visual part does not grow with the image size.

Step 5 in symbols: the gated residual update

Let hh be the hidden state from a frozen language-model layer and xattn(h,v)\mathrm{xattn}(h, v) the output of a new cross-attention block, where vv are the visual tokens. The update is

h′=h+tanh⁡(α) xattn(h,v),h' = h + \tanh(\alpha)\, \mathrm{xattn}(h, v),

where α\alpha is a learned scalar. At the start, α=0\alpha = 0, so tanh⁡(0)=0\tanh(0) = 0 and h′=hh' = h. The conditioned model matches the original language model exactly at initialisation. This is the tanh gating described in Hyperbolic Tangent and the residual form in Residual Connection.

Step 3 in symbols: the per-image mask

Text token ℓ\ell may attend only to the visual tokens of the most recent image m(ℓ)m(\ell) before it. Write the mask as

Mℓ,j={0if visual token j belongs to image m(ℓ),−∞otherwise.M_{\ell, j} = \begin{cases} 0 & \text{if visual token } j \text{ belongs to image } m(\ell), \\ -\infty & \text{otherwise.} \end{cases}

Adding MM to the attention scores before the softmax removes all other images from the cross-attention. A single image is then visible to each token, and the number of images can grow past what was seen in training.

Training: the mixture objective

The model is trained on a weighted sum over datasets m=1,…,Mm = 1, \ldots, M, each with its own weight λm\lambda_m:

∑m=1Mλm E(x,y)∼Dm[−∑ℓ=1Llog⁡p(yℓ∣y<ℓ,x≤ℓ)].\sum_{m=1}^{M} \lambda_m \, \mathbb{E}_{(x, y) \sim \mathcal{D}_m} \left[ -\sum_{\ell=1}^{L} \log p\big(y_\ell \mid y_{\lt \ell}, x_{\leq \ell}\big) \right].

Here E\mathbb{E} is the average over examples drawn from dataset Dm\mathcal{D}_m, and the inner sum is the negative log-likelihood of the whole text, as in step 6. The gradients from all datasets are accumulated into one update. The paper reports that this beats a round-robin schedule, where one dataset is used at a time.

Results

The main claims are few-shot results on 16 vision and language tasks, and the largest model is Flamingo-80B.

  • Few-shot state of the art. With few-shot prompts, Flamingo sets a new state of the art on the tasks that had published few-shot results. The paper reports that it does this for 9 tasks in total.
  • Against fine-tuned models. With only 32 examples and no weight updates, Flamingo surpasses the fine-tuned state of the art on 6 of the 16 tasks. The abstract compares this to models fine-tuned on thousands of times more task-specific data.
  • Scale. Performance grows with the size of the language model (3B, 9B and 80B) and with the number of shots in the prompt. The paper shows this in its scaling figure.
  • Fine-tuning. With a large task-specific dataset, fine-tuned Flamingo improves further, which the paper reports separately.

The ablations in Table 3 show which parts matter most, using the paper's own composite score for the 3B model, where the full model scores 70.7:

  • Removing the interleaved web data (M3W) drops the score to 53.4. This is the largest single drop.
  • Removing the image-text pairs drops it to 60.9.
  • Removing the tanh gating drops it to 66.5.
  • Using round-robin dataset training instead of accumulated gradients drops it to 62.9.
  • Adding cross-attention in only one middle layer, instead of every few layers, drops it to 59.8.

A tradeoff the paper names: adding cross-attention in every layer costs more trainable parameters and time. In its ablation, inserting the layers every fourth block sped up training by 66% while lowering the overall score by 1.9%, so the authors chose sparser placement for the larger models: every fourth block for 9B, every seventh for 80B.

Limits. The results are on 16 benchmarks, with prompts that were chosen by the authors, so few-shot scores depend on the prompt. The method relies on a very large frozen language model, so it is expensive to run. The training data is web data, so the model inherits its biases, which the paper discusses. The paper does not show results on tasks outside vision and language, such as robot control.

Try it: Flamingo-80B adds a gated cross-attention layer before every seventh block of its frozen language model, starting from the first block. Suppose a toy language model had 70 blocks. How many layers would be inserted? Answer: the insertions fall before blocks 1, 8, 15, 22, 29, 36, 43, 50, 57 and 64. The next one, before block 71, does not exist, so there are 10 inserted layers. The 70-block model is a made-up exercise; the real Chinchilla 70B count is not needed for the arithmetic.

Reading guide

The chain of ideas: a frozen image encoder turns images into features, the resampler turns any number of features into 64 tokens, new gated layers let a frozen language model attend to those tokens, and training on interleaved web data teaches the model to learn from examples in its prompt. Read the paper in its order, with these prerequisites at hand.

Check yourself

QuestionWhy does Flamingo keep the vision encoder and the language model frozen rather than training everything from scratch?Show answer

Both pretrained models already hold strong general knowledge, and training them from scratch on the multimodal data would throw that away and cost far more compute. Freezing them and training only the new layers keeps their knowledge, while the resampler and the gated cross-attention layers learn how to connect them.

QuestionA Perceiver Resampler has 64 learned queries. An image yields 1,000 feature rows. How many visual tokens does the language model see for that image, and why does this help when the image is very large?Show answer

The language model sees 64 visual tokens, not 1,000. The queries attend to the features and return one vector per query, so the number of tokens is fixed by the design. The cross-attention cost then depends on 64 rather than on the image size.

QuestionIn the gated update h′=h+tanh⁡(α) xattn(h,v)h' = h + \tanh(\alpha)\, \mathrm{xattn}(h, v), what does the model compute at the start of training, and why does that matter?Show answer

With α=0\alpha = 0, tanh⁡(0)=0\tanh(0) = 0, so h′=hh' = h and the model matches the original language model. Training starts from a model that already works as a language model, which makes training stable and keeps the pretrained knowledge intact at the start.

QuestionA user asks a Flamingo-style model a question about a video of 30 frames. Each frame gives 64 visual tokens after the resampler. Which visual tokens can the answer tokens attend to, and what does this imply about the design?Show answer

Each text token attends only to the visual tokens of the most recent image or frame before it, which is 64 tokens for the frame in question, not all 30 times 64. Earlier frames still reach the answer through the language model's own history, so the model can use them indirectly. The design keeps the cross-attention cost small while still letting the model use earlier context through self-attention.

Sources

Read the full paper

Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc et al., 2022. arXiv:2204.14198