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 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.
Let be the learnable query matrix, with queries of width , and let be the frozen image features with patches of width . The output is
The output size depends only on and , not on .
Here is the number of queries (32 in the paper), is the hidden width of Q-Former (768), is the number of patches the image encoder produces, and is that encoder's feature width. The key fact is that 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 be the query tokens and 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 is the output of the text transformer's [CLS] token. The image-text similarity takes the best of the query outputs:
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 maps each query output to the language model's embedding width, and the projected queries are placed in front of the text embeddings:
Here is the embedding of text token . 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 and Q-Former are trained. The language model and the image encoder stay frozen.
Worked examples
Compare the size of the visual input the language model would receive in two cases.
- Raw features from ViT-L/14 for one image: numbers.
- Q-Former output: numbers.
- Ratio: .
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.
Suppose Q-Former gave three queries of width 2 for one image, and the text embedding is . These numbers are illustrative, not from the paper.
- . Cosine with : .
- . Cosine: .
- . Cosine: .
- Take the maximum: .
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.
The paper gives the training schedule. Multiplying steps by batch size gives the number of image-text samples the model sees.
- Stage one with ViT-L/14: million samples.
- Stage one with ViT-g/14: million samples.
- Stage two with OPT: million samples.
- Stage two with FlanT5: 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.
| Situation | Problem | Better choice |
|---|---|---|
| Frozen encoder and frozen LLM, little compute | Only a small module can be trained | Q-Former or a similar small bridge |
| Fine detail matters (small text, dense scenes) | 32 vectors may drop details | More queries, or pass patch tokens through |
| Many images per prompt | Each image adds 32 tokens to the LLM input | Fewer queries, or a model with a longer context |
| The LLM must learn vision from scratch | A frozen LLM cannot adapt to images | Train the LLM too, or use an interleaved design |
| Need a single global embedding for search | The 32 vectors are not one vector | Pool 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 matrix, which is much smaller than the features of ViT-L/14.
QuestionComputation: a Q-Former output has and . How many numbers does the language model receive from one image if the visual prompt is the projected output, with projection width ?Show answer
The projection maps each query from width 768 to width 2048. The output is 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.