Views
No views yet
| Metric | Value |
|---|---|
| Best Loss | 0.2570 (epoch 44) |
| Initial Loss | 4.3295 |
| Loss Reduction | 93.8% |
| Convergence | Epoch 35-40 |
Epoch 1: Loss = 4.3295
Epoch 10: Loss = 3.3269
Epoch 20: Loss = 0.7544
Epoch 30: Loss = 0.3712
Epoch 44: Loss = 0.2570 (Best)
Epoch 50: Loss = 0.2683best_model.pth - Best performing checkpoint (epoch 44, loss: 0.2570) - 598 MBpip install torch torchvision pandas numpy pillow1import torch
2import torch.nn as nn
3import torch.nn.functional as F
4
5class CLIP(nn.Module):
6 def __init__(self):
7 super().__init__()
8 # Vision Transformer
9 self.visual = VisionTransformer(
10 img_size=224,
11 patch_size=16,
12 embed_dim=768,
13 depth=12,
14 num_heads=12,
15 output_dim=512
16 )
17 # Text Transformer
18 self.text = TextTransformer(
19 vocab_size=49408,
20 embed_dim=512,
21 max_len=77,
22 num_heads=8,
23 depth=8,
24 output_dim=512
25 )
26 self.temperature = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
27
28 def encode_image(self, image):
29 image_features = self.visual(image)
30 return F.normalize(image_features, dim=-1)
31
32 def encode_text(self, text):
33 text_features = self.text(text)
34 return F.normalize(text_features, dim=-1)
35
36 def forward(self, image, text):
37 image_features = self.encode_image(image)
38 text_features = self.encode_text(text)
39 logits = image_features @ text_features.T * torch.exp(self.temperature)
40 return logits, image_features, text_features1from huggingface_hub import hf_hub_download
2import torch
3
4# Download the best model checkpoint
5model_path = hf_hub_download(
6 repo_id="siddharth-magesh/clip-flickr30k",
7 filename="best_model.pth"
8)
9
10# Initialize your model (requires architecture implementation)
11model = CLIP()
12
13# Load weights
14checkpoint = torch.load(model_path, map_location='cpu')
15model.load_state_dict(checkpoint)
16model.eval()
17
18print("Model loaded successfully!")1import torch
2from torchvision import transforms
3from PIL import Image
4
5# Image preprocessing
6transform = transforms.Compose([
7 transforms.Resize((224, 224)),
8 transforms.ToTensor(),
9 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
10])
11
12# Load and preprocess image
13image = Image.open('your_image.jpg').convert('RGB')
14image_tensor = transform(image).unsqueeze(0)
15
16# Simple tokenizer (hash-based)
17def tokenize(text, max_length=77):
18 import numpy as np
19 tokens = text.lower().split()
20 idxs = [min(hash(w) % 49408, 49407) for w in tokens][:max_length]
21 arr = np.zeros(max_length, dtype=np.int64)
22 arr[:len(idxs)] = idxs
23 return torch.tensor(arr, dtype=torch.long)
24
25# Tokenize text
26text = "a photo of a dog"
27text_tensor = tokenize(text).unsqueeze(0)
28
29# Inference
30with torch.no_grad():
31 image_features = model.encode_image(image_tensor)
32 text_features = model.encode_text(text_tensor)
33
34 # Compute similarity
35 similarity = (image_features @ text_features.T).item()
36 print(f"Similarity: {similarity:.4f}")1def zero_shot_classification(image, texts, model):
2 """
3 Classify an image using text descriptions.
4
5 Args:
6 image: PIL Image
7 texts: List of text descriptions
8 model: CLIP model
9
10 Returns:
11 Probabilities for each text
12 """
13 # Preprocess image
14 image_tensor = transform(image).unsqueeze(0)
15
16 # Tokenize all texts
17 text_tensors = torch.stack([tokenize(text) for text in texts])
18
19 with torch.no_grad():
20 image_features = model.encode_image(image_tensor)
21 text_features = model.encode_text(text_tensors)
22
23 # Compute similarities
24 similarities = image_features @ text_features.T
25 probs = F.softmax(similarities / 0.07, dim=-1)
26
27 return probs[0].numpy()
28
29# Example usage
30texts = [
31 "a photo of a dog",
32 "a photo of a cat",
33 "a photo of a bird"
34]
35probs = zero_shot_classification(image, texts, model)
36
37for text, prob in zip(texts, probs):
38 print(f"{text}: {prob:.2%}")1def retrieve_images(query_text, image_paths, model, top_k=5):
2 """
3 Retrieve most relevant images for a text query.
4
5 Args:
6 query_text: Text query
7 image_paths: List of image file paths
8 model: CLIP model
9 top_k: Number of results to return
10
11 Returns:
12 List of (image_path, similarity) tuples
13 """
14 # Encode query
15 query_tensor = tokenize(query_text).unsqueeze(0)
16 with torch.no_grad():
17 query_features = model.encode_text(query_tensor)
18
19 # Encode images
20 similarities = []
21 for img_path in image_paths:
22 image = Image.open(img_path).convert('RGB')
23 image_tensor = transform(image).unsqueeze(0)
24
25 with torch.no_grad():
26 image_features = model.encode_image(image_tensor)
27 sim = (query_features @ image_features.T).item()
28
29 similarities.append((img_path, sim))
30
31 # Sort by similarity
32 similarities.sort(key=lambda x: x[1], reverse=True)
33 return similarities[:top_k]clip.py - Main CLIP modelvision_transformer.py - Vision encodertext_transformer.py - Text encodermodules/transformer.py - Transformer blocksmodules/multi_head_attention.py - Attention mechanismmodules/multi_layer_perceptron.py - MLP layersmodules/patch_embedding.py - Patch embedding1config = {
2 # Vision Transformer
3 'img_size': 224,
4 'patch_size': 16,
5 'vision_embed_dim': 768,
6 'vision_depth': 12,
7 'vision_heads': 12,
8 'vision_dropout': 0.1,
9
10 # Text Transformer
11 'vocab_size': 49408,
12 'text_embed_dim': 512,
13 'max_len': 77,
14 'text_heads': 8,
15 'text_depth': 8,
16 'text_dropout': 0.1,
17
18 # Common
19 'output_dim': 512,
20 'temperature': 0.07,
21}1loss = (cross_entropy(image_to_text_logits, labels) +
2 cross_entropy(text_to_image_logits, labels)) / 21@misc{clip-flickr30k-2025,
2 author = {Siddharth Magesh},
3 title = {CLIP-Flickr30k: PyTorch Implementation},
4 year = {2025},
5 publisher = {HuggingFace Hub},
6 url = {https://huggingface.co/siddharth-magesh/clip-flickr30k}
7}1@inproceedings{radford2021learning,
2 title={Learning Transferable Visual Models From Natural Language Supervision},
3 author={Radford, Alec and Kim, Jong Wook and Hallacy, Chris and others},
4 booktitle={International Conference on Machine Learning},
5 year={2021}
6}