Search

Search papers and lessons

Q-Former

Level 4 · 11 min read

Q-Former is a small transformer with 32 learnable query vectors that reads frozen image features and passes only the text-relevant summary on to a language model.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Losses & regularization
  • Sign in to see your progress

TL;DR

Q-Former is a small transformer that sits between a frozen image encoder and a frozen language model. It holds a fixed set of 32 learnable query vectors. The queries attend to the image features through cross-attention and return 32 vectors, whatever the image size. Only Q-Former is trained, and the language model receives those 32 vectors as a short visual prompt.

Where you'll see it: the bridge module in BLIP-2, which connects a frozen vision encoder to a frozen language model through this small trainable module.

Intuition

A fixed set of questions about the picture

Imagine you must describe a photo to someone who will only read a short note. You do not write down every pixel. You ask a few questions first: what objects are there, what colour is the sky, is anyone smiling. The answers become the note. Q-Former works the same way. Its learnable queries are the questions, and the attention layers let each question look at the image and collect the answer that matters.

The important word is "learnable". The queries are ordinary parameter vectors, trained like any weight matrix. Nobody tells them which questions to ask. Training finds the questions that make the output useful for the text paired with each image.

Why a bottleneck helps

A vision encoder produces many features. For example, a ViT-L/14 produces 257 vectors of width 1024 for a 224×224224 \times 224 image. A language model reads text tokens, and feeding it hundreds of raw visual vectors is expensive and forces it to learn vision from scratch. Q-Former cuts the visual side down to 32 vectors of width 768 (see Example 1). The language model then sees a short, already-summarised prompt.

The size of the bottleneck is also a design choice that carries information. If the 32 queries are too few, detail is lost. If they are too many, the language model gets too much to read. The paper uses 32, and that number is part of the method, not a tuning detail that happens to be convenient.

flowchart LR
  I[Image] --> V[Frozen image encoder]
  V --> F[257 patch features]
  Q[32 learnable queries] --> QF[Q-Former]
  F -->|cross-attention| QF
  T[Text] --> QF
  QF --> Z[32 output vectors]
  Z --> L[Frozen language model]

The math

Architecture

Q-Former has two transformer sub-modules that share their self-attention layers. The image transformer takes the learnable queries as input and attends to the frozen image features. The text transformer takes text tokens and can act as a text encoder or a text decoder. In every block where cross-attention is inserted (every other block), the queries attend to the image features.

Definition: Q-Former output

Let Q∈RK×d\mathbf{Q} \in \mathbb{R}^{K \times d} be the learnable query matrix, with KK queries of width dd, and let F∈RN×dv\mathbf{F} \in \mathbb{R}^{N \times d_v} be the frozen image features with NN patches of width dvd_v. The output is

Z=QFormer(Q,F)∈RK×d.\mathbf{Z} = \mathrm{QFormer}(\mathbf{Q}, \mathbf{F}) \in \mathbb{R}^{K \times d}.

The output size depends only on KK and dd, not on NN.

Here KK is the number of queries (32 in the paper), dd is the hidden width of Q-Former (768), NN is the number of patches the image encoder produces, and dvd_v is that encoder's feature width. The key fact is that Z\mathbf{Z} has the same shape for every image, so a higher-resolution image does not make the language model's input longer.

Q-Former is initialised from the pre-trained weights of BERT-base, a 12-layer encoder with width 768 (see BERT). The cross-attention layers are new and randomly initialised. The whole module has 188M parameters. The queries are counted as model parameters.

Attention masks

All three representation-learning objectives use the same weights and the same input. They differ only in which tokens are allowed to attend to which. Let Z\mathbf{Z} be the query tokens and T\mathbf{T} the text tokens. The masks are:

  • Unimodal (contrastive loss): queries and text cannot see each other. Each side builds its own representation.
  • Multimodal causal (generation loss): queries attend to each other but not to text. Each text token attends to all queries and to earlier text tokens.
  • Bidirectional (matching loss): queries and text attend to each other freely.

The mask is the mechanism that forces the queries to carry the information. In the generation mask, the text tokens can only receive visual information through the queries, because there is no direct path from the frozen image encoder to the text.

Stage one: image-text representation

The first stage trains Q-Former against the frozen image encoder with three losses.

