Sub topic 4
CLIP's dual-encoder architecture
This chapter assumes you know PyTorch tensors, what an embedding and cosine similarity are, and roughly how a Transformer or a CNN turns an input into a feature vector. By the end you should be able to sketch CLIP's architecture, say what shapes flow through it, and explain why the design makes retrieval cheap and joint reasoning weak.
Two towers, one space
CLIP is a dual encoder, also called a two-tower model. It contains two separate networks:
- An image encoder maps an image to a vector.
- A text encoder maps a token sequence to a vector.
The two networks share no weights and never see each other's inputs. Their only meeting point is the output space. Both end in a linear projection to the same dimension, for example 512 for the ViT-B/32 model. The training objective (covered in later chapters) pulls matching image and text vectors together in that space.
What each tower contains
Each tower has a backbone and a projection head.
| Part | Image tower | Text tower |
|---|---|---|
| Input | Pixels, resized and normalized | BPE token ids, at most 77 per caption |
| Backbone | ResNet variant or Vision Transformer | Decoder-style Transformer with causal attention mask |
| Pooled feature | Attention pooling (ResNet) or class token (ViT) | Hidden state at the end-of-text token |
| Head | Linear projection to the shared dimension | Linear projection to the shared dimension |
| Output | One vector per image | One vector per caption |
The next two chapters cover the backbones in detail. For this chapter, treat each as a function that returns one fixed-width feature per example.
Two details matter in practice:
- Pooling picks a single position. The text tower runs over the whole token sequence, but CLIP reads only the hidden state at the end-of-text token. Because the mask is causal, that position is the only one that has attended to every earlier token. The whole caption is summarized in one vector.
- Projections absorb width differences. The backbones usually have different widths. In ViT-B/32 the vision width is 768 and the text width is 512. The projection layers, which have no bias in the original implementation, map both to the shared dimension (512 in this model).
A minimal dual encoder in PyTorch
The class below shows the whole pattern with toy backbones in place of real ones. It runs as written.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class MeanPoolText(nn.Module):
"""Toy text backbone: embed tokens, average over the sequence."""
def __init__(self, vocab_size, width):
super().__init__()
self.embed = nn.Embedding(vocab_size, width)
def forward(self, tokens):
return self.embed(tokens).mean(dim=1) # (batch, width)
class DualEncoder(nn.Module):
def __init__(self, image_backbone, text_backbone,
image_width, text_width, embed_dim=64):
super().__init__()
self.image_backbone = image_backbone
self.text_backbone = text_backbone
self.image_proj = nn.Linear(image_width, embed_dim, bias=False)
self.text_proj = nn.Linear(text_width, embed_dim, bias=False)
# Learned in log space; exp(logit_scale) starts at 1/0.07.
self.logit_scale = nn.Parameter(torch.tensor(math.log(1 / 0.07)))
def encode_image(self, images):
return F.normalize(self.image_proj(self.image_backbone(images)), dim=-1)
def encode_text(self, tokens):
return F.normalize(self.text_proj(self.text_backbone(tokens)), dim=-1)
def forward(self, images, tokens):
img = self.encode_image(images) # (B, D), unit length
txt = self.encode_text(tokens) # (B, D), unit length
logits_per_image = self.logit_scale.exp() * img @ txt.t() # (B, B)
return logits_per_image, logits_per_image.t()
image_backbone = nn.Sequential(nn.Flatten(), nn.Linear(3 * 32 * 32, 256))
model = DualEncoder(image_backbone, MeanPoolText(1000, 128),
image_width=256, text_width=128)
images = torch.randn(4, 3, 32, 32)
tokens = torch.randint(0, 1000, (4, 16))
logits_img, logits_txt = model(images, tokens)
print(logits_img.shape) # torch.Size([4, 4])Notice what the model does not do. No operation combines an image feature with a text feature before the final dot product. The batch-by-batch matrix logits_per_image is the only place the modalities interact, and the interaction is a single inner product per pair.
Inspecting a real CLIP model
You can confirm the same structure in the Hugging Face implementation. This script feeds random pixels, so it needs no image file.
import torch
from transformers import CLIPModel, CLIPProcessor
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
def count(module):
return sum(p.numel() for p in module.parameters())
print("vision tower params:", count(model.vision_model))
print("text tower params: ", count(model.text_model))
print("projection dim:", model.config.projection_dim)
pixels = torch.randn(2, 3, 224, 224)
text = processor(text=["a cat", "a dog", "a red car"],
return_tensors="pt", padding=True)
with torch.no_grad():
img = model.get_image_features(pixel_values=pixels)
txt = model.get_text_features(**text)
print(img.shape, txt.shape) # (2, 512) and (3, 512)
print("logit scale:", model.logit_scale.exp().item())Expect roughly 88 million parameters in the vision tower and 63 million in the text tower. Both outputs have width 512. The features returned by get_image_features and get_text_features are not normalized. You must normalize them yourself before computing cosine similarity, as the retrieval example later in this tutorial does. The final logit scale in the released checkpoint is 100, the clipping limit used in training.
Why separate towers
The dual-encoder design is a deliberate trade-off against a cross-encoder, where image and text tokens attend to each other inside one network.
| Property | Dual encoder (CLIP) | Cross-encoder |
|---|---|---|
| Cost to score N images against one query | One text pass, N dot products against stored vectors | N full forward passes |
| Precomputing the index | Yes, image vectors can be cached | No, the score depends on the pair |
| Fine-grained reasoning over text and image together | Weak | Strong |
| Training signal | Contrastive, works with noisy web pairs | Usually needs labeled pairs or a different objective |
The benefit shows up in two places. First, retrieval scales. You embed a million images once, store the vectors, and each new query costs one text encoding plus a matrix product or a nearest-neighbor lookup. Second, the classifier is built from text. Class names go through the text tower once, and the resulting vectors act as classifier weights for the image tower's output. That is the basis of zero-shot classification.
The cost is that the model has to compress each input into one vector without knowing what it will be compared against. A caption such as "a red cube on top of a blue cube" and one with the colors swapped can land close together, because the pooled text vector may not preserve binding between attributes and objects. Later chapters return to this failure mode.
Gotchas
- Token limit. The text tower has 77 positions. Longer captions are truncated, so a long description loses its tail. Pass
truncation=Trueto the processor explicitly if your inputs may be long. - Preprocessing belongs to the model. The image tower expects a specific resolution, resize method and per-channel mean and standard deviation. Use the matching processor, not a generic image pipeline.
- The towers are not interchangeable. Image vectors from one checkpoint cannot be compared with text vectors from another, even if the dimensions match, because the space is only defined by joint training.
- Cached embeddings go stale. If you switch checkpoint, such as from ViT-B/32 to ViT-L/14, you must re-embed everything in your index.
Check your understanding
Exercise
A teammate says "CLIP is slow for search because it must run the image and the text through the network together for every image." Is that correct? What does your answer imply for how you would build a search index over 10 million images?
Show answer
No. CLIP's towers are independent, so each image is encoded once, offline, and its normalized vector is stored. At query time only the text tower runs, producing one vector, which is compared to the stored image vectors by dot product (typically with an approximate nearest-neighbor index). The index is built by batch-embedding the 10 million images with a fixed checkpoint and its matching preprocessing, and it must be rebuilt if the checkpoint changes.
Exercise
In the DualEncoder class above, what would change in the output if you removed the F.normalize calls from encode_image and encode_text, and why might that hurt training?
Show answer
The logits would become dot products of vectors with arbitrary length rather than cosine similarities scaled by exp(logit_scale). Vector norms could then grow to inflate scores, so the learned temperature would no longer be the sole control over how sharp the softmax is. Rankings at inference could also depend on vector length rather than direction alone.