# Beating OpenAI CLIP with 100x less data and compute

> Demonstrating how to train state-of-the-art Vision-Language transformers for semantic search using 100x less data and compute than OpenAI CLIP.

[Blog](https://www.unum.cloud/blog.md) [AI](https://www.unum.cloud/blog?tag=AI)

Demonstrating how to train state-of-the-art Vision-Language transformers for semantic search using 100x less data and compute than OpenAI CLIP.

- By

  Vladimir Orshulevich, Mikhail Kim, Ash Vardanian

- Published

  Feb 20, 2023

Hello from the Unum AI team! We have been silently pre-training numerous Multi-Modal Models for Semantic Search for the last year. Now we are bundling it with our [DataBase](https://www.unum.cloud/engines/ustore.md) and releasing several extremely performant checkpoints on the [HuggingFace portal](https://huggingface.co/unum-cloud/uform)!

---

So how have we done that? Isn’t training models like [OpenAI CLIP](https://openai.com/blog/clip/) only reserved for Google-scale companies? We don’t think so, and today we will dissect how to train a more precise Vision-Language transformer than the multi-lingual [mCLIP](https://github.com/FreddeFrallan/Multilingual-CLIP), which also works much faster!

## Semantic Search Vertical

Semantic search is built from 3 pieces.

| | |
| - | - |
| Embeddings service | used to vectorize the content and the queries |
| Nearest-Neighbors index | used to search for closest vectors |
| Persistent database | used to store and retrieve the data |

Countless companies are rushing into the space. Similar to how “Postgres on RocksDB” [was the hottest topic of 2021](https://www.unum.cloud/blog/dbms-startups.md), “Future of Search” is the theme of 2023.

| Product | Providers |
| - | - |
| Embeddings service | OpenAI, Co:here, HuggingFace, **Unum UForm** |
| Nearest-Neighbors index | Elastic, Algolia, Pinecone, **Unum USearch** |
| Persistent database | MongoDB, CockroachDB, Neo4J, **Unum UStore** |

In this post, we will not bore you with advances in Computational Geometry applied to indexing or the advanced Linux kernel bypass techniques we have spent years designing.

Semantic search pipeline. The query is vectorized by the embeddings service, the vector search index finds its neighbors, and the persistent database retrieves their contents into the results. Optionally, the database contents return to the embeddings service for reranking, and the query itself is passed along to the results.

A semantic search vectorizes the query, finds its nearest neighbors, retrieves their contents and may send them back to the embeddings service for reranking.

This post focuses just on the Embeddings, the Representation Learning part. And as the multi-modal representations started with CLIP, we will do the same!

## CLIP Fundamentals

“Contrastive Language-Image Pre-training” aims to align vector representations (embeddings) of text and image encoder models by training them with contrastive loss function.

- BERT model is often used for the text encoder.
- ViT is used for images, with older versions referencing ResNets.

The original plan was:

1. Take the CommonCrawl dataset,
2. Extract 400 Million `img` tags from HTML pages,
3. Pair each image with 128 tokens of text around it.

Contrastive Loss is also trivial. To more experienced ML/CS practitioners, it resembles Force-Based Graph drawing algorithms.

1. Sample a random batch of text and image pairs.
2. Build a similarity matrix between vectors produced by BERT and ViT.
3. Compare it against the identity matrix, i.e. ground truth.
4. Use the difference as the loss.

CLIP contrastive pre-training. A batch of captions passes through the text encoder into embeddings T1 to TN, and the matching batch of images passes through the image encoder into embeddings I1 to IN. Every image embedding is compared with every text embedding, and the diagonal of matching pairs is pulled together while all other pairs are pushed apart.

[Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020), OpenAI, 2021.

The ablation studies from the original CLIP paper suggest that bigger global batch sizes with significantly more negative samples lead to better models. Still, growing the global batch size means allocating more GPUs.

- The original `CLIP` was trained on 500x A100 Nvidia GPUs.
- The latest `Open_CLIP` trained on 1024x GPUs.

Where is the catch? How to compete in Language-Vision Pre-training (VLP) on 100x fewer GPUs?

## Data-efficient Approaches

TLDR: If you want to be efficient, you need more, often cross-modal pre-training tasks and higher quality data.

### [ALBEF](https://arxiv.org/abs/2107.07651) by Salesforce

ALBEF architecture. A 12-layer image encoder and a 6-layer text encoder each produce token embeddings led by a CLS token. An image-text contrastive loss aligns the two CLS embeddings against negatives. A 6-layer multimodal encoder takes the text embeddings, attends to the image embeddings through cross attention, and is trained with image-text matching on hard negatives and masked language modeling. A momentum model receives momentum updates and provides momentum distillation.

[Align before Fuse: Vision and Language Representation Learning with Momentum Distillation](https://arxiv.org/abs/2107.07651), Salesforce, 2021.

ALBEF was trained on two datasets, with 4 and 14 Million text-image pairs. The smaller version takes a day to train on 8 GPUs. Unlike CLIP, the quality of data was a priority, rather than quantity. Here is a list of their innovations:

- **Multimodal encoder** utilizes the embeddings from the text-encoder applying cross-attention on the output features of the image encoder output.
- **Image-Text Matching (ITM) loss function** based on the probability of the image complementing the text.
- **Masked Language Modeling (MLM) task** is stacked on top of the multimodal encoder.

We can use a multimodal encoder as a re-ranker during inference!

### [ViCHA](https://arxiv.org/abs/2208.13628)

ViCHA pre-training. A photo of a chef preparing vegetables enters the vision encoder, while visual concepts extracted from it, such as demonstration kitchen, chef and chef knife, are also passed to the vision encoder. Its caption enters the text encoder. A hierarchical image-text contrastive loss, H-ITC, aligns the two encoders. The vision encoder also trains a self-supervised SSL head, and a multimodal decoder over both encoders is trained with MLM and ITM.

[Efficient Vision-Language Pretraining with Visual Concepts and Hierarchical Alignment](https://arxiv.org/abs/2208.13628), Meta AI, 2022.

For ViCHA pre-training authors used 1.1 M and 800 K dataset sizes. On 4 GPUs this takes less than a day.

Innovations:

- **Hierarchical Image-Text Contrastive (H-ITC) alignment** compares representations across layers.
- **Visual Concepts Extraction (VCE)** used [Stanford Scene Graph Parser](https://nlp.stanford.edu/software/scenegraph-parser.shtml) to implement something similar to object detection on the attached textual captions.
- **Masked Image Modeling (SSL)** on top of the image encoder.

## UForm by Unum

We trained on the setup of 3x workstations, with 4x RTX 3090 consumer-grade GPUs in each, connected over 200 GBit InfiniBand HDR. A single experiment would take around a day. Let’s evaluate the results.

### Zero-Shot Image Retrieval, English-only

To produce UForm checkpoints, we further extended the ALBEF setup, and filtered the datasets. Garbage-in, garbage-out, after all. Let’s start with the [Flickr](https://www.kaggle.com/datasets/hsankesara/flickr-image-dataset) dataset.

| Model | Dataset | Recall\@1 | Recall\@5 | Recall\@10 |
| - | - | - | - | - |
| CLIP | 400 M | 0.687 | 0.906 | 0.952 |
| ALBEF | 14 M | **0.759** | **0.963** | **0.981** |
| ViCHA | 1.1 M | 0.726 | 0.911 | 0.950 |
| | | | | |
| **UForm** | 4 M | 0.727 | 0.915 | 0.949 |

With 100x smaller dataset ALBEF, ViCHA, and our UForm all essentially match or surpass original OpenAI CLIP. Good start! AI evaluation, however, is much trickier, than even [database benchmarks](https://github.com/unum-cloud/ucsb). ALBEF experiments, for one, were fine-tuned on MS-COCO before evaluating on Flickr, so the reported results are not indeed zero-shot. Let’s compare the [MS-COCO](https://cocodataset.org/#home) results.

| Model | Dataset | Recall\@1 | Recall\@5 | Recall\@10 |
| - | - | - | - | - |
| CLIP | 400 M | 0.378 | 0.624 | 0.722 |
| ViCHA | 1.1 M | 0.471 | 0.738 | 0.828 |
| | | | | |
| **UForm** | 4 M | **0.510** | **0.761** | **0.838** |

> ALBEF wasn’t evaluated on the MS-COCO dataset.

### Zero-shot Image Retrieval, Multilingual

The classic approach to adding multilingual capabilities to CLIP is to distill that knowledge from much larger Language Models. We took a different path, and added a few more cross-lingual pre-training tasks. Of course.

| Model | English | German | Spanish | French | Italian | Russian | Japanese | Korean | Turkish | Chinese |
| - | - | - | - | - | - | - | - | - | - | - |
| mCLIP | 95.0 | 93.0 | 93.6 | 93.1 | 93.1 | 90.0 | 84.2 | 89.0 | 93.0 | **94.0** |
| **UForm** | **96.6** | **93.3** | **94.7** | **94.0** | **93.9** | **90.6** | **88.0** | **92.5** | **94.8** | 93.4 |

UForm outperforms mCLIP on every language, except for Chinese.

### Inference Speed

Accuracy improvement is fine for a PhD paper, but for production, it has to be efficient. We would previously go to extreme lengths to manually quantize third-party models. Now we are shipping ours!

Let’s compare our `uform` to `bert-base-uncased` used in CLIP, and the `distilbert-base-uncased`, the smallest commonly used `transformer`.

| Model | Multilingual | Backend | Samples per Second | Speedup |
| - | - | - | - | - |
| `bert-base-uncased` | No | PyTorch | 1,612 | |
| `distilbert-base-uncased` | No | PyTorch | 3,174 | x 1.96 |
| `MiniLM-L12` | Yes | PyTorch | 3,604 | x 2.24 |
| `MiniLM-L6` | No | PyTorch | 6,107 | x 3.79 |
| | | | | |
| `uform` | Yes | PyTorch | 6,809 | **x 4.22** |
| UForm | Yes | - | 20,787 | **x 12.89** |

All of those measurements were conducted on a consumer-grade Nvidia RTX 3090 GPU. Best of all, you don’t need to wait for our UForm SaaS product, you can already start using our Neural Networks!

### Try It!

There must be a paywall, right? No! Go get it on the [Hugging Face](https://huggingface.co/unum-cloud/uform) portal!

```python
import uform
from PIL import Image

text = 'a small red panda in a zoo'
image = Image.open('red_panda.jpg')

model = uform.get_model('unum-cloud/uform-vl-multilingual') # or 'english'

image_info = model.preprocess_image(image).unsqueeze(0)
text_info = model.preprocess_text(text)

image_embedding = model.encode_image(image_info)
text_embedding = model.encode_text(text_info)
joint_embedding = model.encode_multimodal(image=image_info, text=text_info)
```

UForm models come with a homonymous package, already available on [our GitHub](https://github.com/unum-cloud/UForm). They not only extend the Hugging Face `transformers` library to support Mid-Fusion used in our models, but also bring nifty helpers for all things Multi-Modal!

---

We are actively adding new modalities, like documents, audio, and video, and you can request early access on our [Discord](https://discord.gg/jsMURnSFM2). Who knows, maybe once we reach [1,000 stars on GitHub](https://github.com/unum-cloud/UForm), we will release our pre-training libraries as well 😉
