Module contents
Lesson 23 of 33Core 115 min

CLIP: aligning images and text with contrastive learning

Derive CLIP's symmetric image–text contrastive objective and zero-shot classification; compare SigLIP, locked-image tuning, data curation, modality gap and distribution shift.

After this lesson you can

  • Derive and implement symmetric CLIP InfoNCE with learned temperature.
  • Build zero-shot classifiers with prompt templates and ensembles and measure their effect.
  • Compare CLIP softmax and SigLIP sigmoid loss for communication cost and small batches.
  • Train a small CLIP with a frozen image tower on a local GPU.
  • Measure a pretrained CLIP's modality gap and discuss its origin.

Before you start

Language as an interface

A conventional classifier fixes its categories during training. A model with aligned image and text embeddings lets us describe categories afterward: “a photograph of a frog” and “a photograph of a horse” are encoded as texts, and an image is compared with both. The same space can be used for retrieval, filtering, or as part of a generative system; that does not mean it understands every relation, count, or bias in an image.

CLIP contrastive pretraining learns two encoders from image–text pairs. For a batch of NN pairs, normalize each embedding ui,vju_i,v_j to unit norm and compute Sij=s ui⊤vjS_{ij}=s\,u_i^\top v_j, where s=1/τ>0s=1/\tau>0. The diagonal contains observed pairs. The symmetric loss averages image-to-text and text-to-image cross-entropy:

LCLIP=−12N∑i[log⁡eSii∑jeSij+log⁡eSii∑jeSji].L_{\mathrm{CLIP}}=-\frac{1}{2N}\sum_i\left[\log\frac{e^{S_{ii}}}{\sum_j e^{S_{ij}}}+\log\frac{e^{S_{ii}}}{\sum_j e^{S_{ji}}}\right].

Each row competes among texts and each column among images. Off-diagonal pairs are treated as negatives in this objective, although two descriptions may both be true for the same image. This introduces false negatives; deduplication or multiple-positive objectives can mitigate them. CLIP trained on 400 million web pairs; that describes the published work, not this page’s small lab.

Under InfoNCE sampling, with positives from the joint distribution and independent negatives from the marginal, log⁡N−LInfoNCE\log N-L_{\mathrm{InfoNCE}} lower-bounds mutual information in expectation. The bound depends on those assumptions and does not automatically make finite-batch loss on web data with duplicates an exact mutual-information measure. Increasing candidate count in particular can change the bound’s usefulness and computational cost.

InteractiveA batch similarity matrix
text jimg i0.77−0.18−0.24−0.120.130.430.07−0.21−0.120.830.20−0.320.120.16−0.280.020.200.040.88−0.090.010.04−0.07−0.050.210.07−0.340.840.00−0.190.28−0.26−0.38−0.040.300.020.78−0.320.050.490.190.04−0.04−0.10−0.340.79−0.29−0.430.19−0.01−0.19−0.39−0.180.050.840.34−0.24−0.060.19−0.10−0.330.130.370.741122334455667788

Texts for image 1

1
0.77
2
0.01
3
0.00
4
0.01
5
0.03
6
0.14
7
0.02
8
0.01

Images for text 1

1
0.80
2
0.01
3
0.05
4
0.05
5
0.00
6
0.04
7
0.04
8
0.01

Normalized deterministic synthetic vectors: the diagonal is the match, not real photographs or texts. The matrix shows cosines; temperature and bias change probabilities and losses, not cosines.

0.20
1
1
-2.0
P(text j | image i)0.772
P(image i | text j)0.797
Pair loss0.148
Symmetric CLIP0.187
SigLIP sum / N1.363
Eight deterministic synthetic pairs; the matrix shows cosines of normalized vectors. Probabilities and both losses are recalculated as temperature and bias change.

Learned temperature controls competition sharpness. Low temperature amplifies differences and can concentrate gradients on a few hard negatives; it does not change cosine ranking at inference. Usually ℓ=log⁡s\ell=\log s is learned to keep s>0s>0 and its scale limited to avoid extreme logits. Softmax should subtract its maximum or use log-sum-exp. Normalization before the product is essential to interpret the score as cosine.

