CLIP
CLIP (Contrastive Language-Image Pre-training) aligns images and text in a shared embedding space by maximizing cosine similarity for matched pairs and minimizing it for mismatched pairs in a mini-batch via symmetric InfoNCE cross-entropy loss. Under softmax and cross-entropy against an identity-matrix target, the gradient with respect to similarity logits simplifies cleanly to p_i - y_i.

Goal: AI By Hand Step-by-Step for CLIP
Train a dual-encoder model that aligns images and text in a shared embedding space, so matched (image, text) pairs have high similarity while mismatched pairs are pushed apart.
Architecture & Training Pipeline
- Input (Mini-Batch):
- The model receives a batch of paired
(image, text)examples simultaneously (e.g., pairs in the hand-calculated diagram, vs. large batches of up to pairs in Radford et al.’s original CLIP training).
- The model receives a batch of paired
- Text Encoding:
- Token Embeddings: In the simplified hand calculation, each word maps to an embedding vector via a lookup table. In actual CLIP, text is split via Byte-Pair Encoding (BPE) subword tokenization and mapped through a learned embedding table trained end-to-end (not frozen Word2Vec).
- Text Encoder: A Transformer processes the sequence of token embeddings to produce a single text feature vector per caption (extracted at the
[EOS]token in CLIP).
- Image Encoding:
- Patching and Flattening: In a Vision Transformer (ViT) image encoder, the image is divided into fixed-size patches, flattened, and linearly projected into patch embeddings with positional encodings.
- Image Encoder: A ViT (or ResNet) processes these tokens to output a single image representation vector.
- Projection to a Shared Embedding Space:
- Separate linear projection heads map the text vector and image vector into the same embedding dimension , followed by L2 normalization (, ) so every vector lies on the unit hypersphere.
- Contrastive Pre-training (Symmetric InfoNCE Loss):
- Similarity Matrix: Pairwise cosine similarities between all image embeddings and text embeddings are computed via a single matrix multiplication and scaled by a learnable temperature parameter (logits ).
- Softmax & Target Identity Matrix: Applying softmax converts each row (image texts) and each column (text images) into probability distributions. Because the -th image matches the -th text, the one-hot ground-truth target matrix is the identity matrix ( on the diagonal, off-diagonal).
- Symmetric Cross-Entropy Loss: CLIP averages the cross-entropy loss across both axes (image-to-text and text-to-image):
- Gradients flow back through the projection layers, image encoder, and text encoder.
Why Does the Gradient Simplify to [Similarity - Target] ()?
Consider one row (or column) of the similarity matrix with raw logits and one-hot target distribution (where ):
-
Softmax Probabilities:
-
Cross-Entropy Loss:
-
Chain-Rule Gradient Derivation: We differentiate with respect to logit :
- The loss derivative wrt probability is .
- The softmax Jacobian has two cases:
- Substituting both into the sum:
- Because for any valid target distribution (including each row/column of the identity matrix), the expression collapses cleanly to:
This is why backpropagation starts directly from [Predicted Softmax Similarity - Target] ().
Diagram
