14.5 Contrastive image-text: CLIP and SigLIP
Vision transformer encoder built a vision tower that turns pixels into vectors, but nothing yet says what those vectors should mean. Every classifier so far, the LeNet of Conv layers and pooling on autograd and the heads of Fine-tuning heads and the linear-head export, needed a fixed label set and a labelled example of each class. Captions are free supervision with an open vocabulary: 400 million image-text pairs trained CLIP, and its descendant SigLIP is the vision tower inside SmolVLM, the model the planned vision-language model section loads.
Concepts from other sections (17)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- sigmoid: , mapping the real line into , with . Read more: 7.3 Activation Functions and Their Derivatives in Mathematics
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3 in Mathematics
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
- Mutual information: , the nats that knowing one variable saves about the other. Read more: 17.3 Mutual information, PMI, and PPMI in Mathematics
- Log-likelihood: , the log probability of the observed counts under a distribution . Read more: 13.3 MLE, Laplace, absolute discounting in Mathematics
- op library (
F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined byfrom_op. Read more: 6.3 The op library and gradcheck_all - Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- CLS token: a learned vector prepended to the sequence whose output summarizes the image. Read more: 14.3 Vision transformer encoder
- pre-LN: with one final LN per stack; trains without warmup. Read more: 11.5 Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing
- pre-LN block: a residual block whose branches normalize their input,
x + branch(LN(x)), leaving the stream itself unnormalized. Read more: 15.2 Whisper encoder: conv stem, sinusoids, pre-LN blocks - processor config: the
preprocessor_config.jsonthat fixes a model’s resize, crop, and normalization recipe. Read more: 14.6 Image preprocessing to the specification - Gradient check: a comparison of an analytic gradient against the numerical one that reports pass or fail and the element furthest past its allowance. Read more: 10.1 Partial derivatives, gradients, and gradcheck in Mathematics
- Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- VJP (vector-Jacobian product): , the gradient of ; what reverse mode computes. Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- all-gather: every rank ends with the concatenation of all ranks’ chunks, in rank order. Read more: 17.2 Collectives over processes: ring all-reduce
- Representation learning: learning the features themselves, not just a decision rule over given features. Read more: Chapter 2: Deep Learning
This section builds the objective that makes an image vector and a text vector comparable, and the two things that fall out of it. The first is a similarity score for any image-text pair, which a planned data-engineering filter will run over a scraped corpus. The second is a classifier for classes named only at test time, which a planned responsible-AI probe will use to look for accuracy disparities. Consent and biometric evidence in model cards in AI Engineering already calls this implementation. The end-to-end evidence that the parts train together is a tiny dual encoder that learns zero-shot classification of 24 color-shape classes.
You will reuse ViT, VisionBlock, and ViTConfig from the vision transformer section, the image processor of Image preprocessing to the specification, Embedding, LayerNorm, Linear, and ModuleList from Module system and basic layers, the ops of The op library and gradcheck_all, from_op from Tensor, broadcasting backward, and no_grad, and PCG32 from Modular arithmetic, hashing, and PCG32 in Mathematics. Useful background is Multi-head attention, softmax with a temperature in Entropy, cross-entropy, KL, JS, and the k3 estimator, and Losses with a fused backward. The full solution is contrastive.py and its contract is course/contracts/py/tinyllm/vision/contrastive.pyi.
Learning objectives
- Derive CLIP’s symmetric InfoNCE loss and SigLIP’s pairwise sigmoid loss from one cosine matrix, and compute both by hand.
- Explain why the temperature is learned as a log scale, why it multiplies, and why CLIP clamps it at 100.
- Implement a numerically stable with its backward.
- Build a dual encoder whose text embeddings are independent of padding.
- Turn class names and prompt templates into a zero-shot classifier.
Notation
Section titled “Notation”These symbols are used throughout.
| Symbol | Meaning | Type / shape |
|---|---|---|
| , | pairs in the batch, embedding width | int |
| , | L2-normalized text and image | float[d], length 1 |
| cosine matrix, texts on rows | float[B, B], in | |
scale; is logit_scale (CLIP) or t (SigLIP) | scalar, | |
| SigLIP bias | scalar | |
| logit of pair | float[B, B] | |
| when , else | float[B, B] | |
| scalar |
One matrix holds every comparison
Section titled “One matrix holds every comparison”Row of the images goes with row of the texts; every other combination is a pair that does not match. Normalize each row to length 1 and take all dot products at once: . The diagonal holds the matching pairs and the off-diagonal entries are negatives that cost nothing to collect. Both losses below normalize inside, so they score directions and ignore lengths. They differ only in how they read this matrix.
CLIP: InfoNCE as two cross-entropies
Section titled “CLIP: InfoNCE as two cross-entropies”CLIP treats “which image goes with text ?” as classification over the images in the batch, with logits : That is the ordinary cross-entropy of row against class . The same matrix read by columns asks “which text goes with image ?” and gives , the cross-entropy of against the diagonal. The loss is the mean of the two, so swapping the modalities transposes and changes nothing.
A model that cannot tell the pairs apart has and loss ; van den Oord et al. show is a lower bound on the mutual information between image and text, which is why larger batches help. Differentiating a softmax cross-entropy gives : each wrong pair is pushed apart in proportion to the probability it stole. At both softmaxes have one class, so the loss and every gradient are 0.
SigLIP: a sigmoid per pair
Section titled “SigLIP: a sigmoid per pair”The softmax couples a whole row: no pair can be scored without all the others. SigLIP instead models every pair as its own Bernoulli variable, “is this a match?”, with logit and . Since , the log-likelihood of the right answer is for both kinds of pair, and
The sum is over terms but the divisor is , as in SiglipModel. With one pair there is still a question to answer, so the loss is and its gradient is not zero.
The bias exists because the questions are unbalanced: say yes and say no. At a fresh model has , every negative costs , and the first steps do nothing but push all logits down. Starting at makes the model’s prior , about one match in 22000, the right order for the batch sizes it was trained with; each negative then costs and the positives carry the gradient. The published init is , .
Warning: Compute , never . The second overflows once in float64, and as written returns at . Its derivative is ; this is the one backward this section adds to the op library, through
from_op.
Why the temperature is learned, and why it is clamped
Section titled “Why the temperature is learned, and why it is clamped”Both losses multiply cosines by a scale , and it is worth seeing why. Cosines live in . With even a perfect model (matching pair at , all others at ) has , so at the loss cannot fall below . The logits need a scale, and how large depends on how separated the embeddings are, so it is a parameter. Learning keeps positive and makes each step a multiplicative change; CLIP starts at .
By the chain rule . When every matching pair already has the largest cosine in its row and column, this is negative: sharpening the softmax moves probability onto the right answer. It stays negative however large gets, because the loss goes to 0 only as . Nothing in the objective stops the growth, and a huge turns the softmax into a hard max that learns only from the single hardest negative and overflows in half precision. So CLIP caps the scale: . In this contract, when the loss is the loss at exactly 100 and logit_scale gets no gradient. Dividing by where the loss multiplies flips the sign of this gradient: the model then cools itself whenever it is right.
The dual encoder
Section titled “The dual encoder”The losses need two embeddings, and the dual encoder supplies them from two towers that never see each other’s input. The image tower is ViT; its pooled output is the CLS token when the tower has one (CLIP) and the mean over patches otherwise (SigLIP). The text tower stacks the same pre-LN VisionBlocks over token plus learned position embeddings and pools by the mean over real tokens: id 0 is padding, hidden as an attention key and left out of the mean, so a caption’s embedding does not depend on its batch. One bias-free Linear per tower projects into the shared -dimensional space, and both encoders return unit rows.
Zero-shot classification
Section titled “Zero-shot classification”Once text and images share a space, a classifier can be written in words. For class names and prompt templates such as "a photo of a {}", embed every filled template and average:
is the weight matrix of a linear classifier that the text tower wrote; no image of any class was labelled. The mean of unit vectors is shorter than 1, so it is normalized again to keep the scores cosines.
Working it by hand
Section titled “Working it by hand”Take two pairs in two dimensions: images , and texts , , all of length 1. Then .
For CLIP with the logits are . A two-class cross-entropy is . Along the text rows, margins and give and , mean . Along the image columns, margins and give and , mean . The loss is .
For SigLIP with , , the logits are ; multiplied by the signs they are . The four costs are , , , , which sum to ; divided by the loss is . The pair with cosine is the expensive one: a negative the model has not yet pushed away.
A correct solution gives both numbers even when the rows are handed over at lengths 2, 0.5, 3, and 5, because both losses normalize first.
Designing the API
Section titled “Designing the API”The interface is two losses, two encoders, and two zero-shot helpers:
def clip_loss(img_emb: Tensor, txt_emb: Tensor, logit_scale: Tensor) -> Tensor: ... # [B, d], [B, d], [1]def siglip_loss(img_emb: Tensor, txt_emb: Tensor, t: Tensor, b: Tensor) -> Tensor: ...class TextEncoder(Module): # ids [N, T] -> [N, T, d]; id 0 is padding def __init__(self, vocab, d, n_layers, n_heads, d_ff, max_len, rng=None): ...class DualEncoder(Module): def __init__(self, vision: ViT, text: Module, d_embed, loss, t_init, b_init=-10.0, rng=None): ... def encode_image(self, pixel_values: Tensor) -> Tensor: ... # [N, d_embed], unit rows def encode_text(self, ids: NDArray) -> Tensor: ... # [N, d_embed], unit rows def encode_images(self, images: Sequence[bytes], cfg: ProcessorConfig) -> Tensor: ... # files -> [N, d_embed] def loss(self, pixel_values: Tensor, ids: NDArray) -> Tensor: ...def zero_shot_classifier(model, tok, class_names, templates) -> NDArray: ... # [n_classes, d_embed]def zero_shot_predict(model, pixel_values: Tensor, W: NDArray) -> NDArray: ... # int64 [N]Building it step by step
Section titled “Building it step by step”Seven observations shape the code.
- Both losses start from one matrix. Normalize, then with texts on rows. A shared
_pairshelper does the shape check and the normalization once, so neither loss can forget either. - CLIP is cross-entropy against the diagonal, twice. Row ‘s correct class is , so the loss of a logit matrix is the mean of
log_softmax(logits)[i, i], negated. Reading by columns is the same function on the transpose. - The clamp must cut the gradient, not just the value. Above the scale is a constant 100 (no path to
logit_scale); below it the scale isexp(t)in the graph. A numpy clamp everywhere would freeze the temperature; no clamp lets it grow forever. - SigLIP needs one new op. must be stable for in the thousands and its derivative is , so it is a
from_opnode with both computed in their stable forms. - SigLIP’s sign trick turns yes-or-no questions into one sum. With , every term is ; the sum divided by is the loss.
- The encoders must return unit rows, independent of padding. Image pooling is CLS or the patch mean depending on the tower; text pooling is the mean over real tokens, and padding is masked as a key too. Both project with a bias-free
Linearand normalize. - A zero-shot classifier is just normalized text embeddings. Average each class’s prompt embeddings, renormalize, stack; prediction is an argmax of cosines.
The shared helpers come first:
def _normalize(x: Tensor) -> Tensor: return x * (F.sum(x * x, axis=-1, keepdims=True) ** -0.5) # unit rows, in the graph
def _pairs(img_emb, txt_emb, who) -> Tensor: """The cosine matrix C[i, j] = <txt_i, img_j>, [B, B].""" if img_emb.ndim != 2 or txt_emb.ndim != 2 or img_emb.shape != txt_emb.shape: raise ValueError(...) # no loss on broadcast noise return F.matmul(_normalize(txt_emb), F.transpose(_normalize(img_emb), 0, 1))
def _diag_ce(logits: Tensor) -> Tensor: """Mean cross-entropy of row i against class i.""" b = logits.shape[0] lp = F.log_softmax(logits, axis=-1) return -F.mean(lp[np.arange(b), np.arange(b)])CLIP implements the clamp as a branch on the value:
def clip_loss(img_emb, txt_emb, logit_scale): c = _pairs(img_emb, txt_emb, "clip_loss") t = F.reshape(logit_scale, ()) # Clamp the temperature at 100: past it the scale is a constant. scale = F.exp(t) if float(t.data) <= LN100 else Tensor(np.array(100.0), dtype=c.data.dtype) logits = c * scale # multiply: a larger s sharpens # texts choose images (rows) and images choose texts (columns) return (_diag_ce(logits) + _diag_ce(F.transpose(logits, 0, 1))) * 0.5The stable op computes both the value and the derivative without overflow:
def _logsigmoid(x: Tensor) -> Tensor: """log sigmoid(x) = min(x, 0) - log(1 + exp(-|x|)), stable for any x.""" a = x.data y = np.minimum(a, 0) - np.log1p(np.exp(-np.abs(a))) # exp only of non-positive numbers # d/dx log sigmoid(x) = 1 - sigmoid(x) = sigmoid(-x), also in a form that cannot overflow sneg = np.exp(np.minimum(-a, 0)) / (1.0 + np.exp(-np.abs(a))) return from_op(y.astype(a.dtype), (x,), lambda g: (g * sneg.astype(a.dtype),), "logsigmoid")With it, SigLIP is four lines:
def siglip_loss(img_emb, txt_emb, t, b): c = _pairs(img_emb, txt_emb, "siglip_loss") n = c.shape[0] logits = c * F.exp(F.reshape(t, ())) + F.reshape(b, ()) # scale e^t first, then the bias z = 2.0 * np.eye(n) - 1.0 # +1 for the matching pair, -1 for every other return -F.sum(_logsigmoid(logits * z)) * (1.0 / n) # B^2 terms, divided by BThe text tower reuses VisionBlock (a pre-LN block does not care what its tokens came from) over token and position embeddings, with padding masked as keys:
def forward(self, ids): a = np.asarray(ids) # ... raise unless [N, T <= max_len] h = self.token_embedding(a) + self.position_embedding(np.arange(a.shape[1])) mask = (a != 0)[:, None, None, :] # padding is never a key for layer in self.layers: h = layer(h, mask) return self.final_layer_norm(h)DualEncoder holds the two towers, two bias-free projections, logit_scale, and logit_bias only for SigLIP. Its encoders pool, project, and normalize:
def encode_image(self, pixel_values): last, _ = self.vision(pixel_values) pooled = last[:, 0] if self.vision.cfg.cls_token else F.mean(last, axis=1) # CLS tower or mean return _normalize(self.visual_projection(pooled))
def encode_text(self, ids): a = np.asarray(ids) keep = (a != 0).astype(np.float32) counts = keep.sum(axis=1, keepdims=True) if np.any(counts == 0): raise ValueError("encode_text: a row holds only padding") # 0/0 would be NaN h = self.text(a) pooled = F.sum(h * keep[:, :, None], axis=1) * (1.0 / counts) # mean over real tokens only return _normalize(self.text_projection(pooled))loss encodes both sides and dispatches on loss_kind. encode_images takes image files, runs preprocess from the image preprocessing section with a single-frame processor config (raising for a splitting processor or pixels that do not match the tower’s size), concatenates the frames in input order, and calls encode_image.
Zero-shot classification is a few lines of numpy on the encoders’ outputs:
def zero_shot_classifier(model, tok, class_names, templates): out = [] for name in class_names: e = model.encode_text(_encode_prompts(tok, [t.format(name) for t in templates])).data m = e.mean(axis=0) # prompt ensemble out.append(m / np.linalg.norm(m)) # renormalize: a mean of unit vectors is shorter than 1 return np.stack(out)
def zero_shot_predict(model, pixel_values, W): scores = model.encode_image(pixel_values).data @ np.asarray(W).T # cosines return np.argmax(scores, axis=1).astype(np.int64)_encode_prompts tokenizes every prompt and right-pads with id 0, which encode_text then ignores. The full solution is contrastive.py.
Why this design
Section titled “Why this design”Both losses are for the matrix plus for the softmaxes or sigmoids; the towers dominate. SigLIP’s terms are independent, so the matrix can be computed in chunks across devices without a batch-wide softmax, which is the reason it scales to very large batches.
Normalizing inside the loss, rather than trusting the caller, makes the losses correct for any input and keeps the scale parameter meaningful, since they are defined on directions. The clamp is a branch rather than minimum because a smooth or numpy clamp either changes the loss below the cap or kills the gradient everywhere; the branch gives exactly “the loss at 100, no gradient” above the cap and the plain graph below it.
For , composing log(sigmoid(x)) overflows. Composing the stable form from minimum, abs, exp, log1p would work if all existed as differentiable ops, but a single node with the known derivative is shorter and exact. Reusing VisionBlock for text works because the block is modality-agnostic, and it keeps one tested block and one set of parameter names.
What can go wrong
Section titled “What can go wrong”The checks below pin both losses to Hugging Face and test the properties derived above, ending with a learning test.
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| hand example: two pairs | unit, smoke | the hand-worked two losses, on unnormalized rows | both definitions are pinned |
| CLIP loss matches HF | golden | CLIPModel’s loss and three gradients at ; zero at | fine-tuning a published CLIP |
| SigLIP loss matches HF | golden | SiglipModel’s loss and four gradients at | SigLIP is SmolVLM’s vision tower |
| gradient check, CLIP | gradcheck | backward to both embeddings and logit_scale | the temperature trains |
| gradient check, SigLIP | gradcheck | backward through to embeddings, , | the one new op is right |
| CLIP is symmetric in the modalities | property | swapping arguments or reordering pairs changes nothing | both towers get a training signal |
| SigLIP is defined at batch one | boundary | : SigLIP has a loss and gradient, CLIP is 0 | small and sharded batches |
| temperature gradient sign | property | on matched pairs, on mismatched | the scale grows when the model is right |
| CLIP temperature clamped at 100 | boundary | past : the loss at 100, no gradient | stable long runs |
| SigLIP stable at large logits | boundary | logits of give , not | late training, half precision |
| dual encoder parameters and loss | unit | names, bias-free projections, logit_bias only for SigLIP, backward reaches every parameter | checkpoints load by name |
| image pooling: CLS or mean | unit | CLS when the tower has one, else the patch mean | CLIP and SigLIP towers both fit |
| text padding is invisible | property | extra padding never changes a caption’s embedding | scoring captions in batches |
| zero-shot classifier is a prompt ensemble | unit | rows are renormalized template means; predict is the argmax | the planned disparity probe |
| bad embedding shapes refused | boundary | unequal batches or widths raise ValueError | no loss on broadcast noise |
| dual encoder learns zero-shot shapes | learning | 600 SigLIP steps on PCG32-drawn shapes: zero-shot accuracy at least 0.80 | the parts train together |
| encoded images match the explicit pixel pipeline | unit | encode_images equals preprocessing then encode_image, in order; a processor with the wrong geometry or splitting raises | the consent evidence practice and the planned filter encode image files directly |
The learning test is the strongest evidence: after 600 steps on captions alone the tiny model labels held-out shapes at about 0.89 accuracy, against a chance of .
Many pitfalls come from getting the loss definitions slightly wrong. Raw dot products instead of cosines let long vectors win and make the scale parameter meaningless; _pairs normalizes both sides before the matmul. Computing only one direction of the CLIP loss gives the image tower half the signal and breaks symmetry; clip_loss averages _diag_ce(logits) and _diag_ce of the transpose. Averaging SigLIP over instead of makes gradients times too small; siglip_loss multiplies the sum by 1.0 / n. Labels 1 and 0 for instead of mean negatives are never pushed away and nothing is learned; z = 2.0 * np.eye(n) - 1.0 gives .
The temperature has its own family of mistakes. Dividing by gives the temperature gradient the wrong sign; the solution multiplies, logits = c * scale. Leaving out the clamp lets the scale grow without bound; clip_loss uses a constant 100 once t > ln 100. Computing the clamp in numpy everywhere silently freezes logit_scale; below the cap the scale is F.exp(t), a graph op. Using itself as SigLIP’s scale instead of makes the init scale 2.3, and it can go negative; siglip_loss uses F.exp(t). Adding the bias before the scale makes the effective init , not , so there is no gradient at the start; the code computes c * F.exp(t) + b, scale first.
For itself, computing as written produces an inf loss once a logit is very negative, and writing its derivative as gives the right loss with wrong gradients. _logsigmoid computes min(x, 0) - log1p(exp(-|x|)) and its VJP multiplies by .
On the encoder side, a text mean taken over padding too makes a caption’s embedding depend on its batch, and so does padding left visible to attention; encode_text weights by keep and divides by the real-token count, and TextEncoder masks keys with (a != 0). An encode_image that does not normalize makes zero-shot scores not cosines. Mean pooling over a CLS tower makes a loaded CLIP projection read the wrong vector; encode_image takes last[:, 0] when cls_token. A prompt mean that is not renormalized gives classes with agreeing prompts larger scores; zero_shot_classifier divides each mean by its norm.
Finally, validation. Unequal batches would give a loss over pairs that do not exist, so _pairs raises unless both are [B, d] of one shape. An unknown loss name would let a typo train SigLIP when you asked for CLIP, so DualEncoder.__init__ raises unless clip or siglip. An all-padding caption would put a NaN embedding into the batch, so encode_text raises when a row’s count is 0.
Where this leads
Section titled “Where this leads”Consent and biometric evidence in model cards in AI Engineering calls this implementation as part of its evidence practice. A planned data-engineering section will score each scraped image-caption pair with the cosine of the two encodings and drop the low ones, and a planned responsible-AI probe will build zero-shot classifiers and compare accuracy across image source domains.
In production, OpenCLIP’s ClipLoss gathers features across GPUs so every device’s batch serves as negatives for all (mlfoundations/open_clip, src/open_clip/loss.py). big_vision’s SigLIP uses a chunked pairwise loss in which devices swap text halves, so no all-gather is needed and batch 32k fits (google-research/big_vision, trainers/proj/image_text/siglip.py). Hugging Face’s CLIPModel and SiglipModel add pretrained towers, EOS-token and attention pooling, and SigLIP 2’s NaFlex resolutions (transformers/models/siglip/modeling_siglip.py). OpenCLIP’s build_zero_shot_classifier uses 80 ImageNet templates, batched over classes (src/open_clip/zero_shot_classifier.py). And the similarity score itself is CLIPScore, a caption metric, and the filter behind LAION-5B.
Further reading
Section titled “Further reading”- Radford et al., “Learning transferable visual models from natural language supervision” (2021), sections 2.3 and 3.1.
- Zhai et al., “Sigmoid loss for language image pre-training” (2023), sections 3 and 4.
- van den Oord et al., “Representation learning with contrastive predictive coding” (2018), for InfoNCE as a bound on mutual information.
- Hessel et al., CLIPScore (2021); Schuhmann et al., LAION-5B (2022).
Key terms
Section titled “Key terms”- dual encoder: two towers, one per modality, projecting into a shared embedding space.
- InfoNCE: a softmax cross-entropy that picks the matching item from a batch of candidates; CLIP applies it in both directions.
- pairwise sigmoid loss: SigLIP’s loss, one independent yes-or-no logistic term per pair.
- logit scale (temperature): the learned factor that multiplies cosines before the loss.
- zero-shot classifier: a linear classifier whose rows are text embeddings of class prompts.
- prompt ensemble: the renormalized mean of several prompt templates’ embeddings for one class.
Summary
Section titled “Summary”- CLIP’s loss is two cross-entropies over one matrix of scaled cosines, texts choosing images along the rows and images choosing texts along the columns, so it is symmetric in the two modalities and equals Hugging Face’s to .
- SigLIP asks independent yes-or-no questions and divides by ; it needs no softmax over the batch, so it is defined, with a gradient, for a single pair.
- The temperature is learned as
logit_scaleand multiplies the cosines. On a batch the model already separates, a larger always lowers the loss, so CLIP caps at 100. - must be computed as ; the formula as written returns at .
- A classifier can be written in words: one row per class, the renormalized mean of its prompt embeddings. After 600 steps on captions alone the tiny model labels held-out shapes at about 0.89 accuracy against a chance of .
Review questions
Section titled “Review questions”-
Why does SigLIP have a nonzero gradient at while CLIP’s loss is exactly 0?
Answer
CLIP’s softmax over one candidate always gives probability 1, so the cross-entropy is 0 whatever the logit. SigLIP asks whether that one pair matches: is positive unless the logit is , and its gradient pushes the cosine up.
-
Why is the temperature multiplied, and what does the clamp change about its gradient?
Answer
Multiplying by means a model that ranks the pairs correctly lowers its loss by growing , so when it is right. Dividing would flip that sign. Above the solution uses a constant, so the loss is the loss at 100 and
logit_scalegets no gradient: the growth stops there. -
Why does SigLIP start the bias at , and why must the scale be applied before the bias?
Answer
Most pairs are negatives, so the prior “no match” should be strong: . With the bias added first and then scaled by , the effective bias would be : every sigmoid saturates and the gradient at the start is essentially zero.
-
What does masking padding as a key add to leaving padding out of the mean?
Answer
Leaving it out of the mean removes padded positions’ own outputs, but real tokens would still attend to padded keys and change with the amount of padding. Masking the keys makes every real token’s output independent of padding, so a caption’s embedding is the same in any batch.
-
Why renormalize the mean of the prompt embeddings?
Answer
Each prompt embedding is a unit vector; their mean is shorter the more the prompts disagree. Without renormalizing, classes whose prompts agree would get longer weight rows and higher scores for every image, a bias unrelated to the image.