Contrastive Language-Image Pre-training explained

CLIP
Caption:Contrastive Language-Image Pre-training (CLIP)
Developer:OpenAI
Released:January 5, 2021
License:MIT License
Website:openai.com/research/clip
Repo:https://github.com/OpenAI/CLIP
Programming Language:Python

Contrastive Language-Image Pre-training (CLIP) is a technique for training a pair of neural network models, one for image understanding and one for text understanding, using a contrastive objective.[1] This method has enabled broad applications across multiple domains, including cross-modal retrieval,[2] text-to-image generation,[3] aesthetic ranking, and image captioning.[4]

Publication history

It was first announced on OpenAI's official blog on January 5, 2021,[5] with a report served directly through OpenAI's CDN,[6] and a GitHub repository.[7] The paper was delivered on arXiv on 26 February 2021.[8]

The report (with some details removed, and its appendix cut out to a "Supplementary PDF") was published in Proceedings of the 38th International Conference on Machine Learning, PMLR, which had a submission deadline of February 2021.[9]

Concurrent to CLIP was ALIGN, published at the same conference. It was done by researchers at Google, with essentially the same algorithm.[10]

Algorithm

The CLIP method trains a pair of models contrastively. One model takes in a piece of text as input and outputs a single vector representing its semantic content. The other model takes in an image and similarly outputs a single vector representing its visual content. The models are trained so that the vectors corresponding to semantically similar text-image pairs are close together in the shared vector space, while those corresponding to dissimilar pairs are far apart.

To train a pair of CLIP models, one would start by preparing a large dataset of image-caption pairs. During training, the models are presented with batches of

N

image-caption pairs. Let the outputs from the text and image models be respectively

v1,...,vN,w1,...,wN

. Two vectors are considered "similar" if their dot product is large.

The loss incurred on this batch is the multi-class N-pair loss,[11] which is a symmetric cross-entropy loss over similarity scores:- \frac 1N \sum_ \ln\frac - \frac 1N \sum_ \ln\frac In essence, this loss function encourages the dot product between matching image and text vectors (

viwi

) to be high, while discouraging high dot products between non-matching pairs. The parameter

T>0

is the temperature, which is parameterized in the original CLIP model as

T=e-\tau

where

\tau\in\R

is a learned parameter.

Other loss functions are possible. For example, Sigmoid CLIP[12] proposes the following loss function:L = \frac 1N \sum_ f((2\delta_ - 1) (e^\tau w_i \cdot v_j + b)) where

f(x)=ln(1+e-x)

is the negative log sigmoid loss.

CLIP models

While the original model was developed by OpenAI, subsequent models have been trained by other organizations as well.

Image model

The image encoding models used in CLIP are typically vision transformers (ViT). The naming convention for these models often reflects the specific ViT architecture used. For instance, "ViT-L/14" means a "vision transformer large" (compared to other models in the same series) with a patch size of 14, meaning that the image is divided into 14-by-14 pixel patches before being processed by the transformer. The size indicator ranges from B, L, H, G (base, large, huge, giant), in that order.

Other than ViT, the image model is typically a convolutional neural network, such as ResNet (in the original series by OpenAI), or ConvNeXt[13] (in the OpenCLIP model series by LAION).

Since the output vectors of the image model and the text model must have exactly the same length, both the image model and the text model have fixed-length vector outputs, which in the original report is called "embedding dimension".

For example, in the original OpenAI model, the ResNet models have embedding dimensions ranging from 512 to 1024, and for the ViTs, from 512 to 768.

Models released by OpenAI!Model name!Resolution!Parameters (total, in millions)!Parameters (vision)!Parameters (text)!Embedding dimension!Size (MB)!Release date
RN5022410238.363.110242442021-01
RN10122412056.363.15122782021-03
RN50x428817887.190.76404022021-03
RN50x16384291167.3123.07686302021-07
RN50x64448623420.4201.8102412602022-01
ViT-B/3222415187.863.15123382021-01
ViT-B/1622415086.263.15123352021-07
ViT-L/14224428304.0123.07688902022-01
ViT-L/14@336px336428304.3123.07688912022-04
Its implementation of ViT was the same as the original one,[14] with one modification: after position embeddings are added to the initial patch embeddings, there is a LayerNorm.

Its implementation of ResNet was the same as the original one,[15] with 3 modifications:

ALIGN used EfficientNet[19] of various sizes, a kind of convolutional neural network.

Text model

The text encoding models used in CLIP are typically Transformers.