For image ii, define Pij=softmax⁡j(Sij)P_{ij}=\operatorname{softmax}_{j}(S_{ij}) and Qij=softmax⁡i(Sij)Q_{ij}=\operatorname{softmax}_{i}(S_{ij}). If uiu_i is already unit length and treated as an independent variable,

∂L∂ui=s2N(∑j(Pij+Qij)vj−2vi).\frac{\partial L}{\partial u_i}=\frac{s}{2N}\left(\sum_j(P_{ij}+Q_{ij})v_j-2v_i\right).

The first average comes from the row and the second from columns. To differentiate with respect to the pre-normalization vector, also apply Jacobian (I−uiui⊤)/∥xi∥(I-u_i u_i^\top)/\|x_i\|; omitting it yields a different gradient. In the lab we check it with finite differences for both modalities.

Classifying without task examples

Zero-shot transfer with prompts encodes a template per class and chooses the text most similar to the image. Results depend on vocabulary, language, and context; a class may need a description distinguishing its possible senses. Ensembling computes several text embeddings per class, averages and renormalizes the prototype. It does not guarantee improvement: it can add biases or unsuitable contexts and should be evaluated independently of data used to choose templates.

InteractiveZero-shot prompt lab

OpenCLIP ViT-B/32 LAION2B; 10 CIFAR-10 test images per class. Embeddings for displayed templates are precomputed; a new template requires the model in the local lab.

Prediction80100000010100000000000900100000008020000000080110000010900000000028000000000010000000000010000000000010airplane1automobile2bird3cat4deer5dog6frog7horse8ship9truck10Columns 1 to 10 follow row order.

Precomputed templates available. For a new one, connect the lab and run the OpenCLIP cell.

Per class: airplane 8/10 · automobile 10/10 · bird 9/10 · cat 8/10 · deer 8/10 · dog 9/10 · frog 8/10 · horse 10/10 · ship 10/10 · truck 10/10.

Precomputed templates
Accuracy on 100 images90.0 %
Active templates1
Real OpenCLIP embeddings and 100 CIFAR-10 images, ten per class. Precomputed templates work offline; a written template requires the model in the local lab. The small set is exploratory.

A linear probe uses labels to learn a boundary over frozen embeddings. Full fine-tuning changes encoders and can adapt more to the task, but needs more resources and may forget prior capabilities. With 50 examples per class, a probe and zero-shot baseline are useful comparisons; the final choice depends on distribution, validation, and cost, with no universal rule.

SigLIP and LiT

SigLIP’s sigmoid loss treats each pair as binary, with zij=+1z_{ij}=+1 on the diagonal and −1-1 elsewhere, scale ss and bias bb:

Lsig=1N∑i,jlog⁡(1+e−zij(sui⊤vj+b)).L_{\mathrm{sig}}=\frac1N\sum_{i,j}\log\left(1+e^{-z_{ij}(s u_i^\top v_j+b)}\right).

The sum is divided by NN, not N2N^2 in this convention. Bias helps with imbalance between NN positives and N(N−1)N(N-1) negatives. SigLIP needs no global softmax denominator; it allows pair blocks to be accumulated independently. To obtain exactly the objective with all global negatives, necessary embeddings must still be obtained or communicated. Changing negative count or partitioning changes the objective; sigmoid loss does not automatically remove all communication.

With small batches, softmax compares each positive with few negatives and its denominator changes with batch composition. In SigLIP each pair contributes independently, but the negative-to-positive ratio also changes with NN and affects suitable bias. The authors observed advantages for sigmoid loss with small batches in their experiments; it does not follow that it will win for every dataset, architecture, or hyperparameter choice.

In locked-image tuning (LiT), a pretrained image tower is frozen and a text tower aligned with it. LiT studied several initializations and found good results with locked image and trainable text. Freezing saves visual-tower gradients and activations, but does not turn a newly initialized text encoder and few captions into the published model. We evaluate a small example separately and retain a pretrained comparison as reference.

Geometry, data and limits

The modality gap is the separation between image and text embedding regions despite sharing a space and producing useful similarities. Mind the Gap studies both the cone induced by initialization and the role of contrastive optimization. A 3D projection is a partial view of a space of hundreds of dimensions: it does not measure the entire distance or demonstrate causality. Shifting and renormalizing text can alter retrieval and classification differently; the effect depends on the dataset and how the shift vector is estimated.

