# This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the read-only "../input/" directory # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import os for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) # You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" # You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session get_ipython().getoutput("pip install nltk") import torch from transformers import BlipProcessor, BlipForConditionalGeneration from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction from tqdm import tqdm device = "cuda" if torch.cuda.is_available() else "cpu" model_name = "utkarshpise/blip-vrs" processor = BlipProcessor.from_pretrained(model_name) model = BlipForConditionalGeneration.from_pretrained(model_name) model.to(device) model.eval() print(" Model loaded") def evaluate_model(model, loader, processor, device): model.eval() total_loss = 0 preds = [] refs = [] with torch.no_grad(): for batch in tqdm(loader, desc="Evaluating"): batch = {k: v.to(device) for k, v in batch.items()} # 🔥 LM LOSS outputs = model(**batch) loss = outputs.loss total_loss += loss.item() # 🔥 Generate captions generated_ids = model.generate( pixel_values=batch["pixel_values"], max_length=50, num_beams=5 ) pred = processor.batch_decode(generated_ids, skip_special_tokens=True) ref = processor.batch_decode(batch["labels"], skip_special_tokens=True) preds.extend(pred) refs.extend(refs if False else ref) avg_loss = total_loss / len(loader) bleu_scores = [] for p, r in zip(preds, refs): score = sentence_bleu([r.split()], p.split(), smoothing_function=smooth) bleu_scores.append(score) bleu = sum(bleu_scores) / len(bleu_scores) return avg_loss, bleu import kagglehub import os path = kagglehub.dataset_download("ayaanmustafa/vrs-bench") print("Dataset path:", path) print("Files:", os.listdir(path)) import json DATA_JSON = os.path.join(path, "/kaggle/input/datasets/ayaanmustafa/vrs-bench/vrsbench_data/VRSBench_train.json") # adjust if needed with open(DATA_JSON) as f: data = json.load(f) print(type(data)) print(data[0]) import json import os # Paths ann_dir = "/kaggle/input/datasets/ayaanmustafa/vrs-bench/vrsbench_data/Annotations_train/Annotations_train" img_dir = "/kaggle/input/datasets/ayaanmustafa/vrs-bench/vrsbench_data/Images_train/Images_train" output_path = "/kaggle/working/blip_train_vrs.json" converted = [] for file in os.listdir(ann_dir): if file.endswith(".json"): # LIMIT TO 1000 if len(converted) >= 1000: break with open(os.path.join(ann_dir, file)) as f: item = json.load(f) # Skip if no caption if "caption" not in item: continue image_name = item["image"] image_path = os.path.join(img_dir, image_name) converted.append({ "image": image_path, "caption": item["caption"] }) # Save with open(output_path, "w") as f: json.dump(converted, f, indent=2) print("Total samples:", len(converted)) import json with open("/kaggle/working/blip_train_vrs.json") as f: data = json.load(f) print(data[0]) from torch.utils.data import Dataset from PIL import Image class VRSDataset(Dataset): def __init__(self, samples, processor): self.samples = samples self.processor = processor def __len__(self): return len(self.samples) def __getitem__(self, idx): item = self.samples[idx] image = Image.open(item["image"]).convert("RGB") caption = item["caption"] encoding = self.processor( images=image, text=caption, padding="max_length", truncation=True, return_tensors="pt" ) encoding = {k: v.squeeze(0) for k, v in encoding.items()} encoding["labels"] = encoding["input_ids"] return encoding import json with open("/kaggle/working/blip_train_vrs.json") as f: samples = json.load(f) print("Samples:", len(samples)) from torch.utils.data import DataLoader dataset = VRSDataset(samples, processor) test_loader = DataLoader( dataset, batch_size=8, shuffle=False, num_workers=0 ) print("Batches:", len(test_loader)) from nltk.translate.bleu_score import SmoothingFunction smooth = SmoothingFunction().method1 loss, bleu = evaluate_model(model, test_loader, processor, device) print("LM Loss:", loss) print("BLEU:", bleu) from huggingface_hub import login login() Evaluating: 100%|██████████| 125/125 [06:48<00:00, 3.27s/it] LM Loss: 0.1737535742521286 BLEU: 0.10278809043174526