In the original OpenAI report, they reported using a Transformer (63M-parameter, 12-layer, 512-wide, 8 attention heads) with lower-cased byte pair encoding (BPE) with 49152 vocabulary size. Context length was capped at 76 for efficiency. Like GPT, it was decoder-only, with only causally-masked self-attention. Its architecture is the same as GPT-2.[20]

Like BERT, the text sequence is bracketed by two special tokens [SOS] and [EOS] ("start of sequence" and "end of sequence"). Take the activations of the highest layer of the transformer on the [EOS], apply LayerNorm, then a final linear map. This is the text encoding of the input sequence. The final linear map has output dimension equal to the embedding dimension of whatever image encoder it is paired with. These models all had context length 77 and vocabulary size 49408.

ALIGN used BERT of various sizes.

Dataset

WebImageText

The CLIP models released by OpenAI were trained on a dataset called "WebImageText" (WIT) containing 400 million pairs of images and their corresponding captions scraped from the internet. The total number of words in this dataset is similar in scale to the WebText dataset used for training GPT-2, which contains about 40 gigabytes of text data.

The dataset contains 500,000 text-queries, with up to 20,000 (image, text) pairs per query. The text-queries were generated by starting with all words occurring at least 100 times in English Wikipedia, then extended by bigrams with high mutual information, names of all Wikipedia articles above a certain search volume, and WordNet synsets.

The dataset is private and has not been released to the public, and there is no further information on it.

Data preprocessing

For the CLIP image models, the input images are preprocessed by first dividing each of the R, G, B values of an image by the maximum possible value, so that these values fall between 0 and 1, then subtracting by [0.48145466, 0.4578275, 0.40821073], and dividing by [0.26862954, 0.26130258, 0.27577711].

The rationale was that these are the mean and standard deviations of the images in the WebImageText dataset, so this preprocessing step roughly whitens the image tensor. These numbers slightly differ from the standard preprocessing for ImageNet, which uses [0.485, 0.456, 0.406] and [0.229, 0.224, 0.225].[21]

If the input image does not have the same resolution as the native resolution (224x224 for all except ViT-L/14@336px, which has 336x336 resolution), then the input image is scaled down by bicubic interpolation, so that its shorter side is the same as the native resolution, then the central square of the image is cropped out.

Others

ALIGN used over one billion image-text pairs, obtained by extracting images and their alt-tags from online crawling. The method was described as similar to how the Conceptual Captions dataset[22] was constructed, but instead of complex filtering, they only applied a frequency-based filtering.

Later models trained by other organizations had published datasets. For example, LAION trained OpenCLIP with published datasets LAION-400M, LAION-2B, and DataComp-1B.[23]

Training

In the original OpenAI CLIP report, they reported training 5 ResNet and 3 ViT (ViT-B/32, ViT-B/16, ViT-L/14). Each was trained for 32 epochs. The largest ResNet model took 18 days to train on 592 V100 GPUs. The largest ViT model took 12 days on 256 V100 GPUs.

All ViT models were trained on 224x224 image resolution. The ViT-L/14 was then boosted to 336x336 resolution by FixRes,[24] resulting in a model. They found this was the best-performing model.

In the OpenCLIP series, the ViT-L/14 model was trained on 384 A100 GPUs on the LAION-2B dataset, for 160 epochs for a total of 32B samples seen.[25]

Applications

Cross-modal retrieval

CLIP's cross-modal retrieval enables the alignment of visual and textual data in a shared latent space, allowing users to retrieve images based on text descriptions and vice versa, without the need for explicit image annotations.[26] In text-to-image retrieval, users input descriptive text, and CLIP retrieves images with matching embeddings. In image-to-text retrieval, images are used to find related text content.

CLIP’s ability to connect visual and textual data has found applications in multimedia search, content discovery, and recommendation systems.

Image classification

CLIP can perform zero-shot image classification tasks. This is achieved by prompting the text encoder with class names and selecting the class whose embedding is closest to the image embedding. For example, to classify an image, they compared the embedding of the image with the embedding of the text "A photo of a .", and the that results in the highest dot product is outputted.

CLIP for multimodal learning

CLIP has been used as a component in multimodal learning. For example, during the training of Google DeepMind's Flamingo (2022),[27] the authors trained a CLIP pair, with BERT as the text encoder and NormalizerFree ResNet F6[28] as the image encoder. The image encoder of the CLIP pair was taken with parameters frozen and the text encoder was discarded. The frozen image encoder was then combined with a frozen Chinchilla language model, by finetuning with some further parameters that connect the two frozen models.

