Sub topic 1
Embeddings: representing images and text as vectors
An embedding is a fixed-length list of numbers (a vector) that a model produces for an input such as an image, a sentence, or a word. Inputs that the model treats as similar get vectors that lie near each other. This chapter covers what embeddings are, how images and text each get turned into them, how to inspect them in code, and the mistakes that most often cause trouble. It sets up the rest of the tutorial, where CLIP puts image and text embeddings into one shared space.
Prerequisites
This chapter assumes you already know the following:
- Basic Python and PyTorch tensor operations: shapes, indexing,
@for matrix multiplication. - Neural network fundamentals: layers, softmax, and cross-entropy loss.
- A high-level picture of convolutional networks and Transformers.
- The dot product and the vector norm (length) of a vector.
You do not need to know anything about CLIP yet.
What an embedding is
Raw inputs are hard for a model to compare directly. A 224×224 RGB image is 150,528 pixel values, and two photos of the same dog can differ in almost every pixel. A sentence is a variable-length string of discrete tokens. Neither form makes "these two things mean the same" easy to compute.
An embedding model maps each input to a point in a vector space of fixed dimension d, for example 512. Training shapes this space so that distance carries meaning. Two photos of dogs end up close together, and a photo of a dog ends up far from a photo of a tractor.
Formally, an encoder is a function f that maps an input x to a vector f(x) in R^d. Everything downstream (classification, search, clustering) then works on vectors, using operations that are cheap and well understood.
Three properties matter in practice:
- Fixed size. Every input produces exactly
dnumbers, regardless of image resolution or sentence length. - Learned, not hand-designed. The axes of the space have no human-readable meaning such as "dogness". Meaning lives in the geometry: directions and distances.
- Task-shaped. What counts as "similar" depends on the training objective. An embedding trained to classify ImageNet categories groups images differently from one trained to match captions.
Embeddings versus the one-hot alternative
A one-hot vector for a vocabulary of 50,000 tokens has 50,000 entries, one of which is 1. Every token is equally far from every other token, so "dog" is as distant from "puppy" as from "carburetor". A learned embedding table replaces this with a dense vector of a few hundred numbers, and training pulls related tokens together.
| Property | One-hot | Learned embedding |
|---|---|---|
| Dimension | Vocabulary size | Chosen, e.g. 512 |
| Density | One nonzero entry | All entries nonzero |
| Similarity between related items | None | Learned from data |
| Trainable | No | Yes |
Where embeddings come from in a network
Most deep networks already compute embeddings as intermediate results. A classifier built from a convolutional network or Vision Transformer ends in a feature vector that feeds a final linear layer producing class scores. That feature vector is an embedding. Take away the classification head and you have an encoder.
Image embeddings
An image encoder, such as a ResNet or a Vision Transformer, reduces a pixel grid to one vector. A ResNet produces a spatial feature map and pools it into a single vector. A Vision Transformer splits the image into patches, processes them with attention, and reads out a summary vector, often from a special classification token. Later chapters describe both in detail. For now, treat the image encoder as a function from (3, H, W) pixels to (d,).
Text embeddings
A text encoder first tokenizes the string into integer IDs, then looks up a learned embedding for each token, and then runs a Transformer over the sequence. To get one vector for the whole sentence, the model pools the sequence. Common choices are averaging the token vectors, or reading the vector at a designated position such as the end-of-text token. The chapter on the text encoder covers the choice CLIP makes.
Note the two levels here. A token embedding is one vector per token. A sentence embedding is one vector for the entire input. When people say "text embedding" in a retrieval context, they almost always mean the sentence-level one.
Looking at real embeddings
The following script loads a pretrained CLIP model only to obtain embeddings. You do not need to understand CLIP's training yet. It prints the shapes and the vector lengths. It assumes an image file named photo.jpg in the working directory.
import torch
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
model.eval()
image = Image.open("photo.jpg")
captions = ["a dog playing in the snow", "a plate of pasta"]
with torch.no_grad():
image_inputs = processor(images=image, return_tensors="pt")
text_inputs = processor(text=captions, return_tensors="pt", padding=True)
image_emb = model.get_image_features(**image_inputs)
text_emb = model.get_text_features(**text_inputs)
print("image embedding shape:", tuple(image_emb.shape))
print("text embedding shape: ", tuple(text_emb.shape))
print("image vector length: ", image_emb.norm(dim=-1).tolist())
print("text vector lengths: ", text_emb.norm(dim=-1).tolist())For this model the shapes are (1, 512) for the image and (2, 512) for the two captions. Both sides have the same dimension, 512. The vector lengths are not 1. Raw embeddings come out with arbitrary lengths, which becomes important in the next chapter.
The first dimension is the batch. One image gives one row, and two captions give two rows. The number of rows is independent of caption length because of pooling.
What similarity means for embeddings
Once inputs are vectors, comparison is arithmetic. Given two embeddings a and b, you can ask how close they are in three common ways:
- Euclidean distance,
||a - b||. Small means close. - Dot product,
a · b. Large means aligned, but it also grows with vector length. - Cosine similarity, the dot product of the vectors after scaling each to length 1. It measures only the angle between them.
Dot products mix direction with length, which is rarely what you want when comparing meaning. The next chapter explains why CLIP uses cosine similarity and normalizes its embeddings.
Here is a small example that compares embeddings from a toy table, to show the mechanics without a pretrained model:
import torch
import torch.nn as nn
torch.manual_seed(0)
vocab = {"dog": 0, "puppy": 1, "tractor": 2}
table = nn.Embedding(num_embeddings=len(vocab), embedding_dim=8)
ids = torch.tensor([vocab["dog"], vocab["puppy"], vocab["tractor"]])
vectors = table(ids) # (3, 8)
print(vectors.shape)
print("dog vs puppy distance: ", (vectors[0] - vectors[1]).norm().item())
print("dog vs tractor distance:", (vectors[0] - vectors[2]).norm().item())Because the table is untrained, the two distances are essentially random. Training is what would make "dog" and "puppy" close. This is the key point: an embedding space is only as meaningful as the objective used to train it.
Common errors
- Comparing embeddings from different models. Each model has its own space. A vector from one model has no meaningful relationship to a vector from another, even when the dimensions match.
- Mixing raw and normalized vectors. If some stored vectors are normalized and others are not, dot products are not comparable. Pick one convention and apply it everywhere.
- Forgetting
torch.no_grad()andmodel.eval()at inference. Without them you build an autograd graph and waste memory. In models with dropout or batch norm, you also get slightly different outputs. - Interpreting individual dimensions. Dimension 17 does not mean anything on its own. Only the geometry of the whole vector is meaningful.
- Assuming a bigger dimension is always better. More dimensions raise storage and search cost. Quality depends on the model and training data.
- Treating token embeddings as sentence embeddings. A per-token tensor has shape
(sequence, d). You must pool it, or use the model's designated sentence-level output.
Why this matters for CLIP
Image embeddings from a vision model and text embeddings from a language model are normally produced in separate spaces. A 512-number image vector from one network cannot be compared with a 512-number text vector from another. CLIP's central idea is to train both encoders together, so their outputs land in one shared space where an image and its caption are close. The following chapters build that up in order: cosine similarity, the joint space, the dual-encoder architecture, and then the contrastive loss that trains it.
Exercise
You compute a 512-dimensional embedding for an image with one pretrained model and a 512-dimensional embedding for a caption with a different, separately trained text model. A colleague proposes taking the dot product of the two vectors as an image-caption match score. Give two reasons this is unreliable.
Show answer
First, the two vectors live in different spaces. Nothing in training linked the image model's axes to the text model's axes, so matching dimension sizes does not make the numbers comparable. Second, raw embeddings have arbitrary lengths, so the dot product mixes vector length with direction and does not isolate how well the two align. A model trained jointly, as CLIP is, with normalized embeddings, addresses both problems.
Exercise
A text encoder returns a tensor of shape (4, 12, 512) for four captions of up to 12 tokens each. What do the three dimensions mean, and what must you do to get one vector per caption?
Show answer
The dimensions are batch (4 captions), sequence length (12 tokens), and embedding dimension (512). These are token-level embeddings. To get one vector per caption you pool over the sequence dimension, for example by averaging over tokens or by taking the vector at a designated position such as the end-of-text token. That gives shape (4, 512).