Views
No views yet
nlpconnect-vit-gpt2-image-captioning_nlpconnect-vit-gpt2-image-captioning, likely a PEFT adapter.nlpconnect/vit-gpt2-image-captioningnlpconnect/vit-gpt2-image-captioningbase_model tag in the metadata above is initially empty. The models listed here are heuristic guesses based on the training directory name (nlpconnect-vit-gpt2-image-captioning_nlpconnect-vit-gpt2-image-captioning). Please verify these against your training configuration and update the base_model: list in the YAML metadata block at the top of this README with the correct Hugging Face model identifiers.1from transformers import AutoProcessor, AutoModelForVision2Seq, Blip2ForConditionalGeneration # Or other relevant classes
2from peft import PeftModel, PeftConfig
3import torch
4
5# --- Configuration ---
6# 1. Specify the EXACT base model identifiers used during training
7base_processor_id = "nlpconnect/vit-gpt2-image-captioning" # <-- Replace with correct HF ID
8base_model_id = "nlpconnect/vit-gpt2-image-captioning" # <-- Replace with correct HF ID (e.g., Salesforce/blip2-opt-2.7b)
9
10# 2. Specify the PEFT adapter repository ID (this repo)
11adapter_repo_id = "ashimdahal/nlpconnect-vit-gpt2-image-captioning_nlpconnect-vit-gpt2-image-captioning"
12
13# --- Load Base Model and Processor ---
14processor = AutoProcessor.from_pretrained(base_processor_id)
15
16# Load the base model (ensure it matches the type used for training)
17# Example for BLIP-2 OPT:
18base_model = Blip2ForConditionalGeneration.from_pretrained(
19 base_model_id,
20 torch_dtype=torch.float16 # Or torch.bfloat16 or float32, match training/inference needs
21)
22# Or for other model types:
23base_model = AutoModelForVision2Seq.from_pretrained(base_model_id, torch_dtype=torch.float16)
24base_model = AutoModelForCausalLM
25......
26
27# --- Load PEFT Adapter ---
28# Load the adapter config and merge the adapter weights into the base model
29model = PeftModel.from_pretrained(base_model, adapter_repo_id)
30model = model.merge_and_unload() # Merge weights for inference (optional but often recommended)
31model.eval() # Set model to evaluation mode
32
33# --- Inference Example ---
34device = "cuda" if torch.cuda.is_available() else "cpu"
35model.to(device)
36
37image = ... # Load your image (e.g., using PIL)
38text = "a photo of" # Optional prompt start
39
40inputs = processor(images=image, text=text, return_tensors="pt").to(device, torch.float16) # Match model dtype
41
42generated_ids = model.generate(**inputs, max_new_tokens=50)
43generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
44print(f"Generated Caption: {{generated_text}}")