|
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor |
|
from qwen_vl_utils import process_vision_info |
|
import torch |
|
import json |
|
|
|
class EndpointHandler: |
|
def __init__(self, model_dir): |
|
|
|
self.model = Qwen2VLForConditionalGeneration.from_pretrained( |
|
model_dir, |
|
torch_dtype=torch.float16, |
|
device_map="auto" |
|
) |
|
self.processor = AutoProcessor.from_pretrained(model_dir) |
|
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
self.model.to(self.device) |
|
self.model.eval() |
|
|
|
|
|
self.model.gradient_checkpointing_enable() |
|
|
|
def preprocess(self, request_data): |
|
|
|
messages = request_data.get('messages') |
|
if not messages: |
|
raise ValueError("Messages are required") |
|
|
|
|
|
image_inputs, video_inputs = process_vision_info(messages) |
|
|
|
|
|
text = self.processor.apply_chat_template( |
|
messages, tokenize=False, add_generation_prompt=True |
|
) |
|
|
|
|
|
inputs = self.processor( |
|
text=[text], |
|
images=image_inputs, |
|
videos=video_inputs, |
|
padding=True, |
|
return_tensors="pt", |
|
) |
|
|
|
return inputs.to(self.device) |
|
|
|
def inference(self, inputs): |
|
|
|
with torch.no_grad(): |
|
|
|
generated_ids = self.model.generate( |
|
**inputs, |
|
max_new_tokens=128, |
|
num_beams=1, |
|
max_batch_size=1 |
|
) |
|
|
|
|
|
generated_ids_trimmed = [ |
|
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) |
|
] |
|
|
|
|
|
torch.cuda.empty_cache() |
|
|
|
return generated_ids_trimmed |
|
|
|
def postprocess(self, inference_output): |
|
|
|
output_text = self.processor.batch_decode( |
|
inference_output, skip_special_tokens=True, clean_up_tokenization_spaces=False |
|
) |
|
return output_text |
|
|
|
def __call__(self, request): |
|
try: |
|
|
|
request_data = json.loads(request) |
|
|
|
inputs = self.preprocess(request_data) |
|
|
|
outputs = self.inference(inputs) |
|
|
|
result = self.postprocess(outputs) |
|
return json.dumps({"result": result}) |
|
except Exception as e: |
|
return json.dumps({"error": str(e)}) |