Image-text contrastive loss (ITC). The text representation t\mathbf{t} is the output of the text transformer's [CLS] token. The image-text similarity takes the best of the KK query outputs:

s(I,T)=max⁡kcos⁡(zk,t),cos⁡(a,b)=a⊤b∥a∥ ∥b∥.s(I, T) = \max_{k} \cos\big(\mathbf{z}_k, \mathbf{t}\big), \qquad \cos(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a}^\top \mathbf{b}}{\lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert}.

The loss then contrasts each image with the texts in its batch, as in CLIP-style training. The paper uses in-batch negatives rather than the momentum queue of BLIP, because the frozen encoder makes it cheap to fit more samples per GPU.

Image-grounded text generation (ITG). The model predicts the caption tokens one at a time, conditioned on the image through the queries. The first text token is a special [DEC] token in place of [CLS]. This is ordinary next-token cross-entropy with the causal mask above.

Image-text matching (ITM). Each output query goes through a two-class linear classifier. The logits are averaged over the queries to give one matched-or-not score. The paper uses hard negatives, pairs that look similar but do not match, chosen with the method of BLIP.

The three losses are summed. ITC pulls the queries towards the text, ITG makes them carry everything the caption says, and ITM checks fine-grained agreement.

Stage two: vision-to-language generation

The second stage attaches the frozen language model. A linear layer WW maps each query output to the language model's embedding width, and the projected queries are placed in front of the text embeddings:

pk=W zk,input=[p1;… ;pK;e(x1);… ;e(xM)].\mathbf{p}_k = W\,\mathbf{z}_k, \qquad \text{input} = [\mathbf{p}_1; \dots; \mathbf{p}_K; \mathbf{e}(x_1); \dots; \mathbf{e}(x_M)].

Here e(xm)\mathbf{e}(x_m) is the embedding of text token mm. The projected queries act as soft visual prompts. For a decoder-only language model, the loss is ordinary language-modelling cross-entropy on the text. For an encoder-decoder model, the text is split into a prefix, which goes into the encoder next to the visual prompts, and a suffix, which is the decoder's target. Only WW and Q-Former are trained. The language model and the image encoder stay frozen.

Worked examples

Example
Example 1: how much the bottleneck compresses

Compare the size of the visual input the language model would receive in two cases.

  1. Raw features from ViT-L/14 for one image: 257×1024=263,168257 \times 1024 = 263{,}168 numbers.
  2. Q-Former output: 32×768=24,57632 \times 768 = 24{,}576 numbers.
  3. Ratio: 263,168/24,576≈10.7263{,}168 / 24{,}576 \approx 10.7.

The language model reads about ten times fewer visual numbers. The compression is not a lossy resize. It is a learned choice of what to keep, and the training objectives judge the kept part by how well it predicts the paired text.

Example
Example 2: picking the best query for a match (toy numbers)

Suppose Q-Former gave three queries of width 2 for one image, and the text embedding is t=(1,0)\mathbf{t} = (1, 0). These numbers are illustrative, not from the paper.

  1. z1=(0.6,0.8)\mathbf{z}_1 = (0.6, 0.8). Cosine with t\mathbf{t}: 0.6/0.62+0.82=0.6/1.0=0.600.6 / \sqrt{0.6^2 + 0.8^2} = 0.6 / 1.0 = 0.60.
  2. z2=(−1,0)\mathbf{z}_2 = (-1, 0). Cosine: −1/1=−1.00-1 / 1 = -1.00.
  3. z3=(0.2,−0.4)\mathbf{z}_3 = (0.2, -0.4). Cosine: 0.2/0.22+0.42=0.2/0.447≈0.450.2 / \sqrt{0.2^2 + 0.4^2} = 0.2 / 0.447 \approx 0.45.
  4. Take the maximum: s=max⁡(0.60,−1.00,0.45)=0.60s = \max(0.60, -1.00, 0.45) = 0.60.

The image-text score is set by query 1, the single query that best matches the text. The other queries did not matter for this score. This is why the 32 queries can specialise: each one can own a different aspect of the image, and the text picks out the relevant one.

Example
Example 3: how many samples the paper's settings imply