InteractiveTwo regions on the hypersphere

100 Flickr8k validation pairs; gap = image mean − text mean. PCA of original vectors is scaled for the figure; three components explain 28.9 % of variance. Retrieval uses those 100 text candidates; accuracy uses 1000 CIFAR-10 images and a fixed template. Both metrics use full vectors, not the projection.

0.0
Gap norm0.744
Retrieval R@183.0 %
CIFAR-10 zero-shot93.6 %
OpenCLIP embeddings of 100 Flickr8k pairs and classification on 1000 CIFAR-10 images. The PCA projection is visual only; shifted texts are renormalized in 512 dimensions and full metrics recalculated.

In this sample, distance between means is 0.744 and the three displayed components explain 28.9% of joint variance. Without shifting, image-to-text R@1 among 100 candidates was 83% and CIFAR-10 accuracy with one template was 93.6% on 1000 images. With α=1\alpha=1, shifting by the difference of means and renormalizing, they were 80% and 93.7%. These are different datasets and tasks; reducing separation between means does not guarantee better retrieval.

Pair curation affects what is learned: language, duplicates, incorrect descriptions, privacy, licenses, and concept imbalance change training and evaluation. DataComp studies data selection under a common training protocol. Deduplication and checking evaluation contamination matter before attributing improvements to an architecture. Out-of-distribution performance depends on the specific shift; improved effective robustness relative to another baseline does not imply general immunity or justify using CLIP similarity as an objective quality measure.

Effective robustness compares out-of-distribution performance with the expected value from a reference of models with similar in-distribution performance. That reference and the chosen datasets are part of the measurement: a later analysis shows a single benchmark can mislead when training distributions differ. Evaluate natural and synthetic shifts, specific classes, and calibration as well as mean accuracy.

Lab: losses and gradients

We use two synthetic modalities with a shared latent variable, 192 training pairs and 64 held out. Projections are learned with CLIP; the SigLIP gradient is also checked and a scale learned on fixed embeddings. Central differences check derivatives of both vector sets, including normalization. Per-batch negative sampling is not equivalent to all global negatives.

In Pyodide, maximum gradient errors were below 10−910^{-9} and learned scale reached 17.642 in that fixed example. Held-out retrieval ranged from 95.31% to 98.44% depending on batch and scale for this synthetic seed; these results do not predict web-training performance.

[ ]CLIP, SigLIP and gradientsBrowser
import numpy as np

def normalize(x):
 n=np.linalg.norm(x,axis=1,keepdims=True)
 if np.any(n<1e-12):raise ValueError('embedding nulo')
 return x/n,n
def pullback(g,u,n):return (g-u*np.sum(u*g,axis=1,keepdims=True))/n
def losses(x,y,scale=10.,bias=-2.,kind='clip'):
 u,nx=normalize(x);v,ny=normalize(y);N=len(x);logits=scale*([email protected]);eye=np.eye(N)
 if kind=='clip':
  def softmax(z):
   z=z-z.max(axis=1,keepdims=True);a=np.exp(z);return a/a.sum(axis=1,keepdims=True)
  row=softmax(logits);col=softmax(logits.T).T
  def lse(z):
   m=z.max(axis=1,keepdims=True);return m[:,0]+np.log(np.exp(z-m).sum(axis=1))
  loss=.5*((lse(logits)-logits.diagonal()).mean()+(lse(logits.T)-logits.diagonal()).mean())
  grad=(row+col-2*eye)/(2*N)
 elif kind=='siglip':
  z=2*eye-1;vlogits=logits+bias;loss=np.logaddexp(0,-z*vlogits).sum()/N
  grad=-z*np.exp(-np.logaddexp(0,z*vlogits))/N
 else:raise ValueError('pérdida desconocida')
 return float(loss),pullback(scale*grad@v,u,nx),pullback(scale*grad.T@u,v,ny)
