|
| 1 | +# Copyright 2022-2023 XProbe Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import logging |
| 15 | +import uuid |
| 16 | +from typing import Iterator, List, Optional, Union |
| 17 | + |
| 18 | +from ....model.utils import select_device |
| 19 | +from ....types import ( |
| 20 | + ChatCompletion, |
| 21 | + ChatCompletionChunk, |
| 22 | + ChatCompletionMessage, |
| 23 | + CompletionChunk, |
| 24 | +) |
| 25 | +from ..llm_family import LLMFamilyV1, LLMSpecV1 |
| 26 | +from ..utils import generate_chat_completion, generate_completion_chunk |
| 27 | +from .core import PytorchChatModel, PytorchGenerateConfig |
| 28 | + |
| 29 | +logger = logging.getLogger(__name__) |
| 30 | + |
| 31 | + |
| 32 | +class Qwen2VLChatModel(PytorchChatModel): |
| 33 | + def __init__(self, *args, **kwargs): |
| 34 | + super().__init__(*args, **kwargs) |
| 35 | + self._tokenizer = None |
| 36 | + self._model = None |
| 37 | + self._device = None |
| 38 | + self._processor = None |
| 39 | + |
| 40 | + @classmethod |
| 41 | + def match( |
| 42 | + cls, model_family: "LLMFamilyV1", model_spec: "LLMSpecV1", quantization: str |
| 43 | + ) -> bool: |
| 44 | + llm_family = model_family.model_family or model_family.model_name |
| 45 | + if "qwen2-vl-instruct".lower() in llm_family.lower(): |
| 46 | + return True |
| 47 | + return False |
| 48 | + |
| 49 | + def load(self): |
| 50 | + from transformers import AutoProcessor, Qwen2VLForConditionalGeneration |
| 51 | + |
| 52 | + device = self._pytorch_model_config.get("device", "auto") |
| 53 | + device = select_device(device) |
| 54 | + self._device = device |
| 55 | + # for multiple GPU, set back to auto to make multiple devices work |
| 56 | + device = "auto" if device == "cuda" else device |
| 57 | + |
| 58 | + self._processor = AutoProcessor.from_pretrained( |
| 59 | + self.model_path, trust_remote_code=True |
| 60 | + ) |
| 61 | + self._tokenizer = self._processor.tokenizer |
| 62 | + self._model = Qwen2VLForConditionalGeneration.from_pretrained( |
| 63 | + self.model_path, device_map=device, trust_remote_code=True |
| 64 | + ).eval() |
| 65 | + |
| 66 | + def _transform_messages( |
| 67 | + self, |
| 68 | + messages: List[ChatCompletionMessage], |
| 69 | + ): |
| 70 | + transformed_messages = [] |
| 71 | + for msg in messages: |
| 72 | + new_content = [] |
| 73 | + role = msg["role"] |
| 74 | + content = msg["content"] |
| 75 | + if isinstance(content, str): |
| 76 | + new_content.append({"type": "text", "text": content}) |
| 77 | + elif isinstance(content, List): |
| 78 | + for item in content: # type: ignore |
| 79 | + if "text" in item: |
| 80 | + new_content.append({"type": "text", "text": item["text"]}) |
| 81 | + elif "image_url" in item: |
| 82 | + new_content.append( |
| 83 | + {"type": "image", "image": item["image_url"]["url"]} |
| 84 | + ) |
| 85 | + elif "video_url" in item: |
| 86 | + new_content.append( |
| 87 | + {"type": "video", "video": item["video_url"]["url"]} |
| 88 | + ) |
| 89 | + new_message = {"role": role, "content": new_content} |
| 90 | + transformed_messages.append(new_message) |
| 91 | + |
| 92 | + return transformed_messages |
| 93 | + |
| 94 | + def chat( |
| 95 | + self, |
| 96 | + messages: List[ChatCompletionMessage], # type: ignore |
| 97 | + generate_config: Optional[PytorchGenerateConfig] = None, |
| 98 | + ) -> Union[ChatCompletion, Iterator[ChatCompletionChunk]]: |
| 99 | + messages = self._transform_messages(messages) |
| 100 | + |
| 101 | + generate_config = generate_config if generate_config else {} |
| 102 | + |
| 103 | + stream = generate_config.get("stream", False) if generate_config else False |
| 104 | + |
| 105 | + if stream: |
| 106 | + it = self._generate_stream(messages, generate_config) |
| 107 | + return self._to_chat_completion_chunks(it) |
| 108 | + else: |
| 109 | + c = self._generate(messages, generate_config) |
| 110 | + return c |
| 111 | + |
| 112 | + def _generate( |
| 113 | + self, messages: List, config: PytorchGenerateConfig = {} |
| 114 | + ) -> ChatCompletion: |
| 115 | + from qwen_vl_utils import process_vision_info |
| 116 | + |
| 117 | + # Preparation for inference |
| 118 | + text = self._processor.apply_chat_template( |
| 119 | + messages, tokenize=False, add_generation_prompt=True |
| 120 | + ) |
| 121 | + image_inputs, video_inputs = process_vision_info(messages) |
| 122 | + inputs = self._processor( |
| 123 | + text=[text], |
| 124 | + images=image_inputs, |
| 125 | + videos=video_inputs, |
| 126 | + padding=True, |
| 127 | + return_tensors="pt", |
| 128 | + ) |
| 129 | + inputs = inputs.to("cuda") |
| 130 | + |
| 131 | + # Inference: Generation of the output |
| 132 | + generated_ids = self._model.generate( |
| 133 | + **inputs, |
| 134 | + max_new_tokens=config.get("max_tokens", 512), |
| 135 | + temperature=config.get("temperature", 1), |
| 136 | + ) |
| 137 | + generated_ids_trimmed = [ |
| 138 | + out_ids[len(in_ids) :] |
| 139 | + for in_ids, out_ids in zip(inputs.input_ids, generated_ids) |
| 140 | + ] |
| 141 | + output_text = self._processor.batch_decode( |
| 142 | + generated_ids_trimmed, |
| 143 | + skip_special_tokens=True, |
| 144 | + clean_up_tokenization_spaces=False, |
| 145 | + )[0] |
| 146 | + return generate_chat_completion(self.model_uid, output_text) |
| 147 | + |
| 148 | + def _generate_stream( |
| 149 | + self, messages: List, config: PytorchGenerateConfig = {} |
| 150 | + ) -> Iterator[CompletionChunk]: |
| 151 | + from threading import Thread |
| 152 | + |
| 153 | + from qwen_vl_utils import process_vision_info |
| 154 | + from transformers import TextIteratorStreamer |
| 155 | + |
| 156 | + text = self._processor.apply_chat_template( |
| 157 | + messages, tokenize=False, add_generation_prompt=True |
| 158 | + ) |
| 159 | + image_inputs, video_inputs = process_vision_info(messages) |
| 160 | + inputs = self._processor( |
| 161 | + text=[text], |
| 162 | + images=image_inputs, |
| 163 | + videos=video_inputs, |
| 164 | + padding=True, |
| 165 | + return_tensors="pt", |
| 166 | + ) |
| 167 | + inputs = inputs.to(self._model.device) |
| 168 | + |
| 169 | + tokenizer = self._tokenizer |
| 170 | + streamer = TextIteratorStreamer( |
| 171 | + tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True |
| 172 | + ) |
| 173 | + |
| 174 | + gen_kwargs = { |
| 175 | + "max_new_tokens": config.get("max_tokens", 512), |
| 176 | + "temperature": config.get("temperature", 1), |
| 177 | + "streamer": streamer, |
| 178 | + **inputs, |
| 179 | + } |
| 180 | + |
| 181 | + thread = Thread(target=self._model.generate, kwargs=gen_kwargs) |
| 182 | + thread.start() |
| 183 | + |
| 184 | + completion_id = str(uuid.uuid1()) |
| 185 | + for new_text in streamer: |
| 186 | + yield generate_completion_chunk( |
| 187 | + chunk_text=new_text, |
| 188 | + finish_reason=None, |
| 189 | + chunk_id=completion_id, |
| 190 | + model_uid=self.model_uid, |
| 191 | + prompt_tokens=-1, |
| 192 | + completion_tokens=-1, |
| 193 | + total_tokens=-1, |
| 194 | + has_choice=True, |
| 195 | + has_content=True, |
| 196 | + ) |
| 197 | + |
| 198 | + yield generate_completion_chunk( |
| 199 | + chunk_text=None, |
| 200 | + finish_reason="stop", |
| 201 | + chunk_id=completion_id, |
| 202 | + model_uid=self.model_uid, |
| 203 | + prompt_tokens=-1, |
| 204 | + completion_tokens=-1, |
| 205 | + total_tokens=-1, |
| 206 | + has_choice=True, |
| 207 | + has_content=False, |
| 208 | + ) |
0 commit comments