Skip to content
E
Educatum

CLIP

By Educatum AI teamLast updated: Original walkthrough ↗
Key Intuition

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.

Reference Diagram & Materials
CLIP matrix calculation diagram

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

  1. Input (Mini-Batch):
    • The model receives a batch of NN paired (image, text) examples simultaneously (e.g., N=3N = 3 pairs in the hand-calculated diagram, vs. large batches of up to 32,76832{,}768 pairs in Radford et al.’s original CLIP training).
  2. 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).
  3. 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.
  4. Projection to a Shared Embedding Space:
    • Separate linear projection heads map the text vector and image vector into the same embedding dimension dd, followed by L2 normalization (u^=u/∥u∥2\hat{u} = u / \|u\|_2, v^=v/∥v∥2\hat{v} = v / \|v\|_2) so every vector lies on the unit hypersphere.
  5. Contrastive Pre-training (Symmetric InfoNCE Loss):
    • Similarity Matrix: Pairwise cosine similarities between all NN image embeddings and NN text embeddings are computed via a single matrix multiplication and scaled by a learnable temperature parameter τ\tau (logits Zij=eτ(u^i⋅v^j)Z_{ij} = e^{\tau} (\hat{u}_i \cdot \hat{v}_j)).
    • Softmax & Target Identity Matrix: Applying softmax converts each row (image →\to texts) and each column (text →\to images) into probability distributions. Because the ii-th image matches the ii-th text, the one-hot ground-truth target matrix is the N×NN \times N identity matrix INI_N (11 on the diagonal, 00 off-diagonal).
    • Symmetric Cross-Entropy Loss: CLIP averages the cross-entropy loss across both axes (image-to-text and text-to-image): LCLIP=12(Limage→text+Ltext→image)\mathcal{L}_{\text{CLIP}} = \frac{1}{2}\left(\mathcal{L}_{\text{image}\to\text{text}} + \mathcal{L}_{\text{text}\to\text{image}}\right)
    • Gradients flow back through the projection layers, image encoder, and text encoder.

Why Does the Gradient Simplify to [Similarity - Target] (pi−yip_i - y_i)?

Consider one row (or column) of the similarity matrix with raw logits z1,…,zNz_1, \dots, z_N and one-hot target distribution y1,…,yNy_1, \dots, y_N (where ∑j=1Nyj=1\sum_{j=1}^N y_j = 1):

  1. Softmax Probabilities: pi=ezi∑k=1Nezkp_i = \frac{e^{z_i}}{\sum_{k=1}^{N} e^{z_k}}

  2. Cross-Entropy Loss: L=−∑j=1Nyjlog⁡(pj)\mathcal{L} = -\sum_{j=1}^{N} y_j \log(p_j)

  3. Chain-Rule Gradient Derivation: We differentiate L\mathcal{L} with respect to logit ziz_i: ∂L∂zi=∑j=1N∂L∂pj⋅∂pj∂zi\frac{\partial \mathcal{L}}{\partial z_i} = \sum_{j=1}^{N} \frac{\partial \mathcal{L}}{\partial p_j} \cdot \frac{\partial p_j}{\partial z_i}

    • The loss derivative wrt probability is ∂L∂pj=−yjpj\frac{\partial \mathcal{L}}{\partial p_j} = -\frac{y_j}{p_j}.
    • The softmax Jacobian has two cases: ∂pj∂zi={pi(1−pi)if j=i−pjpiif j≠i\frac{\partial p_j}{\partial z_i} = \begin{cases} p_i(1 - p_i) & \text{if } j = i \\ -p_j p_i & \text{if } j \ne i \end{cases}
    • Substituting both into the sum: ∂L∂zi=−yipi⋅pi(1−pi)−∑j≠iyjpj⋅(−pjpi)=−yi+piyi+pi∑j≠iyj=pi∑j=1Nyj−yi\frac{\partial \mathcal{L}}{\partial z_i} = -\frac{y_i}{p_i} \cdot p_i(1 - p_i) - \sum_{j \ne i} \frac{y_j}{p_j} \cdot (-p_j p_i) = -y_i + p_i y_i + p_i \sum_{j \ne i} y_j = p_i \sum_{j=1}^{N} y_j - y_i
    • Because ∑j=1Nyj=1\sum_{j=1}^N y_j = 1 for any valid target distribution (including each row/column of the identity matrix), the expression collapses cleanly to: ∂L∂zi=pi−yi\frac{\partial \mathcal{L}}{\partial z_i} = p_i - y_i

This is why backpropagation starts directly from [Predicted Softmax Similarity - Target] (pi−yip_i - y_i).

Diagram

CLIP gradient derivation diagram

More in GenAI by Hand

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.