def gradient_check():
 rng=np.random.default_rng(7);x=rng.normal(size=(4,5));y=rng.normal(size=(4,5));h=1e-6;answer=[]
 for kind in ('clip','siglip'):
  _,gx,gy=losses(x,y,kind=kind);errs=[]
  for arr,g in [(x,gx),(y,gy)]:
   numeric=np.empty_like(arr)
   for k in np.ndindex(arr.shape):
    arr[k]+=h;a=losses(x,y,kind=kind)[0];arr[k]-=2*h;b=losses(x,y,kind=kind)[0];arr[k]+=h;numeric[k]=(a-b)/(2*h)
   errs.append(float(np.max(np.abs(g-numeric))))
  answer.append(errs)
 return answer
def experiment(batch,scale,seed=12):
 rng=np.random.default_rng(seed);z=rng.normal(size=(256,4));A=rng.normal(size=(4,8));B=rng.normal(size=(4,8));X=z@A+.1*rng.normal(size=(256,8));Y=z@B+.1*rng.normal(size=(256,8))
 W=rng.normal(0,.2,(8,8));V=rng.normal(0,.2,(8,8))
 for _ in range(400):
  idx=rng.choice(192,batch,replace=False);loss,gx,gy=losses(X[idx]@W,Y[idx]@V,scale=scale);W-=.04*X[idx].T@gx;V-=.04*Y[idx].T@gy
 x,_=normalize(X[192:]@W);y,_=normalize(Y[192:]@V);return float(np.mean(np.argmax([email protected],axis=1)==np.arange(64)))
def learn_scale(seed=18):
 rng=np.random.default_rng(seed);x=rng.normal(size=(32,8));y=x+.6*rng.normal(size=x.shape);u,_=normalize(x);v,_=normalize(y);[email protected];logscale=0.
 for _ in range(150):
  scale=np.exp(logscale);S=scale*cosine
  def soft(z):z=z-z.max(axis=1,keepdims=True);e=np.exp(z);return e/e.sum(axis=1,keepdims=True)
  grad=(soft(S)+soft(S.T).T-2*np.eye(len(x)))/(2*len(x))
  logscale=np.clip(logscale-.1*np.sum(grad*S),0,np.log(100.))
 return float(np.exp(logscale))
print('error máximo gradientes x/y CLIP y SigLIP:',gradient_check())
print('escala aprendida en embeddings fijos:',round(learn_scale(),3))
for n in (8,32,64):
 for scale in (2.,10.):print('lote',n,'escala',scale,'recuperación retenida:',round(experiment(n,scale),4))

Local lab: LiT and comparison

We use frozen OpenCLIP ViT-B/32 LAION2B and a small text encoder initialized from scratch. The public jxie/flickr8k mirror contains 6000 training and 1000 validation images; the first caption of each image is used. The loss includes all negatives in a batch of 128, although some descriptions may be equivalent. The new tower uses a mean of token embeddings and a projection: it does not implement the published LiT text transformer.

In one RTX 3060 run, after 15 epochs image-to-text R@1 among 1000 validation candidates rose from 0.0% to 21.6%; pretrained OpenCLIP achieved 63.7%. On 1000 balanced CIFAR-10 images, the first 100 per class, the new tower achieved 45.6% with a photo of a {}; OpenCLIP and SigLIP base achieved 93.6% and 93.4% with the same template. Results change with four other templates. Reference models’ pretraining uses different data and may have unknown benchmark overlap; this is not a causal loss comparison or definitive evaluation.

To run, install compatible PyTorch and torchvision, open_clip_torch==4.2.2, transformers, datasets, pyarrow, Pillow and huggingface_hub in a local environment. Approximately 2.5 GB of weights and data plus CIFAR-10 are downloaded; revisions are pinned in code and the process needs space and network access. Visual extraction and training may take several minutes depending on hardware. Files default to clip-lab-data; optional CLIP_LAB_DIR and CLIP_CIFAR_DIR allow reuse of compatible copies. The cell retains OpenCLIP in the local kernel so the figure can query new templates.

[ ]LiT, OpenCLIP and SigLIP on real dataLocal GPU
from pathlib import Path
from io import BytesIO
import os,time
import numpy as np
import pyarrow.parquet as pq
from PIL import Image
from huggingface_hub import snapshot_download
import torch
import open_clip
from torchvision.datasets import CIFAR10
from transformers import AutoModel,AutoProcessor

