Wendy-Fly commited on
Commit
a70a129
·
verified ·
1 Parent(s): c16b291

Upload infer_qwen2_vl.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. infer_qwen2_vl.py +127 -0
infer_qwen2_vl.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
2
+ from qwen_vl_utils import process_vision_info
3
+ import json
4
+
5
+ def read_json(file_path):
6
+ with open(file_path, 'r', encoding='utf-8') as file:
7
+ data = json.load(file)
8
+ return data
9
+
10
+ def write_json(file_path, data):
11
+ with open(file_path, 'w', encoding='utf-8') as file:
12
+ json.dump(data, file, ensure_ascii=False, indent=4)
13
+
14
+ # default: Load the model on the available device(s)
15
+ model_path = '/inspire/hdd/ws-ba572160-47f8-4ca1-984e-d6bcdeb95dbb/a100-maybe/albus/ICCV_2025/qvq/models/QVQ-72B-Preview'
16
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
17
+ model_path, torch_dtype="auto", device_map="auto"
18
+ )
19
+
20
+ # default processer
21
+ processor = AutoProcessor.from_pretrained(model_path)
22
+
23
+ # 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.
24
+ # min_pixels = 256*28*28
25
+ # max_pixels = 1280*28*28
26
+ #processor = AutoProcessor.from_pretrained("Qwen/QVQ-72B-Preview", min_pixels=min_pixels, max_pixels=max_pixels)
27
+
28
+ import glob
29
+ from PIL import Image
30
+ import argparse
31
+ import os
32
+
33
+ # parser = argparse.ArgumentParser(description="Process a dataset with specific index range.")
34
+ # parser.add_argument("--batch_size", type=int, default = 1,help="batch size")
35
+ # #parser.add_argument("--index", type=int, default = 0,help="index")
36
+ # args = parser.parse_args()
37
+
38
+
39
+ folder = "/inspire/hdd/ws-ba572160-47f8-4ca1-984e-d6bcdeb95dbb/a100-maybe/albus/ICCV_2025/qvq/dataset"
40
+
41
+ file_names = os.listdir(folder)
42
+
43
+ num_image = len(file_names)
44
+
45
+ begin, end, batch_size= 0, num_image, 6
46
+ print(f"beigin : {begin}, end : {end}, batch_size : {batch_size}")
47
+ messages = [
48
+ {
49
+ "role": "system",
50
+ "content": [
51
+ {"type": "text", "text": "You are a helpful and harmless assistant. You are Qwen developed by Alibaba. You should think step-by-step."}
52
+ ],
53
+ },
54
+ {
55
+ "role": "user",
56
+ "content": [
57
+ {
58
+ "type": "image",
59
+ "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/QVQ/demo.png",
60
+ },
61
+ {"type": "text", "text": "Please describe in detail the content of the picture."},
62
+ ],
63
+ }
64
+ ]
65
+
66
+ from tqdm import tqdm
67
+ # Preparation for inference
68
+ ans = []
69
+ counter = 0
70
+ for batch_idx in tqdm(range(begin, end, batch_size)):
71
+ up = min(batch_idx + batch_size, end)
72
+ batch = file_names[batch_idx: up]
73
+ print(f"data index range : {batch_idx} ~ {up}")
74
+ image_inputs_batch, video_inputs_batch,text_batch = [], [], []
75
+ for idx,i in enumerate(batch):
76
+ #img = batch[i]
77
+ #print('gain image successfully !')
78
+ img_path = '/inspire/hdd/ws-ba572160-47f8-4ca1-984e-d6bcdeb95dbb/a100-maybe/albus/ICCV_2025/qvq/dataset/' + i
79
+ #print(img_path)
80
+ messages[1]["content"][0]["image"] = '/inspire/hdd/ws-ba572160-47f8-4ca1-984e-d6bcdeb95dbb/a100-maybe/albus/ICCV_2025/qvq/dataset/' + i
81
+ text = processor.apply_chat_template(
82
+ messages, tokenize=False, add_generation_prompt=True
83
+ )
84
+ text_batch.append(text)
85
+ image_inputs, video_inputs = process_vision_info(messages)
86
+ print(video_inputs)
87
+ image_inputs_batch.append(image_inputs)
88
+ video_inputs_batch.append(video_inputs)
89
+ inputs = processor(
90
+ text=text_batch, # [text]
91
+ images=image_inputs_batch,
92
+ videos=None,
93
+ padding=True,
94
+ return_tensors="pt",
95
+ )
96
+ inputs = inputs.to("cuda")
97
+
98
+ # Inference: Generation of the output
99
+
100
+ #print(inputs)
101
+
102
+ # for x in range(len(inputs)):
103
+ # print(f"Generating {x}th image")
104
+ # generated_ids = model.generate(**x, max_new_tokens=8192)
105
+ # generated_ids_trimmed = [
106
+ # out_ids[len(in_ids) :] for in_ids, out_ids in zip(x.input_ids, generated_ids)
107
+ # ]
108
+ # output_text = processor.batch_decode(
109
+ # generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=True
110
+ # )
111
+ # ans.append(output_text)
112
+
113
+ generated_ids = model.generate(**inputs, max_new_tokens=8192)
114
+ generated_ids_trimmed = [
115
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
116
+ ]
117
+ output_text = processor.batch_decode(
118
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
119
+ )
120
+ ans.append(output_text)
121
+ save_path = "output_final.json"
122
+ counter = counter + 1
123
+ if counter % 10 == 0 or up + 10 >= end:
124
+ print(f"Saving data at iteration {idx + 1}")
125
+ write_json(save_path, ans)
126
+
127
+