Sub topic 7
Training data: image-text pairs from the web
This chapter assumes you know what an embedding is, how cosine similarity works, and how a contrastive batch is built. You should also be comfortable reading short PyTorch snippets. Here we look at the data CLIP learns from. The data shapes what the model can and cannot do, so it matters as much as the architecture.
Why the data source matters
CLIP learns by matching images to captions. Each training example is a pair: one image and one piece of text that describes it, or at least sits near it. The model needs hundreds of millions of such pairs. Hand-labeling that many images with fixed class names is too slow and too costly. The web already holds a huge number of images with text attached, such as alt text, captions, titles, and surrounding sentences.
Classic datasets like ImageNet use a closed label set of 1,000 classes. Each label is a single choice from a fixed list. CLIP's text is free-form language instead. A caption such as "a golden retriever catching a frisbee on a beach" carries many concepts at once. This is why the model can later be asked about classes it was never explicitly trained on.
What a training pair looks like
A pair is a tuple of an image and a string. The string is noisy. It may be a faithful description, a product name, a filename, or a vague phrase.
| Source of text | Example | Typical quality |
|---|---|---|
| Alt text | "red bicycle leaning on a brick wall" | Often good |
| Caption under a photo | "Crowds gather in the square on Friday" | Good, but may describe events not visible |
| Page title or filename | "IMG_2041 final v2" | Poor |
| Product listing | "Men's trail shoe, size 10" | Narrow but consistent |
The original CLIP paper reports a dataset of about 400 million image-text pairs, which the authors called WIT (WebImageText). OpenAI collected it by searching the web for about 500,000 text queries and keeping up to roughly 20,000 pairs per query to balance coverage. The dataset was not released. Public replications use other sources, covered below.
How a pair becomes a training signal
In the contrastive setup, each pair in a batch is a positive. Every other image-text combination in that batch is a negative. The data therefore supplies two things at once: positives (the pairs as collected) and negatives (the mismatched combinations that appear by chance inside a batch).
Because negatives come from the same batch, the dataset's diversity directly affects how hard the task is. If a batch holds 32,768 pairs, each image is compared against 32,767 wrong captions. A diverse dataset makes most of those wrong captions clearly different. A narrow dataset makes some of them near duplicates of the right one, which produces confusing signals.
Collection and filtering
Raw web data is messy, so every large pair dataset goes through filtering. Common steps are:
- Download and parse. Collect image URLs and their associated text from crawled pages.
- Basic checks. Drop images that are too small, have extreme aspect ratios, or fail to decode. Drop empty or very short text.
- Language filtering. Keep text in the target language. The original CLIP training was mostly English.
- Deduplication. Remove exact and near-duplicate images, and repeated captions.
- Quality scoring. Optionally score pair quality, for example by using an existing model's image-text similarity as a filter.
Public datasets use step 5 heavily. LAION-400M and LAION-5B were built by computing CLIP similarity between each image and its text, and keeping pairs above a threshold (about 0.28 for the English subset of LAION-5B, as published by its authors). This is a form of bootstrapping: an existing model decides which data trains the next one. It works well in practice, but it also means the new data inherits the filter model's blind spots.
You can write a small version of this filter yourself. The function below keeps only the pairs whose cosine similarity exceeds a threshold, given precomputed embeddings.
import torch
import torch.nn.functional as F
def filter_pairs(image_emb, text_emb, threshold=0.28):
# image_emb, text_emb: (n, dim); row i of each is one candidate pair
image_emb = F.normalize(image_emb, dim=-1)
text_emb = F.normalize(text_emb, dim=-1)
sims = (image_emb * text_emb).sum(dim=-1) # cosine similarity per pair
keep = sims > threshold
return keep, sims
torch.manual_seed(0)
img = torch.randn(6, 8)
txt = img + 0.5 * torch.randn(6, 8) # captions loosely related to images
txt[3] = torch.randn(8) # one unrelated caption
keep, sims = filter_pairs(img, txt)
print(keep.tolist())
print([round(s, 3) for s in sims.tolist()])Note that the product image_emb * text_emb followed by a sum computes one dot product per row. This is cheaper than building the full matrix when you only need the matched pairs.
Edge cases and common errors
Duplicate and near-duplicate captions in a batch. If two different images share the same caption (for example "product photo"), the loss treats one of them as a negative even though the text fits both. This adds label noise. Deduplicating captions, or limiting how often one caption can appear, reduces it.
Test set contamination. Web data may contain images from benchmark test sets. If the same image appears in both training and evaluation, zero-shot scores look better than they should. The CLIP authors ran a duplicate-detection analysis against their evaluation sets and found the effect on reported results to be small. You should still check this for any dataset you build.
Caption versus image mismatch. Many captions describe context rather than visible content. A news photo captioned "Mayor announces budget" does not tell the model what the mayor looks like. The model learns whatever correlations exist, including unhelpful ones.
Text in images. Web images often contain printed words. CLIP learns to read some of this text, because the caption often repeats it. This helps with some tasks and creates the typographic attack described in the limitations chapter.
Language and region skew. The data reflects what is posted online, mostly in English and from regions with more internet content. Concepts that are rare in the data are poorly represented in the embedding space.
Scale and its trade-offs
CLIP's results depend heavily on scale. Published scaling studies with open data, such as the OpenCLIP work, show that zero-shot accuracy improves smoothly as the number of training samples seen and the model size grow. More data helps, but only if it stays reasonably clean. The comparison below summarizes the usual trade-off.
| Choice | Benefit | Cost |
|---|---|---|
| Larger, loosely filtered set | More concept coverage | More noise, more duplicates |
| Smaller, strictly filtered set | Cleaner signal | Gaps in rare concepts |
| Filtering with an existing model | Cheap, scalable | Inherits that model's biases |
| Curated, human-checked data | Reliable labels | Expensive, hard to scale |
Another cost is that web data is uncurated. It includes offensive, private, and copyrighted material. LAION-5B was taken offline by its maintainers in late 2023 after researchers found illegal content in it, and was later re-released in a cleaned form. Anyone training on web-scale data needs a plan for safety review, licensing, and removal requests.
Practical guidance
- If you fine-tune CLIP on your own pairs, check caption quality before you check anything else. A few thousand clean pairs often help more than a large noisy set.
- Keep batches diverse. Shuffle across sources so that one batch does not contain many near-identical items.
- Hold out an evaluation set before filtering, and check for overlap by embedding both sets and looking for near-identical image vectors.
- Record where each pair came from. You will need this when you debug a bias or a removal request.
Exercise
Your fine-tuning set has 10,000 pairs, and 2,000 of them share the caption "product photo" across different images. Explain how this affects the contrastive loss within a batch, and name one fix.
Show answer
When two images with the caption "product photo" appear in the same batch, the loss treats the caption of one as a wrong match (a negative) for the other, even though it fits both. This pushes the model to separate things that should be close and adds noise. Fixes include replacing the generic captions with specific ones, removing most of the duplicates, or capping how often a single caption can appear in the dataset or in one batch.
Exercise
A team builds a new pair dataset by keeping only pairs whose cosine similarity under an existing CLIP model exceeds 0.30. Give one advantage and one risk of this approach.
Show answer
The advantage is that it is cheap and scales to billions of pairs without human labeling. The risk is that the new dataset inherits the existing model's biases and blind spots, because pairs that the old model scores low are removed even when they are correct. Examples include rare concepts, uncommon languages, and unusual phrasing.