4.5.16 · D3Generative Models

Worked examples — Text-to-image conditioning (CLIP)

2,712 words12 min readBack to topic

This page is the exercise floor for Text-to-image conditioning (CLIP). The parent note built the machinery — cosine similarity, temperature, contrastive loss, classifier-free guidance. Here we run the numbers through every awkward corner: matching pairs, mismatched pairs, temperature going to zero or infinity, guidance scale sweeping through , , and large values, and one exam-style trap.

Before we start, one promise: every symbol we touch was defined in the parent, but we re-anchor each to a picture so you never have to scroll back.


The scenario matrix

Every problem CLIP can throw at you lives in one of these cells. Throughout, denotes the number of items softmax is comparing — the batch size in the contrastive loss, or the number of candidate labels in zero-shot classification. The exam twist (Cell K) is the classic slip of feeding a raw, un-normalised dot product into the similarity slot: because it still carries the vectors' lengths, it escapes the range and silently corrupts the temperature — the fix is to divide by both lengths first. The worked examples below are labelled by cell.

Cell Scenario class What's extreme about it Example
A Matching pair, sim near positive pair, loss should be tiny Ex 1
B Mismatched pair, sim near or negative pair, loss should be large Ex 1
C Full batch loss (both directions) the real symmetric objective Ex 2
D Temperature softmax becomes a hard argmax Ex 3
E Temperature softmax becomes uniform (with = number of items compared) Ex 3
F Guidance pure unconditional — prompt ignored Ex 4
G Guidance plain conditional, no amplification Ex 4
H Guidance (e.g. ) extrapolation past the condition Ex 4
I Degenerate: identical embeddings every similarity equal → tie Ex 5
J Real-world word problem zero-shot classification decision Ex 6
K Exam twist: un-normalised vectors raw dot product breaks the range — "forgot to normalise" Ex 7

Warm-up figure

Figure — Text-to-image conditioning (CLIP)

Figure 1 above is the whole idea of cosine similarity in two dimensions. The angle between the blue image arrow and the pink text arrow is what we measure; . When they overlap, and . When they're at a right angle, . When they point opposite, .


Example 1 — Cells A & B: one positive, two negatives, by hand

Forecast: guess now — will be close to (great match) or a big positive number? Because dominates the others, I predict a small loss.

  1. Divide each similarity by . Why this step? This is the temperature step of the softmax formula above. Small stretches the gaps, so the correct pair pulls far ahead.

  2. Exponentiate. Why this step? Softmax works on so every score becomes positive and bigger scores blow up faster.

  3. Normalise into a probability. Why this step? is the correct-text slice of the pie — numerator over the sum of all slices.

  4. Take negative log. Why this step? Cross-entropy loss is of the probability you put on the truth.

Verify: the loss is tiny and positive, matching the forecast — a confident correct match costs almost nothing. Cell A (the positive) dominated; cells B (the and negatives) contributed almost nothing because their values are dwarfed. Good.


Example 2 — Cell C: the full symmetric batch loss

Forecast: the matrix is symmetric and diagonal-heavy, so both directions should give the same loss, and it should be small-ish but not zero.

  1. Scale by : every entry → diagonal , off-diagonal . Why? Same temperature step as before; .

  2. Row softmax for image 1 (row ): Why? needs the row's own pie — here items. By symmetry too.

  3. Image-to-text loss: Why this step? Using the definition above, is the average over the two images of each image's own cross-entropy ; the is with , and both terms are equal here.

  4. Text-to-image loss uses columns. Why? asks "given text , which image?" — that reads down a column. The matrix is symmetric, so columns equal rows → .

  5. Average the two directions:

Verify: symmetric matrix ⇒ both directional losses equal ⇒ the average equals either one. Value , small because . Consistent.


Example 3 — Cells D & E: temperature at both extremes

Figure — Text-to-image conditioning (CLIP)

Figure 2 above plots the answer to this example: as sweeps from cold to hot.

Forecast: tiny should snap the probability toward the biggest entry (), so . Huge should flatten everything across all items, so .

  1. Case (approaching 0). Why this step? blows the gaps wide open. Scaled: . Then Nearly 1 — the softmax became an almost-hard argmax. That is cell D.

  2. Case (approaching ). Why this step? crushes every gap to near zero. Scaled: . Then Almost exactly — the softmax became uniform over all items. That is cell E.

  3. The limiting law. As , softmax → one-hot on the max; as , softmax → uniform (here ). Figure 2 plots against so you can see the S-curve between these two shelves.

