Code Architecture — CLIP (Contrastive Language–Image Pre-training)

Overview

The notebook builds a very small CLIP from scratch in PyTorch. An MLP image encoder and a GRU text encoder map 32×32 pictures of coloured shapes and their captions into a shared 128-d space. They are trained with the paper’s symmetric contrastive loss on 800 pairs for 20 epochs. Then 200 test pictures are classified by comparing them with the 18 possible captions. These captions are the same ones used in training, so this “zero-shot” test is much easier than the paper’s. The model is tiny and runs on a CPU.

Notebook Structure

1. Setup & Imports

  • PyTorch, NumPy, matplotlib, PIL and scikit-learn (t-SNE); nothing is installed
  • Seed 42 for random, NumPy and torch; CUBLAS_WORKSPACE_CONFIG set before importing torch, cuDNN deterministic, torch.use_deterministic_algorithms(True, warn_only=True)
  • Figures as JPEG at 80 dpi; on Kaggle an atexit hook and a small background process copy the executed notebook to executed_solution.ipynb

2. Synthetic Dataset (ShapeDataset)

  • draw_shape() draws a circle, square or triangle in one of 6 colours on a white 32×32 picture (IMG_SIZE = 32)
  • add_jitter() adds pixel noise (±10) and a random shift of up to 2 pixels
  • Caption "a {color} {shape}", so there are only 18 different captions
  • 800 training pairs and 200 test pairs, drawn at random; a grid of 10 samples is shown

3. Character-Level Tokenizer (CharTokenizer)

  • Maps each character to an integer (0 is padding); vocabulary size 20
  • Captions are padded or cut to MAX_LEN = 20
  • collate_fn returns images, token ids, caption strings and labels
  • Batch size 64: 12 training batches (drop_last=True, seeded shuffling) and 4 test batches

4. Image Encoder (ImageEncoder)

  • Flatten (3×32×32 = 3,072) → Linear 512 → ReLU → Linear 256 → ReLU → Linear 128
  • 1,737,600 parameters

5. Text Encoder (TextEncoder)

  • nn.Embedding(20, 128) → 1-layer nn.GRU(128, 128) → last hidden state → nn.Linear(128, 128)
  • 118,144 parameters

6. CLIP Model (CLIPModel)

  • L2-normalises both embeddings and returns logits_per_image = scale · image_emb @ text_embᵀ and its transpose
  • Learnable logit_scale initialised to log(1/0.07), so the scale starts at 14.29; the scale is clipped at 100
  • 1,855,745 parameters in total

7. Contrastive Loss (contrastive_loss)

  • Cross-entropy over rows (image → caption) and over columns (caption → image) with targets 0…N−1, averaged
  • Check: equal logits give exactly ln(4) for a 4×4 matrix; random logits give a different value

8. Training Loop

  • Adam, learning rate 1e-3, 20 epochs
  • Prints the loss and the temperature (scale) after epoch 1 and every 4 epochs; keeps the loss of every epoch

9. Training Visualization

  • Loss curve over the 20 epochs

10. “Zero-Shot” Classification (zero_shot_classify)

  • Encodes the 18 prompts "a {color} {shape}" and the 200 test pictures, and predicts the most similar prompt
  • Prints the accuracy; the prompts are exactly the training captions
  • Shows 10 random test pictures with predicted and true labels

11. Embedding Space Visualization

  • t-SNE (perplexity 25) of the 200 normalised 128-d test image embeddings, coloured by class

12. Similarity Heatmap

  • Scaled similarity matrix for the first test batch (64 × 64)
  • For the first 8 pictures, prints the best-matching caption and marks it OK when its text equals the picture’s own caption (many pictures in a batch share a caption)

13. Summary

  • ### What the run above shows with the saved run’s numbers

Key Shapes

Stage Shape (B = 64)
Images (64, 3, 32, 32)
Flattened (64, 3072)
Image MLP (64, 512) → (64, 256) → (64, 128)
Token ids (64, 20)
Character embeddings (64, 20, 128)
GRU last hidden state (1, 64, 128) → (64, 128)
Text projection (64, 128)
L2-normalised embeddings (64, 128) each
logits_per_image, logits_per_text (64, 64)
Zero-shot similarity (200 pictures × 18 prompts) (200, 18), computed in chunks of 100

Deliberate Simplifications vs Full Paper

  1. Data: 800 synthetic pictures with 18 different captions, instead of 400 million (image, text) pairs from the internet (Section 2.2).
  2. Image encoder: a 3-layer MLP on 32×32 pictures, instead of a modified ResNet or a Vision Transformer at 224 pixels or more (Section 2.4).
  3. Text encoder: a character-level tokenizer and a 1-layer GRU, instead of byte-pair encoding (49,152 tokens) and a 12-layer, 512-wide Transformer (Section 2.4).
  4. Projections: the last linear layer of each encoder plays the role of the paper’s linear projection into the shared space.
  5. Embedding size: 128, instead of 512 for ViT-B/32 (Table 20).
  6. Training: batches of 64 for 20 epochs with plain Adam, instead of batches of 32,768 for 32 epochs with decoupled weight decay and a cosine schedule (Section 2.5).
  7. Evaluation: the “zero-shot” prompts are the training captions, and there is no prompt ensembling; the paper tests on over 30 datasets it was not trained on (Sections 3.1.1 and 3.1.4).