Unit 3 of 9 · about 6 hours · derive, implement

The symmetric CLIP contrastive loss, the SigLIP pairwise sigmoid loss and batch-size behavior

The Deep Learning unit on paired modalities already implemented symmetric CLIP. Here the new work is an independent loss oracle, gradient checks and the reduction and negative-sampling contracts needed for a controlled objective comparison.

You'll be able to

  • Derive CLIP and SigLIP losses and their logit gradients with explicit reductions.
  • Differential-test both losses and gradients against OpenCLIP 3.3.0 on one device.
  • Separate batch-size effects on negatives, reduction scale and optimization budget.

Covers

Symmetric CLIP contrastive loss and temperatureSigLIP pairwise sigmoid loss and batch-size behavior
1

Read

In this order, only the parts listed

0 of 3 done

  1. CLIP, ICML 2021 PMLR editionCLIP Paper and Official Code

    Section 2.2 and Figure 3: normalized embeddings, learned logit multiplier and the two cross-entropies

    Use this edition's numbering, not the earlier prerequisite card's section labels. Reconstruct the gradient rather than repeating the first-pass implementation.

  2. Sigmoid Loss for Language Image Pre-Training, arXiv:2303.15343v4Sigmoid Loss for Language Image Pre-Training (Zhai et al., 2023)

    Sections 3.1 and 3.2 and Algorithm 1; Figure 2 and Sections 4.1 and 4.2 for batch-size experiments

    Algorithm 1 in this version uses positive similarity logits with positive diagonal labels; the first arXiv version printed a negated dot product there. OpenCLIP, below, uses the same positive-similarity and bias convention. Read the batch curves under their own model, data and seen-example budgets; do not reproduce the large runs.

  3. OpenCLIP release 3.3.0 loss definitionsOpenCLIP

    ClipLoss.get_logits, ClipLoss.forward, SigLipLoss.get_ground_truth and SigLipLoss._loss

    Use world_size=1. Pass normalized features and the multiplier itself; these loss classes do not normalize features or exponentiate the supplied multiplier.

2

Focus on

  • For batch size , normalized features and logits , CLIP averages row and column cross-entropy: . A shared scalar bias cancels from both softmaxes.
  • SigLIP uses , with diagonal labels 1 and off-diagonal labels -1. For this reduction, . Use a stable softplus or log-sigmoid implementation.
  • TensorTonic divides the SigLIP sum by ; OpenCLIP divides by . Multiply the exercise loss and gradients by before comparison, keeping logits identical.
  • SigLIP removes the softmax normalization across candidates, not the need for negative pairs. Batch size changes negative coverage and class imbalance; accumulating isolated microbatch losses does not create the cross-microbatch negatives of a full batch.
Common mistakes · 3
  • Passing a stored logarithmic scale where the API expects its exponential. The OpenCLIP loss call and TensorTonic's SigLIP problem take the multiplier itself; TensorTonic's CLIP problem takes the temperature and divides by it.
  • Using a one-pair CLIP batch as a learning test. Its loss and gradient are zero because there are no competing candidates; SigLIP still trains its positive term.
  • Treating every off-diagonal pair as truly negative. Duplicate images or equivalent captions can make the diagonal-only supervision contradictory.
3

Try it yourself

Closed-book, before checking anything

On CPU with PyTorch 2.14.1 and open_clip_torch==3.3.0, use two orthogonal unit vectors as both image and text features in float64. CLIP with multiplier 1 gives 0.3132616875. SigLIP with multiplier 2 and bias -1 gives 0.6265233750 in OpenCLIP and 0.3132616875 as an all-pairs mean. Derive the factor of two, then compare your losses and feature, multiplier and bias gradients against OpenCLIP on seeded nonzero random features, using torch.manual_seed(42) and torch.testing.assert_close with rtol=1e-7, atol=1e-9.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why is a learned scalar bias useful for SigLIP but ineffective for CLIP's softmax loss?Answer

    SigLIP's bias moves all binary decision logits to reflect the positive-negative imbalance. In CLIP a common additive bias cancels inside each softmax.

  2. 2.What happens to the SigLIP reduction factor for a batch of eight pairs?Answer

    OpenCLIP's sum divided by eight is eight times the all-64-pairs mean, for identical logits and labels. Gradients differ by the same factor.

  3. 3.Does a lower raw SigLIP loss than CLIP loss prove a better encoder?Answer

    No. Their objectives and reductions differ. Compare held-out retrieval on the same candidates and account for data exposure, optimization and compute.

  4. 4.If two captions describe the same image, is diagonal-only retrieval accuracy a complete evaluation?Answer

    No. A different valid caption may be counted as wrong. Keep relevance groups and specify whether any valid caption counts as a retrieval hit.

5

Practice

  • TensorTonic: Implement Symmetric CLIP Contrastive Loss

    symmetric_clip_loss: public cases Orthogonal matched pairs, Single normalized pair and One ambiguous image

    Reuse your prerequisite implementation. The cases check normalized logits, loss and directional accuracies including an argmax tie; they do not check gradients. Add the OpenCLIP differential tests instead of treating this as a new first-pass exercise.

  • TensorTonic: Implement the SigLIP Pairwise Loss

    siglip_pairwise_loss: public cases Aligned orthogonal pairs, Single confident pair and Swapped pairs

    Follow its all-pairs-mean contract for the exercise, then convert the reduction for your OpenCLIP oracle. Add large-magnitude finite-logit tests and a gradient check on nonzero features; the public cases do not validate gradients.