torch.manual_seed(23);torch.set_num_threads(2);device='cuda' if torch.cuda.is_available() else 'cpu'
root=Path(os.environ.get('CLIP_LAB_DIR','clip-lab-data'));root.mkdir(exist_ok=True,parents=True)
clip_dir=snapshot_download('laion/CLIP-ViT-B-32-laion2B-s34B-b79K',revision='1a25a446712ba5ee05982a381eed697ef9b435cf',local_dir=root/'openclip',allow_patterns=['open_clip_model.safetensors','open_clip_config.json','config.json','preprocessor_config.json','tokenizer*','vocab.json','merges.txt','special_tokens_map.json'])
data_dir=snapshot_download('jxie/flickr8k',repo_type='dataset',revision='56f58c967835f7c508d684f36bd7897cca9d7634',local_dir=root/'flickr8k',allow_patterns=['data/*.parquet','README.md'])
sig_dir=snapshot_download('google/siglip-base-patch16-224',revision='7fd15f0689c79d79e38b1c2e2e2370a7bf2761ed',local_dir=root/'siglip',allow_patterns=['model.safetensors','*.json','*.model'])
_clip_prompt_model,_,preprocess=open_clip.create_model_and_transforms('ViT-B-32',pretrained=str(Path(clip_dir)/'open_clip_model.safetensors'),device=device)
_clip_prompt_model.eval();_clip_prompt_tokenizer=open_clip.get_tokenizer('ViT-B-32');_clip_prompt_device=device
for p in _clip_prompt_model.parameters():p.requires_grad_(False)
def frozen_features(split):
 features=[];captions=[];texts=[]
 for path in sorted((Path(data_dir)/'data').glob(split+'*.parquet')):
  for batch in pq.ParquetFile(path).iter_batches(batch_size=32,columns=['image','caption_0']):
   rows=batch.to_pylist();im=torch.stack([preprocess(Image.open(BytesIO(row['image']['bytes'])).convert('RGB')) for row in rows]).to(device);cap=[row['caption_0'] for row in rows]
   with torch.no_grad():
    features.append(_clip_prompt_model.encode_image(im,normalize=True).cpu());texts.append(_clip_prompt_model.encode_text(_clip_prompt_tokenizer(cap).to(device),normalize=True).cpu())
   captions.extend(cap)
 return torch.cat(features).to(device),captions,torch.cat(texts).to(device)
start=time.perf_counter();train_img,train_caps,_=frozen_features('train');val_img,val_caps,val_text=frozen_features('validation')
print('Flickr8k train/valid:',len(train_caps),len(val_caps),'dimensión:',train_img.shape[1])
cifar_dir=os.environ.get('CLIP_CIFAR_DIR',str(root/'cifar'))
cifar=CIFAR10(root=cifar_dir,train=False,download=True);ids=[]
for k in range(10):ids.extend([i for i,y in enumerate(cifar.targets) if y==k][:100])
labels=np.array(cifar.targets)[ids];templates=['a photo of a {}','a blurry photo of a {}','a photo of the {}','a close-up photo of a {}','a sketch of a {}']
tokens=[_clip_prompt_tokenizer([t.format(c) for c in cifar.classes]).to(device) for t in templates];cifar_img=[]
with torch.no_grad():
 for k in range(0,len(ids),32):
  im=torch.stack([preprocess(cifar[i][0]) for i in ids[k:k+32]]).to(device);cifar_img.append(_clip_prompt_model.encode_image(im,normalize=True))
 cifar_img=torch.cat(cifar_img);openclip_scores=[]
 for tok in tokens:openclip_scores.append(float(((cifar_img@_clip_prompt_model.encode_text(tok,normalize=True).T).argmax(1).cpu().numpy()==labels).mean()))
 openclip_retrieval=float((val_img@val_text.T).argmax(1).eq(torch.arange(len(val_text),device=device)).float().mean())
train_tokens=_clip_prompt_tokenizer(train_caps).to(device);val_tokens=_clip_prompt_tokenizer(val_caps).to(device)
torch.manual_seed(23)
class TextTower(torch.nn.Module):
 def __init__(self):super().__init__();self.emb=torch.nn.Embedding(49408,256,padding_idx=0);self.proj=torch.nn.Linear(256,512)
 def forward(self,x):
  mask=(x!=0).float();v=self.emb(x);v=(v*mask[...,None]).sum(1)/mask.sum(1,keepdim=True).clamp_min(1);return torch.nn.functional.normalize(self.proj(v),dim=-1)
