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
2. Import PIL
3. Import CLIP
CLIPModel
CLIPProcessor
4. Load the CLIP model
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
6. Load the image
7. Define possible captions
“Which of these four captions best matches my image?”Conceptually:
8. Prepare image + text
return_tensors="pt"
pt means PyTorch.
The processor converts the inputs into PyTorch tensors.
Instead of ordinary Python data, we get something like:
padding=True
The captions have different lengths:
0s are padding tokens.
9. Disable gradient calculation
“Don’t calculate gradients.”This saves:
- Memory
- Computation
- Time
10. Run CLIP
**inputs means:
Take everything inside inputs and pass it to the model as arguments.
Conceptually:
11. Get image embeddings
Image embedding
12. Get text embeddings
13. Normalize image embeddings
1.
Why?
Because we want to compare vectors fairly.
Imagine:
1.
The important concept is:
Normalization puts vectors onto the same scale.
14. Normalize text embeddings
15. Calculate similarity
@ operator performs matrix multiplication.
Because the embeddings have been normalized, this effectively gives us cosine similarity between the image and each caption.
Conceptually:
16. Find the highest similarity
argmax()
Finds the position of the largest value.
Suppose:
.item()
PyTorch returns a tensor.
For example:
.item() converts it into a normal Python number:
17. Print similarity scores
18. Loop through captions and scores
zip() pairs them together.
19. Format the score
f creates an f-string.
And:
Show the number with 4 digits after the decimal point.For example:
20. Print best caption
\n means new line.
Then:
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: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.