CLIP puts every image in one region and every caption in another. The centres of the two clouds sit 0.82 apart on a sphere of radius 1. A ranking inside one gallery never notices. A search over images and text together breaks.
Pick a stage of the model, or drag the angle between the two cones. Watch which item the dog caption finds first. Then we build the gap piece by piece: its cause, what the loss does to it, and how to live with it.
You need a vector (a list of numbers) and cosine similarity (how closely two vectors point the same way). It helps to have met Contrastive Learning and CLIP. We build the rest from zero.
The stops are the paper’s gap sizes (Liang et al. 2022). Trained CLIP on 5,000 MSCOCO pairs: 0.82. A CLIP trained from scratch, at its random start: 1.19. The four items are the 3-D toy of Chapter 4: weight 0.96 on the cone direction, 0.28 on meaning. We set the angle so that the toy’s gap equals each stop.
Chapter 0
Compare a photo with its own caption and with an unrelated photo, and find the wrong one wins
You have a photo of a golden retriever on a porch, and its caption: "a golden retriever on a wooden porch". CLIP has two encoders, one for images and one for text. Training makes a photo and its caption point the same way. Each encoder turns its input into an embedding: a list of 512 numbers, scaled to length 1.
How alike are two embeddings? Call the image embedding u and the text embedding v. Call their k-th numbers uk and vk. Their cosine similarity is the cosine of the angle between them.
Cos of u and v equals the sum over k of u-k times v-k.
Multiply u and v position by position. Add the products. Because both vectors have length 1, the total is the cosine.
With made-up 3-number vectors u = (0.6, 0.8, 0) and v = (0.8, 0.6, 0): 0.48 + 0.48 + 0 = 0.96. The two point almost the same way.
Now the measurements. Liang and colleagues, in Mind the Gap (2022), embedded 5,000 MSCOCO images and captions with CLIP. Two images average a cosine of 0.47. Two captions average 0.51. A photo and its own caption score lower than either: about 0.3 in typical use.
Each bump is the spread of cosine scores for one kind of pair. Drag the threshold. Try to keep the matched pairs and reject the unrelated photos.
The two within-modality means, 0.47 and 0.51, are the paper’s averages over all pairs of 5,000 MSCOCO embeddings (Sec. 2.1). The matched mean 0.30 is illustrative. The wrong-caption mean 0.15 is our estimate from Chapter 1. All spreads are illustrative.
No threshold works. Any line low enough to keep the matched pairs also keeps almost every pair of unrelated photos. The space holds two islands, one for images and one for text, with an empty channel between them. That channel is the modality gap.
CLIP still works for its usual jobs. Retrieval asks "which of these captions fits this photo best?" Every caption pays the same handicap, so the ranking survives. Systems that compare scores across the two islands fail.
Failure. Symptom: a yes or no match filter rejects correct photo and caption pairs, or a text query never returns an image. Measure: print the mean score of image-image, text-text and image-text pairs on your data. Fix: the calibration in Chapter 7.
Chapter 1
Average each island into one point, subtract, and read the gap from three averages
A gap between two clouds needs one number. Liang and colleagues take the centre of each cloud and measure the distance between the centres. Call the i-th image embedding xi, its caption’s embedding yi, and the number of pairs n. The gap vector Δ is the image centre minus the text centre.
Delta equals one over n times the sum over i of x-i, minus one over n times the sum over i of y-i.
Average all image vectors x-i into one point. Average all text vectors y-i into another. Subtract the second from the first. The length of the result is the gap.
The paper reports a length of 0.82 for CLIP on 5,000 MSCOCO pairs. Two points on the unit sphere are at most 2 apart, so the centres are far apart.
The centres are shorter than 1, because averaging vectors that point in slightly different directions shortens them. That fact links the gap to the averages from Chapter 0. Over all pairs, call the average cosine of two images sII, of two texts sTT, and of an image with a text sIT.
The length of delta, squared, equals s-I-I plus s-T-T minus two s-I-T.
Tight islands make a big gap. Images and texts that look alike shrink it. The gap squared is the two island tightnesses s-I-I and s-T-T, minus twice the cross score s-I-T.
With the paper’s s-I-I = 0.47, s-T-T = 0.51 and gap 0.82: 0.82 × 0.82 = 0.67, so 2 s-I-T = 0.98 − 0.67 = 0.31 and s-I-T ≈ 0.15. This is our estimate: it assumes all three numbers come from the same model and data.
Orange dots are images, teal dots are their captions. The purple arrow is the gap vector. Change the cone angle and the spread, and check that both ways of measuring agree.
An illustrative toy: 40 pairs in 5 dimensions. Horizontal is the gap direction; vertical is one direction of meaning. The averages include each point with itself, which is what makes the identity exact.
The identity is not an approximation. Expand the squared length of the difference of the two centres and you get exactly these three averages. For thousands of items, the self-pairs barely change them.
Failure. Symptom: a UMAP plot shows two blobs and someone calls it proof. Measure: UMAP can make clusters out of noise, so compute the gap length instead. Fix: report the gap with s-I-I, s-T-T and s-I-T beside it.
Chapter 2
Push random inputs through a random network and watch their outputs crowd into a narrow cone
Take a network with random weights, never trained. Feed it unrelated photos and measure the average cosine between pairs of outputs. You might expect 0. The paper finds 0.99 for a randomly initialized ResNet, and the effect holds for pure noise as input. This crowding is the cone effect: the outputs fill only a narrow cone of directions.
The cause is the activation function, the non-linear step after each layer. ReLU keeps positive numbers and turns negative ones into 0. After ReLU no entry is negative, so two outputs can no longer point away from each other.
How much cosine does one ReLU add? Take one entry, a standard normal number X. Call the average of max(0, X) μ and the average of its square q. Call the output cosine ρ1.
Rho-one equals mu squared over q, which is one over pi.
The dot product of the two outputs averages μ times μ per entry. Each output’s squared length averages q per entry. Divide the first by the second. The layer width cancels.
μ2 = 0.399 × 0.399 = 0.159. Divide by q = 0.5: ρ1 = 0.318. One ReLU takes unrelated inputs from cosine 0 to about one third.
Each further layer repeats the squeeze. For a wide ReLU layer, Cho and Saul (2009) give the exact map from the input cosine ρ to the output cosine ρ′. It uses the angle θ between the inputs.
Rho-prime equals sine theta plus pi minus theta times cosine theta, all over pi, where theta is the arc cosine of rho.
Turn the cosine ρ into an angle θ. Put θ into the bracket. Divide by π. The answer ρ′ is the next layer’s cosine, and it is always closer to 1.
Start at ρ = 0: θ = 1.571, bracket = 1 + 0 = 1, so ρ′ = 0.318. Again from 0.318: θ = 1.247, sin θ = 0.948, (π − θ) cos θ = 1.895 × 0.318 = 0.602, so ρ′ = 1.550 / 3.142 = 0.494.
Your browser measures the dots live on a random network. The dashed line is the formula for ReLU. Pick an activation and drag the depth.
The paper’s setup, scaled down: 100 normal inputs, layers 64 wide, weights from N(0, 1/64), 4 networks averaged, no biases (biases tighten the cone more). The paper (512 wide) reports 0.99 after two sigmoid layers.
| ReLU layers | Angle | Average cosine |
|---|---|---|
| 0 | 90.0° | 0.000 |
| 1 | 71.4° | 0.318 |
| 2 | 60.4° | 0.494 |
| 4 | 47.1° | 0.681 |
| 8 | 33.4° | 0.834 |
Without an activation the cosine stays near 0. Tanh keeps the sign of each number, so its squeeze is weak. ReLU and sigmoid outputs are never negative, and the cone closes fast.
Failure. Symptom: unrelated items get high cosines from a fresh or poorly trained encoder. Measure: the average cosine between random pairs. Fix: compare scores against that baseline, never against 0.
Chapter 3
Give the same inputs to two random networks and find two cones that point different ways
The cone effect gives each network one narrow cone. A gap needs two cones that point in different directions. CLIP has two encoders with separate random weights, and the direction of a cone depends on the weights. The paper shows this by starting one model 25 times with 25 seeds. Each start makes a different cone.
This happens even when both networks read the same inputs. So the gap does not need two kinds of data. It is born at initialization, the moment the computer draws the random weights.
Both networks read the same 100 random inputs. Orange is network A, teal is network B. Choose the seeds and drag the depth.
Live toy: ReLU layers 64 wide, weights and biases from N(0, 1/64). A final random linear layer follows, because real encoders end in one. We compute the gap from the 64-number outputs; the picture shows two of those directions.
Read the gap from Chapter 1’s identity. A final random linear layer points each cone in a random direction. In many dimensions, two random directions are close to perpendicular, so s-I-T is near 0. The gap is then about the square root of s-I-I + s-T-T. In the device, four layers give cone tightnesses near 0.7, and the gap comes out near 1.17.
The paper trains CLIP from scratch on MSCOCO. At its random start the gap is 1.19. The authors then remove the starting gap by rotating the text embeddings onto the image embeddings, and train again. The gap grows back to 0.75, which is 57% of the 1.30 gap the unrotated model ends with. So initialization makes the gap, and training keeps it open.
| Model (paper, Sec. 4.4) | Gap at start | Gap after training |
|---|---|---|
| CLIP from scratch | 1.19 | 1.30 |
| Same, gap rotated away at start | 0.04 | 0.75 |
Failure. Symptom: you swap one encoder for a fresh copy and every cross-modal score collapses. Measure: the gap before and after the swap. Fix: never mix towers from different runs without retraining them together.
Chapter 4
Build four unit vectors in 3-D and compute every score of a modality gap with a pencil
Here is the smallest object with a real gap. It has three directions. The image cone points along a = (1, 0, 0). The text cone points along b = (0.28, 0.96, 0). Meaning lives on e = (0, 0, 1). Item 1 is a dog, item 2 is a fire truck.
Each embedding is 0.96 of its cone direction plus or minus 0.28 of meaning. Call the cone weight m = 0.96 and the meaning weight s = 0.28. Since 0.962 + 0.282 = 1, all four vectors have length 1.
dog photo I1 = (0.96, 0, +0.28) truck photo I2 = (0.96, 0, −0.28) dog caption T1 = (0.2688, 0.9216, +0.28) truck caption T2 = (0.2688, 0.9216, −0.28)
The matrix holds every cosine between the four items. Bright cells score high. Move the cones together, then change the meaning weight, and watch the margin.
An illustrative toy. R is the cosine between the two cone directions a and b; m equals √(1 − s2), so every vector keeps length 1.
The two photos share the cone part, 0.9216, and their meaning parts cancel: 0.9216 − 0.0784 = 0.8432. The two captions score the same. A photo and its caption share R × 0.9216 = 0.2580 of cone, plus 0.0784 of meaning: 0.3364. A photo and the wrong caption get 0.2580 − 0.0784 = 0.1796.
What separates a right caption from a wrong one? Call the cosine between the cone directions R. Subtract the mismatched score from the matched score. Call the difference the margin.
The margin equals m squared R plus s squared, minus m squared R minus s squared, which is two s squared.
Both photo-caption scores carry the same cone part m-squared R. Subtracting one from the other removes it. The margin is two s-squared, whatever the gap.
With s = 0.28: margin = 2 × 0.0784 = 0.1568, which matches 0.3364 − 0.1796. Move R from 0.28 to 1 and both scores rise by 0.66; the margin stays 0.1568.
Now the gap. Averaging each pair cancels the meaning parts, so the centres are 0.96a and 0.96b. Their difference is (0.6912, −0.9216, 0), of length 1.152. Along it, both photos sit at +0.576 and both captions at −0.576.
Search with the dog caption over the other three items. The truck caption scores 0.8432, the dog photo 0.3364. Modality outweighs meaning: this is the mixed-search bug of Chapter 7.
Failure. Symptom: a heat map of a "joint" space shows two bright squares on its diagonal. Measure: compare the within blocks with the cross block. Fix: treat the space as two islands until you calibrate.
Chapter 5
Write CLIP’s loss, see why a clean batch ignores the gap, and see why mismatched pairs keep it open
CLIP trains on a batch of photo and caption pairs. For each photo, the right caption must win against every other caption in the batch. Call the i-th photo xi, the j-th caption yj, and a dividing number called the temperature τ. The loss for photo i is Li.
L-i equals minus log of: e to the x-i dot y-i over tau, divided by the sum over j of e to the x-i dot y-j over tau.
Divide every cosine by τ. Turn the results into probabilities with a softmax (e to the power, then divide by the total). L-i is minus the log of the right caption’s probability.
The toy of Chapter 4 with two captions, cosines 0.3364 and 0.1796, τ = 0.1: probability = 1 / (1 + e−1.568) = 0.828, so L = 0.189. At τ = 0.01, L = 0.00000015.
CLIP learns τ. Radford and colleagues start it at 0.07 and clip it so that it never scales the cosines by more than 100. The trained model sits at τ = 1/100.
A softmax ignores a constant added to every score. In the clean toy, closing the gap adds 0.66 to both cosines, so the loss stays the same. Real data is not clean. Some captions fit another photo better than their own: the paper calls these mismatched pairs.
The curve is the loss of six pairs as the paper’s shift moves the islands. The dot marks the starting gap. Pick a temperature and switch the mismatch on and off.
Our toy, after the paper’s Fig. 3: six pairs on a 3-D sphere, images at 25° above the equator, captions at 25° below. Mismatch moves two captions 60% of the way toward the other’s photo. The shift is x − λΔ and y + λΔ, then length 1 again. It shows the direction of the paper’s result, not its numbers.
With mismatched pairs at τ = 1/100, closing the toy’s gap from 0.85 to 0 raises the loss from 2.86 to 3.50. Opening it lowers the loss. At τ = 1, the loss is lowest with the gap closed. On real CLIP at τ = 1/100, the paper finds the loss lowest at the trained gap of 0.82. Fine-tuning at τ = 1/10 or 1 shrinks or closes the gap.
Why not train hot? A low temperature focuses the loss on the hardest wrong captions, and that focus makes CLIP sharp.
Failure. Symptom: you close the gap before training and it reopens. Measure: track the gap every few hundred steps. Fix: expect the loss to push back at low τ; first decide whether you need a closed gap.
Chapter 6
Move every caption along the gap direction and see when a ranking changes and when it cannot
Take a zero-shot classifier. It embeds one prompt per class, "a photo of a cat" and "a photo of a dog". It picks the class with the highest cosine. Now move every prompt embedding by the same amount along the gap direction. Does the answer change?
If you only add a vector t to each caption vj, every score gains the same u·t. The ranking cannot change. But the paper puts each shifted vector back on the sphere, and that changes everything. Call the photo u, a class prompt vj, the unit gap direction Δ̂, and the shift size α.
Score-j equals u dot v-j plus alpha u dot delta-hat, over the square root of one plus two alpha v-j dot delta-hat plus alpha squared.
The top line adds the same amount to every prompt. The bottom line divides each prompt by its own new length. A prompt that sits far on the text side gets a short new length, so its score grows most.
With made-up numbers: u·vcat = 0.302, u·vdog = 0.295, u·Δ̂ = 0.41, vcat·Δ̂ = −0.25, vdog·Δ̂ = −0.45, α = 0.6. Cat: 0.548 / 1.030 = 0.532. Dog: 0.541 / 0.906 = 0.597. Dog now wins.
Two curves: the cat prompt and the dog prompt. Drag the shift. Then switch off the step that puts each prompt back to length 1.
We made up the five dot products. The formula is exact for unit vectors.
The paper runs this shift on real CLIP and measures zero-shot accuracy. Some tasks gain from a wider gap, some from a narrower one. The changes are small.
| Task (CLIP ViT-B/16) | Original gap | Best shifted gap | Better direction |
|---|---|---|---|
| CIFAR-10 | 0.9013 | 0.9081 | wider |
| CIFAR-100 | 0.6658 | 0.6737 | narrower |
| EuroSAT | 0.5410 | 0.5645 | narrower |
| SVHN | 0.5389 | 0.5396 | wider |
Fairness moves too. On FairFace with CLIP ViT-B/32, widening the gap from 0.82 to 0.97 lowers the share of offensive top predictions for every race group. Top-1 accuracy drops by only 0.0008. A gap shrunk to 0.07 raises crime-related labels; a gap of 1.29 raises non-human labels.
Failure. Symptom: you "close the gap" on a gallery and retrieval stays identical. Measure: did you put the vectors back to length 1? Fix: know which of the two you ran; only the renormalized shift changes rankings.
Chapter 7
Put text passages and diagrams in one index, watch the diagram vanish, and bring it back with per-modality statistics
Your team embeds its documentation with CLIP: text passages through the text encoder, architecture diagrams through the image encoder, all into one index. A user types "diagram of a transformer block". The results are five passages. The right diagram exists, and it never shows.
The cause is the gap. Against a text query, passages average a cosine of 0.62 and images 0.25 in this example. The best diagram scores 0.34. That beats every other image by far, and loses to every passage.
The fix is to score each item against its own modality, its kind (text or image). Call an item’s raw cosine s, the average score of its modality μm, and the spread of that modality’s scores σm. The calibrated score is the z-score z.
Z equals s minus mu-m, over sigma-m.
Subtract the modality’s average mu-m from the raw score s. Divide by the modality’s spread sigma-m. Now a text score and an image score use the same scale.
With the example’s numbers: the diagram has s = 0.34, μ = 0.25, σ = 0.04, so z = 0.09 / 0.04 = 2.25. The best passage has s = 0.68, μ = 0.62, σ = 0.05, so z = 1.20. The diagram now ranks first.
Orange bars are images, teal bars are passages. The ringed item is the one the user wants. Change the scoring mode and watch the order.
An illustrative index. Reference statistics: text μ = 0.62, σ = 0.05; images μ = 0.25, σ = 0.04. They come from a fixed reference set, not from these ten results.
Three rules decide whether this works in production. Estimate μ and σ once per checkpoint on a fixed reference set; the retrieved top results are a biased sample. Keep one index per modality and retrieve from each: a single mixed index can return zero images before any calibration runs. Never store an absolute cosine threshold; a new checkpoint has a new gap.
Failure. Symptom: after a model upgrade, a match filter keeps nothing or everything. Measure: the per-modality score means on the new checkpoint. Fix: express every threshold in z-units and refit μ and σ with each checkpoint.
Chapter 8
Center each island, learn what centering cannot fix, and turn the gap into one known constant
Chapter 7 fixed scores. Sometimes you need the embeddings themselves to line up: to average a photo with a caption, or to search one mixed index. The cheapest tool is centering: subtract each modality’s own mean vector, then scale every vector back to length 1.
Lines join each photo to its caption. Switch centering on. Then raise the item noise: the part of each pair that no shift can remove.
An illustrative toy: 12 pairs in 8 dimensions, cone angle 50.6° (a gap near 0.82), meaning weight 0.28. The noise differs between a photo and its caption. "Right first" counts captions whose top hit, among all other 23 items, is their own photo.
Centering wins the mixed search when the noise is small. As the noise grows, the right photo slips. Centering removes the shared offset, not what each photo shows and its caption leaves out. Watch the means: they must come from a fixed reference sample, or scores drift from batch to batch.
A rotation goes further. Find the best orthogonal matrix that maps text embeddings onto their images, by one SVD. The paper used exactly this to remove the gap at the start of training. Chapter 3 showed what followed: training reopened it to 0.75. A fix applied before training does not survive training.
The other camp uses the gap. Train a linear classifier on text embeddings, score w·v + b. Apply it to a photo u, modelled as its caption v plus the gap Δ. The score becomes (w·v + b) + w·Δ. The whole cost of crossing is one constant, the same for every input. With made-up numbers, w·Δ = 0.05: estimate it on a few paired examples and subtract it.
| Tool | Needs training | What it fixes |
|---|---|---|
| Per-modality z-scores | No | Scores on one scale; index unchanged |
| Centering | No | Shared offset; rankings change |
| Rotation (SVD) | No | The rigid part; reopens if you train again |
| Bias shift w·Δ | No | Text-trained linear heads on images |
| High τ fine-tune | Yes | Shrinks the gap; trades away hard-negative focus |
Failure. Symptom: you average a photo embedding and a caption embedding into one "multimodal" query, and results look random. Measure: the averaged vector sits between the islands, where no item lives. Fix: center both modalities first, or keep two queries and fuse their ranks.
Chapter 9
Keep the numbers, the checklist and the code in one place
A random network squeezes its outputs into a cone. Two encoders make two cones, and the gap is born. At CLIP’s low temperature, mismatched pairs make the loss prefer an open gap. Rankings inside one gallery ignore it. Anything that compares across modalities needs per-modality calibration.
| Term | Rule or number | Source |
|---|---|---|
| Gap vector Δ | Image centre minus text centre | Liang et al., Sec. 4.2 |
| CLIP gap | 0.82 on 5,000 MSCOCO pairs | Liang et al., Fig. 3 |
| Island tightness | 0.47 (CLIP images), 0.51 (CLIP texts) | Liang et al., Sec. 2.1 |
| Gap identity | ‖Δ‖2 = sII + sTT − 2sIT | Algebra |
| One ReLU | Cosine 0 becomes 1/π = 0.318 | Cho and Saul, 2009 |
| Gap at random start | 1.19; after training 1.30 | Liang et al., Sec. 4.4 |
| CLIP temperature | Starts at 0.07, clipped at 1/100 | Radford et al., 2021 |
| Fairness shift | Gap 0.82 to 0.97: fewer offensive labels, −0.0008 accuracy | Liang et al., Table 2 |
| Z-score | (s − μm) / σm, per modality, per checkpoint | Standard practice |
pythonimport numpy as np def unit(X): return X / np.linalg.norm(X, axis=1, keepdims=True) def gap_report(I, T): # I, T: (n, d) unit rows, row i is pair i cI, cT = I.mean(0), T.mean(0) # (d,) each, shorter than 1 s_II, s_TT, s_IT = cI @ cI, cT @ cT, cI @ cT # all-pairs averages gap = np.linalg.norm(cI - cT) assert abs(gap**2 - (s_II + s_TT - 2*s_IT)) < 1e-6 return dict(gap=gap, s_II=s_II, s_TT=s_TT, s_IT=s_IT) def center(X, mu): return unit(X - mu) # mu from a fixed reference sample def zscore(s, modality, stats): # stats fitted once per checkpoint mu, sd = stats[modality] return (s - mu) / sd
| Lesson | What it adds |
|---|---|
| Contrastive Learning and CLIP | The model whose geometry this lesson takes apart |
| Contrastive Learning | InfoNCE, negatives, alignment and uniformity |
| Vector Embeddings | What an embedding is |
| Similarity Metrics | Cosine, dot product and distance |
| Vector Databases | Where the mixed index lives |
| Multimodal RAG | Retrieval over text and images together |
| Embedding Benchmarks | Why leaderboards hide calibration problems |
| Multimodal Foundation Models | The wider family of joint spaces |
| Vision-Language Models | The generative branch |
| SigLIP | A sigmoid loss with a learned bias |
| ImageBind | Six modalities in one space |
| OpenCLIP | Open checkpoints to measure your own gap |
| EVA-CLIP | The recipe at larger scale |
Liang, Zhang, Kwon, Yeung and Zou, Mind the Gap: Understanding the Modality Gap in Multi-modal Contrastive Representation Learning, NeurIPS 2022: the gap, the cone effect, the shift and temperature experiments. Radford et al., Learning Transferable Visual Models From Natural Language Supervision, ICML 2021: CLIP and its learned temperature. Cho and Saul, Kernel Methods for Deep Learning, NeurIPS 2009: the arc-cosine kernel behind the ReLU formula.
Now press Present or Teach. Explain from memory where the cone comes from and why two encoders make a gap. Then explain the low temperature and how to calibrate a mixed search. Then go back to the cones and find the angle where the dog caption first finds its own photo.