The Annotated CLIP (Part-1)
This post is part-1 of the two series blog posts on CLIP. In this blog, we present an Introduction to CLIP in an easy to digest manner. We also compare CLIP to other research papers and look at the background and inspiration behind CLIP.
1 Personal Updates
Hello, and welcome back everybody to the blog! This is my first blog of the year 2023 and as publicly announced on Twitter, I am returning to blogging with a commitment of 1 blog a week, planned to be released every Monday at 9am AEST.
Starting 01 Mar, 2023 I’ll be going back to blogging 1 post a week every Monday at 9am AEST.
These blogs will be about AI research, new technologies, updates, frameworks, Kaggle competitions and more.
If you have a topic that you’d like me to cover, please let me know. 🙂
— Aman Arora ( (amaarora?) ) February 7, 2023
Also, in case you missed it, I was also recently interviewed by Radek Osmulski — “How to Blog to Advance Your Career and Learn Faster” (in AI). In the video, we discuss and talk about my motivation for writing blogs, blogging to advance your career and learn, how to get started with blogging & more!
I have also updated my personal blog to use Quarto. The idea is to release all future blog posts which are working Jupyter Notebooks themeselves.
Now, with personal updates out of the way, let’s get started with CLIP.
2 Introduction
As part of this blog post we will be uncovering the inner workings of CLIP — Learning Transferable Visual Models From Natural Language Supervision ( Radford et al. (2021) ), and we will be looking at it’s PyTorch implementation in part-2 of the blog that will be released next week.
CLIP in itself does not present a new idea, but implements an older idea of learning Image representations from text. CLIP applies this idea to a large scale dataset (400M images), and achieves zero shot transfer on ImageNet that matches ResNet-50. At the time of writing CLIP was the first model architecture to achieve such great zero shot results on ImageNet.
2.1 Key Contributions
If I am to summarise key contributions from the paper:
- New (image, text) pair dataset:We demonstrate that the simple pre-training task of predicting which caption goes with which image is an efficient and scalable way to learn SOTA image representations from scratch on a dataset of 400 million (image, text) pairs collected from the internet.
- Zero-shot performance that is competitive with supervised models:We study the performance of this approach by benchmarking on over 30 different existing computer vision datasets, spanning tasks such as OCR, action recognition in videos, geo-localization, and many types of fine-grained object classification. The model transfers non-trivially to most tasks and is often competitive with a fully supervised baseline without the need for any dataset specific training.
- High zero shot performance on ImageNet: We match the accuracy of the original ResNet-50 on ImageNet zero-shot without needing to use any of the 1.28 million training examples it was trained on.
- Open source model and weights:We release our code and pre-trained model weights at https://github.com/OpenAI/CLIP.
Before we start looking at the inner workings of CLIP, let’s look at some background that led to the development of CLIP.
3 Motivation for CLIP & Prior Work
CLIP was written in 2021, at a time where text transformer based models like GPT-3 (and others) were competitive across many tasks on various benchmark datasets, swhile requiring little to no dataset specific training data. This was made possible by pretraining on huge amounts of data found directly from the web. Pre-training on Wikipidea articles (WebText which contained the text subset of these 45 million links), became standard practice.
It was clear that models pre-trained on high web-scale collections of text surpassed that of high-quality crowd-labeled NLP datasets.
But, for vision based models, it was still standard practice to pre-train models on crowd-labeled datasets such as ImageNet. The question then is Could scalable pre-training methods which learn directly from web text result in a similar breakthrough in computer vision?
At the time it was still common practice to train on crowd labeled datasets for computer vision.
For example, Kolesnikov et al. (2019) and Dosovitskiy et al. (2020) had demonstrated large gains on a broader set of transfer benchmarks by pre-training models to predict the classes of the noisily labeled JFT-300M dataset. But both approaches used static softmax classifiers to perform prediction, which severely curtails their flexibility and limits their “zero-shot” capabilities.
But also, before CLIP some attempts had been made to learn image representations directly from text — VirTex (Desai & Johnson, 2020), ICMLM (Bulent Sariyildiz et al., 2020), and ConVIRT (Zhang et al., 2020).
In my humble opinion, ConVirt — “Contrastive Learning of Medical Visual Representations from Paired Images and Text” (Zhang et al., 2020) is of most interest of all prior work.
Figure 1: Two example chest X-ray images with different abnormality categories
ConVirt introduced a new method of pretraining medical image encoders with the paired text data (as in Figure 1) via a bidirectional contrastive objective between the two modalities. This method was domain-agnostic, and required no additional expert input.
However, ConVirt had been applied in the medical context. CLIP expanded this idea to general visual recognition. Thus, ConVirt directly inspired CLIP.
Figure 2: Overview of ConVirt
The figure above shows the overview of ConVirt, and as you’ll notice, CLIP is quite similar.
From the ConVirt paper:
ConVIRT has directly inspired subsequent studies such as the CLIP framework (Radford et al., 2021) and the ALIGN model (Jia et al., 2021), which showed that direct adaptations of ConVIRT-style pretraining at much larger scales lead to state-of-the-art general visual recognition capabilities.
4 Approach
At the core of our approach is the idea of learning perception from supervision contained in natural language. As discussed before, this is not at all a new idea.
Learning from natural language has several potential strengths over other training methods. Can you think of some?
- It’s much easier to scale natural language supervision compared to standard crowd-sourced labeling for image classification.
- Learning from natural language also has an important advantage over most unsupervised or self-supervised learning approaches in that it doesn’t “just” learn a representation but also connects that representation to language which enables flexible zero-shot transfer.
4.1 Summary with Pseudo-Code
In this section I will present the summary of CLIP architecture from the paper.
The overall approach has been presented in Figure 3 below. Can you notice the similarities to ConVirt in Figure 2?
Figure 3: Summary of CLIP approach
CLIP Is architecture agnostic. You can use any models as visual and text encoders in Figure 3.
A team led by Ross Wightman, Cade Gordon, and Vaishaal Shankar have a repository OpenCLIP that is an open source implementation of CLIP and enables training for any vision models with contrastive image-text supervision.
Also, recently, Ross Wightman also announced a 847M param ConvNext model trained via CLIP training that achieves 79.43% ImageNet zero-shot eval. Astonishing, right?
The approach presented in Figure 3 has been summarised in pseudo code from paper:
Let’s look at what it all means with the help of Microsoft Excel.
Figure 4: Illustration of contrastive loss
Let’s say we have 8 images with corresponding text descriptions as in Figure 4. CLIP presents a training framework to maximise the cosine similarity of text and image embeddings.
As from the pseudo-code, first we pass the images through image encoder and texts through text encoder respective to get image and text features.
Therefore in the above case, referencing to pseuo-code, \(n=8\) and \(d_i = 2048\) .
Similarly, referencing to pseudo-code, \(n=8\) and \(d_t=768\) .
Let’s just assume the embedding dimension \(d_e = 1024\) , now, as per psuedo-code, we can have two projection layers- \(W_i[d_i, d_e]\) and \(W_t[d_t, d_e]\) both for text and image features respectively.
Now that we have our projection layers, as per pseudo-code, we get our joint multimodal embeddings through dot product.
Now that we both our Image and Text embeddings, we can find cosine-similarity.
Figure 5: Cosine similarity between text and image features
We want the cosine similarity of real (text, image) pairs to be high (right diagonal), and everywhere else to be low.
So what loss function could we use in this case? The answer is in the pseudo-code.
When we do cross entropy loss with both axis=1 and axis=0, we are pushing logits to be high for the diagonal and low everywhere else. This is also referred to as Contrastive Loss. Thus, by doing this the CLIP model is able to learn visual features directly from text.
By training on a dataset of 400 million (image, text) pairs, the CLIP model is able to attain zero shot performance on ImageNet that is comparable to ResNet-50!
And that’s really all the magic behind CLIP.
5 Conclusion
As part of this blog post, we introduced the CLIP architecture to the reader. We saw how the CLIP approach is very similar to ConVirt with some very minor differences which we will discuss further in part-2 of the blog to be released next week.
In part-2, we will also be looking at the PyTorch code of CLIP, and the training code from OpenClip.
If you enjoyed reading, please feel free to subscribe to receive regular updates regarding new blog posts.
Связывание изображений и текста с помощью OpenAI CLIP
Хотя глубокое обучение произвело революцию в компьютерном зрении и обработке естественного языка, использование современных методов все еще сложно и требует значительного опыта.
Подходы OpenAI, такие как предварительное обучение контрастного языка и изображения (CLIP), направлены на снижение этой сложности, что позволяет разработчикам сосредоточиться на практических случаях.
CLIP — это нейронная сеть, обученная на большом наборе (400M) пар изображений и текста. Как следствие этого многомодального обучения, CLIP можно использовать для поиска фрагмента текста, который лучше всего представляет данное изображение, или наиболее подходящего изображения по текстовому запросу.
Это особенно делает CLIP невероятно полезным для нестандартного поиска изображений и текста.
Как это работает ?
CLIP был обучен таким образом, что по изображению он предсказывал, с какими из 32768 произвольно выбранных фрагментов текста изображение было связано в наборе обучающих данных. Идея состоит в том, что для решения задачи модели необходимо изучить несколько концепций изображения.
Этот подход значительно отличается от классических задач с изображениями, где модель обычно требуется для идентификации класса из большого набора классов (например, ImageNet).
Таким образом, CLIP совместно обучает кодировщик изображений (например, ResNet50) и кодировщик текста (например, BERT) для прогнозирования правильного сочетания пакета изображений и текста.
Если кто-то желает использовать модель для классификации, классы могут быть встроены кодировщиком текста и сопоставлены с изображением. Этот процесс обычно называют обучением с нулевым выстрелом.
Начиная
В следующих разделах объясняется, как настроить CLIP в Google Colab и как использовать CLIP для поиска изображений и текста.
Установка
Чтобы использовать CLIP, нам сначала нужно установить набор зависимостей. Чтобы облегчить это, мы собираемся установить их через Conda. Кроме того, для упрощения репликации будет использоваться Google Colab.
- Откройте Google Colab
Затем нажмите ссылку НОВЫЙ НОУТБУК PYTHON 3 внизу экрана.
Как вы, наверное, заметили, интерфейс ноутбука похож на тот, который предоставляет Jupyter. Есть окно кода, в котором вы должны ввести свой код Python.
2. Проверьте Python в Colab
Чтобы установить правильную версию Conda для работы с Colab, нам сначала нужно знать, какую версию Python использует Colab. Для этого в первой ячейке типа colab
Это должно вернуть что-то вроде
3. Установить Conda
Затем скопируйте имя версии miniconda, соответствующее основной версии Python, указанной в выходных данных выше. Версия miniconda должна выглядеть примерно так: «Miniconda3-py
Наконец, введите следующий фрагмент в новую ячейку colab, убедившись, что переменная conda_version установлена правильно.
Еще раз подтвердите, что основная версия Python осталась прежней.
Это должно вернуть что-то вроде
4. Установите зависимости CLIP +
Теперь Conda должна быть хорошо настроена. Следующим шагом является установка зависимостей модели CLIP (pytorch, torchvision и cudatoolkit) с помощью Conda с последующей установкой самой библиотеки CLIP.
Для этого скопируйте следующий фрагмент в Colab.
Этот шаг может занять некоторое время, так как требуемые библиотеки велики.
5. Добавить путь conda к sys
Последний шаг перед использованием CLIP — добавить путь conda site-packages в sys. В противном случае установленные пакеты могут некорректно идентифицироваться в среде Colab.
Текст и изображение
Наша среда теперь готова к использованию.
- Импортировать модель CLIP
Чтобы использовать CLIP, начните с импорта необходимых библиотек и загрузки модели. Для этого скопируйте следующий фрагмент в Colab.
Это должно показать что-то вроде возврата, показывающего, что модель была загружена правильно.
2. Извлечь вложения изображений
Давайте теперь протестируем модель, используя следующий образец изображения
Для этого скопируйте следующий фрагмент в Colab. Этот код сначала загрузит изображение с помощью PIL, а затем предварительно обработает его с помощью модели клипа.
Это должно отобразить образец изображения, за которым следует тензор обработанного изображения.
Характеристики изображения теперь можно извлечь, вызвав метод encode_image из модели клипа следующим образом.
Это должно вернуть размер тензора функций изображения
3. Извлеките вложения текста
Давайте создадим набор текстовых фрагментов, в которые разные значения классов будут вставлены следующим образом: «фотография # КЛАССА #».
Затем мы можем запустить токенизатор клипа для предварительной обработки фрагментов.
Это должно вернуть форму текстового тензора
Текстовые функции теперь можно извлечь, вызвав метод encode_text из модели клипа, как показано ниже.
4. Сравните встраивание изображений и текста
Поскольку теперь у нас есть вложения как изображения, так и текста, мы можем сравнивать каждую комбинацию и ранжировать их в соответствии с сходством.
Для этого мы можем просто вызвать модель для обоих вложений и вычислить softmax.
Это должно вернуть следующий результат.
Как и ожидалось, мы видим, что фрагмент текста «фотография собаки» имеет наибольшее сходство с образцом изображения.
Теперь вы можете сделать текстовые запросы более контекстными и посмотреть, как они будут сравниваться. Например, если вы добавите «фотографию собаки, бегущей по траве», как вы думаете, как теперь будет выглядеть рейтинг?
Полный сценарий
Чтобы просмотреть полный сценарий, перейдите на мою страницу github по этой ссылке:
Или перейдите непосредственно в записную книжку Google Colab, перейдя по этой ссылке:
Вывод
CLIP — это чрезвычайно мощная модель встраивания изображений и текста, которую можно использовать для поиска фрагмента текста, который наилучшим образом представляет данное изображение (например, в классической задаче классификации) или наиболее подходящего изображения по текстовому запросу (например, поиск изображения) .
CLIP не только мощный, но и исключительно простой в использовании. Эту модель можно легко встроить в API и сделать доступной, например, через лямбда-функцию AWS.
CLIP: Connecting text and images
We’re introducing a neural network called CLIP which efficiently learns visual concepts from natural language supervision. CLIP can be applied to any visual classification benchmark by simply providing the names of the visual categories to be recognized, similar to the “zero-shot” capabilities of GPT-2 and GPT-3.
More resources
Although deep learning has revolutionized computer vision, current approaches have several major problems: typical vision datasets are labor intensive and costly to create while teaching only a narrow set of visual concepts; standard vision models are good at one task and one task only, and require significant effort to adapt to a new task; and models that perform well on benchmarks have disappointingly poor performance on stress tests, [^reference-1] [^reference-2] [^reference-3] [^reference-4] casting doubt on the entire deep learning approach to computer vision.
We present a neural network that aims to address these problems: it is trained on a wide variety of images with a wide variety of natural language supervision that’s abundantly available on the internet. By design, the network can be instructed in natural language to perform a great variety of classification benchmarks, without directly optimizing for the benchmark’s performance, similar to the “zero-shot” capabilities of GPT-2 [^reference-5] and GPT-3. [^reference-6] This is a key change: by not directly optimizing for the benchmark, we show that it becomes much more representative: our system closes this “robustness gap” by up to 75% while matching the performance of the original ResNet-50 [^reference-7] on ImageNet zero-shot without using any of the original 1.28M labeled examples.
Background and related work
CLIP (Contrastive Language–Image Pre-training) builds on a large body of work on zero-shot transfer, natural language supervision, and multimodal learning. The idea of zero-data learning dates back over a decade [^reference-8] but until recently was mostly studied in computer vision as a way of generalizing to unseen object categories. [^reference-9] [^reference-10] A critical insight was to leverage natural language as a flexible prediction space to enable generalization and transfer. In 2013, Richer Socher and co-authors at Stanford [^reference-11] developed a proof of concept by training a model on CIFAR-10 to make predictions in a word vector embedding space and showed this model could predict two unseen classes. The same year DeVISE [^reference-12] scaled this approach and demonstrated that it was possible to fine-tune an ImageNet model so that it could generalize to correctly predicting objects outside the original 1000 training set.
Most inspirational for CLIP is the work of Ang Li and his co-authors at FAIR [^reference-13] who in 2016 demonstrated using natural language supervision to enable zero-shot transfer to several existing computer vision classification datasets, such as the canonical ImageNet dataset. They achieved this by fine-tuning an ImageNet CNN to predict a much wider set of visual concepts (visual n-grams) from the text of titles, descriptions, and tags of 30 million Flickr photos and were able to reach 11.5% accuracy on ImageNet zero-shot.
Finally, CLIP is part of a group of papers revisiting learning visual representations from natural language supervision in the past year. This line of work uses more modern architectures like the Transformer [^reference-32] and includes VirTex, [^reference-33] which explored autoregressive language modeling, ICMLM, [^reference-34] which investigated masked language modeling, and ConVIRT, [^reference-35] which studied the same contrastive objective we use for CLIP but in the field of medical imaging.
Approach
We show that scaling a simple pre-training task is sufficient to achieve competitive zero-shot performance on a great variety of image classification datasets. Our method uses an abundantly available source of supervision: the text paired with images found across the internet. This data is used to create the following proxy training task for CLIP: given an image, predict which out of a set of 32,768 randomly sampled text snippets, was actually paired with it in our dataset.
In order to solve this task, our intuition is that CLIP models will need to learn to recognize a wide variety of visual concepts in images and associate them with their names. As a result, CLIP models can then be applied to nearly arbitrary visual classification tasks. For instance, if the task of a dataset is classifying photos of dogs vs cats we check for each image whether a CLIP model predicts the text description “a photo of a dog” or “a photo of a cat” is more likely to be paired with it.
CLIP was designed to mitigate a number of major problems in the standard deep learning approach to computer vision:
Costly datasets: Deep learning needs a lot of data, and vision models have traditionally been trained on manually labeled datasets that are expensive to construct and only provide supervision for a limited number of predetermined visual concepts. The ImageNet dataset, one of the largest efforts in this space, required over 25,000 workers to annotate 14 million images for 22,000 object categories. In contrast, CLIP learns from text–image pairs that are already publicly available on the internet. Reducing the need for expensive large labeled datasets has been extensively studied by prior work, notably self-supervised learning, [^reference-14] [^reference-15] [^reference-16] contrastive methods, [^reference-17] [^reference-18] [^reference-19] [^reference-20] [^reference-21] self-training approaches, [^reference-22] [^reference-23] and generative modeling. [^reference-24] [^reference-25] [^reference-26] [^reference-27]
Narrow: An ImageNet model is good at predicting the 1000 ImageNet categories, but that’s all it can do “out of the box.” If we wish to perform any other task, an ML practitioner needs to build a new dataset, add an output head, and fine-tune the model. In contrast, CLIP can be adapted to perform a wide variety of visual classification tasks without needing additional training examples. To apply CLIP to a new task, all we need to do is “tell” CLIP’s text-encoder the names of the task’s visual concepts, and it will output a linear classifier of CLIP’s visual representations. The accuracy of this classifier is often competitive with fully supervised models.
We show random, non-cherry picked, predictions of zero-shot CLIP classifiers on examples from various datasets below.
Poor real-world performance: Deep learning systems are often reported to achieve human or even superhuman performance [^reference-28] [^footnote-1] on vision benchmarks, yet when deployed in the wild, their performance can be far below the expectation set by the benchmark. In other words, there is a gap between “benchmark performance” and “real performance.” We conjecture that this gap occurs because the models “cheat” by only optimizing for performance on the benchmark, much like a student who passed an exam by studying only the questions on past years’ exams. In contrast, the CLIP model can be evaluated on benchmarks without having to train on their data, so it can’t “cheat” in this manner. This results in its benchmark performance being much more representative of its performance in the wild. To verify the “cheating hypothesis”, we also measure how CLIP’s performance changes when it is able to “study” for ImageNet. When a linear classifier is fitted on top of CLIP’s features, it improves CLIP’s accuracy on the ImageNet test set by almost 10%. However, this classifier does no better on average across an evaluation suite of 7 other datasets measuring “robust” performance. [^reference-30]
Key takeaways
1. CLIP is highly efficient
CLIP learns from unfiltered, highly varied, and highly noisy data, and is intended to be used in a zero-shot manner. We know from GPT-2 and 3 that models trained on such data can achieve compelling zero shot performance; however, such models require significant training compute. To reduce the needed compute, we focused on algorithmic ways to improve the training efficiency of our approach.
We report two algorithmic choices that led to significant compute savings. The first choice is the adoption of a contrastive objective for connecting text with images. [^reference-31] [^reference-17] [^reference-35] We originally explored an image-to-text approach, similar to VirTex, [^reference-33] but encountered difficulties scaling this to achieve state-of-the-art performance. In small to medium scale experiments, we found that the contrastive objective used by CLIP is 4x to 10x more efficient at zero-shot ImageNet classification. The second choice was the adoption of the Vision Transformer, [^reference-36] which gave us a further 3x gain in compute efficiency over a standard ResNet. In the end, our best performing CLIP model trains on 256 GPUs for 2 weeks which is similar to existing large scale image models. [^reference-37] [^reference-23] [^reference-38] [^reference-36]
2. CLIP is flexible and general
Because they learn a wide range of visual concepts directly from natural language, CLIP models are significantly more flexible and general than existing ImageNet models. We find they are able to zero-shot perform many different tasks. To validate this we have measured CLIP’s zero-shot performance on over 30 different datasets including tasks such as fine-grained object classification, geo-localization, action recognition in videos, and OCR. [^footnote-2] In particular, learning OCR is an example of an exciting behavior that does not occur in standard ImageNet models. Above, we visualize a random non-cherry picked prediction from each zero-shot classifier.
This finding is also reflected on a standard representation learning evaluation using linear probes. The best CLIP model outperforms the best publicly available ImageNet model, the Noisy Student EfficientNet-L2, [^reference-23] on 20 out of 26 different transfer datasets we tested.
CLIP от OpenAI: модель для обучения компьютерному зрению
Всем хорошо известно, что нейронные сети (НС) и, в частности, модели компьютерного зрения хорошо справляются с конкретными задачами, но зачастую не могут быть использованы в задачах, которым они не обучались. К примеру, модель, которая хорошо работает с информацией о продуктах питания, может не справляться с анализом снимков спутника.
CLIP – модель от OpenAI претендует на то, чтобы закрыть этот пробел.
Что подразумевается под классификацией? Имеется набор примеров, каждому из которых соответствует категория. Количество категорий ограничено. Модель обучается различать «кошек» и «собак», но при добавлении нового класса «дельфин» нам придется добавить примеры с изображением дельфинов и обучить модель заново, а хорошо работающей моделью признаем ту, которая верно определит на изображении дельфина. Однако CLIP устроен иначе и результатом будет вероятность того, что это изображение соответствует категории «кошек», «собак» или «дельфинов».
Предлагаю рассмотреть, как можно использовать CLIP для классификации фотографий людей. В моем примере представлена классификация известных людей. Вы их, конечно, узнаете, но для примера я изменю имена. Установим и запустим CLIP от PyTorch:
Скопируем репозитории CLIP:
Установим предобученную модель:
Подготовим исходные данные. Для примера я взяла фотографии трех известных людей (2 женщины, 1 мужчина), по 4 — 6 изображений каждого из них. Фотографии хранятся в папках с именами Виктор, Тамара и Ирина.
Для классификации изображений определим классы, которые могут быть представлены в виде текста, описывающего изображение. Например, «это изображение артиста». В этом случае артист и есть метка класса. Изображения, которые я хочу протестировать, хранятся в папках с именами классов:
Далее токенизируем текст и вычисляем вложения из токенов
Для корректного отображения изображений воспользуемся набором данных ImageFolder от PyTorch и нормализуем снимки:
Выведем все изображения из набора данных:
Выполняем классификацию с помощью готовых меток. Считаем все изображения и истинные метки:
Вы можете заметить, что CLIP не очень хорошо справился с этими метками – правильно распознаны только 5 изображений из 16. Возможно, дело в незнакомых CLIP именах. Давайте поэкспериментируем и посмотрим, как это повлияет на результаты. Я изменю метки на более распространенные иностранные имена.
У этого эксперимента результат лучше предыдущего – 13 из 16 изображений распознаны верно.
Проведем еще один эксперимент – классифицируем мужчин и женщин.
Результат этого эксперимента еще лучше – все 16 изображений распознаны правильно. Кроме уже продемонстрированных экспериментов по распознаванию людей и классификации по их полу, CLIP поможет определить вероятность присутствия различных предметов на изображениях (микрофон, гарнитура, украшения, очки и т.д.), а также их количество. На мой взгляд, это важная особенность CLIP может найти свое применение в практической деятельности аудитора: различить пустые страницы, схемы, диаграммы, технические чертежи; установить есть ли на изображении человека ключи, бейдж, медицинская маска и еще другие детали, распознавание которых в ручную отняло бы слишком много трудовых ресурсов.