CLIP Multi-domain Feature Extractor

Represent words and images as vectors

This model is also available through the function LAIONSearch in the Wolfram Function Repository

Released in 2021 by researchers at OpenAI, the CLIP (Contrastive Language–Image Pre-training) family of transformer-based neural nets is a collection of models trained as pure feature extractors learning joint text and image representations from scratch. Using a dataset of four hundred million image-text pairs collected from the internet, the feature extractors were trained to embed images and their correct textual descriptions close to each other in feature space. The learned image embeddings are shown to be much more representative compared to the standard embeddings coming from the fully supervised image recognition task. The authors show the generalization capabilities of CLIP models by performing zero-shot learning on a variety of datasets spanning tasks such as OCR, action recognition in videos, geo-localization and many types of fine-grained object classification.

Training Set Information

Model Information

Examples

Resource retrieval

Get the pre-trained net:

In[1]:=
NetModel["CLIP Multi-domain Feature Extractor"]
Out[1]=

NetModel parameters

This model consists of a family of individual nets, each identified by a specific parameter combination. Inspect the available parameters:

In[2]:=
NetModel["CLIP Multi-domain Feature Extractor", "ParametersInformation"]
Out[2]=

Pick a non-default net by specifying the parameters:

In[3]:=
NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Text", "Architecture" -> "ViT-B/16"}]
Out[3]=

Pick a non-default uninitialized net:

In[4]:=
NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Text", "Architecture" -> "ViT-B/16"}, "UninitializedEvaluationNet"]
Out[4]=

Basic usage

Use the CLIP text encoder to obtain the feature representation of a piece of text:

In[5]:=
textEmbedding = NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Text"}]["Challenge accepted!"];

The default CLIP text encoder embeds the input text into a vector of size 512:

In[6]:=
Dimensions[textEmbedding]
Out[6]=

Use the CLIP image encoder to obtain the feature representation of an image:

In[7]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/72c21d16-533f-490b-85bc-ff36bf7f415b"]

The default CLIP image encoder embeds the input text into a vector of size 512:

In[8]:=
Dimensions[imageEmbedding]
Out[8]=

Feature space visualization

Get a set of images:

In[9]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/ac12e60d-ec89-4fa6-9266-00d35a4162be"]

Visualize the features of a set of images:

