Views
No views yet
1from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
2from peft import PeftModel
3from qwen_vl_utils import process_vision_info
4import torch
5
6base_model_id = "Qwen/Qwen2.5-VL-7B-Instruct"
7adapter_id = "onurulu17/Qwen2.5-VL-7B-CXR"
8
9# Load base model
10model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
11 base_model_id,
12 device_map="auto",
13 torch_dtype=torch.bfloat16,
14)
15
16# Load LoRA adapter
17model = PeftModel.from_pretrained(model, adapter_id)
18
19# Processor
20processor = AutoProcessor.from_pretrained(base_model_id)
21
22# Example inference
23def generate_text_from_sample(model, processor, sample, max_new_tokens=1024, device="cuda"):
24 text_input = processor.apply_chat_template(sample[:1], tokenize=False, add_generation_prompt=True)
25 image_inputs, _ = process_vision_info(sample)
26 model_inputs = processor(text=[text_input], images=image_inputs, return_tensors="pt").to(device)
27 generated_ids = model.generate(**model_inputs, max_new_tokens=max_new_tokens)
28 trimmed_generated_ids = [out_ids[len(in_ids):] for in_ids, out_ids in zip(model_inputs.input_ids, generated_ids)]
29 output_text = processor.batch_decode(trimmed_generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
30 return output_text[0]
31
32# Example usage
33sample = [
34{'role': 'user',
35 'content': [{'type': 'image',
36 'image': "./chest_xray_image.jpg"},
37 {'type': 'text',
38 'text': 'Please analyze this chest X-ray and provide the findings and impression.'}]},
39 ]
40
41output = generate_text_from_sample(model, processor, sample)
42print(output)