Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

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.

InterfaceConcrete input → outputWhat reaches the language model?
CLIP dual encodersImages and candidate descriptions → similarity scoresNo generative decoder is required
Projector + decoderImage feature sequence and prompt → answer tokensProjected image features occupy decoder positions
Resampler + cross-attentionImage features and prompt → answer tokensText 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 BB paired examples with shared embedding width dd. For image ii and description jj, write their normalized embeddings as vi,tj∈Rdv_i,t_j\in\mathbb R^d. Distinguish cosine similarity CC from the temperature-scaled logits ZZ:

Cij=vi⊤tj,Zij=Cij/τ,τ>0.C_{ij}=v_i^\top t_j,\qquad Z_{ij}=C_{ij}/\tau,\qquad \tau>0.

Both embedding arrays have shape [B,d][B,d]; the comparison matrix has shape [B,B][B,B]. Pair ii 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:

Li→t=−1B∑i=1Blog⁡exp⁡Zii∑j=1Bexp⁡Zij,Lt→i=−1B∑j=1Blog⁡exp⁡Zjj∑i=1Bexp⁡Zij.\begin{aligned} \mathcal L_{i\to t}&=-\frac1B\sum_{i=1}^{B}\log\frac{\exp Z_{ii}}{\sum_{j=1}^{B}\exp Z_{ij}},\\[0.5em] \mathcal L_{t\to i}&=-\frac1B\sum_{j=1}^{B}\log\frac{\exp Z_{jj}}{\sum_{i=1}^{B}\exp Z_{ij}}. \end{aligned} LCLIP=12(Li→t+Lt→i).\mathcal L_{\mathrm{CLIP}}=\tfrac12(\mathcal L_{i\to t}+\mathcal L_{t\to i}).

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 [B,d][B,d], 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 0.20.2. 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 PP be the number of retained image features, dvd_v the vision width, and dℓd_\ell the language width. With batch size BB and TT text positions, a linear projector has the shape contract

Hv∈RB×P×dv,W∈Rdv×dℓ,Xv=HvW∈RB×P×dℓ.\begin{aligned} H_v&\in\mathbb R^{B\times P\times d_v},\\ W&\in\mathbb R^{d_v\times d_\ell},\\ X_v&=H_vW\in\mathbb R^{B\times P\times d_\ell}. \end{aligned} Xinput=[Xv;Xtext]∈RB×(P+T)×dℓ.X_{\mathrm{input}}=[X_v;X_{\mathrm{text}}] \in\mathbb R^{B\times(P+T)\times d_\ell}.

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, [1,256,768][1,256,768] image features projected to width 4,096 become [1,256,4096][1,256,4096]. Adding 32 text positions yields [1,288,4096][1,288,4096]. 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 [B,P,dv]→[B,K,dm][B,P,d_v]\to[B,K,d_m], where KK is the resampled memory length and dmd_m its feature width. Text queries still have TT 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 KK memory slots are not appended to the decoder’s self-attention sequence.

A simplified view of one gated attention branch is

y=x+tanh⁡(α) CrossAttend(x,M).y=x+\tanh(\alpha)\,\mathrm{CrossAttend}(x,M).

Here xx and yy are text states, MM is visual memory, and α\alpha 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 14×1414\times14 pixel patch produces one feature; there are no extra class tokens, crops, or merged patches. Let ss be the square image’s side length in pixels, mm the image count, and T=32T=32 the text positions, including any image markers. Then

P=(s/14)2,Sprojector=T+mP.P=(s/14)^2,\qquad S_{\mathrm{projector}}=T+mP.

For one 224×224224\times224 image, P=162=256P=16^2=256 and the projected decoder sequence has 288 positions. Doubling both image dimensions gives P=322=1024P=32^2=1024 and 1,056 positions. A dense attention score matrix per head changes from 2882=82,944288^2=82{,}944 to 10562=1,115,1361056^2=1{,}115{,}136 entries—about 13.4×13.4\times. 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 K=64K=64 memory slots per image. The decoder sequence remains 32 positions while separate memory holds 64m64m slots. A text-to-memory attention matrix over all slots would have T(mK)T(mK) 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.

patches per image16 × 16 = 256input features across all images256 × 1 = 256

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.

Projection uses 288 decoder positions. Cross-attention uses 32 decoder positions and 64 visual memory slots.

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.

Choose a receipt and read its total line.
One pack of drawing paper and one box of pencils. The last line reads Total 31.50.One pack of drawing paper and one box of pencils. The last line reads Total 42.00.One pack of drawing paper and one box of pencils. There is no total or price below the items.
Original experiment inputs, drawn with Pillow. The 1 beside each item is a quantity. None of the receipts gives a unit price.

Read A and B, then switch to C. If you had just C and the prompt above, what could you write without guessing?

Input PNGExpected answerModel answer
Receipt ATotal 31.5031.50
Receipt BTotal 42.0042.00
Receipt C (total removed)MISSING1

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 quantityPencils read 1 boxPencils read 8 box
1 pack18 box
7 pack18 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 32+2×1024=208032+2\times1024=2080 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

  1. Radford, A., et al. (2021). Learning Transferable Visual Models From Natural Language Supervision. arXiv:2103.00020.
  2. 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.
  3. Liu, H., et al. (2023). Visual Instruction Tuning. Original linear connector and two-stage training: Section 4. arXiv:2304.08485.
  4. Brown, E., et al. (2026). Unbundling Multimodal Vision Encoding, v1. Verified 2026-11-25. arXiv:2611.17334v1.
  5. Hugging Face TB. SmolVLM-256M-Instruct, revision d039ab0. Model card and image processor configuration.