You're done when

Both exercise contracts pass, both converted objectives and gradients agree with OpenCLIP within the stated tolerance, and you explain why microbatch accumulation does not reproduce full-batch negatives.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 12 more in the section
  • CLIP Paper and Official CodeOpenAI · required

    Read Section 2.2 and the Figure 3 pseudocode (normalized embeddings, logits scaled by a learned temperature, the symmetric cross-entropy), then Section 2.3. Check preprocessing and tokenization in the official code (clip/clip.py _transform and tokenize, https://github.com/openai/CLIP). The README says logits are "times 100", but the model learns the scale.

  • Sigmoid Loss for Language Image Pre-Training (Zhai et al., 2023)Google DeepMind · required

    Read Sections 3.1 and 3.2 and Algorithm 1: a pairwise sigmoid loss with a learned temperature and bias instead of a softmax over the batch. Negatives still matter; keep the reduction convention explicit.

  • OpenCLIPML Foundations · reference

    Use release 3.3.0 for one small comparison: ClipLoss and SigLipLoss in src/open_clip/loss.py as oracles for your losses, and the zero-shot classifier. OpenAI RN50 weights need force_quick_gelu=True. The main branch has a refactored training stack; do not adopt the distributed trainer.

Also in this section

  • CS336 2026 - Alignment and MultimodalityStanford University · primary

    Step through the Lecture 17 trace ("multimodal models": CLIP, SigLIP, LLaVA, LLaVA-OneVision, Qwen-VL, Qwen2-VL, Qwen3-VL, Chameleon). Reconstruct patching, projector, fusion, multimodal positions and the chosen objective before implementing the bounded image-text path.

  • LLaVA - Visual Instruction TuningLLaVA Team · required

    Read Section 3 (GPT-assisted instruction data built from captions and boxes) and Sections 4.1 and 4.2 (a linear projection, then two-stage training). LLaVA-1.5 (https://arxiv.org/abs/2310.03744) swaps in a two-layer MLP; see build_vision_projector in the code. Build only a tiny frozen-encoder plus projector path and compare it with text-only and shuffled-pair controls.

  • Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution (Wang et al., 2024)Alibaba Qwen · required

    Read Section 2.1 and Figure 3 (dynamic resolution, 2x2 token merging, M-RoPE with temporal, height and width components) and Section 3.3.2 (the M-RoPE ablation). Variable resolution means variable tokens and memory.

  • POPE: Evaluating Object Hallucination in Large Vision-Language ModelsRenmin University · required

    Read Sections 5.1 and 5.2 of the paper (https://aclanthology.org/2023.emnlp-main.20.pdf), then evaluate one negative-sampling slice (random, popular or adversarial) with accuracy, F1 and the yes ratio. Join answers by question id, not row order, and keep the original files apart from POPEv2.

  • Modern LLM Notebook - Vision-Language ModelsWalking Labs · support

    Complete notebooks-en/part4-frontiers/29-vlm.ipynb through the minimal VLM. Add missing-image, conflicting-caption, resolution and serialization tests that the walkthrough does not supply.

  • smol-course Unit 3 - Vision Language ModelsHugging Face · support

    Work through Unit 3 for a runnable VLM fine-tuning path on SmolVLM2. Check its memory notes against your GPU and shrink the model, image resolution or batch before running.

  • COCO Captions SubsetCOCO Consortium · support

    Select 50 to 200 image ids from one annotation split with all their captions, record each image's license, and keep every caption of an evaluation image out of training. The annotations are CC BY 4.0; the images keep their own terms.

  • Flamingo: a Visual Language Model for Few-Shot Learning (Alayrac et al., 2022)DeepMind · support

    Read Sections 2.1 to 2.3 (details in Appendix A.1.1 to A.1.3): the Perceiver Resampler, gated cross-attention with tanh gates starting at zero, and multi-image masking. It is the cross-attention contrast to LLaVA's token concatenation.

  • TensorTonic - Alignment and Multimodality SetTensorTonic · support

    Solve Patchify a Batch of Images (cs336-l17-vision-transformer-patchify), Implement Symmetric CLIP Contrastive Loss (cs336-l17-symmetric-clip-loss), Implement the SigLIP Pairwise Loss (cs336-l17-siglip-pairwise-loss) and Assign Multimodal RoPE Coordinates (cs336-l17-multimodal-rope-coordinates). Its SigLIP loss averages over all B squared pairs while OpenCLIP divides the sum by B, so multiply by B before comparing. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution.

  • Chameleon: Mixed-Modal Early-Fusion Foundation Models (Chameleon Team, 2024)Meta FAIR · reference

    Read Sections 2.1 to 2.3: images as 1024 discrete tokens from an 8192-entry codebook, interleaved data and the stability fixes. Early fusion still depends on the image tokenizer.

  • LLM Post-Training Laboratory - Multimodal ModuleRoadmap-Final · support

    Use the optional multimodal evidence module for versioned aligned data, projector or fusion tests, retrieval and generation evaluation, and modality-specific safety checks.

  • High Fidelity Neural Audio Compression (EnCodec)Meta AI · reference

    Sections 3.1 to 3.4 of arXiv:2210.13438v1: temporal downsampling, residual codebooks, code prediction and codec reconstruction objectives. Read for audio-token vocabulary and rate accounting, not a codec training run.