text=TextTower().to(device);logscale=torch.nn.Parameter(torch.tensor(np.log(10),dtype=torch.float32,device=device));optimizer=torch.optim.AdamW(list(text.parameters())+[logscale],lr=.001,weight_decay=.001)
def metrics():
 with torch.no_grad():
  vt=torch.cat([text(tok) for tok in val_tokens.split(128)]);r=float(([email protected]).argmax(1).eq(torch.arange(len(vt),device=device)).float().mean())
  acc=[float(((cifar_img@text(tok).T).argmax(1).cpu().numpy()==labels).mean()) for tok in tokens]
 return r,acc
initial=metrics()
for epoch in range(15):
 ids_train=torch.randperm(len(train_img),device=device)
 for batch in ids_train.split(128):
  scores=logscale.clamp(0,np.log(100)).exp()*(train_img[batch]@text(train_tokens[batch]).T);target=torch.arange(len(batch),device=device)
  loss=.5*(torch.nn.functional.cross_entropy(scores,target)+torch.nn.functional.cross_entropy(scores.T,target));optimizer.zero_grad();loss.backward();optimizer.step()
 if epoch in (0,4,9,14):print('época',epoch+1,'loss',round(float(loss.detach()),4),'escala',round(float(logscale.detach().exp()),3))
final=metrics();print('Flickr R@1 LiT inicial/final, OpenCLIP:',initial[0],final[0],openclip_retrieval)
print('CIFAR LiT por plantilla:',np.round(final[1],4),'OpenCLIP:',np.round(openclip_scores,4))
sig_processor=AutoProcessor.from_pretrained(sig_dir);sig_model=AutoModel.from_pretrained(sig_dir).to(device).eval();sig_image=[]
with torch.no_grad():
 for k in range(0,len(ids),32):
  batch=sig_processor(images=[cifar[i][0] for i in ids[k:k+32]],return_tensors='pt').to(device);v=sig_model.get_image_features(**batch).pooler_output;sig_image.append(torch.nn.functional.normalize(v,dim=-1))
 sig_image=torch.cat(sig_image);sig_scores=[]
 for template in templates:
  batch=sig_processor(text=[template.format(c) for c in cifar.classes],padding='max_length',return_tensors='pt').to(device)
  v=sig_model.get_text_features(**batch).pooler_output;v=torch.nn.functional.normalize(v,dim=-1);sig_scores.append(float((([email protected]).argmax(1).cpu().numpy()==labels).mean()))
print('CIFAR SigLIP por plantilla:',np.round(sig_scores,4),'tiempo total s:',round(time.perf_counter()-start,2),'dispositivo:',device)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofGradient in two directions
Prove: Derive the symmetric loss gradient with respect to a unit image embedding.
0
Let Sij = s ui·vj, P be row softmax and Q column softmax.

Step 1 of 3. What is the derivative of one row's cross-entropy with respect to Sij?

CodeTwo losses for pairs
Implement clip_loss(img_emb, txt_emb, logit_scale) and siglip_loss(img_emb, txt_emb, t, b). Both arrays have shape (N,D) and nonzero rows; normalize each row. logit_scale is log(s), t is positive scale s and b is bias. Use the sigmoid sum divided by N.
import numpy as np
def clip_loss(img_emb, txt_emb, logit_scale):
  pass
def siglip_loss(img_emb, txt_emb, t, b):
  pass
Shift+Enter to run
Numeric
For N = 32768, how many GiB does the N×N float32 similarity matrix occupy, excluding gradients?
GiB
Quiz
What does a zero-shot prompt ensemble do?
Quiz
You have 50 examples per class of industrial parts and a limited budget. What is the most reasonable initial comparison?
Key idea
Contrastive alignment makes image and text comparable, but negatives, temperature, prompts, and data determine what can be retrieved and transferred.

Sources: CLIP, SigLIP, LiT, modality gap, OpenCLIP and DataComp.