VerifiedarXiv:2204.1419831 min
Multimodal · Vision-language

Flamingo: a Visual Language Model for Few-Shot Learning

Join a frozen vision model to a frozen language model with a few trained layers, and it learns new image tasks from examples in its prompt.

DeepMind's 2022 model reads text with images and videos placed anywhere in it and writes text. The vision encoder and the 70-billion-parameter language model inside it never change during training; the layers that connect them, 13% of the largest model, are all that learn.

Explaining the paperFlamingo: a Visual Language Model for Few-Shot LearningAlayrac, Donahue, Luc, Miech, et al. · DeepMind · NeurIPS 2022 · arXiv:2204.14198 ↗

Prompted with 32 examples and never fine-tuned, one set of Flamingo weights beat the fine-tuned state of the art on 6 of 16 image and video benchmarks, against models trained on up to hundreds of thousands of labeled examples per task.

A large language model such as GPT-3 learns a new text task from examples typed into its prompt. You write a few questions with their answers, then a new question, and the model continues the pattern with no change to its weights. GPT-3 called this in-context few-shot learning. For vision in 2022, the standard way to get a model that answers questions about photos, or captions them in a house style, was still to label thousands of images for that task and fine-tune on them. Earlier few-shot vision-language models existed but trailed far behind: the best previous few-shot score on the VQAv2 question-answering benchmark was 38.2, against 80.2 for a fine-tuned model. CLIP removed the labeling step for classification, because it scores how well an image matches each candidate label written as text, but a matching score cannot write a caption or answer an open question.

Flamingo, from DeepMind (Alayrac et al.), is a visual language model: its input is text with images and videos placed anywhere in it, and its output is text. Once trained, it takes a new image or video task the GPT-3 way, as a few (image, text) examples in the prompt. On 16 benchmarks it beat every earlier zero-shot and few-shot method, with as few as four examples per task. On six of them, one set of weights prompted with 32 examples outperformed models fine-tuned on that benchmark's own training set, which held up to hundreds of thousands of labeled examples: about 1000 times more task-specific data.

Flamingo builds very little from scratch. A pretrained vision encoder and a pretrained language model of up to 70 billion parameters are both frozen, and the new parts connect them. Five ideas explain the method, in the order this page takes them, before the ablations (which choices matter, in points) and the benchmark results:

How a Flamingo prompt works: examples instead of fine-tuning

A Flamingo prompt is a sequence of text tokens with images or videos at chosen positions. To pose a task, you write a few support examples, each an image followed by the text you want for it, then the query image, and the model continues the text. With the paper's template for non-question tasks, a two-shot captioning prompt is

# one token sequence, shown one example per line
<image>Output: This is a chinchilla.<EOC>
<image>Output: This is a shiba.<EOC>
<image>Output:

Each <image> marks where an image sits, and <EOC> (“end of chunk”) is a token added to the vocabulary that closes each example. Question-answering tasks use Question: ... Answer: ... instead. The paper keeps these two templates fixed across benchmarks (HatefulMemes and RareAct get their own), so no prompt is tuned per task.

There are two ways to read off an answer. For open-ended tasks such as captioning or free-form questions, the model generates with beam search (beam size 3) and the prediction is the text up to the first <EOC> it emits. For close-ended tasks with a fixed list of answers, each candidate is appended to the prompt, the model scores each completed sequence by its log-likelihood, and the highest-scoring candidate is the answer.

Drag the shot count in Figure 1. The bar at the bottom counts images in the prompt against the most any training sequence held, which was five.

Figure 1 · a few-shot prompt
shots2-shot
Support pairs written as <image>Output: text<EOC>, then the query image and the model's generated text. Drag from 0 to 32 shots. At 0 the examples carry no images (the paper's zero-shot format); past 4 the middle pairs are drawn as small tiles. The bar turns amber where the prompt holds more images than any training sequence.

In the paper, zero-shot means zero image examples, not zero examples. The prompt holds two examples from the task with their images removed, and the only image is the query. The paper's example:

# zero-shot: two text-only examples; the query is the only image
<BOS>Output: This is a cat wearing sunglasses.<EOC>
Output: Three elephants walking in the savanna.<EOC>
<image>Output:

