CLIP: matching images and text through a shared geometry
CLIP
Train two tiny towers and inspect duplicate pairs, normalization and candidate-dependent probabilities.
clipMatch the picture to a candidate description
Suppose a picture could match “a red cup”, “a blue cup” or “a red car”. A useful representation must preserve the distinctions that matter to those descriptions. Predicting one fixed class ID is one way to train that representation; learning which image and text belong together is another.
CLIP’s 2021 paper uses paired images and text to train two encoders with a symmetric contrastive objective. At inference, descriptions of candidate classes become inputs to the text encoder. Comparing their embeddings with the image embedding yields a classifier without fitting a new classification head to labeled examples of those candidate classes. This is a particular zero-shot transfer protocol, not proof that the concepts were absent from pretraining. Start with contrastive learning and Softmax.
Two directions share one score matrix
For N paired examples, let the image and text encoders produce vectors a and b of the same embedding dimension. Normalize each nonzero vector:
The positive scale exp(γ) is an inverse temperature: increasing it sharpens Softmax without changing the ordering of a fixed row. The released inference model normalizes both encoders’ outputs and exponentiates logit_scale. Its forward function returns scores; it is not the original training loop.
With one designated positive text per image and a corresponding positive image per text, the objective is:
The first denominator searches a row for the matching text. The second searches a column for the matching image. Compute log denominators by subtracting the maximum before exponentiation; this changes neither probability nor gradient and avoids unnecessary overflow. The two-direction loss and linear projection design are described in §2.2 and Figure 3.
Let P be the row-normalized score matrix and Q its column-normalized counterpart. The score gradient is:
Normalization also participates in backpropagation. For a vector a, its unit vector u, and an upstream derivative g with respect to u:
This removes the radial component: multiplying an already nonzero feature by a positive scalar does not change its normalized direction. Omitting this derivative trains a different model. At zero norm the expression is undefined; this example rejects such rows rather than silently choosing a direction.
For candidate descriptions with embeddings v₁,…,vK, the inference distribution is:
The candidate set C is part of this quantity. Add a duplicate high-scoring description and probability is shared between the duplicates. A high value is not automatically a calibrated probability that a statement is true in an open world. Prompt wording and the chosen candidates are therefore part of the evaluation procedure, not cosmetic labels.
There is another assumption in the training objective: every off-diagonal pair is treated as a negative. If two rows describe the same thing equally well, the labels can demand an artificial distinction. With two identical image features and two identical text features, every score is equal, so:
No temperature can resolve that ambiguity. The loss is matching individual pair identities, while a semantic evaluation may accept both descriptions. Multiple captions, duplicates and broad descriptions require a deliberate definition of positives.
Train a small pair of linear towers
Save as clip.py; use Python 3.12 and NumPy 1.26.4. Eight points on a circle stand for synthetic meanings. Two different linear maps turn them into image-side and text-side observations. The program learns two 2×2 projections and one log scale: nine parameters, with explicit gradients through normalization. These observations are numeric features, not photographs or natural-language tokens.
Projected gradient descent uses 800 updates at rate .08, constraining the log scale to [−3,log(50)]. The bound is a stated teaching choice, not a claim about the released training implementation. The final scale is below that upper bound. A batch requires O(N²d) work and O(N²) score storage beyond the encoders; a real encoder’s cost is additional. Our linear projections add O(Nd²).
"""Original linear two-tower contrastive model; no images or pretrained CLIP."""
import json
import numpy as np
def normalize(x):
x=np.asarray(x,float)
if x.ndim!=2 or not np.isfinite(x).all():raise ValueError('Finite matrix required')
norm=np.linalg.norm(x,axis=1,keepdims=True)
if np.any(norm<1e-12):raise ValueError('Nonzero finite rows required')
return x/norm,norm
def logsoftmax(x,axis=1):
x=x-np.max(x,axis=axis,keepdims=True)
return x-np.log(np.exp(x).sum(axis=axis,keepdims=True))
def features(offset=0.,count=8):
if not isinstance(count,int) or isinstance(count,bool) or not 2<=count<=64:raise ValueError('Use 2..64 pairs')
angle=2*np.pi*(np.arange(count)+offset)/count;s=np.c_[np.cos(angle),np.sin(angle)]
return s@np.array([[1.2,.3],[.2,.8]]),s@np.array([[-.2,1.1],[.9,.1]])
def objective(theta,x,y):
theta=np.asarray(theta,float);x=np.asarray(x,float);y=np.asarray(y,float)
if theta.shape!=(9,) or x.shape!=y.shape or x.ndim!=2 or x.shape[1]!=2 or len(x)<2 or not np.isfinite(theta).all() or abs(theta[-1])>8:raise ValueError('Invalid paired inputs')
wi,wt=theta[:4].reshape(2,2),theta[4:8].reshape(2,2);u,nu=normalize(x@wi);v,nv=normalize(y@wt)
scale=np.exp(theta[-1]);score=scale*u@v.T;n=len(x);a,b=logsoftmax(score),logsoftmax(score,0)
loss=-.5*np.mean(np.diag(a)+np.diag(b));g=(np.exp(a)+np.exp(b)-2*np.eye(n))/(2*n)
gu=scale*g@v;gv=scale*g.T@u
dx=(gu-u*np.sum(gu*u,axis=1,keepdims=True))/nu;dy=(gv-v*np.sum(gv*v,axis=1,keepdims=True))/nv
grad=np.r_[(x.T@dx).ravel(),(y.T@dy).ravel(),np.sum(g*score)]
return float(loss),grad,score
def train(updates=800):
if not isinstance(updates,int) or isinstance(updates,bool) or not 0<=updates<=3000:raise ValueError('Invalid update count')
theta=np.r_[np.random.default_rng(7).normal(size=8),np.log(2.)];x,y=features();history=[]
for step in range(updates+1):
loss,g,_=objective(theta,x,y)
if step%100==0 or step==updates:history.append(loss)
if step<updates:
theta-=.08*g;theta[-1]=np.clip(theta[-1],-3,np.log(50))
return theta,history
def demo():
theta,history=train();x,y=features(.5);score=objective(theta,x,y)[2]
duplicate=np.ones((2,2));duplicate_loss=objective(theta,duplicate,duplicate)[0]
return dict(training_loss=history,logit_scale=float(np.exp(theta[-1])),train_accuracy=float(np.mean(np.argmax(objective(theta,*features())[2],axis=1)==np.arange(8))),heldout_pair_accuracy=float(np.mean(np.argmax(score,axis=1)==np.arange(8))),duplicate_pair_loss=duplicate_loss,candidate_probabilities={str(s):np.exp(logsoftmax(np.array([[1.,.8,0.]])*s))[0].tolist() for s in [2,20]},parameters=theta.tolist())
if __name__=='__main__':print(json.dumps(demo(),indent=2))
Loss falls from 2.21137236 to .0002880981; the learned scale is about 30.19945. Training pairs and eight held-out interleaved angles both have perfect nearest-candidate accuracy. This only shows recovery of a deliberately simple geometric relationship. It does not establish zero-shot recognition of natural images.
The duplicate experiment stays at log(2). For fixed similarities [1,.8,0], scaling by 2 produces probabilities approximately [.554,.371,.075]; scaling by 20 produces [.982,.018,0.000000002]. The winner never changes. Independently check all nine gradients, a two-orthogonal-pair closed-form loss, joint pair permutation, feature rescaling and held-out geometry before interpreting the training curve.
Similarity is useful, but its meaning is conditional
Image–text alignment is not an image generator or a conversational answerer. A dual tower compares independent encodings; a fine-grained matching model can instead let image and text tokens interact before scoring. See multimodal fusion and vision–language models for those separate design choices.
Dataset biases, duplicated captions, representation bottlenecks and descriptions that omit spatial relations can all undermine the intended comparison. A benchmark needs a declared dataset split, candidate vocabulary, prompt templates, preprocessing and aggregation rule. Performance on one such protocol does not prove reliable counting, negation or calibration on another. This article makes no numerical claim about a released CLIP benchmark.
Change a choice before changing the model
- Calculation. Two orthogonal unit image features exactly match two orthogonal text features. What is the symmetric loss at inverse temperature 3? Answer: Each positive logit is 3 and each negative logit is 0. Both directions give log(1+exp(−3)), about .04859.
- Prediction. Multiply one encoder’s nonzero feature by 10 before normalization. Does its score change? Answer: No. The positive scalar cancels. Changing its direction, or replacing the normalization rule, can change the score.
- Boundary. Can increasing temperature scale drive the two-identical-pair loss to zero? Answer: No. Every row and column remains [.5,.5], and the designated-pair loss stays log(2). Revising the positive-pair definition addresses a different problem.
- Transfer. A candidate has score 2 and its alternative has score 0. Add a second copy of the first candidate. Why does its reported probability fall? Answer: The denominator changes from exp(2)+1 to 2exp(2)+1. The score and semantic evidence did not improve or deteriorate; the candidate list changed.
Read the training objective beside the inference path
Read the paper’s §2.2–2.3 and Figure 3, then the fixed model’s encoding and forward methods. The former specifies the learning objective; the latter reveals pooling, normalization and score conventions. We inspected those bounded portions, including PDF page 3, and wrote the NumPy experiment independently. The repository version is dated 2026, not the original 2021 training commit. No upstream code or pretrained weights are bundled.
Make a prediction, then check
Does a duplicate candidate leave Softmax probabilities unchanged?
Learning objectives
- Derive the symmetric loss and normalization gradient.
- Explain a duplicate-positive ambiguity.
- Separate candidate probability from calibration.
- Run and check both linear towers.
Prerequisites & connections
Explore related knowledge →References
- Learning Transferable Visual Models From Natural Language Supervision (ICML2021)
Alec Radford; Jong Wook Kim; Chris Hallacy; Aditya Ramesh; Gabriel Goh; Sandhini Agarwal; Girish Sastry; Amanda Askell; Pamela Mishkin; Jack Clark; Gretchen Krueger; Ilya Sutskever · 2021 - clip-model reference at d05afc4
openai/CLIP contributors · 2026
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked ICML2021 sections2.2-2.3/Figure3 and fixed OpenAI normalization/logit-scale code. Six paired equations and four explained exercises; original nine-parameter two-tower training, all gradients, joint permutation, normalized tangent gradients, duplicate-pair loss and candidate-dependent probabilities. Synthetic geometry, not natural-image accuracy or calibrated truth.
- Single AI author checked ICML2021 sections2.2-2.3/Figure3 and fixed OpenAI normalization/logit-scale code. Six paired equations and four explained exercises; original nine-parameter two-tower training, all gradients, joint permutation, normalized tangent gradients, duplicate-pair loss and candidate-dependent probabilities. Synthetic geometry, not natural-image accuracy or calibrated truth.
- Four computed SVG variants per topic. Thirteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. English spacing correction and initial test-mixin discovery error preserved. Full article acceptance recorded separately.
Source locations checked:
- Learning Transferable Visual Models From Natural Language Supervision (ICML2021) · Read selected2.2-2.3, Figure3 and candidate-classification description; PDF page3 viewed. No original training or natural-image benchmark reproduction.
- clip-model reference at d05afc4 · 295,343-370: EOS pooling, normalization and exp logit scale; inference only. MIT read in full. Fixed public code, reference only; no copying/execution.
Related topics