In[10]:=
FeatureSpacePlot[imgs, FeatureExtractor -> NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Image"}], LabelingSize -> 150, ImageSize -> Large]
Out[10]=

Define a list of sentences in two categories:

In[11]:=
sentences = {
   "The Charging Bull in the financial district of New York has become a symbol of market optimism.",
   "Times Square in New York is best known for its bright billboards and bustling atmosphere.",
   "The Statue of Liberty in New York stands as a universal symbol of freedom and opportunity.",
   "Central Park in New York is an urban oasis, providing a natural escape amidst the city's skyscrapers.",
   "Sacré-Cœur in Paris offers both spiritual solace and panoramic views from its hilltop location.",
   "The Eiffel Tower's light in Paris show adds a romantic touch to the city's engineering marvel.",
   "Bridges over the Seine in Paris are scenic spots that often host art and book vendors.",
   "The Louvre's glass pyramid in Paris modernizes the entrance to a museum filled with historical art.",
   "The Panthéon in Paris serves as a tribute to national heroes, complete with educational exhibits."
   };
In[12]:=
FeatureSpacePlot[
 Thread[NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Text"}][
    sentences] -> (Tooltip[Style[Text@#, Medium]] & /@ sentences)],
 LabelingSize -> {90, 60}, RandomSeeding -> 23,
 LabelingFunction -> Callout,
 ImageSize -> 700,
 Method -> "TSNE",
 AspectRatio -> 0.9
 ]
Out[12]=

Connecting text and images

Define a test image:

In[13]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/456e0797-beb6-4a71-bcbe-b7c42996eb29"]

Define a list of text descriptions:

In[14]:=
descriptions = {
   "Blossoming rose on textbook among delicate petals",
   "Photo of foggy forest",
   "A portrait of a man with red hair taking a picture with an analog camera",
   "Yellow flower in tilt shift lens",
   "Woman in black leather jacket and white pants",
   "A portrait of a woman with red hair taking a picture with an analog camera",
   "Calm body of lake between mountains",
   "Close up shot of a baby girl",
   "Smiling man surfing on wave in ocean",
   "A portrait of a woman with red hair taking a picture with a phone",
   "A portrait of a woman with red hair taking a picture with a digital camera",
   "A woman with eyeglasses smiling",
   "Elderly woman carrying a baby",
   "A portrait of a woman with blue hair taking a picture with an analog camera"
   };

Embed the test image and text descriptions into the same feature space:

In[15]:=
textFeatures = NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Text", "Architecture" -> "ViT-B/16"}][
   descriptions];
imgFeatures = NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Image", "Architecture" -> "ViT-B/16"}][img];

Rank the text description with respect to the correspondence to the input image according to the CosineDistance. Smaller distances mean higher correspondence between the text and the image:

In[16]:=
Dataset@SortBy[
  Thread[{descriptions, First@DistanceMatrix[{imgFeatures}, textFeatures, DistanceFunction -> CosineDistance]}], Last]
Out[16]=

Zero-shot image classification

By using the text and image feature extractors together, it's possible to perform generic image classification between any set of classes without having to explicitly train any model for those particular classes (zero-shot classification). Obtain the FashionMNIST test data, which contains ten thousand test images and 10 classes:

In[17]:=
testData = ResourceData["FashionMNIST", "TestData"];

Display a few random examples from the set:

In[18]:=
RandomChoice[testData, 5]
Out[18]=

Get a mapping between class IDs and labels:

In[19]:=
idToLabel = ResourceData["FashionMNIST", "ClassLabels"]
Out[19]=

Generate the text templates for the FashionMNIST labels and embed them. The text templates will effectively act as classification labels:

In[20]:=
labelTemplates = "This is a photo of a " <> # & /@ ToLowerCase[Values@idToLabel]
Out[20]=
In[21]:=
textEmbeddings = NetModel["CLIP Multi-domain Feature Extractor", "InputDomain" -> "Text"][labelTemplates];
In[22]:=
Dimensions[textEmbeddings]
Out[22]=

Classify an image from the test set. Obtain its embedding:

In[23]:=
img = testData[[5634, 1]]
Out[23]=
In[24]:=
imgFeatures = NetModel["CLIP Multi-domain Feature Extractor", "InputDomain" -> "Image"][img];
In[25]:=
Dimensions[imgFeatures]
Out[25]=

The result of the classification is the description the embedding of which is closest to the image embedding:

In[26]:=
Nearest[textEmbeddings -> labelTemplates, imgFeatures, DistanceFunction -> CosineDistance]
Out[26]=

Find the top 10 description nearest to the image embedding:

In[27]:=
SortBy[Rule @@@ MapAt[labelTemplates[[#]] &, Nearest[textEmbeddings -> {"Index", "Distance"}, imgFeatures, 10, DistanceFunction -> CosineDistance], {All, 1}], Last]
Out[27]=

Obtain the accuracy of this procedure on the entire test set. Extract the features for all the images (if a GPU is available, setting TargetDevice->"GPU" is recommended as the computation will take several minutes on CPU):

In[28]:=
imageEmbeddings = NetModel["CLIP Multi-domain Feature Extractor", "InputDomain" -> "Image"][testData[[All, 1]], TargetDevice -> "CPU"];
In[29]:=
Dimensions[imageEmbeddings]
Out[29]=

Calculate the distance matrix between the computed text and image embeddings:

In[30]:=
distanceMatrix = DistanceMatrix[imageEmbeddings, textEmbeddings, DistanceFunction -> CosineDistance];

Obtain the top-1 prediction:

In[31]:=
predictedClassIDs = Flatten[Ordering[#, 1] & /@ distanceMatrix] - 1;

Obtain the final classification results:

In[32]:=
ClassifierMeasurements[idToLabel /@ predictedClassIDs, idToLabel /@ testData[[All, 2]]]
Out[32]=

Attention visualization for images

Just like the original Vision Transformer (see the model "Vision Transformer Trained on ImageNet Competition Data"), the image feature extractor divides the input images in 7x7 patches and performs self-attention on a set of 50 vectors: 49 vectors, or "tokens," representing the 7x7 patches and an additional one, a "feature extraction token," that is eventually used to produce the final feature representation of the image. Thus the attention procedure for this model can be visualized by inspecting the attention weights between the feature extraction token and the patch tokens. Define a test image:

In[33]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/24045968-120c-4f6c-8e0f-83c7fbb21654"]

Extract the attention weights used for the last block of self-attention:

In[34]:=
attentionMatrix = Transpose@
   NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Image"}][testImage, NetPort[{"transformer", -1, "self-attention", "attention", "AttentionWeights"}]];
In[35]:=
Dimensions[attentionMatrix]
Out[35]=

Extract the attention weights between the feature extraction token and the input patches. These weights can be interpreted as which patches in the original image the net is "looking at" in order to perform the feature extraction:

In[36]:=
featureAttention = attentionMatrix[[All, 1, 2 ;;]];
{numHeads, numPatches} = Dimensions[featureAttention]
Out[37]=

Reshape the weights as a 3D array of 12 7x7 matrices. Each matrix corresponds to an attention head, while each element of the matrices corresponds to a patch in the original image:

In[38]:=
featureAttention = ArrayReshape[
   featureAttention, {numHeads, Sqrt[numPatches], Sqrt[numPatches]}];
In[39]:=
Dimensions[featureAttention]
Out[39]=

Visualize the attention weight matrices. Patches with higher values (red) are what is mostly being "looked at" for each attention head:

In[40]:=
GraphicsRow[MatrixPlot /@ featureAttention, ImageSize -> Full]
Out[40]=

Define a function to visualize the attention matrix on an image:

In[41]:=
visualizeAttention[img_Image, attentionMatrix_] := Block[{heatmap, wh},
  wh = ImageDimensions[img];
  heatmap = ImageApply[{#, 1 - #, 1 - #} &, ImageAdjust@Image[attentionMatrix]];
  heatmap = ImageResize[heatmap, wh*256/Min[wh]];
  ImageCrop[ImageCompose[img, {ColorConvert[heatmap, "RGB"], 0.4}], ImageDimensions[heatmap]]
  ]

Visualize the mean attention across all the attention heads:

In[42]:=
visualizeAttention[testImage, Mean[featureAttention]]
Out[42]=

Visualize each attention head separately:

In[43]:=
visualizeAttention[testImage, #] & /@ featureAttention
Out[43]=

Attention visualization for text

The text feature extractor tokenizes the input string prepending and appending the special tokens StartOfString and EndOfString and then performs causal self-attention on the token embedding vectors. After the self-attention stack, the last vector (corresponding to the token EndOfString) is used to obtain the final feature representation of the text. Thus the attention procedure for this model can be visualized by inspecting the attention weights between the last vector and the previous ones. Define a test string:

In[44]:=
text = "A portrait of a woman with red hair taking a picture with an analog camera";

Extract the NetEncoder of the net to encode the string:

In[45]:=
netEnc = NetExtract[
  NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Text"}], "Input"]
Out[45]=
In[46]:=
codes = netEnc[text]
Out[46]=

Extract the list of available tokens and inspect how the input string was tokenized. Even though the BPE tokenization generally segments the input into subwords, it's common to observe that all tokens correspond to full words. Also observe that the StartOfString and EndOfString tokens are added automatically:

In[47]:=
allTokens = NetExtract[netEnc, "Tokens"];
In[48]:=
tokens = allTokens[[codes]]
Out[48]=
In[49]:=
Length[tokens]
Out[49]=

Feed the string to the net and extract the attention weights used for the last block of self-attention:

In[50]:=
attentionMatrix = Transpose@
   NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Text"}][text, NetPort[{"transformer", -1, "self-attention", "attention", "AttentionWeights"}]];
Dimensions[attentionMatrix]
Out[17]=

Extract the attention weights between the last vector and the previous ones, leaving the initial vector corresponding to StartOfString out. These weights can be interpreted as which tokens in the original sentence the net is "looking at" in order to perform the feature extraction:

In[51]:=
featureAttention = attentionMatrix[[All, -1, 2 ;; -2]];
Dimensions[featureAttention]
Out[19]=

Inspect the average attention weights for each token across the attention heads. Observe that the tokens the net is mostly focused on are "hair" and "camera":

In[52]:=
BarChart[
 Reverse@MapThread[
   Labeled, {Mean[featureAttention], tokens[[2 ;; -2]]}], BarOrigin -> Left]
Out[52]=

Visualize each head separately:

In[53]:=
BarChart[
 Reverse@MapThread[
   Labeled, {Transpose[featureAttention], tokens[[2 ;; -2]]}], BarOrigin -> Left]
Out[53]=

Extract the attention weights for all the 12 attention layers:

In[54]:=
spec = Table[
   NetPort[{"transformer", i, "self-attention", "attention", "AttentionWeights"}], {i, 1, 12}];
In[55]:=
allAttentionWeights = Transpose[
   Values@NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Text"}][text, spec], 2 <-> 3];
Dimensions[allAttentionWeights]
Out[22]=

Compute the average across all heads, leaving the StartOfString token out:

In[56]:=
avgAttentionWeights = ArrayReduce[Mean, allAttentionWeights, 2][[All, 2 ;; -1, 2 ;; -1]];
Dimensions[avgAttentionWeights]
Out[24]=

Define a function to visualize the attention weights:

In[57]:=
visualizeTokenAttention[attnMatrix_] := Block[{g, style},
  g = WeightedAdjacencyGraph[attnMatrix];
  style = Thread@Directive[
     Arrowheads[.02],
     Thickness /@ (Rescale[AnnotationValue[g, EdgeWeight]]/200),
     Opacity /@ Rescale@AnnotationValue[g, EdgeWeight]
     ];
  Graph[g, GraphLayout -> "LinearEmbedding", EdgeStyle -> Thread[EdgeList[g] -> style], VertexLabels -> Thread[Range[Length@Rest[tokens]] -> Map[Rotate[Style[Text[#], 12, Bold], 60 Degree] &, Rest[tokens]]], VertexCoordinates -> Table[{i, 0}, {i, Length[attnMatrix]}], ImageSize -> Large]
  ]

Explore the attention weights for every layer. A thicker arrow pointing from token A to token B indicates that the layer is paying attention to token B when generating the vector corresponding to token A:

In[58]:=
Manipulate[
 visualizeTokenAttention@
  avgAttentionWeights[[i]], {{i, 12, "AttentionLayer #"}, Range[12]}, ControlType -> SetterBar]
Out[58]=

Transfer learning

Use the pre-trained model to build a classifier for telling apart indoor and outdoor photos. Create a test set and a training set:

In[59]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/ca854c12-d01e-4f21-ae94-85e9159ffbe5"]
In[60]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/3cd9f207-73c9-4512-9890-358c0520540f"]

Remove the last linear layer from the pre-trained net:

In[61]:=
tempNet = NetModel[{"CLIP Multi-domain Feature Extractor", "InputDomain" -> "Image"}]
Out[61]=

Create a new net composed of the pre-trained net followed by a linear layer and a softmax layer:

In[62]:=
newNet = NetAppend[
   tempNet, {"linearNew" -> LinearLayer[], "softmax" -> SoftmaxLayer[]}, "Output" -> NetDecoder[{"Class", {"indoor", "outdoor"}}]];

Train on the dataset, freezing all the weights except for those in the "linearNew" layer (use TargetDevice -> "GPU" for training on a GPU):

In[63]:=
trainedNet = NetTrain[newNet, trainSet, LearningRateMultipliers -> {"linearNew" -> 1, _ -> 0}]
Out[63]=

Perfect accuracy is obtained on the test set:

In[64]:=
ClassifierMeasurements[trainedNet, testSet, "Accuracy"]
Out[64]=

Net information

Inspect the number of parameters of all arrays in the net:

In[65]:=
Information[
 NetModel[
  "CLIP Multi-domain Feature Extractor"], "ArraysElementCounts"]
Out[65]=

Obtain the total number of parameters:

In[66]:=
Information[
 NetModel[
  "CLIP Multi-domain Feature Extractor"], "ArraysTotalElementCount"]
Out[66]=

Obtain the layer type counts:

In[67]:=
Information[
 NetModel["CLIP Multi-domain Feature Extractor"], "LayerTypeCounts"]
Out[67]=

Export to ONNX

Export the net to the ONNX format:

In[68]:=
onnxFile = Export[FileNameJoin[{$TemporaryDirectory, "net.onnx"}], NetModel["CLIP Multi-domain Feature Extractor"]]
Out[68]=

Get the size of the ONNX file:

In[69]:=
FileByteCount[onnxFile]
Out[69]=

Check some metadata of the ONNX model:

In[70]:=
{OpsetVersion, IRVersion} = {Import[onnxFile, "OperatorSetVersion"], Import[onnxFile, "IRVersion"]}
Out[70]=

Import the model back into Wolfram Language. However, the NetEncoder and NetDecoder will be absent because they are not supported by ONNX:

In[71]:=
Import[onnxFile]
Out[71]=

Resource History

Reference

  • A. Radford, J. W. Kim, C. Hallacy, A. Ramesh, G. Goh, S. Agarwal, G. Sastry, A. Askell, P. Mishkin, J. Clark, G. Krueger, I. Sutskever "Learning Transferable Visual Models from Natural Language Supervision," arXiv:2103.00020 (2021)
  • Available from: https://github.com/openai/CLIP
  • Rights: MIT License