testing for inference endpoints
#57
by
nbroad
HF staff
- opened
- handler.py +60 -0
- requirements.txt +2 -0
handler.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
|
2 |
+
from qwen_vl_utils import process_vision_info
|
3 |
+
|
4 |
+
|
5 |
+
|
6 |
+
class EndpointHandler():
|
7 |
+
|
8 |
+
def __init__(self, path):
|
9 |
+
# default: Load the model on the available device(s)
|
10 |
+
self.model = Qwen2VLForConditionalGeneration.from_pretrained(
|
11 |
+
path, torch_dtype="auto", device_map="auto",
|
12 |
+
)
|
13 |
+
|
14 |
+
# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
|
15 |
+
# model = Qwen2VLForConditionalGeneration.from_pretrained(
|
16 |
+
# path,
|
17 |
+
# torch_dtype=torch.bfloat16,
|
18 |
+
# attn_implementation="flash_attention_2",
|
19 |
+
# device_map="auto",
|
20 |
+
# )
|
21 |
+
|
22 |
+
# default processer
|
23 |
+
self.processor = AutoProcessor.from_pretrained(path)
|
24 |
+
|
25 |
+
# 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.
|
26 |
+
# min_pixels = 256*28*28
|
27 |
+
# max_pixels = 1280*28*28
|
28 |
+
# processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
|
29 |
+
|
30 |
+
|
31 |
+
|
32 |
+
def __call__(self, data):
|
33 |
+
|
34 |
+
text = self.processor.apply_chat_template(
|
35 |
+
data["messages"], tokenize=False, add_generation_prompt=True
|
36 |
+
)
|
37 |
+
image_inputs, video_inputs = process_vision_info(data["messages"])
|
38 |
+
|
39 |
+
inputs = self.processor(
|
40 |
+
text=[text],
|
41 |
+
images=image_inputs,
|
42 |
+
videos=video_inputs,
|
43 |
+
padding=True,
|
44 |
+
return_tensors="pt",
|
45 |
+
)
|
46 |
+
|
47 |
+
inputs = inputs.to(self.model.device)
|
48 |
+
|
49 |
+
# Inference: Generation of the output
|
50 |
+
generated_ids = self.model.generate(**inputs, max_new_tokens=data.get("max_new_tokens", 128))
|
51 |
+
generated_ids_trimmed = [
|
52 |
+
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
53 |
+
]
|
54 |
+
output_text = self.processor.batch_decode(
|
55 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
56 |
+
)
|
57 |
+
return {
|
58 |
+
"output": output_text,
|
59 |
+
}
|
60 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
qwen-vl-utils
|
2 |
+
git+https://github.com/huggingface/transformers.git@b99ca4d28b47fa7166e7882cb0695a5c0cc0d411
|