Update README.md
Browse files
README.md
CHANGED
@@ -15,6 +15,9 @@ See https://huggingface.co/spaces/pdufour/Qwen2-VL-2B-Instruct-ONNX-Q4-F16 for a
|
|
15 |
|
16 |
**Python**
|
17 |
|
|
|
|
|
|
|
18 |
```
|
19 |
import os
|
20 |
import sys
|
@@ -27,206 +30,118 @@ from PIL import Image
|
|
27 |
from io import BytesIO
|
28 |
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer
|
29 |
|
30 |
-
# Constants
|
31 |
-
DEBUG = True
|
32 |
-
PRINT = print
|
33 |
-
|
34 |
-
# Try importing config, set defaults if not found
|
35 |
-
try:
|
36 |
-
from export_config import (
|
37 |
-
INPUT_IMAGE_SIZE,
|
38 |
-
IMAGE_RESIZE,
|
39 |
-
MAX_SEQ_LENGTH,
|
40 |
-
HEIGHT_FACTOR,
|
41 |
-
WIDTH_FACTOR
|
42 |
-
)
|
43 |
-
except:
|
44 |
-
INPUT_IMAGE_SIZE = [960, 960]
|
45 |
-
HEIGHT_FACTOR = 10
|
46 |
-
WIDTH_FACTOR = 10
|
47 |
-
IMAGE_RESIZE = [HEIGHT_FACTOR * 28, WIDTH_FACTOR * 28]
|
48 |
-
MAX_SEQ_LENGTH = 1024
|
49 |
-
|
50 |
# Command line arguments
|
51 |
model_path = sys.argv[1]
|
52 |
onnx_path = sys.argv[2]
|
53 |
|
54 |
-
# ONNX model paths
|
55 |
-
model_paths = {
|
56 |
-
'A': os.path.join(onnx_path, 'QwenVL_A_q4f16.onnx'),
|
57 |
-
'B': os.path.join(onnx_path, 'QwenVL_B_q4f16.onnx'),
|
58 |
-
'C': os.path.join(onnx_path, 'QwenVL_C_q4f16.onnx'),
|
59 |
-
'D': os.path.join(onnx_path, 'QwenVL_D_q4f16.onnx'),
|
60 |
-
'E': os.path.join(onnx_path, 'QwenVL_E_q4f16.onnx')
|
61 |
-
}
|
62 |
-
|
63 |
-
PRINT('\n[PATHS] ONNX model paths:')
|
64 |
-
for key, path in model_paths.items():
|
65 |
-
PRINT(f" Model {key}: {path}")
|
66 |
-
|
67 |
-
# Test image and prompt
|
68 |
-
TEST_IMAGE_URL = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg'
|
69 |
-
TEST_PROMPT = 'Describe this image.'
|
70 |
-
|
71 |
# Initialize model and tokenizer
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
hidden_size = model.config.hidden_size
|
86 |
-
|
87 |
-
MAX_ITERATIONS = 12
|
88 |
-
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=DEBUG)
|
89 |
-
|
90 |
-
# ONNX session options
|
91 |
session_options = ort.SessionOptions()
|
92 |
-
session_options.log_severity_level = 3
|
93 |
-
session_options.inter_op_num_threads = 0
|
94 |
-
session_options.intra_op_num_threads = 0
|
95 |
-
session_options.enable_cpu_mem_arena = DEBUG
|
96 |
-
session_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
97 |
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
98 |
-
session_options.add_session_config_entry('session.intra_op.allow_spinning', '1')
|
99 |
-
session_options.add_session_config_entry('session.inter_op.allow_spinning', '1')
|
100 |
-
|
101 |
-
# Initialize ONNX sessions
|
102 |
-
sessions = {
|
103 |
-
'A': ort.InferenceSession(model_paths['A'], sess_options=session_options),
|
104 |
-
'B': ort.InferenceSession(model_paths['B'], sess_options=session_options),
|
105 |
-
'C': ort.InferenceSession(model_paths['C'], sess_options=session_options),
|
106 |
-
'D': ort.InferenceSession(model_paths['D'], sess_options=session_options),
|
107 |
-
'E': ort.InferenceSession(model_paths['E'], sess_options=session_options)
|
108 |
-
}
|
109 |
|
110 |
-
#
|
|
|
|
|
|
|
|
|
|
|
111 |
inputs = {
|
112 |
-
'A':
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
'
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
'
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
'D': {
|
126 |
-
'names': [inp.name for inp in sessions['D'].get_inputs()],
|
127 |
-
'outputs': [out.name for out in sessions['D'].get_outputs()]
|
128 |
-
},
|
129 |
-
'E': {
|
130 |
-
'names': [inp.name for inp in sessions['E'].get_inputs()],
|
131 |
-
'outputs': [out.name for out in sessions['E'].get_outputs()]
|
132 |
-
}
|
133 |
}
|
134 |
|
135 |
# Process image
|
136 |
-
|
137 |
-
image = Image.open(BytesIO(
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
use_images = DEBUG
|
146 |
-
prompt = f"\n<|im_start|>user\n<|vision_start|><|vision_end|>{TEST_PROMPT}<|im_end|>\n<|im_start|>assistant\n"
|
147 |
-
eos_token_id = np.array([5], dtype=np.int64)
|
148 |
-
total_ids = WIDTH_FACTOR * HEIGHT_FACTOR
|
149 |
-
|
150 |
-
# Initialize tensors
|
151 |
-
input_ids = tokenizer(prompt, return_tensors='pt')['input_ids']
|
152 |
input_lengths = np.array([input_ids.shape[1]], dtype=np.int64)
|
153 |
tokens = np.zeros(max_length, dtype=np.int32)
|
154 |
-
tokens[:
|
155 |
position = np.zeros(1, dtype=np.int64)
|
156 |
|
157 |
-
# Initialize
|
158 |
key_cache = np.zeros((num_layers, num_key_value_heads, max_length, head_dim), dtype=np.float16)
|
159 |
value_cache = key_cache.copy()
|
160 |
-
logits_mask = np.array([-65504.], dtype=np.float16)
|
161 |
-
position_mask = np.array([.0], dtype=np.float16)
|
162 |
-
max_total_tokens = 1 - total_ids + WIDTH_FACTOR
|
163 |
-
batch_size = np.array(0, dtype=np.int32)
|
164 |
|
165 |
# Process initial inputs
|
166 |
-
hidden_states = sessions['B'].run(
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
if use_images:
|
171 |
-
image_features = sessions['A'].run([inputs['A']['output']], {inputs['A']['input']: image_array})[0]
|
172 |
-
input_lengths += total_ids
|
173 |
-
remaining_tokens = np.array(max_length - input_lengths[0] - total_ids, dtype=np.int32)
|
174 |
-
tokens_to_stop = np.array(input_lengths[0] - eos_token_id[0], dtype=np.int32)
|
175 |
-
hidden_states, batch_size = sessions['D'].run(
|
176 |
-
[inputs['D']['outputs'][0], inputs['D']['outputs'][1]],
|
177 |
-
{
|
178 |
-
inputs['D']['names'][0]: hidden_states,
|
179 |
-
inputs['D']['names'][1]: image_features,
|
180 |
-
inputs['D']['names'][2]: input_lengths,
|
181 |
-
inputs['D']['names'][3]: tokens_to_stop,
|
182 |
-
inputs['D']['names'][4]: remaining_tokens
|
183 |
-
}
|
184 |
-
)
|
185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
186 |
start_time = time.time()
|
187 |
-
|
188 |
-
|
189 |
-
while (iterations < MAX_ITERATIONS) & (position < max_length):
|
190 |
token, key_cache, value_cache = sessions['E'].run(
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
inputs['E']['names'][3]: value_cache,
|
197 |
-
inputs['E']['names'][4]: position,
|
198 |
-
inputs['E']['names'][5]: input_lengths,
|
199 |
-
inputs['E']['names'][6]: batch_size,
|
200 |
-
inputs['E']['names'][7]: position_mask
|
201 |
-
}
|
202 |
)
|
203 |
|
204 |
-
if
|
205 |
break
|
|
|
|
|
|
|
|
|
206 |
else:
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
position_mask += 1
|
219 |
-
|
220 |
-
tokens[0] = token
|
221 |
-
hidden_states = sessions['B'].run(
|
222 |
-
[inputs['B']['output']],
|
223 |
-
{inputs['B']['input_ids']: tokens, inputs['B']['input_lengths']: input_lengths}
|
224 |
-
)[0]
|
225 |
-
decoded_token = tokenizer.decode(token)
|
226 |
-
PRINT(f"Decoded token: {decoded_token}")
|
227 |
-
PRINT(decoded_token, end='', flush=DEBUG)
|
228 |
-
|
229 |
-
total_time = time.time() - start_time
|
230 |
```
|
231 |
|
232 |
# Technical Information:
|
|
|
15 |
|
16 |
**Python**
|
17 |
|
18 |
+
Download the following script ./infer.py and then run like so:
|
19 |
+
python3 infer.py Qwen/Qwen2-VL-2B-Instruct 'path-to/Qwen2-VL-2B-Instruct-onnx/onnx'
|
20 |
+
|
21 |
```
|
22 |
import os
|
23 |
import sys
|
|
|
30 |
from io import BytesIO
|
31 |
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
# Command line arguments
|
34 |
model_path = sys.argv[1]
|
35 |
onnx_path = sys.argv[2]
|
36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
# Initialize model and tokenizer
|
38 |
+
model = Qwen2VLForConditionalGeneration.from_pretrained(
|
39 |
+
model_path, torch_dtype=torch.float32, device_map='mps'
|
40 |
+
)
|
41 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
42 |
+
|
43 |
+
# Model configuration
|
44 |
+
max_length = 1024
|
45 |
+
num_attention_heads = model.config.num_attention_heads
|
46 |
+
num_key_value_heads = model.config.num_key_value_heads
|
47 |
+
head_dim = model.config.hidden_size // num_attention_heads
|
48 |
+
num_layers = model.config.num_hidden_layers
|
49 |
+
|
50 |
+
# Setup ONNX sessions
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
session_options = ort.SessionOptions()
|
|
|
|
|
|
|
|
|
|
|
52 |
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
+
# Model paths and sessions
|
55 |
+
models = ['A', 'B', 'C', 'D', 'E']
|
56 |
+
model_paths = {m: os.path.join(onnx_path, f'QwenVL_{m}_q4f16.onnx') for m in models}
|
57 |
+
sessions = {m: ort.InferenceSession(path, sess_options=session_options) for m, path in model_paths.items()}
|
58 |
+
|
59 |
+
# Input/output names
|
60 |
inputs = {
|
61 |
+
'A': sessions['A'].get_inputs()[0].name,
|
62 |
+
'B': [sessions['B'].get_inputs()[i].name for i in range(2)],
|
63 |
+
'C': sessions['C'].get_inputs()[0].name,
|
64 |
+
'D': [inp.name for inp in sessions['D'].get_inputs()],
|
65 |
+
'E': [inp.name for inp in sessions['E'].get_inputs()]
|
66 |
+
}
|
67 |
+
|
68 |
+
outputs = {
|
69 |
+
'A': sessions['A'].get_outputs()[0].name,
|
70 |
+
'B': sessions['B'].get_outputs()[0].name,
|
71 |
+
'C': sessions['C'].get_outputs()[0].name,
|
72 |
+
'D': [out.name for out in sessions['D'].get_outputs()],
|
73 |
+
'E': [out.name for out in sessions['E'].get_outputs()]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
}
|
75 |
|
76 |
# Process image
|
77 |
+
image_url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg'
|
78 |
+
image = Image.open(BytesIO(requests.get(image_url).content)).resize((960, 960)).convert('RGB')
|
79 |
+
image_array = np.expand_dims(np.transpose(np.array(image).astype(np.float32), (2, 0, 1)), axis=0) / 255.
|
80 |
+
|
81 |
+
# Prepare inputs
|
82 |
+
prompt = "Describe this image."
|
83 |
+
formatted_prompt = f"\n<|im_start|>user\n<|vision_start|><|vision_end|>{prompt}<|im_end|>\n<|im_start|>assistant\n"
|
84 |
+
input_ids = tokenizer(formatted_prompt, return_tensors='pt')['input_ids']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
input_lengths = np.array([input_ids.shape[1]], dtype=np.int64)
|
86 |
tokens = np.zeros(max_length, dtype=np.int32)
|
87 |
+
tokens[:input_ids.shape[1]] = input_ids[0, :]
|
88 |
position = np.zeros(1, dtype=np.int64)
|
89 |
|
90 |
+
# Initialize caches
|
91 |
key_cache = np.zeros((num_layers, num_key_value_heads, max_length, head_dim), dtype=np.float16)
|
92 |
value_cache = key_cache.copy()
|
|
|
|
|
|
|
|
|
93 |
|
94 |
# Process initial inputs
|
95 |
+
hidden_states = sessions['B'].run(
|
96 |
+
[outputs['B']],
|
97 |
+
{inputs['B'][0]: tokens, inputs['B'][1]: input_lengths}
|
98 |
+
)[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
|
100 |
+
batch_size = np.array(0, dtype=np.int32)
|
101 |
+
batch_size, = sessions['C'].run([outputs['C']], {inputs['C']: batch_size})
|
102 |
+
|
103 |
+
# Process image features
|
104 |
+
image_features = sessions['A'].run([outputs['A']], {inputs['A']: image_array})[0]
|
105 |
+
total_ids = 100 # 10 * 10 from original factors
|
106 |
+
input_lengths += total_ids
|
107 |
+
remaining_tokens = np.array(max_length - input_lengths[0] - total_ids, dtype=np.int32)
|
108 |
+
tokens_to_stop = np.array(input_lengths[0] - 5, dtype=np.int32)
|
109 |
+
|
110 |
+
hidden_states, batch_size = sessions['D'].run(
|
111 |
+
outputs['D'],
|
112 |
+
dict(zip(inputs['D'],
|
113 |
+
[hidden_states, image_features, input_lengths, tokens_to_stop, remaining_tokens]))
|
114 |
+
)
|
115 |
+
|
116 |
+
# Generate tokens
|
117 |
start_time = time.time()
|
118 |
+
for i in range(12): # MAX_ITERATIONS
|
|
|
|
|
119 |
token, key_cache, value_cache = sessions['E'].run(
|
120 |
+
outputs['E'],
|
121 |
+
dict(zip(inputs['E'],
|
122 |
+
[hidden_states, np.array([-65504. if i==0 else 0.], dtype=np.float16),
|
123 |
+
key_cache, value_cache, position, input_lengths, batch_size,
|
124 |
+
np.array([1-total_ids+10 if i==0 else position[0]+1], dtype=np.float16)]))
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
)
|
126 |
|
127 |
+
if token in [151643, 151645]: # End tokens
|
128 |
break
|
129 |
+
|
130 |
+
if i < 1:
|
131 |
+
position += input_lengths[0]
|
132 |
+
input_lengths[0] = 1
|
133 |
else:
|
134 |
+
position += 1
|
135 |
+
|
136 |
+
tokens[0] = token
|
137 |
+
hidden_states = sessions['B'].run(
|
138 |
+
[outputs['B']],
|
139 |
+
{inputs['B'][0]: tokens, inputs['B'][1]: input_lengths}
|
140 |
+
)[0]
|
141 |
+
print(tokenizer.decode(token), end='', flush=True)
|
142 |
+
|
143 |
+
print(f"\nTotal time: {time.time() - start_time:.2f}s")
|
144 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
```
|
146 |
|
147 |
# Technical Information:
|