The Modality Gap

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.

Move the text cone, then search

50.6°

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

Two Islands

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.

Say it aloud

Cos of u and v equals the sum over k of u-k times v-k.

cos(u, v)
cos of u and v the cosine similarity: 1 means the same direction, 0 means a right angle.
Σk
the sum over k one term for each of the 512 positions.
uk
u-k the k-th number of the image embedding.
vk
v-k the k-th number of the text embedding.
In plain words

Multiply u and v position by position. Add the products. Because both vectors have length 1, the total is the cosine.

With numbers

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.

Find a threshold that only keeps true pairs

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.

0.25

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.

The road

  1. Measuring the gap: two centroids, one vector, and 0.82.
  2. The cone effect: why a random network squeezes everything together.
  3. Two networks, two cones: the gap exists before training.
  4. The gap by hand: four vectors that hold the whole story.
  5. The loss and its temperature: what training does to the gap.
  6. Shifting the gap: move one island and watch a prediction flip.
  7. Mixed search: the production bug and its fix.
  8. Close it or use it: centering, rotation and the probe trick.
  9. Field guide: numbers, code and links.
In CLIP, two unrelated photos average a cosine of 0.47. A photo and its own caption score about 0.3. What does that tell you?

Chapter 1

Measuring the Gap

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.

Say it aloud

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.

Δ
delta the gap vector: it points from the text centre to the image centre.
1/n
one over n divide by the number of pairs, here 5,000, to get an average.
Σi
the sum over i add one term for each pair.
xi
x-i the i-th image embedding, length 1.
yi
y-i the i-th text embedding, length 1.
In plain words

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.

With numbers

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.

Say it aloud

The length of delta, squared, equals s-I-I plus s-T-T minus two s-I-T.

‖Δ‖2
the length of delta, squared the gap times itself.
sII
s-I-I average cosine of two image embeddings: how tight the image island is.
sTT
s-T-T average cosine of two text embeddings.
2 sIT
two s-I-T twice the average cosine of an image with a text, over every image and every text.
In plain words

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 numbers

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.

Measure a gap two ways

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.

50°
0.35

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.

Two islands have s-I-I = 0.6, s-T-T = 0.6 and s-I-T = 0.1. What is the gap length?

Chapter 2

The Cone Effect

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.

Say it aloud

Rho-one equals mu squared over q, which is one over pi.

ρ1
rho-one the expected cosine of two outputs after one ReLU, for inputs with cosine 0.
μ2
mu squared μ = 1/√(2π) = 0.399 is the average of max(0, X). Two independent entries multiply to μ times μ.
q
q the average of max(0, X) squared: half the time 0, else X squared, so q = 1/2.
1/π
one over pi 0.318: the result, the same at any layer width.
In plain words

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.

With numbers

μ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.

Say it aloud

Rho-prime equals sine theta plus pi minus theta times cosine theta, all over pi, where theta is the arc cosine of rho.

ρ′
rho-prime the cosine of the two outputs of one more layer.
θ = arccos ρ
theta is the arc cosine of rho the angle between the two inputs, from their cosine ρ.
sin θ
sine theta the part from the two inputs’ perpendicular pieces.
(π − θ) cos θ
pi minus theta, times cosine theta the part from the inputs’ shared direction.
π
pi 3.1416, the value the bracket takes when the inputs are identical.
In plain words

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.

With numbers

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.

Build a random network and measure its cone

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.

4

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 layersAngleAverage cosine
090.0°0.000
171.4°0.318
260.4°0.494
447.1°0.681
833.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.

Two unrelated inputs pass through one wide ReLU layer with random weights. What is their expected output cosine?

Chapter 3

Two Networks, Two Cones

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.

Start two networks and see two cones

Both networks read the same 100 random inputs. Orange is network A, teal is network B. Choose the seeds and drag the depth.

4

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 startGap after training
CLIP from scratch1.191.30
Same, gap rotated away at start0.040.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.

Two untrained networks with different seeds read the same inputs. Why are their outputs far apart?

Chapter 4

The Gap by Hand

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)

Turn the cones and read the matrix

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.

0.28
0.28

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.

Say it aloud

The margin equals m squared R plus s squared, minus m squared R minus s squared, which is two s squared.

margin
margin how much the right caption beats the wrong one, in cosine.
m2 R
m squared R the cone part of any photo-caption score: cone weight squared times the cone cosine R.
s2
s squared the meaning part: added for the right caption, subtracted for the wrong one.
2 s2
two s squared what is left: only meaning, no R.
In plain words

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 numbers

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.

In the toy, the cones move from R = 0.28 to R = 0.9. What happens to the margin between the right and the wrong caption?

Chapter 5

The Loss and Its Temperature

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.

Say it aloud

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.

