Self-supervised and contrastive learning (SimCLR, CLIP)
What is Self-supervised Learning?
Key distinction:
- Unsupervised learning: Find structure (clustering, density estimation) with no labels
- Self-supervised learning: Create pseudo-labels from data structure, then train with those
- Supervised learning: Use human-provided labels
Why does this work?
To solve pretext tasks well, the model must learn general features about the data. If you train a model to predict whether two image crops come from the same photo, it must learn:
- Object parts and boundaries
- Colors, textures, shapes
- Spatial relationships
These representations transfer to downstream tasks like classification or detection.
What is Contrastive Learning?
The contrastive objective mathematically:
For anchor sample , positive (augmented/related view), and negatives :
where:
- is the learned representation
- is cosine similarity
- is a temperature parameter (controls concentration)
Why this form? This is the InfoNCE loss (Noise Contrastive Estimation). Let's derive why it makes sense:
- Goal: Make positive pair similar, negatives dissimilar
- Softmax over similarities: Treat it as classifying the positive among N+1 choices
- Temperature : Smaller → sharper distribution, model must be more confident
- Logarithm: Convert products to sums, stabilize gradients
The denominator normalizes so the loss interprets as "negative log probability of identifying the positive sample."
SimCLR: Simple Framework for Contrastive Learning
The SimCLR Recipe (4 key ingredients)
1. Data Augmentation Create two random augmented views and from image :
- Random crop + resize
- Color distortion (brightness, contrast, saturation, hue)
- Gaussian blur
- Random grayscale
Why? Strong augmentation creates challenging positive pairs. The model can't cheat by memorizing pixels; it must learn semantic features invariant to these transforms.
2. Base Encoder A neural network (typically ResNet) that maps images to representations:
3. Projection Head A small MLP that maps representations to a space where contrastive loss is applied:
Why a projection head? Loss is applied to , but we save for downstream tasks. This separation improves performance (empirically shown in the SimCLR paper). The projection head can contain information useful for the pretext task but not for transfer.
4. Contrastive Loss For a batch of samples, we get augmented views. For each positive pair :
The final loss averages over all positive pairs:
Why this formulation? Each augmented view serves as anchor once. We treat all other samples in the batch as negatives (all images in the batch are different, except the paired augmentation).
Step 1: Sample 4 images: cat, dog, car, tree
Step 2: Augment each twice → 8 views: cat₁, cat₂, dog₁, dog₂, car₁, car₂, tree₁, tree₂
Step 3: Encode through and :
Step 4: Compute loss for anchor cat₁:
- Positive: cat₂ (sim = 0.85)
- Negatives: dog₁, dog₂, car₁, car₂, tree₁, tree (sims ≈ 0.1-0.3)
With , numerator , denominator , so loss .
Why this step? Softmax amplifies the positive pair's contribution. Gradients push cat₁ and cat₂ closer, push negatives away.
Result: After training, embedings cluster same objects together, generalize to new images.
Why SimCLR Works: The Magic of Large Batches & Strong Augmentation
With , each sample contrasts against 8190 negatives. This provides rich supervision.
Temperature : Controls hardness of negatives.
- Small (e.g., 0.1): Focus on hard negatives (sharp distribution)
- Large (e.g., 1.0): Treat all negatives more equally (soft distribution)
Typical value:
Augmentation strength: Stronger augmentation forces invariance to more transformations. SimCLR found combining color distortion + crop + blur crucial.
CLIP: Contrastive Language-Image Pre-training
The CLIP Architecture
Two encoders:
-
Image encoder: Vision Transformer (ViT) or ResNet
-
Text encoder: Transformer
Both project to a joint embedding space of dimension (typically 512 or 1024).
Training data: 400 million (image, text) pairs scraped from the internet.
CLIP's Contrastive Objective: A Symmetric Dance
Given a batch of (image, caption) pairs:
- Compute image embedings:
- Compute text embedings:
- Compute pairwise cosine similarities:
The symmetric loss: For each image, its correct caption is positive, all others are negative (and vice versa).
Image-to-text loss (row-wise softmax):
Text-to-image loss (column-wise softmax):
Total CLIP loss:
Why symmetric? Both directions (image→text and text→image) provide gradient signal. This treats both modalities equally, preventing one from dominating.
Similarity matrix (after encoding, values are cosine similarities):
T_cat T_dog T_car T_tree
I_cat 0.85 0.15 0.10 0.12
I_dog 0.18 0.82 0.14 0.11
I_car 0.09 0.13 0.88 0.15
I_tree 0.11 0.10 0.16 0.84
Image-to-text for I_cat (want to pick T_cat):
With : numerator , denominator dominated by correct pair, loss≈ 0.05 (small, good).
Why this step? High diagonal values (correct pairs) mean low loss. Gradients make encoders align matching pairs more strongly.
Zero-shot use: At test time, for class "airplane", compute similarity between image and text "a photo of an airplane" without any airplane training labels.
Why CLIP is Revolutionary
1. Zero-shot transfer: No labeled data for new tasks
- Create text prompts for classes: "a photo of a [CLASS]"
- Compute similarity with image embedding
- Predict class with highest similarity
2. Robustness: Trained on diverse internet data, not curated datasets
- Better handles distribution shift
- More robust to adversarial examples (not explicitly optimized for ImageNet quirks)
3. Flexibility: Understands nuanced language
- Can distinguish "a photo of a cat" vs "a drawing of a cat"
- Handles compositional queries: "a cat wearing sunglasses"
Encode: , each
Compute logits:
where is a learned temperature scaling.
Apply softmax for probability:
Why this works: The embedding space was trained so that semantically matching (image, text) pairs have high cosine similarity. At test time, the image naturally aligns with the correct class description.
Common Mistakes & Misconceptions
Why it's wrong: The model never sees the same augmented view twice. It must learn semantic features that remain invariant across augmentations (rotation, crop, color jitter). It can't memorize pixel patterns.
The fix: Contrastive learning forces the model to extract features robust to augmentations. These features generalize because they capture high-level semantics, not low-level pixels.
Why it's wrong: Contrastive learning needs many negatives. With batch size 32, SimCLR only has 62 negatives per sample. This provides weak signal.
The fix: Use large batch sizes (≥1024) or memory banks/momentum encoders (like MoCo) to maintain a large pool of negatives. More negatives → harder task → better representations.
Math: With samples, negatives = . For :62 negatives. For : 8190 negatives (132× more contrast).
Why it's wrong: Empirically, using a projection head and saving for downstream tasks improves transfer performance by 10+ percentage points.
Why it works: The projection head can contain information useful for the contrastive pretext task (e.g., color, exact spatial position) that's not useful for semantic downstream tasks. By separating representation () from contrastive space (), we get better general features.
Why it's wrong: For tasks with abundant labeled data (e.g., ImageNet classification), fine-tuned supervised models still outperform CLIP zero-shot. CLIP's strength is generalization to new tasks/distributions, not peak accuracy on standard benchmarks.
The tradeoff: CLIP trades some peak accuracy for flexibility and robustness. Use CLIP for:
- Zero/few-shot learning
- Tasks with scarce labels
- Domain adaptation
- Open-vocabulary recognition
Use supervised fine-tuning when:
- You have abundant labeled data
- You need maximum accuracy on a fixed task
- Latency/compute is critical (CLIP models are larger)
Connections
- Supervised learning fundamentals - contrastive learning avoids expensive labeling
- Transfer learning and fine-tuning - self-supervised pretraining → fine-tune on downstream tasks
- Data augmentation techniques - SimCLR depends critically on augmentation design
- Metric learning and embedings - contrastive learning learns a metric space with semantic meaning
- Vision transformers (ViT) - CLIP uses ViT as image encoder
- Attention mechanisms and transformers - CLIP's text encoder is a Transformer
- Zero-shot and few-shot learning - CLIP enables zero-shot classification via language
- Multi-modal learning - CLIP bridges vision and language modalities
- Representation learning - core goal: learn features that transfer across tasks
- Batch normalization and training techniques - large batch training requires careful optimization (LARS optimizer)
Recall Explain to a 12-year-old
Imagine you're learning what cats and dogs look like, but nobody tells you which is which.
Instead, you play a game: I show you two photos. Sometimes they're two pictures of the same cat (just from different angles or lighting). Sometimes one is a cat and one is a dog. Your job is to say "same" or "different."
At first you guess randomly. But to get good at this game, you start noticing: "Oh, cats have pointy ears and whiskers. Dogs have floppy ears and longer snouts." You're learning what makes cats look like cats and dogs look like dogs, even though nobody labeled them!
That's contrastive learning. SimCLR does this with millions of images. It learns "these two weird-looking pictures are actually the same cat" by focusing on what doesn't change when you tilt the camera or change the lighting.
CLIP adds language: now you also have captions. It learns "this picture goes with the sentence 'a fluffy cat' but not with'a red car'." So when you show it a new picture and ask "is this a cat or a car?", it compares the image to those descriptions and answers correctly—without ever being told "this is a cat photo" during training!
CLIP = Contrastive Language-Image Pre-training
"CLIP images to captions with contrastive loss"
Contrastive loss mnemonic: "Push Negatives, Pull Positives"
The loss denominator includes positives (numerator) and negatives, normalized.
Key equation structure:
Think: "Maximize probability of picking the positive from a lineup"
#flashcards/ai-ml
What is the core principle of contrastive learning? :: Contrastive learning maximizes agreement (similarity) between positive pairs while minimizing agreement between negative pairs in a learned embedding space.
What are the four key components of SimCLR?
Write the InfoNCE contrastive loss formula for anchor , positive , and negatives :: where is cosine similarity and is temperature.
Why does SimCLR use a projection head on top of the encoder?
What is CLIP's training objective?
How does CLIP perform zero-shot classification?
Why do contrastive methods need large batch sizes?
What is the temperature parameter τ in contrastive loss and what does it control?
What is the difference between self-supervised and unsupervised learning?
Why is CLIP robust to distribution shift?
What data augmentations are critical for SimCLR?
When should you use CLIP vs supervised models?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho yaar, core intuition simple hai: humare paas internet pe crores images aur text available hain, but unko manually label karna (yeh cat hai, yeh dog hai) bohot mehenga aur time-consuming kaam hai. Toh self-supervised learning kehti hai ki data ko khud hi apna label banane do! Model ko ek "pretext task" diya jaata hai — jaise ek image ke do alag-alag crops dekhke pehchano ki dono same photo se aaye hain ki nahi. Yeh task solve karne ke liye model ko automatically object ke shapes, colors, textures, boundaries sab seekhna padta hai. Bina kisi human label ke, model useful features seekh leta hai.
Ab contrastive learning ismein ek specific trick hai — iska funda hai "positive pairs ko paas kheencho, negative pairs ko door dhakelo." Matlab same cat ke do augmented views (thoda crop kiya, color thoda change kiya) ko representation space mein similar banao, aur cat vs dog ko alag rakho. Yeh maths mein InfoNCE loss ke through hota hai, jismein basically ek softmax classification jaisa setup hota hai — model ko positive sample ko N+1 options mein se pehchanna hai. Temperature parameter τ control karta hai ki distribution kitni sharp ho. SimCLR isi idea ko use karta hai: strong augmentation lagao, ResNet encoder se features nikaalo, aur ek projection head ke through contrastive loss apply karo.
Yeh cheez important kyun hai? Kyunki pretraining ek baar bina labels ke ho jaaye, toh phir tumhe downstream tasks (classification, detection) ke liye sirf thode se labeled data ki zaroorat padti hai. CLIP jaise models toh images aur text dono ko ek saath align karte hain, jisse zero-shot classification possible ho jaata hai — bina training ke naye categories pehchan lena. Regional students ke liye yeh isliye bhi kaam ka hai kyunki jahan labeled data kam hai (jaise local languages ya specific domains), wahan self-supervised approach bohot powerful ban jaata hai. Yeh modern AI ka backbone hai — GPT, BERT, foundation models sab isi philosophy pe khade hain.