Sub topic 5
The image encoder: ResNet and Vision Transformer variants
This chapter assumes you know what a convolution is, how a Transformer block uses self-attention, and what an embedding vector is. It also assumes you can read PyTorch tensor shapes. The earlier chapters covered the dual-encoder layout. Here we look inside the image half of that layout.
What the image encoder must do
The image encoder maps a picture to one vector. That vector must live in the same space as the text encoder's output, so it needs the same length and a comparable scale. The contrastive loss only sees the final vectors. It does not care how the image encoder produces them, which is why CLIP could train both ResNets and Vision Transformers (ViTs) under the same recipe.
The model has three jobs:
- Turn pixels into a feature representation.
- Collapse that representation into a single vector for the whole image.
- Project that vector to the shared embedding dimension.
The two families do jobs 1 and 2 differently. Job 3 is a single linear layer in both.
The ResNet variants
CLIP trained five ResNets: RN50, RN101, and three larger models called RN50x4, RN50x16 and RN50x64. The suffix says how much compute the model uses compared with RN50. The larger models scale width, depth and input resolution together, in the style of EfficientNet.
The CLIP ResNets are not the plain torchvision ResNets. They have three changes:
- ResNet-D tweaks. The stem uses three small 3x3 convolutions instead of one 7x7 convolution. Downsampling in the shortcut paths uses average pooling.
- Anti-aliased pooling. Strided convolutions are replaced by a blur filter followed by a stride-1 convolution, so downsampling loses less information.
- Attention pooling. The usual global average pooling is replaced by one layer of multi-head QKV attention. The query is the average of the final feature map. The keys and values are the individual spatial positions. The output of that layer is the image vector.
Attention pooling lets the model weight image regions differently instead of averaging them all equally. For a caption such as "a dog on a beach", the region around the dog can count for more than empty sky.
The Vision Transformer variants
The ViT family has three standard sizes, written as size/patch, for example ViT-B/32:
- ViT-B/32: base size, 32x32 pixel patches.
- ViT-B/16: base size, 16x16 pixel patches.
- ViT-L/14: large size, 14x14 pixel patches. A fine-tuned version, ViT-L/14@336, runs at 336x336 input.
The ViT pipeline has these steps:
- Cut the 224x224 image into a grid of non-overlapping patches. A single convolution with kernel size and stride both equal to the patch size does this and projects each patch to the model width.
- Prepend a learned class token (CLS).
- Add learned position embeddings.
- Apply a layer norm to the sum. This extra "pre" layer norm is one of CLIP's small changes to the standard ViT.
- Run the sequence through the Transformer blocks.
- Take the output at the CLS position, apply a layer norm, and multiply by a learned projection matrix.
How patch size sets the cost
Self-attention cost grows with the square of the number of tokens, so patch size matters a great deal. At 224x224 input:
| Model | Patch size | Patches | Tokens with CLS | Width | Layers | Embedding size |
|---|---|---|---|---|---|---|
| ViT-B/32 | 32 | 49 | 50 | 768 | 12 | 512 |
| ViT-B/16 | 16 | 196 | 197 | 768 | 12 | 512 |
| ViT-L/14 | 14 | 256 | 257 | 1024 | 24 | 768 |
ViT-B/16 uses the same weights shape as ViT-B/32 but processes about four times as many tokens, so it costs several times more compute per image. Smaller patches keep more fine detail, such as small text or distant objects. The ResNets use embedding sizes from 1024 (RN50) upward, and the exact size depends on the variant.
Inspecting the encoder in code
You can read these numbers from the model configuration without downloading the weights.
from transformers import CLIPConfig
names = [
"openai/clip-vit-base-patch32",
"openai/clip-vit-base-patch16",
"openai/clip-vit-large-patch14",
]
for name in names:
cfg = CLIPConfig.from_pretrained(name).vision_config
grid = cfg.image_size // cfg.patch_size
tokens = grid * grid + 1 # patches plus the CLS token
print(
f"{name}: patch={cfg.patch_size} tokens={tokens} "
f"width={cfg.hidden_size} layers={cfg.num_hidden_layers} "
f"embed={cfg.projection_dim}"
)Next, follow one tensor through the real model. A random tensor is enough to show the shapes.
import torch
from transformers import CLIPModel
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").eval()
pixel_values = torch.randn(1, 3, 224, 224)
with torch.no_grad():
vision_out = model.vision_model(pixel_values=pixel_values)
tokens = vision_out.last_hidden_state # (1, 50, 768)
cls_vec = vision_out.pooler_output # (1, 768), CLS after post layer norm
embedding = model.visual_projection(cls_vec) # (1, 512)
reference = model.get_image_features(pixel_values=pixel_values)
print(tokens.shape, cls_vec.shape, embedding.shape)
print(torch.allclose(embedding, reference, atol=1e-5))The last line prints True. get_image_features is the vision transformer, the CLS pooling, and the projection in one call. It is the same function used in the retrieval example in a later chapter. Note that the output is not normalized. You normalize it yourself before computing cosine similarity.
Preprocessing belongs to the encoder
The image encoder was trained on inputs that went through a specific pipeline. Resize the short side to 224 with bicubic interpolation, center-crop to 224x224, scale pixel values to 0-1, then normalize per channel. The mean is (0.48145466, 0.4578275, 0.40821073). The standard deviation is (0.26862954, 0.26130258, 0.27577711). CLIPProcessor does all of this. If you write your own loader, copy these values exactly. The ImageNet statistics are close but not the same, and a mismatch causes a small, silent drop in accuracy.
Choosing between the families
In the CLIP paper, the ViTs reached the same zero-shot quality with roughly three times less training compute than the ResNets. That result is why most later CLIP-style models, including OpenCLIP's large checkpoints, use ViTs. The trade-offs in practice are:
- ViT-B/32: the cheapest option. Good for large-scale indexing where throughput matters. It is weakest on fine detail.
- ViT-B/16 and ViT-L/14: better accuracy, higher cost. Use them when quality matters more than speed.
- ResNets: convolutions work well on small devices with mature convolution kernels, and attention pooling makes them still competitive. They are less common in new work.
Failure modes and edge cases
- Changing the input resolution. The position embeddings are learned for a fixed grid. Feeding 336x336 images to a 224 model fails, or needs the position embeddings to be interpolated. Interpolation often works but can lower accuracy. Use the checkpoint trained for that resolution (ViT-L/14@336) when you can.
- Mixing up embedding sizes. Image embeddings from ViT-B/32 have 512 values, and from ViT-L/14 have 768. Never compare vectors from different checkpoints, and never reuse a vector index after switching models. The spaces differ even when the sizes match.
- Using
last_hidden_statedirectly. Those token features are in the transformer's width (768), not the joint space. Only the projected CLS output is aligned with text. - Half precision. Float16 inference is usually fine. If you see NaN values, check the pre layer norm and fall back to bfloat16 or float32.
Exercise
A ViT-B/16 encoder receives a 224x224 image. How many tokens enter the Transformer blocks, what is the shape of the CLS output after the post layer norm for a batch of 8 images, and what is the shape after the projection to a 512-dimensional embedding?
Show answer
The 224x224 image gives a 14x14 grid of 16x16 patches, which is 196 patch tokens. Adding the CLS token makes 197 tokens. The CLS output after the post layer norm has shape (8, 768), because the base model's width is 768. The projection maps it to shape (8, 512).
Exercise
You build a search index with ViT-B/32 image embeddings. Later you switch to ViT-L/14 for better accuracy and embed only the new queries with it. Why does retrieval break, and what is the fix?
Show answer
The two models produce vectors in different embedding spaces, and their sizes differ (512 against 768). Even if the sizes matched, the axes would carry unrelated meanings, so cosine similarity between them is meaningless. The fix is to re-embed every indexed image with ViT-L/14 and use the same checkpoint for the queries.