Li
L-i the loss for photo i: 0 when the right caption takes all the probability.
−log
minus log turns a probability near 1 into a loss near 0, and a small probability into a big loss.
exi·yi/τ
e to the x-i dot y-i over tau the right pair’s cosine, divided by τ, made positive by e to the power.
Σj
the sum over j the same term for every caption j in the batch, right one included.
In plain words

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.

With numbers

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.

Probe the loss as the gap closes

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.

The paper fine-tunes CLIP at several temperatures. What happens to the gap?

Chapter 6

Shifting the Gap

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 α.

Say it aloud

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.

scorej
score-j the cosine of the photo with prompt j after the shift.
u·vj
u dot v-j the old cosine of photo and prompt j.
α u·Δ̂
alpha u dot delta-hat what the shift adds on top: the same for every prompt.
√(…)
the square root of one plus two alpha v-j dot delta-hat plus alpha squared the shifted prompt’s length. It differs per prompt, through v-j dot delta-hat.
In plain words

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 numbers

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.

Shift the prompts and flip a prediction

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.

0.00

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 gapBest shifted gapBetter direction
CIFAR-100.90130.9081wider
CIFAR-1000.66580.6737narrower
EuroSAT0.54100.5645narrower
SVHN0.53890.5396wider

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.

You add the same vector to every caption in a gallery and do not renormalize. What happens to the ranking for a photo query?

Chapter 7

Mixed Search and Calibration

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.

Say it aloud

Z equals s minus mu-m, over sigma-m.

z
z how many spreads the item sits above its own modality’s average.
s
s the item’s raw cosine with the query.
μm
mu-m the average cosine for modality m, from a fixed reference set.
σm
sigma-m the standard deviation of those cosines: their typical spread.
In plain words

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 numbers

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.

Rank a mixed index three ways

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.

A mixed index returns only passages for a text query. Which change most reliably surfaces the right images?

Chapter 8

Close It or Use It

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.

Center the islands, then search

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.

0.04

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.

ToolNeeds trainingWhat it fixes
Per-modality z-scoresNoScores on one scale; index unchanged
CenteringNoShared offset; rankings change
Rotation (SVD)NoThe rigid part; reopens if you train again
Bias shift w·ΔNoText-trained linear heads on images
High τ fine-tuneYesShrinks 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.

You train a linear head on text embeddings and run it on image embeddings. If an image is its caption plus the gap Δ, what does the gap cost?

Chapter 9

Field Guide

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.

TermRule or numberSource
Gap vector ΔImage centre minus text centreLiang et al., Sec. 4.2
CLIP gap0.82 on 5,000 MSCOCO pairsLiang et al., Fig. 3
Island tightness0.47 (CLIP images), 0.51 (CLIP texts)Liang et al., Sec. 2.1
Gap identity‖Δ‖2 = sII + sTT − 2sITAlgebra
One ReLUCosine 0 becomes 1/π = 0.318Cho and Saul, 2009
Gap at random start1.19; after training 1.30Liang et al., Sec. 4.4
CLIP temperatureStarts at 0.07, clipped at 1/100Radford et al., 2021
Fairness shiftGap 0.82 to 0.97: fewer offensive labels, −0.0008 accuracyLiang et al., Table 2
Z-score(s − μm) / σm, per modality, per checkpointStandard practice

Checklist before you ship

  1. Measure the gap and s-I-I, s-T-T, s-I-T on your own data.
  2. Ask whether your operation ranks inside one gallery. If yes, stop: the gap is not your bug.
  3. For mixed search, keep one index per modality and retrieve from each.
  4. Fit μ and σ per modality on a fixed reference set; store them with the checkpoint.
  5. Write every threshold in z-units. Never hard-code a raw cosine.
  6. Center embeddings before you average across modalities.
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

Keep going

LessonWhat it adds
Contrastive Learning and CLIPThe model whose geometry this lesson takes apart
Contrastive LearningInfoNCE, negatives, alignment and uniformity
Vector EmbeddingsWhat an embedding is
Similarity MetricsCosine, dot product and distance
Vector DatabasesWhere the mixed index lives
Multimodal RAGRetrieval over text and images together
Embedding BenchmarksWhy leaderboards hide calibration problems
Multimodal Foundation ModelsThe wider family of joint spaces
Vision-Language ModelsThe generative branch
SigLIPA sigmoid loss with a learned bias
ImageBindSix modalities in one space
OpenCLIPOpen checkpoints to measure your own gap
EVA-CLIPThe recipe at larger scale

Sources

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.

The takeaway. A shared space is a claim about a loss, not about locations. Before you trust a cross-modal score, ask whether your operation compares across the two islands.
You inherit a CLIP-based system and have ten minutes to decide whether the gap is your bug. What do you check first?

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.

The Modality Gap
Read the paper · Back to Gleams