vsg_eval / eval_pvsg /model_loader.py
royguw's picture
Add files using upload-large-folder tool
0cbed7c verified
Raw History Blame Contribute Delete
4.52 kB
"""
Model loading utilities for Qwen-VL evaluation
"""
import sys
import os
import torch
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
from pathlib import Path
# Add the Qwen2-VL-Finetune src to path for imports
sys.path.append("/weka/royg/vsg_train/Qwen2-VL-Finetune/src")
from config import MODELS
class QwenVLModelLoader:
"""Load and manage Qwen-VL models for evaluation"""
def __init__(self, model_variant: str, device: str = "auto"):
self.model_variant = model_variant
self.device = device
self.model_config = MODELS[model_variant]
self.model = None
self.processor = None
def load_model(self):
"""Load the specified model variant"""
model_path = self.model_config["path"]
if not os.path.exists(model_path):
raise FileNotFoundError(f"Model path not found: {model_path}")
print(f"Loading {self.model_variant} model from {model_path}")
# Load processor - use base model processor for consistency
base_model_name = "Qwen/Qwen2.5-VL-3B-Instruct"
self.processor = AutoProcessor.from_pretrained(base_model_name)
# Load fine-tuned model
self.model = Qwen2VLForConditionalGeneration.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
device_map="auto" if self.device == "auto" else None,
trust_remote_code=True
)
if self.device != "auto":
self.model = self.model.to(self.device)
self.model.eval()
print(f"Successfully loaded {self.model_variant} model")
def generate_response(self, messages, max_new_tokens=1024, temperature=0.1):
"""Generate response from the model"""
if self.model is None or self.processor is None:
raise RuntimeError("Model not loaded. Call load_model() first.")
# Prepare inputs
text = self.processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
# Process inputs
inputs = self.processor(
text=[text],
images=messages[0].get("content", [{}])[0].get("image") if "image" in str(messages) else None,
videos=messages[0].get("content", [{}])[0].get("video") if "video" in str(messages) else None,
padding=True,
return_tensors="pt"
)
# Move to device
if self.device != "auto":
inputs = {k: v.to(self.device) if isinstance(v, torch.Tensor) else v
for k, v in inputs.items()}
# Generate
with torch.no_grad():
generated_ids = self.model.generate(
**inputs,
max_new_tokens=max_new_tokens,
temperature=temperature,
do_sample=temperature > 0,
pad_token_id=self.processor.tokenizer.eos_token_id
)
# Decode response
generated_ids_trimmed = [
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
response = self.processor.batch_decode(
generated_ids_trimmed,
skip_special_tokens=True,
clean_up_tokenization_spaces=False
)[0]
return response
def unload_model(self):
"""Free model memory"""
if self.model is not None:
del self.model
self.model = None
if self.processor is not None:
del self.processor
self.processor = None
torch.cuda.empty_cache()
def load_all_models(device="auto"):
"""Load all three model variants"""
models = {}
for variant in MODELS.keys():
loader = QwenVLModelLoader(variant, device)
loader.load_model()
models[variant] = loader
return models
def get_model_prompt_template(model_variant: str):
"""Get the appropriate prompt template for model variant"""
from config import VSG_PROMPT_TEMPLATE, VSG_PROMPT_NO_ID, VSG_PROMPT_SPECIAL_TOKENS
if model_variant == "with_id":
return VSG_PROMPT_TEMPLATE
elif model_variant == "without_id":
return VSG_PROMPT_NO_ID
elif model_variant == "special_tokens":
return VSG_PROMPT_SPECIAL_TOKENS
else:
raise ValueError(f"Unknown model variant: {model_variant}")