The paper gives the training schedule. Multiplying steps by batch size gives the number of image-text samples the model sees.

  1. Stage one with ViT-L/14: 250,000×2,320=580250{,}000 \times 2{,}320 = 580 million samples.
  2. Stage one with ViT-g/14: 250,000×1,680=420250{,}000 \times 1{,}680 = 420 million samples.
  3. Stage two with OPT: 80,000×1,920=153.680{,}000 \times 1{,}920 = 153.6 million samples.
  4. Stage two with FlanT5: 80,000×1,520=121.680{,}000 \times 1{,}520 = 121.6 million samples.

The pre-training set is 129M images. So stage one sees each image several times, and the samples are drawn from a pool of about 129M images, each with its captions. Counts are arithmetic from the stated settings; the paper does not report the number of epochs directly.

Tradeoffs and failure modes

Q-Former's strength is that it is cheap to train and keeps both large models frozen. Its weakness is that the bottleneck is fixed, so a question that needs a detail the 32 queries did not capture cannot be answered later.

SituationProblemBetter choice
Frozen encoder and frozen LLM, little computeOnly a small module can be trainedQ-Former or a similar small bridge
Fine detail matters (small text, dense scenes)32 vectors may drop detailsMore queries, or pass patch tokens through
Many images per promptEach image adds 32 tokens to the LLM inputFewer queries, or a model with a longer context
The LLM must learn vision from scratchA frozen LLM cannot adapt to imagesTrain the LLM too, or use an interleaved design
Need a single global embedding for searchThe 32 vectors are not one vectorPool them, or use a Bi-Encoder with a dedicated pooled output

A common failure is blaming the language model for missing detail that Q-Former never extracted. Check the bottleneck first. Another is evaluating only the zero-shot numbers. The reported gains depend on the frozen encoder and LLM chosen, so a comparison should keep those fixed.

History

Q-Former was introduced in BLIP-2 by Junnan Li, Dongxu Li, Silvio Savarese and Steven Hoi, all at Salesforce Research. It was published in January 2023 as a way to get vision-language pre-training without training a large model from scratch. The earlier BLIP paper had already used the same three representation-learning objectives on a model trained end to end. BLIP-2 kept the objectives and moved the heavy parts into frozen models.

The idea of a small set of learned queries that read a large set of visual features had earlier relatives. Flamingo, in 2022, used a Perceiver Resampler with learned latent vectors for a similar purpose. Q-Former initialises from a pre-trained BERT-base and pairs the module with off-the-shelf frozen models, which keeps the trainable part small (188M parameters).

Check yourself

QuestionRecall: how many learnable queries does BLIP-2's Q-Former use, and what is the width of each output vector?Show answer

It uses 32 queries. Each output query has width 768, the same as the hidden width of Q-Former. The output is therefore a 32×76832 \times 768 matrix, which is much smaller than the 257×1024257 \times 1024 features of ViT-L/14.

QuestionComputation: a Q-Former output has K=32K = 32 and d=768d = 768. How many numbers does the language model receive from one image if the visual prompt is the projected output, with projection width dLM=2048d_{\text{LM}} = 2048?Show answer

The projection WW maps each query from width 768 to width 2048. The output is 32×2048=65,53632 \times 2048 = 65{,}536 numbers. The count of visual tokens is still 32, which is what the language model pays for in context length. The total width grows with the projection, but the sequence length does not.

QuestionWhy: why does the generation loss use a causal mask on the text and stop queries from seeing text, while the matching loss allows full attention?Show answer

In the generation loss, the model must predict the next caption token. If text tokens could see future tokens, the task would be trivial, so the mask is causal. The queries are also blocked from seeing text, so they must already hold the visual information needed for the whole caption. In the matching loss, the task is classification of a pair, not prediction, so there is no leak to prevent and full attention lets the two sides align fine-grained details.

QuestionApplied scenario: you want a vision-language model that answers questions about detailed medical scans, and the frozen-encoder design misses small lesions. Which change would you test first, and why?Show answer

Test the bottleneck first: increase the number of queries, or give the language model access to more patch-level features, and measure the lesion-detection accuracy. The language model is frozen, so changing it cannot recover information the 32 vectors discarded. If the detail is still lost, the encoder or training data is the next suspect. Testing the language model first would waste compute on a component that cannot see the lesion.

Sources