Sub topic 6
The text encoder: a Transformer over captions
This chapter covers the text half of CLIP's dual encoder. It assumes you know basic PyTorch, how self-attention and softmax work at a high level, and what an embedding is. By the end you should be able to explain how a caption becomes one vector in the joint space, and you should be able to spot the usual mistakes when you feed text to a pretrained CLIP model.
What the text encoder has to do
The image encoder turns a picture into one vector. The text encoder does the same for a caption. Both vectors have the same length, so the contrastive loss can compare them with a dot product after normalization.
The text encoder's job is narrow. It does not generate text and it does not answer questions. It reads a short string and returns a single vector that sits near the vectors of images that string describes.
Because the pipeline is fixed from tokens to one vector, there are only a few places where things go wrong. The sections below follow the pipeline in order.
Tokenization
CLIP uses a byte-pair encoding (BPE) tokenizer. BPE is a method that starts from bytes or characters and repeatedly merges the most frequent adjacent pairs, so common words become single tokens and rare words split into pieces. The original CLIP vocabulary has 49,152 merged tokens plus two special tokens, so the vocabulary size is 49,408.
The two special tokens matter:
<|startoftext|>is placed at the start of every sequence.<|endoftext|>(EOT) is placed at the end, and its position is used later to read out the sentence vector.
The context length is fixed at 77 tokens, counting both special tokens. A caption longer than 77 tokens is truncated. Shorter captions are padded, and the padding is ignored by the readout step.
The 77-token limit has a practical effect. Long, detailed descriptions lose their tail. If the important word sits at token 90, the model never sees it.
The Transformer body
The text encoder is a Transformer in the GPT-2 style. For the base model (the one paired with ViT-B/32) the settings are:
| Setting | Value |
|---|---|
| Layers | 12 |
| Width (hidden size) | 512 |
| Attention heads | 8 |
| Context length | 77 |
| Vocabulary size | 49,408 |
| Output embedding size | 512 |
Larger CLIP models scale the width and depth. For example, the text encoder paired with ViT-L/14 has width 768 and the same 12 layers, with a 768-dimensional output embedding.
Three design points are worth knowing.
- Learned position embeddings. Each of the 77 positions has its own trainable vector that is added to the token embedding. There are no sinusoidal or rotary encodings. This is also why you cannot simply feed a longer sequence to a pretrained model: positions beyond 77 have no learned vector.
- Causal attention mask. Each token can attend only to itself and earlier tokens, as in a language model. A bidirectional encoder such as BERT would also work, but the original CLIP kept the causal mask. A consequence is that the last real token, EOT, is the only position that has seen the whole caption.
- Pre-LayerNorm blocks. LayerNorm is applied before attention and before the feed-forward layer in each block, and again once at the end of the stack.
Reading out one vector
A Transformer returns one hidden state per token, so you need a rule to collapse them into a single vector. CLIP takes the hidden state at the EOT position. Since attention is causal, that state is the only one that has attended to every real token in the caption.
The state then passes through a learned linear projection, with no bias, that maps from the Transformer width to the shared embedding size. For ViT-B/32 this is a map from 512 to 512. For ViT-L/14 it maps 768 to 768. Finally the vector is L2-normalized, so every text embedding has length 1.
The EOT token has the highest token id in the vocabulary. The original implementation exploits this and finds the readout position with argmax over the token ids. A short version of the readout looks like this:
import torch
def eot_readout(hidden, token_ids, projection):
# hidden: (batch, seq_len, width) output of the final LayerNorm
# token_ids: (batch, seq_len) integer ids; EOT has the largest id
# projection: (width, embed_dim) learned matrix
eot_pos = token_ids.argmax(dim=-1) # (batch,)
batch_idx = torch.arange(hidden.size(0), device=hidden.device)
pooled = hidden[batch_idx, eot_pos] # (batch, width)
emb = pooled @ projection # (batch, embed_dim)
return torch.nn.functional.normalize(emb, dim=-1)
hidden = torch.randn(2, 77, 512)
token_ids = torch.zeros(2, 77, dtype=torch.long)
token_ids[0, :6] = torch.tensor([49406, 320, 1125, 539, 320, 49407])
token_ids[1, :4] = torch.tensor([49406, 1929, 530, 49407])
projection = torch.randn(512, 512)
out = eot_readout(hidden, token_ids, projection)
print(out.shape, out.norm(dim=-1))The two example rows use ids 49406 for the start token and 49407 for EOT, which matches the original vocabulary. The printed norms are all 1.0.
What the encoder learns to represent
The text encoder is trained only through the contrastive loss from the earlier chapters. It never sees a classification label. Its gradient signal is simply: make this caption's vector closer to its own image's vector than to the other images in the batch.
This has consequences for what the embedding captures.
- It captures what is visually describable. Words like "striped," "sunset," and "kitchen" are useful. Words with no visual signature are weak signals.
- It behaves partly like a bag of concepts. The model tends to be less sensitive to word order and relations than a person is. "A horse riding a man" and "a man riding a horse" often land close together.
- It is shaped by caption style. Web alt-text is short and noun-heavy, so prompts that look like captions work better than long instructions.
Using the text encoder in practice
With Hugging Face Transformers you get the text embeddings through get_text_features. The processor handles tokenization, special tokens, truncation, and padding.
import torch
import torch.nn.functional as F
from transformers import CLIPModel, CLIPProcessor
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
captions = ["a photo of a cat", "a photo of a dog", "a diagram of a neural network"]
inputs = processor(text=captions, return_tensors="pt", padding=True, truncation=True)
print(inputs["input_ids"].shape) # (3, longest caption length in tokens)
with torch.no_grad():
text_emb = model.get_text_features(**inputs)
text_emb = F.normalize(text_emb, dim=-1)
print(text_emb.shape) # (3, 512)
print(text_emb @ text_emb.t()) # pairwise cosine similaritiesThe diagonal of the printed matrix is 1.0. The cat and dog captions should score higher with each other than either does with the diagram caption, because the encoder places similar concepts nearby.
Note that padding=True pads to the longest caption in the batch, not to 77. This is fine for the Hugging Face model, because it finds the EOT position from the ids, and padding cost drops. Always pass truncation=True, or a caption over 77 tokens raises an error in the position-embedding lookup.
Common errors
- Forgetting to normalize.
get_text_featuresreturns unnormalized vectors. Dot products between them mix direction with length. Normalize before you compute cosine similarity, as the earlier chapter on cosine similarity explained. - Mixing model families. A text encoder only works with the image encoder it was trained alongside. Text vectors from
clip-vit-base-patch32cannot be compared with image vectors fromclip-vit-large-patch14, even if you could force the shapes to match. - Assuming long captions work. Anything past 77 tokens is dropped. Split long documents into short pieces and embed each piece.
- Case and whitespace surprises. The original tokenizer lowercases text and cleans whitespace, so "Cat" and "cat" give the same tokens. Do not rely on capitalization to carry meaning.
- Treating it as a language model. The text encoder was trained on short captions. It does not do well on negation ("a room with no windows"), counting, or long reasoning. A query phrased as a negation often retrieves images that contain the negated object.
- Prompt wording drift. A small change such as "a photo of a cat" versus "cat" changes the vector enough to shift zero-shot accuracy. A later chapter on prompt templates covers how to handle this.
Why a Transformer here
The authors tried alternatives for the text side. A Transformer gave strong results at a cost that stayed small next to the image encoder. The text input is short, so attention over 77 positions is cheap. Most of the compute in a training step goes to the image tower, and the text tower adds relatively little. This asymmetry is why the text encoder can be a fairly deep Transformer without dominating training time.
At inference the asymmetry helps again. Text embeddings for a fixed label set, such as 1,000 class names, are computed once and cached. After that, classifying an image needs only one pass through the image encoder and a matrix multiplication against the cached text matrix.
Exercise
A teammate embeds product descriptions of about 200 words each with CLIP's text encoder and finds that two descriptions that differ only in their final sentence get almost identical embeddings. Explain why this happens and give one fix.
Show answer
A 200-word description is far more than 77 tokens, so the tokenizer truncates it. The final sentence is dropped before the Transformer sees it, and the two inputs become identical or nearly so. A fix is to split each description into pieces under about 75 tokens (leaving room for the start and end tokens), embed each piece, and then average the normalized piece embeddings or store them separately for retrieval.
Exercise
Why does CLIP read the sentence embedding from the EOT token's hidden state instead of averaging all token states, and what would break if you picked the last padded position instead?
Show answer
With a causal mask, the EOT token is the only position that has attended to every real token in the caption, so its state summarizes the whole sentence. Positions after EOT are padding. They are not the position the model was trained to read from, so their states do not summarize the caption in the way the projection expects, and the resulting embeddings would be wrong and would not match the image embeddings well.