Skip to main content
The main idea of this code is:
Give CLIP an image + several possible captions → CLIP calculates how well each caption matches the image → choose the highest score.
For example, if image.jpg contains a dog in a park, the output should favor “A dog playing in the park”.

1. Import PyTorch

torch is PyTorch, a deep-learning framework. We use it here mainly for:
  • Running the CLIP model
  • Working with tensors
  • Calculating vector similarity
  • Disabling gradients during prediction
Think of it as the mathematical engine behind the model.

2. Import PIL

PIL/Pillow is used to work with images. For example:
This loads your image into Python. So:

3. Import CLIP

Here we’re importing two Hugging Face classes.

CLIPModel

This is the actual CLIP neural network. It contains two important parts:
The image encoder understands the image. The text encoder understands the caption.

CLIPProcessor

The processor prepares the inputs in the format CLIP expects. For example:
And text:
So: Model = does the AI work Processor = prepares the input

4. Load the CLIP model

This downloads/loads a pretrained CLIP model from Hugging Face. The model name:
means this is OpenAI’s CLIP model using a Vision Transformer architecture.

from_pretrained()

This means:
“Load a model that has already been trained.”
You don’t need to train CLIP yourself. It already knows relationships between images and text. For example, it has learned that:

5. Load the CLIP processor

This loads the matching processor for the model. Important:
is the AI model.
is the input preparation system.

6. Load the image

This opens:
and stores it in:
For example, imagine your image looks like:
The variable:
now contains that image.

7. Define possible captions

This is a Python list containing four possible descriptions. We’re asking CLIP:
“Which of these four captions best matches my image?”
Conceptually:
CLIP will compare the image against all four.

8. Prepare image + text

This is an important line. We’re giving the processor:
and:
So it receives both image and text.

return_tensors="pt"

pt means PyTorch. The processor converts the inputs into PyTorch tensors. Instead of ordinary Python data, we get something like:
These are the formats the neural network expects.

padding=True

The captions have different lengths:
Padding makes their token sequences the same length. For example:
The 0s are padding tokens.

9. Disable gradient calculation

Normally, during training, PyTorch calculates gradients. But we’re not training CLIP. We’re only using it to make predictions. Therefore:
means:
“Don’t calculate gradients.”
This saves:
  • Memory
  • Computation
  • Time
Think:

10. Run CLIP

This is where the actual AI model runs. The **inputs means:
Take everything inside inputs and pass it to the model as arguments.
Conceptually:
The model processes both:

11. Get image embeddings

An embedding is a numerical representation of something. The image is converted into a vector:
This vector represents the semantic meaning of the image. For example:
might be represented by thousands of numerical values. This is called an:
Image embedding

12. Get text embeddings

Each caption is also converted into a vector. For example:
And:
So now we have:

13. Normalize image embeddings

This makes the embedding vector have a length of approximately 1. Why? Because we want to compare vectors fairly. Imagine:
We normalize it so that its magnitude becomes 1. The important concept is:
Normalization puts vectors onto the same scale.

14. Normalize text embeddings

Same thing, but now for the text vectors. So both image and text embeddings are normalized.

15. Calculate similarity

This is one of the most important lines. The @ operator performs matrix multiplication. Because the embeddings have been normalized, this effectively gives us cosine similarity between the image and each caption. Conceptually:
For example, CLIP might produce:
Higher = more similar.

16. Find the highest similarity

Let’s break it down.

argmax()

Finds the position of the largest value. Suppose:
The largest value is:
It is at index:
Therefore:

.item()

PyTorch returns a tensor. For example:
.item() converts it into a normal Python number:

17. Print similarity scores

Simply prints:

18. Loop through captions and scores

This combines each caption with its corresponding similarity score. For example:
zip() pairs them together.

19. Format the score

The f creates an f-string. And:
means:
Show the number with 4 digits after the decimal point.
For example:
becomes:
So you might get:

20. Print best caption

\n means new line. Then:
If:
then:
is:
So final output:

Complete Flow

The entire code can be understood as this:

The key concept to remember

CLIP doesn’t generate a caption in this code. It does caption selection. You provide:
CLIP essentially asks:
Then:

One-line interview explanation

CLIP is a multimodal model that maps images and text into a shared embedding space, allowing us to measure their semantic similarity and identify which text best matches an image.