Views
No views yet
pip install transformers==4.47.0 torch opencv-python matplotlib pillow requestsopenai/clip-vit-large-patch14alibidaran/SMOLL_image_captionerHuggingFaceTB/SmolLM2-360M1from PIL import Image
2import requests
3from transformers import CLIPProcessor, CLIPModel
4import cv2
5from transformers import AutoTokenizer, AutoModelForCausalLM
6import torch
7import matplotlib.pyplot as plt1clip_model = CLIPModel.from_pretrained("openai/clip-vit-large-patch14").to('cuda:0')
2clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14")
3print(torch.cuda.is_available())1device = 'cuda' if torch.cuda.is_available() else 'cpu'
2tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-360M")
3
4llm_model = AutoModelForCausalLM.from_pretrained("alibidaran/SMOLL_image_captioner").to('cuda')wget https://huggingface.co/alibidaran/SMOLL_image_captioner/resolve/main/content/SMOLL_image_captioner.pt1from SMOLLM_VisionModel import SMOLLm_VISION_ImageCaptioning,SmoLLM_processor
2
3image_captioning_model = SMOLLm_VISION_ImageCaptioning(llm_model=llm_model, hidden_dim=4096).to('cuda')
4model = image_captioning_model
5processor=SmoLLM_processor(image_model=clip_model,image_processor=clip_processor)
6saved_model = torch.load('/content/SMOLL_image_captioner.pt', map_location=torch.device('cuda'))1import cv2
2import matplotlib.pyplot as plt
3
4image_url = '/content/54322546688_71515f8335_w.jpg'
5image_features = processor.get_features(image_url, device='cuda')1tokenizer.pad_token = tokenizer.eos_token
2prompt = """
3 ##User <image> Write a caption
4 ##Assitant:"""
5
6# Tokenize input
7tokenized = tokenizer(prompt, return_tensors='pt')
8label = tokenized['input_ids'].to('cuda')
9att = tokenized['attention_mask'].to('cuda')
10
11# Generate caption
12with torch.no_grad():
13 _, embeds = model(image_features.unsqueeze(0).to('cuda'), label, att)
14 generate_kwargs = {
15 "input_ids": None,
16 "inputs_embeds": embeds,
17 "max_new_tokens": 50,
18 }
19 output = saved_model.llm_model.generate(**generate_kwargs, do_sample=True, temperature=0.8, top_p=0.99, top_k=10)
20
21# Decode and display result
22print(tokenizer.decode(output[0]))
23plt.imshow(image)