11.1 Vision-Language Models: CLIP, Projectors, and Cross-Attention
A vision-language model connects image representations with language. The connection can support different outputs: CLIP scores whether an image matches a supplied description; a generative model conditions a language decoder on image features to produce an answer. A vision-language bridge is the interface that makes those representations compatible.
Consider a photograph of a receipt. “Find receipts among these photographs” can use image–text similarity. “What is the total, and which line shows it?” requires a model to read the image and generate a grounded response. Reusing a CLIP image encoder does not, by itself, turn its similarity scores into that response.
| Interface | Concrete input → output | What reaches the language model? |
|---|---|---|
| CLIP dual encoders | Images and candidate descriptions → similarity scores | No generative decoder is required |
| Projector + decoder | Image feature sequence and prompt → answer tokens | Projected image features occupy decoder positions |
| Resampler + cross-attention | Image features and prompt → answer tokens | Text states query a separate visual memory |
Try the visual token calculator for a 224-pixel image. Then read the three answers a small model gave when the total on a receipt changed or disappeared.
1. CLIP: Learning Which Image and Text Belong Together
CLIP trains an image encoder and a text encoder with paired examples. Each produces a single embedding for comparison, projected into a common dimension and normalized to unit length. The original work uses a symmetric contrastive objective and learns its logit scale [1].
Let a batch contain paired examples with shared embedding width . For image and description , write their normalized embeddings as . Distinguish cosine similarity from the temperature-scaled logits :
Both embedding arrays have shape ; the comparison matrix has shape . Pair occupies the diagonal because the arrays use the same pairing order. The losses classify the matching caption within each row and the matching image within each column:
The off-diagonal entries are assumed negatives, not necessarily incorrect descriptions. Two photographs may show the same scene, or two captions may both fit one image. Duplicates and multiple valid captions require a deliberate sampling or multi-positive loss policy. Lower temperature sharpens the softmax; it does not change the nearest-neighbor ranking for fixed embeddings.
The PyTorch loss in isolation
Educational loss implementation: Inputs are nonzero image/text embeddings with matching shape , dtype, device, and pair order. This shows normalization, a positive learned scale, and the two loss directions. It omits encoders, distributed negative gathering, multi-positive targets, mixed-precision safeguards, and a training/checkpoint loop. It is not a complete CLIP trainer.
import torch
import torch.nn as nn
import torch.nn.functional as F
class CLIPLoss(nn.Module):
def __init__(self, init_temperature=0.07):
super().__init__()
if init_temperature <= 0:
raise ValueError("Temperature must be positive")
self.logit_scale = nn.Parameter(torch.tensor(1.0 / init_temperature).log())
def forward(self, image_embeddings, text_embeddings):
# Inputs: [batch_size, embed_dim]; paired rows have equal indices.
image_embeddings = F.normalize(image_embeddings, p=2, dim=-1)
text_embeddings = F.normalize(text_embeddings, p=2, dim=-1)
batch_size = image_embeddings.size(0)
logits = torch.matmul(image_embeddings, text_embeddings.t()) * self.logit_scale.exp()
labels = torch.arange(batch_size, device=image_embeddings.device)
loss_i = F.cross_entropy(logits, labels)
loss_t = F.cross_entropy(logits.t(), labels)
return (loss_i + loss_t) / 2
A runnable pairing experiment, without downloading a model
Scope: This standalone Python 3 program uses only the standard library and three authored unit vectors. It computes ranking and loss on CPU with Python floats; it neither reads pixels nor trains an encoder. Temperature is fixed at . The diagonal-target assumption is intentionally broken in the second case to expose a pairing bug.
from math import exp, isclose, log
def contrastive_logits(images, texts, temperature=0.2):
# This exercise supplies unit vectors; no encoder or normalization here.
return [[sum(a * b for a, b in zip(image, text)) / temperature
for text in texts] for image in images]
def diagonal_cross_entropy(rows):
losses = []
for target, row in enumerate(rows):
peak = max(row)
log_partition = peak + log(sum(exp(x - peak) for x in row))
losses.append(log_partition - row[target])
return sum(losses) / len(losses)
def symmetric_loss(logits):
columns = list(zip(*logits))
return (diagonal_cross_entropy(logits)
+ diagonal_cross_entropy(columns)) / 2
def top_matches(rows):
return [max(range(len(row)), key=row.__getitem__) for row in rows]
images = [(1., 0., 0.), (0., 1., 0.), (0., 0., 1.)]
paired = images.copy()
shuffled = [paired[2], paired[0], paired[1]]
good = contrastive_logits(images, paired)
bad = contrastive_logits(images, shuffled)
print("paired image-to-text:", top_matches(good))
print("shuffled image-to-text:", top_matches(bad))
print("shuffled text-to-image:", top_matches(list(zip(*bad))))
print(f"paired loss: {symmetric_loss(good):.6f}")
print(f"shuffled diagonal-target loss: {symmetric_loss(bad):.6f}")
assert top_matches(good) == [0, 1, 2]
assert top_matches(bad) == [1, 2, 0]
assert top_matches(list(zip(*bad))) == [2, 0, 1]
assert isclose(symmetric_loss(good), log(1 + 2 * exp(-5)))
assert isclose(symmetric_loss(bad) - symmetric_loss(good), 5.0)
Expected losses are 0.013386 and 5.013386. The embeddings did not become worse when the captions moved: the targets became wrong. Restore the pair order or remap both target directions before blaming the encoder. Printing a loss from random embeddings would not reveal this data-pipeline mistake.
2. Projectors: Turning Image Features into Decoder Positions
For generation, retain a sequence of spatial features, rather than the single global embedding used for CLIP retrieval. In the original LLaVA architecture, a linear projection maps CLIP ViT grid features to the language model’s embedding width [3].
Let be the number of retained image features, the vision width, and the language width. With batch size and text positions, a linear projector has the shape contract
The bracket means concatenation along the sequence axis. It depicts an image followed by text; an implementation can insert image features at marked positions instead. An MLP can replace the linear map without changing this interface. These visual vectors are continuous inputs, not vocabulary IDs that the text tokenizer emits.
For a hypothetical shape example, image features projected to width 4,096 become . Adding 32 text positions yields . The projector changed the width, not the feature count. A small connector can therefore create a long, expensive decoder input.
Freezing is a separate decision. Original LLaVA trains only the projector during feature alignment, then trains the projector and language model during instruction tuning while keeping the vision encoder frozen [3]. “Uses a projector” does not mean “trains only a projector.”
3. Cross-Attention: Keeping Visual Memory Beside the Text
Flamingo connects frozen vision and language backbones with a trainable Perceiver Resampler and gated cross-attention blocks. Its original vision encoder is NFNet, not a ViT patch encoder. The resampler uses learned queries to convert spatial or spatiotemporal features into 64 visual latents per image/video; added language-model blocks query those latents [2].
For a single image, describe the interface as , where is the resampled memory length and its feature width. Text queries still have positions. Cross-attention projects the text and memory to compatible query/key/value widths, producing an update with the same shape as the text states. The memory slots are not appended to the decoder’s self-attention sequence.
A simplified view of one gated attention branch is
Here and are text states, is visual memory, and is a learned scalar initialized to zero. This omits the block’s feed-forward branch. At initialization the added contribution is zero; this does not guarantee language retention after the gates and other trainable components change. Flamingo also masks each text position’s direct cross-attention to the most recent preceding image/video; earlier evidence can persist through text self-attention [2].
Multi-image behavior depends on image ordering, markers, masks, positional encoding, and training data in either design. Concatenation alone does not restrict a model to one image, and cross-attention alone does not guarantee correct comparisons between images.
4. Work Out the Visual Token Budget
Use a deliberately matched toy setup: each pixel patch produces one feature; there are no extra class tokens, crops, or merged patches. Let be the square image’s side length in pixels, the image count, and the text positions, including any image markers. Then
For one image, and the projected decoder sequence has 288 positions. Doubling both image dimensions gives and 1,056 positions. A dense attention score matrix per head changes from to entries—about . This counts full matrix entries before causal masking; it is not a measured latency or GPU-memory ratio, and efficient kernels need not materialize the matrix.
In the alternative toy path, resample to memory slots per image. The decoder sequence remains 32 positions while separate memory holds slots. A text-to-memory attention matrix over all slots would have entries per head; a per-image mask can restrict which entries are used. The encoder and resampler still process the input features, and cross-attention has its own projections, layers, and caches. A fixed memory length does not make high-resolution input free.
Change resolution and image count below. The two routes share the same illustrative patch grid to isolate where features go; this is not a reconstruction of Flamingo’s NFNet or a benchmark between released models.
Where do the image features go?
For this exercise, each 14 × 14 pixel patch produces one feature. The prompt has 32 text positions, including any image markers.
Project each patch
- Decoder sequence
- 288 positions
- Separate visual memory
- 0 slots
One patch adds one decoder position.
Resample, then cross-attend
- Decoder sequence
- 32 positions
- Separate visual memory
- 64 slots
Each image contributes 64 memory slots. A text query can read them at a cross-attention layer.
Both paths use the same illustrative patch grid. The counts describe sequence length and memory slots. Measuring latency or detail retention requires a model and workload. Architectures · LLaVA · Flamingo
For a receipt reader, test small-font totals and line items before choosing a smaller visual budget. A model may preserve the coarse fact “this is a receipt” while losing the digits needed for the answer. Keep image preprocessing, crop count, prompt, decoding, and answer rubric fixed when measuring that trade-off. For concatenated visual tokens, include the extra positions in the KV-cache budget; separate cross-attention memory needs its own accounting.
5. Test What the Bridge Preserves
Can a model tell when a receipt has no printed total? We gave SmolVLM-256M-Instruct three versions of this 512 × 384 image, one at a time. Only the pixels on the total line changed. The prompt was identical each time.
Read the printed Total line. Copy that line exactly. If the Total line is missing, answer MISSING.
Read A and B, then switch to C. If you had just C and the prompt above, what could you write without guessing?
| Input PNG | Expected answer | Model answer |
|---|---|---|
| Receipt A | Total 31.50 | 31.50 |
| Receipt B | Total 42.00 | 42.00 |
| Receipt C (total removed) | MISSING | 1 |
Scoring only the amounts gives the model two correct answers on the two receipts with totals. Scoring the printed line gives it zero on those same receipts because it omitted the word Total both times. With the line removed it still returned a number. The table trims one leading space from each answer. The raw outputs and token IDs preserve it.
In the 2026-11-25 CPU run, the checkpoint’s image processor turned each PNG into 13 views of 512 × 512 pixels. Each view contributed 64 image placeholders. That accounts for 832 of the 893 input positions. The other 61 came from the prompt and the processor’s formatting. We used FP32, greedy decoding and a 32-token output cap. Those 13 views illustrate why the toy calculator’s one unbroken patch grid cannot predict this checkpoint’s actual input length. [5]
Download the three PNGs, Python script and recorded run (ZIP). After extracting the files, install the packages listed in the script and run python receipt_grounding.py .. The first run downloads about 513 MB of model weights.
Which printed digit changed the answer?
Receipt C still shows two 1s, one beside each item. Which one could explain the model’s answer? Starting from C, we changed the paper count to 7, the pencil count to 8, or both. We left the total blank and ran the same checkpoint and prompt. Each cell shows its decoded answer with leading whitespace trimmed.
| Paper quantity | Pencils read 1 box | Pencils read 8 box |
|---|---|---|
1 pack | 1 | 8 box |
7 pack | 1 | 8 box |
Cover the column headings. From the answer you can recover the pencil count in all four images, but you learn nothing about how much the customer paid. Changing the paper digit made no difference in either column. This isolates a response to the pencil line for this layout and prompt. It does not identify an attention head or show how the model would handle another receipt.
Run python receipt_quantity_probe.py from the extracted ZIP. It includes the quantity experiment (Python) and its reference output. It starts with receipt C and generates the three edited PNGs in a temporary directory. The recorded outputs, input hashes, and generated token IDs let you compare your results.
Does the answer follow the pencils wherever they appear? With seven packs of paper and eight boxes of pencils, swapping the two printed rows changed the answer from 8 box to 7. under the same prompt. Inspect all eight inputs and compare the generated strings.
These three cases test copying and abstention on one layout. To test retrieval, separately rank the receipt description against descriptions of other documents. To test image order, present both labeled receipts, reverse them and ask about the same label. Hold the images and decoding settings fixed when measuring changes in visual budget, latency or peak memory.
If adaptation is needed, use the SFT procedure for the training contract. The multimodal details to verify are the image processor and selected feature layer, native chat-template image markers, image–answer alignment after truncation, and exclusion of visual positions from answer loss. Frozen LM weights reduce gradient/optimizer state, but an upstream projector may still need gradients through the LM and its activation memory. Keep these evaluation receipts out of training and use the evaluation and release gates for a larger deployment decision.
Research Check: Which Part of a Vision Encoder Helps?
As of 2026-11-25. Unbundling Multimodal Vision Encoding separates upstream visual pretraining, dedicated vision capacity, and where that capacity enters the backbone. In its controlled, matched-lifetime-compute experiments, jointly trained vision capacity can match a pretrained encoder, while removing dedicated vision capacity hurts visual understanding [4]. That is evidence about the tested setup, not proof that pretrained encoders are unnecessary at every scale or data budget.
To investigate the result, compare a pretrained encoder, a same-size jointly trained encoder, and a capacity-matched encoder-free model on common data. Count upstream pretraining in one budget and report an encoder-reuse scenario separately. Keep visual tokenization and evaluation conditions explicit; measure language retention and time to first token alongside visual question answering. Comparing unrelated released models cannot isolate this mechanism.
Choose the interface by the required output, then count the features it introduces and test the details it preserves. A retrieval score, a decoder position, and a cross-attention memory slot serve different purposes even when all three are called “image embeddings.”
Quizzes
Quiz 1: Why use two CLIP loss directions when the dot product is symmetric?
Swapping the two vectors leaves one dot product unchanged, but the image-to-text row and text-to-image column normalize over different candidates. Both directions need the correct pairing labels. Neither loss creates a text generator.
Quiz 2: Why does shuffling captions raise the example’s loss by exactly 5?
With temperature 0.2, each row or column has one logit of 5 and two of 0. The log-partition is unchanged by permutation, but every diagonal target changes from 5 to 0. Each cross-entropy therefore rises by 5 even though the embedding matches are intact.
Quiz 3: Does projecting 256 features from width 768 to 4,096 reduce the visual token budget?
No. A position-wise projection changes feature width, not the 256 positions. In the example, 32 text positions make a 288-position decoder sequence. Pooling, merging, or resampling would be a separate operation.
Quiz 4: With two 448-pixel images, how do the toy routes differ?
Each image has 1,024 patches. Concatenation gives decoder positions. Resampling to 64 slots per image gives 128 separate memory slots while the text sequence stays at 32 positions. These counts alone do not establish a latency ratio or equal accuracy.
Quiz 5: Do a frozen LM and a zero-initialized visual gate guarantee capability retention?
No. A zero gate initially removes the added branch’s contribution, but trained gates and visual conditioning can change outputs even with frozen base weights. Evaluate language retention and visual grounding after adaptation; freezing also does not eliminate all activation memory needed for backpropagation.
References
- Radford, A., et al. (2021). Learning Transferable Visual Models From Natural Language Supervision. arXiv:2103.00020.
- Alayrac, J. B., et al. (2022). Flamingo: a Visual Language Model for Few-Shot Learning. Architecture, masking, and gated blocks: Sections 2.1–2.3 and Appendix A.1. arXiv:2204.14198.
- Liu, H., et al. (2023). Visual Instruction Tuning. Original linear connector and two-stage training: Section 4. arXiv:2304.08485.
- Brown, E., et al. (2026). Unbundling Multimodal Vision Encoding, v1. Verified 2026-11-25. arXiv:2611.17334v1.
- Hugging Face TB. SmolVLM-256M-Instruct, revision
d039ab0. Model card and image processor configuration.