Verify: hugs (argmax shelf), hugs (uniform shelf). Both limits confirmed. This is exactly why CLIP learns — it wants sharp-but-not-brittle, sitting on the steep part of the curve.


Example 4 — Cells F, G, H: guidance scale sweep

Figure — Text-to-image conditioning (CLIP)

Figure 3 above draws the guidance line and marks the three values worked below.

Forecast: ignores the prompt (should give ); gives the plain conditional (); overshoots past .

  1. Find the guidance direction. Why this step? The bracket is the arrow "toward the prompt". See Figure 3 — it is the pale-yellow arrow from the unconditional dot to the conditional dot.

  2. Cell F, : The prompt is entirely ignored — you get generic images. This is why is useless for text-to-image.

  3. Cell G, : Exactly the conditional prediction — faithful but low-contrast, often washed-out.

  4. Cell H, : We extrapolate far beyond . This is extrapolation, not interpolation — that is what makes samples look punchy and prompt-obedient, but push too high and they oversaturate.

Verify: the three answers lie on the straight line ; Figure 3 shows them as three chalk dots on that line. Sanity: at we exactly recover , which the formula must do (plug : ). Correct. For the derivation of why the bracket approximates the classifier gradient, see 4.5.15-Classifier-free-guidance.


Example 5 — Cell I: degenerate identical embeddings (the tie)

Forecast: every score equal ⇒ softmax can't tell them apart ⇒ perfect three-way tie ⇒ , and the loss should be .

  1. Scale and exponentiate. Why? ; all three values are identical, call it .

  2. Softmax collapses to uniform. Why? regardless of . The temperature cancels — a tie stays a tie at any temperature.

  3. Loss:

Verify: is exactly the cross-entropy of a uniform guess over 3 classes — the maximum-confusion loss for . This is the sanity floor every fresh CLIP run starts near: at initialisation all embeddings are near-random, similarities are roughly equal, and the loss sits near . If your training loss starts far above , something is wrong. Degenerate case handled.


Example 6 — Cell J: real-world zero-shot classification decision

Forecast: dog has the highest similarity, so dog wins; with the gaps get amplified, so confidence should be high — I'd guess .

  1. Scale by . Why? Same conditioning step. Scaled logits:

  2. Exponentiate: . Why? Softmax numerators.

  3. Normalise:

  4. Decision: pick dog with confidence .

Verify: probabilities sum to ✓ (must, since softmax). Dog beats cat by a hair in raw similarity ( vs ) but temperature stretches it to a vs gap — that is exactly what low buys you. This is the mechanism behind zero-shot transfer: no training on this task, just similarity + softmax.


Example 7 — Cell K: the "forgot to normalise" exam trap

Forecast: the correct cosine must land in ; since the two vectors are close-ish in direction, expect something like .

  1. Dot product (the student's number): Why? . Correct arithmetic, wrong measure — it still carries the lengths.

  2. Compute the two lengths. Why this step? Cosine strips length; we must divide it out.

  3. Divide:

  4. Diagnose the trap. The dot product was outside purely because the arrows are long ( units each). Cosine's denominator exactly cancels that length, returning the honest direction-agreement .

Verify: ✓. Cross-check via the angle: , a small angle — matching the fact that and are near-mirror-images that point in nearly the same direction. Never feed raw dot products into the CLIP softmax; always normalise first, or your temperature is silently wrong.


Recall Self-test

At , what does approach for a batch of ? ::: (uniform) — see Ex 3, cell E. A perfectly-tied similarity row gives what loss for ? ::: — Ex 5, cell I. With , , , what is ? ::: — Ex 4, cell H. For raw vectors and , the cosine similarity is? ::: — Ex 7, cell K.

Where to go next: the attention-based text encoder that produces these embeddings lives in 4.4.7-Attention-mechanisms; the broader picture of joining modalities is 4.5.17-Multimodal-learning; the diffusion sampler that consumes is in 4.5.14-Diffusion-models.