Applications in other domains

CLIP has been used in various domains beyond its original purpose:

External links

Notes and References

  1. Radford . Alec . Kim . Jong Wook . Hallacy . Chris . Ramesh . Aditya . Goh . Gabriel . Agarwal . Sandhini . Sastry . Girish . Askell . Amanda . Mishkin . Pamela . Clark . Jack . Krueger . Gretchen . Sutskever . Ilya . 2021-07-01 . Learning Transferable Visual Models From Natural Language Supervision . Proceedings of the 38th International Conference on Machine Learning . PMLR . 8748–8763.
  2. Hendriksen . Mariya . Bleeker . Maurits . Vakulenko . Svitlana . van Noord . Nanne . Kuiper . Ernst . de Rijke . Maarten . 2021 . Extending CLIP for Category-to-image Retrieval in E-commerce . cs.CV . 2112.11294.
  3. Web site: 17 September 2022 . Stable Diffusion Repository on GitHub . live . https://web.archive.org/web/20230118183342/https://github.com/CompVis/stable-diffusion . January 18, 2023 . 17 September 2022 . CompVis - Machine Vision and Learning Research Group, LMU Munich.
  4. Mokady . Ron . Hertz . Amir . Bermano . Amit H. . 2021 . ClipCap: CLIP Prefix for Image Captioning . cs.CV . 2111.09734.
  5. Web site: January 5, 2021 . Clip: Connecting text and images . OpenAI.
  6. https://web.archive.org/web/20210105204011/https://cdn.openai.com/papers/Learning_Transferable_Visual_Models_From_Natural_Language.pdf
  7. Web site: 5 January 2021 . initial commit · openai/CLIP@b1c4b6b . https://web.archive.org/web/20210209174132/https://github.com/openai/CLIP/commit/b1c4b6be5871f1b94359ba55901627f29ecc9ae9 . 9 Feb 2021 . 2024-09-06 . GitHub .
  8. Radford . Alec . Kim . Jong Wook . Hallacy . Chris . Ramesh . Aditya . Goh . Gabriel . Agarwal . Sandhini . Sastry . Girish . Askell . Amanda . Mishkin . Pamela . Clark . Jack . Krueger . Gretchen . Sutskever . Ilya . 2021 . Learning Transferable Visual Models From Natural Language Supervision . cs.CV . 2103.00020.
  9. Web site: ICML 2021 Call for Papers . 2024-09-06 . icml.cc.
  10. Jia . Chao . Yang . Yinfei . Xia . Ye . Chen . Yi-Ting . Parekh . Zarana . Pham . Hieu . Le . Quoc . Sung . Yun-Hsuan . Li . Zhen . Duerig . Tom . 2021-07-01 . Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision . Proceedings of the 38th International Conference on Machine Learning . PMLR . 4904–4916.
  11. Sohn . Kihyuk . 2016 . Improved Deep Metric Learning with Multi-class N-pair Loss Objective . Advances in Neural Information Processing Systems . Curran Associates, Inc. . 29.
  12. Zhai . Xiaohua . Mustafa . Basil . Kolesnikov . Alexander . Beyer . Lucas . 2023. IEEE/CVF International Conference on Computer Vision (ICCV) . Sigmoid Loss for Language Image Pre-Training . 11975–11986.
  13. Liu . Zhuang . Mao . Hanzi . Wu . Chao-Yuan . Feichtenhofer . Christoph . Darrell . Trevor . Xie . Saining . 2022 . IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). A ConvNet for the 2020s . 11976–11986.
  14. 2010.11929 . cs.CV . Alexey . Dosovitskiy . Lucas . Beyer . An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale . 2021-06-03 . Kolesnikov . Alexander . Weissenborn . Dirk . Zhai . Xiaohua . Unterthiner . Thomas . Dehghani . Mostafa . Minderer . Matthias . Heigold . Georg . Gelly . Sylvain . Uszkoreit . Jakob.
  15. He . Kaiming . Zhang . Xiangyu . Ren . Shaoqing . Sun . Jian . 10 Dec 2015 . Deep Residual Learning for Image Recognition . 1512.03385.
  16. He . Tong . Bag of Tricks for Image Classification with Convolutional Neural Networks . 2018-12-05 . 1812.01187 . Zhang . Zhi . Zhang . Hang . Zhang . Zhongyue . Xie . Junyuan . Li . Mu. cs.CV .
  17. Zhang . Richard . 2018-09-27 . Making Convolutional Networks Shift-Invariant Again . en.
  18. Zhang . Richard . Making Convolutional Networks Shift-Invariant Again . 2019-06-08 . cs.CV . 1904.11486.
  19. Tan . Mingxing . EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks . 2020-09-11 . 1905.11946 . Le . Quoc V.. cs.LG .
  20. Radford . Alec . Wu . Jeff . Child . R. . Luan . D. . Amodei . Dario . Sutskever . I. . 2019 . Language Models are Unsupervised Multitask Learners . 160025533 .
  21. Web site: std and mean for image normalization different from ImageNet · Issue #20 · openai/CLIP . 2024-09-19 . GitHub . en.
  22. Sharma . Piyush . Ding . Nan . Goodman . Sebastian . Soricut . Radu . July 2018 . Gurevych . Iryna . Miyao . Yusuke . Conceptual Captions: A Cleaned, Hypernymed, Image Alt-text Dataset For Automatic Image Captioning . Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers) . Melbourne, Australia . Association for Computational Linguistics . 2556–2565 . 10.18653/v1/P18-1238. free .
  23. Book: Cherti . Mehdi . Beaumont . Romain . Wightman . Ross . Wortsman . Mitchell . Ilharco . Gabriel . Gordon . Cade . Schuhmann . Christoph . Schmidt . Ludwig . Jitsev . Jenia . Reproducible Scaling Laws for Contrastive Language-Image Learning . June 2023 . 2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) . 2818–2829 . 10.1109/CVPR52729.2023.00276. 2212.07143 . 979-8-3503-0129-8 .
  24. Touvron . Hugo . Vedaldi . Andrea . Douze . Matthijs . Jegou . Herve . 2019 . Fixing the train-test resolution discrepancy . Advances in Neural Information Processing Systems . Curran Associates, Inc. . 32.
  25. Web site: 2023-09-10 . laion/CLIP-ViT-L-14-laion2B-s32B-b82K · Hugging Face . 2024-09-06 . huggingface.co.
  26. Hendriksen . Mariya . Bleeker . Maurits . Vakulenko . Svitlana . van Noord . Nanne . Kuiper . Ernst . de Rijke . Maarten . 2021 . Extending CLIP for Category-to-image Retrieval in E-commerce . cs.CV . 2112.11294.
  27. Alayrac . Jean-Baptiste . Donahue . Jeff . Luc . Pauline . Miech . Antoine . Barr . Iain . Hasson . Yana . Lenc . Karel . Mensch . Arthur . Millican . Katherine . Reynolds . Malcolm . Ring . Roman . Rutherford . Eliza . Cabi . Serkan . Han . Tengda . Gong . Zhitao . 2022-12-06 . Flamingo: a Visual Language Model for Few-Shot Learning . Advances in Neural Information Processing Systems . 35 . 23716–23736.
  28. Brock . Andy . De . Soham . Smith . Samuel L. . Simonyan . Karen . 2021-07-01 . High-Performance Large-Scale Image Recognition Without Normalization . Proceedings of the 38th International Conference on Machine Learning . PMLR . 1059–1071.
  29. Web site: 17 September 2022 . Stable Diffusion Repository on GitHub . live . https://web.archive.org/web/20230118183342/https://github.com/CompVis/stable-diffusion . January 18, 2023 . 17 September 2022 . CompVis - Machine Vision and Learning Research Group, LMU Munich.
  30. Ramesh . Aditya . Hierarchical Text-Conditional Image Generation with CLIP Latents . 2022-04-12 . 2204.06125 . Dhariwal . Prafulla . Nichol . Alex . Chu . Casey . Chen . Mark. cs.CV .
  31. Nichol . Alex . GLIDE: Towards Photorealistic Image Generation and Editing with Text-Guided Diffusion Models . 2022-03-08 . 2112.10741 . Dhariwal . Prafulla . Ramesh . Aditya . Shyam . Pranav . Mishkin . Pamela . McGrew . Bob . Sutskever . Ilya . Chen . Mark. cs.CV .
  32. Web site: Whitaker . Jonathan . 2022-05-22 . Fun With Neural Cellular Automata . 2024-09-08 . W&B . en.
  33. Mokady . Ron . Hertz . Amir . Bermano . Amit H. . 2021 . ClipCap: CLIP Prefix for Image Captioning . cs.CV . 2111.09734.