Update README.md
Browse files
README.md
CHANGED
|
@@ -16,19 +16,30 @@ See https://huggingface.co/spaces/pdufour/Qwen2-VL-2B-Instruct-ONNX-Q4-F16 for a
|
|
| 16 |
**Python**
|
| 17 |
|
| 18 |
```
|
|
|
|
|
|
|
| 19 |
import time
|
| 20 |
import torch
|
| 21 |
import numpy as np
|
| 22 |
-
import onnxruntime
|
| 23 |
-
from PIL import Image
|
| 24 |
-
import os
|
| 25 |
-
import sys
|
| 26 |
import requests
|
|
|
|
|
|
|
| 27 |
from io import BytesIO
|
|
|
|
| 28 |
|
|
|
|
|
|
|
|
|
|
| 29 |
|
|
|
|
| 30 |
try:
|
| 31 |
-
from export_config import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
except:
|
| 33 |
INPUT_IMAGE_SIZE = [960, 960]
|
| 34 |
HEIGHT_FACTOR = 10
|
|
@@ -36,220 +47,186 @@ except:
|
|
| 36 |
IMAGE_RESIZE = [HEIGHT_FACTOR * 28, WIDTH_FACTOR * 28]
|
| 37 |
MAX_SEQ_LENGTH = 1024
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
print(f" Model C: {onnx_model_C}")
|
| 52 |
-
print(f" Model D: {onnx_model_D}")
|
| 53 |
-
print(f" Model E: {onnx_model_E}")
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer
|
| 59 |
|
|
|
|
| 60 |
with torch.inference_mode():
|
| 61 |
-
model = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
num_key_value_heads = model.config.num_key_value_heads
|
| 65 |
-
head_dim = model.config.hidden_size //
|
| 66 |
num_layers = model.config.num_hidden_layers
|
| 67 |
hidden_size = model.config.hidden_size
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
in_name_E1 = in_name_E[1].name
|
| 120 |
-
in_name_E2 = in_name_E[2].name
|
| 121 |
-
in_name_E3 = in_name_E[3].name
|
| 122 |
-
in_name_E4 = in_name_E[4].name
|
| 123 |
-
in_name_E5 = in_name_E[5].name
|
| 124 |
-
in_name_E6 = in_name_E[6].name
|
| 125 |
-
in_name_E7 = in_name_E[7].name
|
| 126 |
-
out_name_E0 = out_name_E[0].name
|
| 127 |
-
out_name_E1 = out_name_E[1].name
|
| 128 |
-
out_name_E2 = out_name_E[2].name
|
| 129 |
-
|
| 130 |
-
response = requests.get(image_url)
|
| 131 |
image = Image.open(BytesIO(response.content))
|
| 132 |
-
|
| 133 |
if image.mode != 'RGB':
|
| 134 |
image = image.convert('RGB')
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
prompt = f"\n<|im_start|>user\n<|vision_start|><|vision_end|>{
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
[
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
})[0]
|
| 172 |
-
|
| 173 |
-
position_ids, = ort_session_C.run(
|
| 174 |
-
[out_name_C0],
|
| 175 |
-
{
|
| 176 |
-
in_name_C0: dummy
|
| 177 |
-
})
|
| 178 |
-
|
| 179 |
-
if use_vision:
|
| 180 |
-
|
| 181 |
-
image_embed = ort_session_A.run(
|
| 182 |
-
[out_name_A0],
|
| 183 |
-
{in_name_A0: pixel_values})[0]
|
| 184 |
-
|
| 185 |
-
ids_len += image_embed_size
|
| 186 |
-
|
| 187 |
-
split_factor = np.array(max_seq_len - ids_len[0] - image_embed_size, dtype=np.int32)
|
| 188 |
-
|
| 189 |
-
ids_len_minus = np.array(ids_len[0] - prompt_head_len[0], dtype=np.int32)
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
hidden_states, position_ids = ort_session_D.run(
|
| 193 |
-
[out_name_D0, out_name_D1],
|
| 194 |
{
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
}
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
[out_name_E0, out_name_E1, out_name_E2],
|
| 210 |
{
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
}
|
| 220 |
-
|
| 221 |
-
|
|
|
|
| 222 |
break
|
| 223 |
else:
|
| 224 |
-
|
| 225 |
-
if
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
if use_vision:
|
| 233 |
-
pos_factor = np.array(pos_factor_v + ids_len[0], dtype=np.float16)
|
| 234 |
else:
|
| 235 |
-
|
| 236 |
else:
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
hidden_states =
|
| 242 |
-
[
|
| 243 |
-
{
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
print(decoded_token, end="", flush=True)
|
| 251 |
-
|
| 252 |
-
generation_time = time.time() - end_time
|
| 253 |
```
|
| 254 |
|
| 255 |
# Technical Information:
|
|
|
|
| 16 |
**Python**
|
| 17 |
|
| 18 |
```
|
| 19 |
+
import os
|
| 20 |
+
import sys
|
| 21 |
import time
|
| 22 |
import torch
|
| 23 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
import requests
|
| 25 |
+
import onnxruntime as ort
|
| 26 |
+
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
|
|
|
|
| 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 |
with torch.inference_mode():
|
| 73 |
+
model = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 74 |
+
model_path,
|
| 75 |
+
torch_dtype=torch.float32,
|
| 76 |
+
device_map='mps',
|
| 77 |
+
low_cpu_mem_usage=DEBUG
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
max_length = MAX_SEQ_LENGTH
|
| 81 |
+
num_attention_heads = model.config.num_attention_heads
|
| 82 |
num_key_value_heads = model.config.num_key_value_heads
|
| 83 |
+
head_dim = model.config.hidden_size // num_attention_heads
|
| 84 |
num_layers = model.config.num_hidden_layers
|
| 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 |
+
# Get input/output names for each session
|
| 111 |
+
inputs = {
|
| 112 |
+
'A': {
|
| 113 |
+
'input': sessions['A'].get_inputs()[0].name,
|
| 114 |
+
'output': sessions['A'].get_outputs()[0].name
|
| 115 |
+
},
|
| 116 |
+
'B': {
|
| 117 |
+
'input_ids': sessions['B'].get_inputs()[0].name,
|
| 118 |
+
'input_lengths': sessions['B'].get_inputs()[1].name,
|
| 119 |
+
'output': sessions['B'].get_outputs()[0].name
|
| 120 |
+
},
|
| 121 |
+
'C': {
|
| 122 |
+
'input': sessions['C'].get_inputs()[0].name,
|
| 123 |
+
'output': sessions['C'].get_outputs()[0].name
|
| 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 |
+
response = requests.get(TEST_IMAGE_URL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
image = Image.open(BytesIO(response.content))
|
| 138 |
+
image = image.resize((INPUT_IMAGE_SIZE[1], INPUT_IMAGE_SIZE[0]))
|
| 139 |
if image.mode != 'RGB':
|
| 140 |
image = image.convert('RGB')
|
| 141 |
|
| 142 |
+
image_array = np.transpose(np.array(image).astype(np.float32), (2, 0, 1))
|
| 143 |
+
image_array = np.expand_dims(image_array, axis=0) / 255.
|
| 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[:input_lengths[0]] = input_ids[0, :]
|
| 155 |
+
position = np.zeros(1, dtype=np.int64)
|
| 156 |
+
|
| 157 |
+
# Initialize cache tensors
|
| 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([inputs['B']['output']],
|
| 167 |
+
{inputs['B']['input_ids']: tokens, inputs['B']['input_lengths']: input_lengths})[0]
|
| 168 |
+
batch_size, = sessions['C'].run([inputs['C']['output']], {inputs['C']['input']: batch_size})
|
| 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 |
+
iterations = 0
|
| 188 |
+
|
| 189 |
+
while (iterations < MAX_ITERATIONS) & (position < max_length):
|
| 190 |
+
token, key_cache, value_cache = sessions['E'].run(
|
| 191 |
+
[inputs['E']['outputs'][0], inputs['E']['outputs'][1], inputs['E']['outputs'][2]],
|
|
|
|
| 192 |
{
|
| 193 |
+
inputs['E']['names'][0]: hidden_states,
|
| 194 |
+
inputs['E']['names'][1]: logits_mask,
|
| 195 |
+
inputs['E']['names'][2]: key_cache,
|
| 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 (token == 151643) | (token == 151645):
|
| 205 |
break
|
| 206 |
else:
|
| 207 |
+
iterations += 1
|
| 208 |
+
if iterations < 2:
|
| 209 |
+
position += input_lengths[0]
|
| 210 |
+
input_lengths[0] = 1
|
| 211 |
+
logits_mask = np.array([.0], dtype=np.float16)
|
| 212 |
+
if use_images:
|
| 213 |
+
position_mask = np.array(max_total_tokens + input_lengths[0], dtype=np.float16)
|
|
|
|
|
|
|
|
|
|
| 214 |
else:
|
| 215 |
+
position_mask = np.array(position[0] + 1, dtype=np.float16)
|
| 216 |
else:
|
| 217 |
+
position += 1
|
| 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:
|