Views
No views yet
1""" inference finetune model """
2
3import torch
4from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
5from qwen_vl_utils import process_vision_info
6
7# ------------------------------
8# 1. 모델 & 프로세서 로드
9# ------------------------------
10print("모델 로드 중...")
11model_name = "Rfy23/qwen2vl-ko-zh" # 내 병합 모델
12device = "cuda" if torch.cuda.is_available() else "cpu"
13
14model = Qwen2VLForConditionalGeneration.from_pretrained(
15 model_name,
16 torch_dtype=torch.float16 if device=="cuda" else torch.float32,
17 device_map="auto" if device=="cuda" else None
18)
19model.eval()
20print("모델 로드 완료!")
21
22processor = AutoProcessor.from_pretrained(model_name)
23print("프로세서 로드 완료!")
24
25# ------------------------------
26# 2. 고정 질문 + 이미지 URL
27# ------------------------------
28image_url = "/home/jwlee/volume/Qwen2-vl-finetune-wo/scripts/test-out-2/images/00002.jpg"
29fixed_question = "这张处方上写了什么? 尤其是药品、服用次数等,请准确全部告诉我。" # 원하는 고정 질문
30
31messages = [
32 {
33 "role": "user",
34 "content": [
35 {"type": "image", "image": image_url},
36 {"type": "text", "text": f"<image>\n{fixed_question}"}
37 ],
38 }
39]
40
41# ------------------------------
42# 3. processor로 입력 준비
43# ------------------------------
44print("입력 텐서 준비 중...")
45text_input = processor.apply_chat_template(
46 messages, tokenize=False, add_generation_prompt=True
47)
48image_inputs, _ = process_vision_info(messages)
49
50inputs = processor(
51 text=[text_input],
52 images=image_inputs,
53 # videos=video_inputs,
54 padding=True,
55 return_tensors="pt"
56).to(device)
57print("입력 텐서 준비 완료!")
58
59# ------------------------------
60# 4. 추론
61# ------------------------------
62print("모델 추론 시작...")
63with torch.no_grad():
64 generated_ids = model.generate(**inputs, max_new_tokens=128)
65
66generated_ids_trimmed = [
67 out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
68]
69
70print("디코딩 중...")
71output_text = processor.batch_decode(
72 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
73)
74
75print("모델 출력:")
76print(output_text[0])
77
78""" inference base model """
79
80# from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
81# from qwen_vl_utils import process_vision_info
82
83# # default: Load the model on the available device(s)
84# model = Qwen2VLForConditionalGeneration.from_pretrained(
85# "Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map="auto"
86# )
87
88# # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
89# # model = Qwen2VLForConditionalGeneration.from_pretrained(
90# # "Qwen/Qwen2-VL-2B-Instruct",
91# # torch_dtype=torch.bfloat16,
92# # attn_implementation="flash_attention_2",
93# # device_map="auto",
94# # )
95
96# # default processer
97# processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
98
99# # The default range for the number of visual tokens per image in the model is 4-16384. You can set min_pixels and max_pixels according to your needs, such as a token count range of 256-1280, to balance speed and memory usage.
100# # min_pixels = 256*28*28
101# # max_pixels = 1280*28*28
102# # processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
103
104# messages = [
105# {
106# "role": "user",
107# "content": [
108# {
109# "type": "image",
110# "image": "/home/jwlee/volume/Qwen2-vl-finetune-wo/scripts/test-out/images/00003.jpg",
111# },
112# {"type": "text", "text": "这张处方上写了什么?"},
113# ],
114# }
115# ]
116
117# # Preparation for inference
118# text = processor.apply_chat_template(
119# messages, tokenize=False, add_generation_prompt=True
120# )
121# image_inputs, _ = process_vision_info(messages)
122# inputs = processor(
123# text=[text],
124# images=image_inputs,
125# # videos=video_inputs,
126# padding=True,
127# return_tensors="pt",
128# )
129# inputs = inputs.to("cuda")
130
131# # Inference: Generation of the output
132# generated_ids = model.generate(**inputs, max_new_tokens=128)
133# generated_ids_trimmed = [
134# out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
135# ]
136# output_text = processor.batch_decode(
137# generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
138# )
139# print(output_text)
140
141