72 min total

Computer Vision & OpenCV

CLIP

CLIP

Problem: Traditional CV models are limited to a fixed set of categories defined during supervised training.

Solution: Pretrain model using (text, image) pairs to predict which caption matches which image. Allows zero-shot transfer (no additional training required to adapt the model to new tasks/datasets)

Contrastive learning: self-supervised method where goal is to pull together representations of related pairs and push apart representations of unrelated pairs.

Representations: latent dimensions of data

Motivating work:

  • Pretraining on raw text (GPT3, BERT, T5) has transformed NLP, these models can generalize across tasks via zero-shot learning, if this worked in NLP, can we do the same in computer vision?
  • Computer vision depends on supervised datasets, each labelling consumes many human hours, is expensive and is limited in scope. Can we replace manual labels with natural language supervision (e.g. using image captions from the internet?)
  • There have been attempts to learn from image-text pairs previously, these methods were underpowered, zero-shot ImageNet accuracy was low (11.5%) and approaches were not scalable. Approaches {a} 1999-2012 - works tried predicting captions from images {b} Joulin et al. 2016 used image metadata as supervision {c} Li et al. 2017 used visual n-grams and tried zero-shot classification {d} VirTex 2020 used transformer based models and masked language modelling with image-text
  • Mahajan et al. 2018 used Instagram hashtags to pretrain CNNs these were still limited to fixed class vocabularies and relies on static softmax

Approach: Created a dataset of 400M image-text pairs from the internet uses contrastive learning to align images and text to shared latent space

  • ConVIRT 2020 is a pretraining approach trained on 200K pairs only, CLIP builds on ConVIRT architecture and scales it massively.
CLIP contrastive training and zero-shot classification

Benefit from learning from natural language:

  • easier to scale than manual image labelling since it doesn’t needs structured annotations
  • Models can learn passively from massive text found on internet
  • It also links representations to language enabling zero-shot transfer

CLIP dataset creation: WIT (WebImageText) contains 400 million image–text pairs collected from publicly available internet sources. The search process used a large query list, including frequent Wikipedia words, to broaden concept coverage. Public source material does not mean the assembled WIT training dataset was publicly released.

The dataset motivation contrasts curated, crowd-labeled MSCOCO and Visual Genome with internet-scale supervision. Their high-quality annotations are useful, but their size limits training at CLIP’s target scale. The notes list captions, alt text, titles, and descriptions as examples of text associated with web images.

The paper describes 500,000 search queries. Their construction starts with words appearing at least 100 times in English Wikipedia, then adds other terms to broaden coverage. The source note compresses these steps into one sentence.

Correction to the source’s filtering rule: keeping natural-language English titles or descriptions is explicitly discussed for the YFCC100M alternative. It should not be presented as a complete documented filtering specification for WIT.

CLIP paper — dataset construction

Selecting pretraining method:

  • Tried jointly training a CNN and Transformer to predict captions was inefficient and slow due to variation in exact image descriptions
  • shifted to predicting which image-text pairs match instead of exact words, Adopted contrastive loss instead of prediction based loss, found 4x efficiency improvement

How CLIP trains: for a batch N (image, text) pairs, model must identify correct pairing among NxN combinations, Trains text vision encoders to closely associate correct pairs and distance incorrect pairs, uses symmetric cross-entropy loss over similarity scores.

Embedding space: inspired by N-pair loss and InfoNCE loss

Training simplifications:

  • trained from scratch
  • no ImageNet pretraining
  • no pretrained text model
  • No non-linear projection heads → use linear projections
  • no sentence sampling, most texts are short
  • simple image augmentations (random square crop)
  • Temperature parameter τ is learned directly, not a hyperparameter

Choosing the right Architecture:

Image Encoder Architectures:

  • ResNet50 2016 - widely adopted and proven performance, applied resnet-D improvements (He et al. 2019) antialiased blur pooling, replaced global average pooling with attention pooling (transformer style multi-head QKV attention, Query is conditioned on global average pooled image representation)
  • Vision Transformer 2020 - follows original ViT closely, modifications include adding layer normalization to combine patch and position embeddings before transformer, uses a slight different initialization scheme

Text encoder: the base CLIP configuration uses 12 Transformer layers, a 512-dimensional hidden state, and eight attention heads. Lowercased byte-pair encoding uses a vocabulary of 49,152 tokens, with a 77-token context including boundary tokens. The final end-of-text representation is normalized and linearly projected into the shared embedding space.