The authors chose this over a written task description because a description has to be validated on labeled examples to be any good, and they argue that validation makes it not truly zero-shot (citing Perez et al.'s result that such validation is unreliable with only a handful of samples). They report that a single text example is “highly detrimental”, because outputs drift toward that one example, and that more than two helps only marginally.

At the other end of the slider, a 32-shot prompt holds 33 images, while no training sequence held more than five. Scores still rise from 4 to 32 shots on most benchmarks, for a reason the masking section gives.

How Flamingo works: two frozen models joined by trained layers

The language half of Flamingo is a pretrained Chinchilla model, DeepMind's compute-optimal language model, at 1.4, 7 or 70 billion parameters. The vision half is a pretrained NFNet-F6 image encoder, described in the next section. Both are frozen: during Flamingo training their weights receive no gradient updates. Two kinds of new modules sit between them, trained from scratch:

The obvious alternative is to fine-tune the language model on image-text data so it can adapt to images directly. The ablations on Flamingo-3B, scored on an overall benchmark score defined in the ablation section, rule it out. Unfreezing the pretrained language model lowers the score from 70.7 to 62.7, and starting from a randomly initialized one lowers it to 57.8. The paper attributes the first drop to catastrophic forgetting: trained on the new objective, the model gradually loses what it learned in pretraining. A standard remedy for forgetting is to keep training on the original text alongside the new data. The authors tried it, co-training on MassiveText (Chinchilla's pretraining set) with the LM unfrozen, and scored 68.6 starting from the pretrained LM and 55.9 starting from scratch, both below the frozen model. Freezing is also cheaper: no gradients for the language model's weights and no extra dataset to train on.

Picture the frozen language model as a finished textbook and the new layers as notes written in its margins. The printed text never changes, though what the reader takes from each page does, because each gated layer changes the hidden states that the frozen layers after it read.

Switch the model size in Figure 2 and compare where the gated layers sit and how many parameters train.

Figure 2 · frozen vs trainable
size
The frozen language model drawn layer by layer, with gated cross-attention layers inserted before layer 1 and then before every 1st, 4th or 7th layer; the Resampler's 64 tokens feed all of them. The bar is the parameter split from the paper's Table 5. Switch size: the trainable share falls from 43% at 3B to 13% at 80B.

At 80B, the frozen Chinchilla has 70 billion parameters in 80 layers. Twelve gated layers add 10 billion trainable parameters, the Resampler 0.19 billion, and the frozen NFNet-F6 0.435 billion, for 80 billion in total. The model names count everything, so Flamingo-80B contains a 70B language model, Flamingo-9B a 7B one (7.1B in Table 5) and Flamingo-3B a 1.4B one. The trainable share falls with size because the bigger models get gated layers less often: before every layer at 3B (24 gated layers), every 4th at 9B (10), every 7th at 80B (12), while the Resampler is the same at all three sizes.

The vision encoder: an NFNet trained with CLIP's contrastive loss

A frozen vision model is useful to a language model only if its features already encode the things language talks about. Flamingo gets such features the way CLIP does. Take a batch of NN image-text pairs, encode each image to a normalized vector ViV_i and each text to LiL_i, and train so that each text scores highest against its own image among all NN:

Ltxt2im=−1N∑i=1Nlog⁡exp⁡(Li⊤Viβ)∑j=1Nexp⁡(Li⊤Vjβ)L_{\text{txt2im}} = -\frac{1}{N}\sum_{i=1}^{N} \log \frac{\exp(L_i^{\top} V_i \beta)}{\sum_{j=1}^{N} \exp(L_i^{\top} V_j \beta)}Ltxt2im=−1N∑i=1Nlog⁡exp⁡(Li⊤Viβ)∑j=1Nexp⁡(Li⊤Vjβ)\begin{aligned} L_{\text{txt2im}} &= -\frac{1}{N}\sum_{i=1}^{N} \\ &\quad \log \frac{\exp(L_i^{\top} V_i \beta)}{\sum_{j=1}^{N} \exp(L_i^{\top} V_j \beta)} \end{aligned}
(3)

β\beta is a learned inverse temperature. The image-to-text loss, the paper's (4), swaps the roles of VV and LL, and the sum of the two is minimized. With the paper's batch of 16,384 pairs, each term is a 16,384-way classification: which of these images goes with this text?

Despite the shared loss, Flamingo does not use OpenAI's CLIP weights. The authors trained their own encoder from scratch: an NFNet-F6, a convolutional ResNet variant that removes batch normalization and trains stably with scaled weight standardization and adaptive gradient clipping instead. Its text partner was a BERT encoder, the data was ALIGN plus the authors' own LTIP image-text pairs, and the resolution was 288×288. Only the vision half goes into Flamingo, frozen. In the ablations, swapping it for OpenAI's public CLIP ViT-L/14 lowers the overall score from 70.7 to 64.9, and the smaller NFNet-F0 lowers it to 62.7.

From the encoder, Flamingo takes the output of the final stage, before the pooling that the contrastive loss uses: a 2D grid of feature vectors, flattened into a sequence, so spatial layout survives as separate tokens. The paper does not state the grid size. With Flamingo's 320×320 input (raised from the 288 used in contrastive training) and the NFNet's total downsampling factor of 32, it would be 10×10, about 100 feature vectors per image by our arithmetic. Video frames are sampled at one per second and encoded independently, and a learned temporal embedding is added to every feature of frame tt to record which frame it came from. An 8-frame training clip becomes about 800 features. There are no spatial position embeddings: a convolutional encoder already carries position in its channels, and the authors saw no gain from adding them.

The Perceiver Resampler: any image or video in, 64 tokens out

The number of visual features depends on the input: about 100 for one image, 800 for an 8-frame training clip, and 3,000 for the 30 frames Flamingo reads at inference (30 frames at 3 per second, with the learned temporal embeddings linearly interpolated). If text cross-attended to the raw features, the cost of every gated layer would grow with video length, and a 32-shot prompt of 33 videos would hold close to 100,000 visual features.

The Perceiver Resampler fixes the count. It owns 64 learned vectors, the latent queries, which are parameters of the module and the same for every input. In each of its 6 layers, the latents cross-attend to the visual features: the latents supply the queries, and the keys and values come from the features concatenated with the latents themselves. The authors found including the latents' own keys and values “slightly better” than using the features alone. A feed-forward layer follows each attention. The output is the 64 latents after the last layer, which become the 64 visual tokens. The design follows the Perceiver and the object queries of DETR, both of which let a small learned set of queries read a large input. The paper's pseudo-code:

# Perceiver Resampler (paper Fig. 5 pseudo-code)
# x_f: visual features [T, S, d]   (T frames, S spatial positions)
# time_embeddings: [T, 1, d]        x: 64 learned latents [64, d]
def perceiver_resampler(x_f, time_embeddings, x, num_layers=6):
    x_f = x_f + time_embeddings          # mark which frame each feature is from
    x_f = flatten(x_f)                   # [T, S, d] -> [T*S, d]
    for i in range(num_layers):
        x = x + attention_i(q=x, kv=concat([x_f, x]))
        x = x + ffw_i(x)
    return x                             # [64, d], whatever T and S were

Shapes for an 8-frame training clip: x_f is [8, 100, d] and the time embeddings [8, 1, d], added to every spatial position of their frame. Flattening gives [800, d]. The latents are [64, d], with d = 1536 in all three Flamingo models (Table 4). Each layer's attention scores 64 queries against 864 keys (800 features plus 64 latents) in each of 16 heads, and the output is [64, 1536]. The gated layers' key and value projections then map these 64 tokens to the language model's width.

In Figure 3, drag the input from one image to 30 frames. The two bars at the bottom count the keys each text token reads in one gated layer, with and without the Resampler.

Figure 3 · the resampler bottleneck
input1 frame · 100 features
Visual features (about 100 per frame, our estimate) are read by 64 learned latent queries over 6 layers, which emit exactly 64 visual tokens. Drag from 1 image to 30 frames (8 is a training clip, 30 is the inference setting): the feature cloud and the raw-key bar grow, and the output stays at 64.

The count of 64 applies to each image or video separately. A 32-shot prompt carries 33 images and so 33 × 64 = 2,112 visual tokens, and each text token reads 64 of them (the masking section explains which 64). In the ablations, at an equal parameter budget, an MLP in place of the Resampler scores 66.6 and a plain Transformer 66.7, against 70.7, and both train more slowly (1.85 s and 1.81 s per step, against 1.74 s). A small Resampler scores 67.9 and a large one 69.0; the larger one was also unstable when scaled up with the language model, so all three Flamingo sizes use the same medium Resampler of about 200 million parameters.

Gated cross-attention: how the frozen language model reads the images

Cross-attention is attention between two sequences. Each text position computes a query from its hidden state; each of the 64 visual tokens supplies a key and a value; and the text position takes an average of the values, weighted by a softmax over how well its query matches each key. Attention began as this kind of soft lookup in neural machine translation, and the original Transformer uses it as encoder-decoder attention. There is one output per text position, so the text sequence keeps its length. The image is mixed into the hidden states of the text positions, not appended as extra positions.

In numbers, for Flamingo-3B: its 24-layer language model has width 2048, so the hidden states of a 256-token training sequence form a [256, 2048] matrix. A gated layer projects the 64 visual tokens to keys and values in 16 heads of 128 dimensions, and each text position computes 64 attention scores per head. A feed-forward (“dense”) layer follows the cross-attention, hence the name xattn-dense. The new layers use a Squared ReLU activation; the frozen layers keep the GeLU they were pretrained with.

Inserting freshly initialized layers into a pretrained network causes a problem at step 0. Their outputs are random, so every frozen layer after them receives hidden states unlike anything it saw in pretraining, and the model's language ability is gone before training has started. Flamingo multiplies each new layer's output by tanh⁡(α)\tanh(\alpha) before adding it to the residual stream, where α\alpha is a learnable scalar, one per layer, initialized to 0. Since tanh⁡(0)=0\tanh(0) = 0, every new layer adds exactly zero at initialization and the model's output equals the pretrained language model's. The paper's pseudo-code for one block:

# One Flamingo block (paper Fig. 4 pseudo-code).
# y: language hidden states   x: the 64 visual tokens of the current image
# alpha_xattn, alpha_dense: learnable scalars, both initialized to 0
def gated_xattn_dense(y, x, alpha_xattn, alpha_dense):
    y = y + tanh(alpha_xattn) * attention(q=y, kv=x)   # new, trained
    y = y + tanh(alpha_dense) * ffw(y)                 # new, trained
    y = y + frozen_attention(q=y, kv=y)                # pretrained LM layer
    y = y + frozen_ffw(y)                              # pretrained LM layer
    return y      # at init tanh(0) = 0: identical to the frozen LM

Each block has two gates, one on the cross-attention and one on the feed-forward. Training can still move a gate that starts at zero. The derivative of tanh⁡(α) f\tanh(\alpha)\,f with respect to α\alpha is (1−tanh⁡2α) f(1-\tanh^2\alpha)\,f, which is ff at zero, so each α\alpha gets a gradient from the very first step. The weights inside ff get none on that step, since their contribution is multiplied by tanh⁡(0)=0\tanh(0)=0; they start learning once α\alpha has moved off zero. The tanh⁡\tanh also bounds each gate to (−1,1)(-1, 1), so a gate can flip the sign of its branch but cannot scale it up. Drag α\alpha in Figure 4 from 0, the value at initialization, up to 3.

Figure 4 · the tanh gate
αα=0.60 tanh α=0.54
The frozen language model's residual stream carries a hidden state x. The new block reads the visual tokens and produces a correction Δ, which passes a gate of value tanh⁡(α)\tanh(\alpha) before it is added back. At α=0\alpha=0 the block is the identity. Drag α\alpha up and the gate opens toward 1.

The paper credits the tanh gate to LSTMs (Hochreiter and Schmidhuber) and the zero-initialized scalar to ReZero. Without the gate the overall score falls from 70.7 to 66.5, and the authors report that training became unstable. During Flamingo-3B training the absolute gate values grow quickly away from zero in all 24 layers and end larger in deeper layers; the authors caution that the scale of activations before the gate may also vary with depth.

Gated layers cost compute and memory, which is why the bigger models get fewer of them. On Flamingo-3B, a gated layer before every fourth language-model layer instead of every layer lowers the overall score from 70.7 to 68.8 and cuts the training step from 1.74 s to 1.02 s (the paper reports this as 66% faster). Two other ways of attaching vision scored lower: Transformer-decoder cross-attention without the gated dense layer (66.9), and “grafting”, which leaves the language model untouched and stacks new cross-attention layers on its output (63.1). Flamingo-9B and -80B use every 4th and every 7th layer, the most gated layers their hardware budget allowed.

Many images in one prompt: the per-image masking rule

With several images in one sequence, each text token needs a defined set of images it may use. Write yy for the text tokens and xx for the images and videos. Flamingo models the text autoregressively:

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

Token yℓy_\ell is predicted from the earlier text y<ℓy_{<\ell} and the visual inputs x≤ℓx_{\le\ell}. The paper pins these down with a function ϕ\phi that maps each text position to the index of the last image or video before it, or 0 if none has appeared yet; x≤ℓx_{\le\ell} is the set of images with index at most ϕ(ℓ)\phi(\ell). In the sequence t1 <img1> t2 t3 <img2> t4, ϕ\phi gives 0 for t1, 1 for t2 and t3, and 2 for t4.

The cross-attention is narrower than Eq. (1). A text token cross-attends to the 64 visual tokens of exactly one image, image ϕ(ℓ)\phi(\ell), and is masked from all others. Earlier images still reach it through the language model's self-attention: the text that followed image 1 took in image 1 through its own cross-attention, and later tokens attend to that text. Equation (1)'s conditioning on every earlier image is thus split into a direct path from the latest image and an indirect path through the text.

Click a text token in Figure 5, or step through them with the slider, and switch between Flamingo's mask and the attend-to-all variant.

Figure 5 · per-image masking
t4
An interleaved sequence of images and text. In the mask (rows are text tokens, columns are images), Flamingo's rule lights one column per row, image ϕ(ℓ)\phi(\ell); t1 comes before any image, so its row is empty. Toggle to attend-to-all, the ablated variant, where each row lights every earlier image.

Attending to all previous images scored 63.5 in the extended ablation (Table 10), 7.2 points below the single-image rule. The authors' explanation is that with all images pooled into the keys, nothing in the cross-attention tells one image from another. They tried numbered image tags and learned per-image index embeddings, and neither held up when the number of images changed between training and test. Under the single-image rule, every text token sees the same kind of input, 64 tokens of one image, whether the prompt holds 2 images or 33. Training on sequences of at most 5 images is therefore enough for 32-shot prompts.

On web pages, “the image before the text” is not always the right one. A caption can sit above its photo (“This is my dog! <dog image>”) or below it (“<dog image> That was my dog!”). So for the web-page training data the authors flip a fair coin per page: with probability pnext=1/2p_{\text{next}} = 1/2, text on that page is mapped to the next image instead of the previous one. The coin scored 70.7, against 69.6 for always-previous and 70.4 for always-next. Evaluation prompts always put each image before its text, so at test time the previous-image rule matches the data.

Training data and the loss: 43 million web pages plus image-text pairs

The few-shot ability comes from training on interleaved data, sequences in which images and text alternate the way they do in a prompt. The authors built MultiModal MassiveWeb (M3W) from the HTML of about 43 million web pages. They extracted the text and images, placed each image by its position in the page's document structure, inserted an <image> tag there, and inserted <EOC> before each image and at the end of the document. A training example is a random 256-token window of a page with at most the first 5 images in it; further images are dropped to save compute.

Three paired datasets fill in the rest:

Each pair is rewritten in M3W syntax, with <image> before the caption and <EOC> after it, so it reads like a one-image web page. The training objective is a weighted sum over the datasets of the expected negative log-likelihood of the text given the images:

∑m=1Mλm⋅E(x,y)∼Dm[−∑ℓ=1Llog⁡p(yℓ∣y<ℓ, x≤ℓ)]\sum_{m=1}^{M} \lambda_m \cdot \mathbb{E}_{(x,y)\sim \mathcal{D}_m}\Big[ -\sum_{\ell=1}^{L} \log p\big(y_\ell \mid y_{<\ell},\, x_{\le\ell}\big) \Big]∑m=1Mλm⋅E(x,y)∼Dm[−∑ℓ=1Llog⁡p(yℓ∣y<ℓ, x≤ℓ)]\begin{aligned} &\sum_{m=1}^{M} \lambda_m \cdot \mathbb{E}_{(x,y)\sim \mathcal{D}_m}\Big[ \\ &\qquad -\sum_{\ell=1}^{L} \log p\big(y_\ell \mid y_{<\ell},\, x_{\le\ell}\big) \Big] \end{aligned}
(2)

Dm\mathcal{D}_m is the mm-th dataset and λm\lambda_m its weight. The loss covers text tokens only, since images are inputs and are never predicted. It includes <EOC>, which is how the model learns to end an answer. The weights are 1.0 for M3W, 0.2 for ALIGN and for LTIP, and 0.03 for VTP; the paper calls tuning them “key to performance”.

Every update draws a batch from each dataset, computes each weighted loss, and sums the four gradients before a single optimizer step. The alternative, round-robin, takes each update from one dataset in turn; in the ablation it scored 62.9 against 70.7. Accumulation is also why the ablation runs count 1 million gradient computations as 250,000 updates. In code:

# One Flamingo update: gradients summed over all four datasets (Eq. 2)
LAMBDA = {"M3W": 1.0, "ALIGN": 0.2, "LTIP": 0.2, "VTP": 0.03}
grads = zeros_like(trainable)        # Resampler + gated layers only
for name, lam in LAMBDA.items():
    x, y = next_batch(name)          # images/videos x, text tokens y
    logp = flamingo(x, y)            # log p(y_l | y_<l, x_<=l) per text token
    loss = lam * (-logp.sum(axis=1)).mean()
    grads += grad(loss, trainable)   # NFNet and LM weights: forward pass only
optimizer.step(trainable, grads)     # one update per four-dataset round

Only the Resampler and the gated layers receive a gradient. The NFNet and the language model run forward only, which is why raising the input resolution from 288 to 320 pixels for Flamingo training cost little: no backpropagation runs through the vision encoder.

Which design choices matter: the Flamingo ablations

The ablations train Flamingo-3B on a shorter schedule and evaluate at 4 shots on the five benchmarks the authors used for development decisions: COCO (image captioning), OKVQA and VQAv2 (image question answering), MSVDQA (video question answering) and VATEX (video captioning). Each benchmark has its own metric, so the paper divides each score by the fine-tuned state of the art on that benchmark (from its Table 1) and averages the five ratios:

overall=1005∑k=15skskFT\text{overall} = \frac{100}{5}\sum_{k=1}^{5} \frac{s_k}{s_k^{\text{FT}}}

For the full model the five ratios are 86.5/143.3, 42.1/54.4, 55.8/80.2, 36.3/47.9 and 53.4/76.3, which are 0.604, 0.774, 0.696, 0.758 and 0.700. Their mean, 0.706, gives 70.6 against the reported 70.7 (the table's inputs are rounded). Differences on this page are points of this score: “−8.0” means 70.7 became 62.7. Because these five benchmarks guided design decisions, their scores may be optimistic, and the paper also reports 11 benchmarks that were never used for any choice.

Figure 6 collects the rows. Start with the headline group, then switch groups and click bars to compare per-benchmark scores and step times.

Figure 6 · what each choice is worth
row53.4
Overall score of Flamingo-3B at 4 shots with one choice removed or swapped (paper Table 3; rows marked Table 10 are from the extended ablations). The full model scores 70.7; the faded amber span is each change's cost. Switch groups; click a bar for its five benchmark scores and step time.

The largest drops come from the training data and from what is frozen: no M3W −17.3, a language model trained from scratch −12.9, no image-text pairs −9.8, an unfrozen language model −8.0, round-robin updates −7.8. The architectural pieces cost less: the tanh gate 4.2, the Resampler's replacements about 4, gating every fourth layer 1.9. Per benchmark, removing M3W takes VATEX from 53.4 to 23.5, and unfreezing the language model costs the question-answering benchmarks most (OKVQA 42.1 to 33.7) while VATEX holds at 53.9.

Few-shot results against fine-tuned models

The paper's Table 1 lists every Flamingo model at 0, 4 and 32 shots on 16 benchmarks, next to the best earlier zero- or few-shot result and the best fine-tuned result. Figure 7 divides each Flamingo score by the fine-tuned score on that benchmark, the same normalization as the overall score, so a bar past 100% beats a model trained on that benchmark's training set.

Figure 7 · few-shot vs fine-tuned
model
shots
benchmarkOKVQA
Flamingo's score on each benchmark divided by the fine-tuned state of the art (Table 1). Bars past the dashed 100% line are wins; amber ticks mark the best earlier zero/few-shot result where one existed. Pick a model and shot count; click a row for the raw numbers.

At Flamingo-80B with 32 shots, six bars cross 100%: OKVQA (57.8 vs 54.4), MSVDQA (52.3 vs 47.9), Flickr30K (75.4 vs 67.4), iVQA (45.3 vs 35.4), STAR (42.2 vs 36.7) and NextQA (33.5 vs 25.2). The fine-tuned models behind those lines trained on 6,000 to 46,000 task examples each; Flamingo saw 32. The largest remaining gaps are COCO captioning (113.8 vs 143.3 CIDEr), YouCook2 (86.8 vs 138.7) and VQAv2 (67.6 vs 80.2), whose fine-tuned models had up to 500,000 examples. At 0 shots Flamingo-80B already crosses on iVQA, STAR and NextQA. Smaller models and fewer shots lower almost every bar (at 3B, 32 shots crosses on four benchmarks), and the paper notes that the largest model makes better use of extra shots than the smaller ones. RareAct, the 16th benchmark, is zero-shot only and has no fine-tuned score; Flamingo-80B gets 60.8 against an earlier 40.7.

With more labeled data, Flamingo can also be fine-tuned. The language model stays frozen, the Flamingo layers train as before, and the input resolution rises from 320 to 480 pixels. The vision encoder is unfrozen too, which the authors found typically improves results, likely in part because of the higher resolution. Fine-tuned this way, Flamingo set a new state of the art on five more benchmarks: VQAv2, VATEX, VizWiz, MSRVTTQA and HatefulMemes.

When a task has more support examples than fit in a prompt, such as classification over hundreds of classes, the paper chooses the prompt by retrieval (RICES, from Yang et al.). It embeds the query image with the frozen vision encoder, takes the support examples whose images are most similar, and orders them from least to most similar, so that the closest example sits right before the query.

Later vision-language models kept the pattern of a pretrained language model joined to a pretrained vision encoder by a small trained connector. BLIP-2 freezes both models and trains a querying transformer between them, and LLaVA maps CLIP features into the language model's input with a trained projection, then fine-tunes the language model as well in its second stage.

Limitations

The paper lists these, most of them inherited from the language model:

The paper's Table 2 shows what fine-tuning on a full training set adds over 32 shots: VQAv2 rises from 67.6 to 82.0 (test-dev) and COCO captioning from 113.8 to 138.1.

Provenance Verified against primary literatureHow we verify
Brown et al. 2020 (GPT-3)In-context few-shot learning from examples in the prompt, which Flamingo carries over to image and video prompts.
Hoffmann et al. 2022 (Chinchilla)The frozen 1.4B, 7B and 70B language models inside Flamingo-3B, -9B and -80B.
Radford et al. 2021 (CLIP)The two-term contrastive loss used to pretrain Flamingo’s own NFNet-F6 encoder. OpenAI’s CLIP ViT-L/14 appears only as an ablation baseline (64.9 vs 70.7).
Brock et al. 2021 (NFNet)The normalizer-free convolutional backbone, F6 variant, 435M parameters. Its stem and stage strides give a total stride of 32, which is the basis of this page’s 10x10-grid estimate; the Flamingo paper does not state the grid size.
Jaegle et al. 2021 (Perceiver); Carion et al. 2020 (DETR)A fixed set of learned latent queries cross-attending to a variable-size input. Flamingo adds the latents’ own keys and values to the attended set (App. A.1.1).
Hochreiter & Schmidhuber 1997 (LSTM); Bachlechner et al. 2021 (ReZero)The paper cites LSTM for the tanh gate and ReZero for the zero-initialized scalar alpha (Sec. 2.2, refs [41] and [4]).
Flamingo arXiv source, figures/fig4_xattn_dense.pdf and fig3_resampler.pdfThe pseudo-code quoted on this page, read from the paper’s source files: two gates per block (alpha_xattn, alpha_dense, both init 0) and the Resampler loop with kv = concat([x_f, x]).
Yang et al. 2021 (RICES); Perez et al. 2021Retrieval-based selection of in-context examples, and the argument that validating prompts on labeled data is not zero-shot.
correctionFew-shot Flamingo beats the fine-tuned state of the art on six of the 16 benchmarks, as the introduction, Figure 2, Section 3.1 and the conclusion say, and as Table 1 itself shows (OKVQA, MSVDQA, Flickr30K, iVQA, STAR, NextQA at 80B, 32 shots). The Table 1 caption says "seven"; six is correct. Two unit notes on Section 3.3: the ablation drops it writes as "−8.0%" are differences in points of the overall score (70.7 − 62.7 = 8.0), not relative percentages; and "inserting them every fourth block accelerates training by 66%" corresponds to Table 3 step times of 1.74 s and 1.02 s, which is 1.71 times the throughput.

Questions you might still have

?

Is Flamingo’s vision encoder OpenAI’s CLIP?
No. The authors trained their own NFNet-F6 from scratch with the CLIP contrastive loss on ALIGN plus their own LTIP image-text data, then froze it. OpenAI’s CLIP ViT-L/14 appears only as an ablation baseline, where it scores 64.9 against the NFNet-F6’s 70.7.

?

Does Flamingo-80B contain an 80-billion-parameter language model?
No. It contains the frozen 70B Chinchilla. The 80B counts everything: 70B LM, 10B of gated cross-attention layers, 0.19B Resampler and the 0.435B vision encoder. Flamingo-9B wraps a 7B LM and Flamingo-3B a 1.4B one.

?

If a text token cross-attends to only one image, how can it use earlier images?
Through the language model’s self-attention. Text after image 1 took in image 1 through its own cross-attention, and every later token can attend to that text. The likelihood in Eq. (1) conditions on all earlier images; the mask splits that into a direct path from the latest image and an indirect path through the text.

?

What does zero-shot mean in the Flamingo paper?
Zero image examples. The prompt holds two text-only examples from the task, for format, and the query image. The authors chose this over a hand-written task description because validating such a description needs labeled examples. One text example was highly detrimental (outputs copied it) and more than two helped only marginally.

?

Why not fine-tune the language model on image-text data?
In the ablations it scores lower: unfreezing the pretrained LM gives 62.7 against 70.7, which the paper calls catastrophic forgetting, and co-training on the LM’s original text data while unfrozen still gives only 68.6. Freezing also saves the gradient computation for every LM weight.

?

How many visual tokens does a 32-shot prompt use?
33 images (32 examples plus the query) times 64 tokens each, so 2,112 visual tokens. Each text token reads only the 64 of the image just before it, so the per-token cross-attention cost does not grow with the number of shots.

?

Can Flamingo generate images?
No. It takes text interleaved with images and videos as input and produces only text. Images enter through the vision encoder and the Resampler; the training loss in Eq. (2) is over text tokens only.

Footnotes & further reading

  1. The paper: Alayrac, Donahue, Luc, Miech et al., Flamingo: a Visual Language Model for Few-Shot Learning (DeepMind, NeurIPS 2022). Pseudo-code for the gated block and the Resampler is in Figures 4 and 5.
  2. In-context few-shot learning: Brown et al., Language Models are Few-Shot Learners (GPT-3). Our explainer: GPT-3.
  3. The frozen language models: Hoffmann et al., Training Compute-Optimal Large Language Models (Chinchilla). Our explainer: Chinchilla.
  4. The contrastive loss used to pretrain the vision encoder: Radford et al., Learning Transferable Visual Models From Natural Language Supervision (CLIP). Our explainer: CLIP.
  5. The vision backbone: Brock, De, Smith, Simonyan, High-Performance Large-Scale Image Recognition Without Normalization (NFNet; adaptive gradient clipping and the F0 to F6 family).
  6. The Resampler's ancestors: Jaegle et al., Perceiver: General Perception with Iterative Attention, and Carion et al., End-to-End Object Detection with Transformers (DETR). Our explainer: DETR.
  7. The gate's sources as the paper cites them: Hochreiter & Schmidhuber, Long Short-Term Memory (1997), for tanh gating; Bachlechner et al., ReZero is All You Need, for the zero-initialized scalar.
  8. On validating prompts in few-shot evaluation: Perez, Kiela, Cho, True Few-Shot Learning with Language Models. Retrieval-based example selection: Yang et al., An Empirical Study of GPT-3 for Few-Shot Knowledge-Based VQA.