The base text encoder has approximately 63 million parameters and follows the Transformer with the architectural modifications described by Radford et al. (2019). The notes name the boundary markers [SOS] and [EOS]. Masked self-attention preserves compatibility with autoregressive language-model training, although CLIP’s text encoder was trained from scratch with its contrastive objective.

The paper and notebook say “76 tokens,” whereas the released implementation allocates a context length of 77 including boundary tokens. These are different source conventions; use the tokenizer’s actual context limit when implementing the model.

CLIP paper — text encoder

Released CLIP tokenizer and context-length handling

Scaling strategy

Image Encoder: scaled model by increasing width, depth and resolution simultaneously, allocated compute equally across three dimensions

Text Encoder: only width is scaled proportionally to image encoder, depth remains unchanged

Training process: Adam optimizer | cosine decay in learning rate | batch size 32,768 | epochs 32 | Hyperparameters tuned on RN50.

Efficiency techniques include mixed precision training, gradient checkpointing, GPU sharding for similarity computation.

CE denotes cross-entropy. Each row of the similarity matrix compares one image with all texts; each column compares one text with all images. The paired item is the target in each direction.

Compute: RN50X64: 18 days on 592 V100 GPUs, ViT L/14: 12 days on 256 V100 GPUs

ViT-L/14@336px is one CLIP model configuration, evaluated with higher-resolution inputs.

Loss function used: InfoNCE loss (symmetric cross-entropy) loss over similarity scores bw image text pairs

CLIP for zero shot transfer:

  • class names from target dataset used as candidate labels
  • image and class names are encoded using CLIPs image and text encoders.
  • cosine similarity computed between image and each class name
  • results are scaled by a temperature parameter and passed through softmax to get probabilities (interpreted as L2 normalized multinomial logistic regression)

Prompt engineering in CLIP: similar to GPT3 customizing input prompt can enhance performance. 'a photo of a xyz' will improve generalizability of CLIP model. We can also create multiple context prompts to increase improvement

CLIPs performance: CLIP outperforms supervised ResNet pretrained weights logistic regression model in 16 out of 27 datasets. Its because CLIP uses natural language prompts. 20.8 examples/class required for that logistic regression model to train on to match zero-shot CLIP performance. There is a room for improvement in abstract domains.

CLIP for downstream tasks:

  • Linear classifier: we freeze the CLIP model, add a simple linear layer on top of CLIPs features to classify images
  • We unfreeze the whole model and train it end-to-end on a new task, adjusts all the weights of the model to fit the new task better. Usually gives better performance, costs more compute. CLIP transformers are 3x more compute efficient than ResNet backbone

Human and CLIP performance on Oxford-IIIT Pets

SettingAverage per-class accuracy
Zero-shot human53.7%
Zero-shot CLIP93.5%
One-shot human75.7%
Two-shot human75.7%

These are the full-dataset figures in Table 2 of the CLIP paper. The one- and two-shot settings describe the human participants; CLIP remains the zero-shot comparison.

The comparison is specifically for Oxford-IIIT Pets. The original table repeats the same zero-shot CLIP score beside different human-example conditions; that repetition does not mean CLIP was retrained under each human condition.

Data overlap analysis: large internet pretraining datasets may unintentionally include images from evaluation datasets, undermining true generalization.

Methods to detect

  • duplicate detection - use nearest neighbor detector, for each eval dataset, run the detector, manually inspect results, set similarity threshold, discard over the threshold dataset (overlapping dataset).
  • contamination estimation - measure contamination using formulas.

CLIP Limitations:

  • zero shot performance is comparable to ResNet50 + linear classifier
  • would require 1000x more compute to match SOTA models on specific vision datasets
  • Poor on fine-grained classification (e.g. bird species)
  • fails on systematic tasks (e.g. counting)
  • Novel tasks (e.g. estimating car distance) performs poorly)
  • Relies on scale rather than efficient learning
  • Training data is unfiltered, inherits social biases
  • Transitioning from zero-shot to few-shot can result in a drop, unlike humans who improve significantly
  • labels like criminal disproportionately misclassifies Black individuals and children

Paper contributions:

  • introduced contrastive learning to jointly training image and text embeddings
  • Collected 400M image, text pairs
  • enabled zero shot image classification over 30 diverse datasets without finetuning
  • created unified multimodal embedding space
  • Explored ResNet, ViT and Transformers
  • Analyzed societal biases and ethical considerations inherent in the model
  • highlighted challenges in robustness, fairness and evaluation for multimodal models
  • established a foundation to inspire further research in vision-language representation learning

Paper: Learning Transferable Visual Models From Natural Language Supervision