|
| 1 | +from threading import Lock |
| 2 | +from typing import Any, Dict, List, Optional |
| 3 | +from dataclasses import dataclass |
| 4 | + |
| 5 | +from transformers import Qwen2VLForConditionalGeneration, AutoProcessor |
| 6 | +from qwen_vl_utils import process_vision_info |
| 7 | +import torch |
| 8 | + |
| 9 | +from helm.common.cache import CacheConfig |
| 10 | +from helm.common.gpu_utils import get_torch_device_name |
| 11 | +from helm.common.hierarchical_logger import hlog, htrack_block |
| 12 | +from helm.common.media_object import TEXT_TYPE |
| 13 | +from helm.common.request import Request, RequestResult, GeneratedOutput, Token |
| 14 | +from helm.common.request import wrap_request_time |
| 15 | +from helm.clients.client import CachingClient, generate_uid_for_multimodal_prompt |
| 16 | + |
| 17 | + |
| 18 | +@dataclass(frozen=True) |
| 19 | +class LoadedQwen2ModelProcessor: |
| 20 | + model: Qwen2VLForConditionalGeneration |
| 21 | + processor: AutoProcessor |
| 22 | + |
| 23 | + |
| 24 | +_models_lock: Lock = Lock() |
| 25 | +_models: Dict[str, Optional[LoadedQwen2ModelProcessor]] = { |
| 26 | + "Qwen/Qwen2-VL-7B-Instruct": None, |
| 27 | + "Qwen/Qwen2-VL-72B-Instruct": None, |
| 28 | +} |
| 29 | + |
| 30 | + |
| 31 | +class Qwen2VLMClient(CachingClient): |
| 32 | + def __init__(self, cache_config: CacheConfig): |
| 33 | + super().__init__(cache_config=cache_config) |
| 34 | + self._device: str = get_torch_device_name() |
| 35 | + |
| 36 | + def _get_model_name(self, helm_model_name: str) -> str: |
| 37 | + if helm_model_name == "qwen2-vl-7b-instruct": |
| 38 | + return "Qwen/Qwen2-VL-7B-Instruct" |
| 39 | + elif helm_model_name == "qwen2-vl-72b-instruct": |
| 40 | + return "Qwen/Qwen2-VL-72B-Instruct" |
| 41 | + else: |
| 42 | + raise ValueError(f"Unhandled model name: {helm_model_name}") |
| 43 | + |
| 44 | + def _get_model(self, helm_model_name: str) -> LoadedQwen2ModelProcessor: |
| 45 | + global _models_lock |
| 46 | + global _models |
| 47 | + |
| 48 | + model_name = self._get_model_name(helm_model_name) |
| 49 | + |
| 50 | + with _models_lock: |
| 51 | + loaded = _models[model_name] |
| 52 | + if loaded is None: |
| 53 | + hlog(f"Loading model {model_name} and caching in memory...") |
| 54 | + # https://huggingface.co/docs/transformers/model_doc/qwen2_vl#flash-attention-2-to-speed-up-generation |
| 55 | + model = Qwen2VLForConditionalGeneration.from_pretrained( |
| 56 | + model_name, |
| 57 | + torch_dtype=torch.bfloat16, |
| 58 | + device_map="auto", |
| 59 | + attn_implementation="flash_attention_2", |
| 60 | + ).eval() |
| 61 | + processor = AutoProcessor.from_pretrained(model_name) |
| 62 | + loaded = LoadedQwen2ModelProcessor(model=model, processor=processor) |
| 63 | + _models[model_name] = loaded |
| 64 | + |
| 65 | + return loaded |
| 66 | + |
| 67 | + def make_request(self, request: Request) -> RequestResult: |
| 68 | + assert request.multimodal_prompt is not None, "Multimodal prompt is required" |
| 69 | + loaded = self._get_model(request.model_engine) |
| 70 | + model = loaded.model |
| 71 | + processor = loaded.processor |
| 72 | + |
| 73 | + # Build Qwen2 messages |
| 74 | + # We assume all media objects go into a single "user" message: |
| 75 | + # messages = [ |
| 76 | + # { |
| 77 | + # "role": "user", |
| 78 | + # "content": [ |
| 79 | + # {"type": "image", "image": "file:///path/to/image1.jpg"}, |
| 80 | + # {"type": "image", "image": "file:///path/to/image2.jpg"}, |
| 81 | + # {"type": "text", "text": "Describe these images."} |
| 82 | + # ] |
| 83 | + # } |
| 84 | + # ] |
| 85 | + message_content = [] |
| 86 | + for media_object in request.multimodal_prompt.media_objects: |
| 87 | + if media_object.is_type("image") and media_object.location: |
| 88 | + message_content.append({"type": "image", "image": media_object.location}) |
| 89 | + elif media_object.is_type(TEXT_TYPE): |
| 90 | + if media_object.text is None: |
| 91 | + raise ValueError("MediaObject of text type has missing text field value") |
| 92 | + message_content.append({"type": "text", "text": media_object.text}) |
| 93 | + else: |
| 94 | + raise ValueError(f"Unrecognized MediaObject type {media_object.type}") |
| 95 | + |
| 96 | + messages = [{"role": "user", "content": message_content}] |
| 97 | + |
| 98 | + # Prepare text and vision inputs |
| 99 | + text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) |
| 100 | + image_inputs, video_inputs = process_vision_info(messages) |
| 101 | + |
| 102 | + inputs = processor( |
| 103 | + text=[text], |
| 104 | + images=image_inputs, |
| 105 | + videos=video_inputs, |
| 106 | + padding=True, |
| 107 | + return_tensors="pt", |
| 108 | + ).to(self._device) |
| 109 | + |
| 110 | + generation_args = { |
| 111 | + "max_new_tokens": request.max_tokens, |
| 112 | + } |
| 113 | + |
| 114 | + completions: List[GeneratedOutput] = [] |
| 115 | + request_time: float = 0 |
| 116 | + request_datetime: Optional[int] = None |
| 117 | + all_cached: bool = True |
| 118 | + |
| 119 | + with htrack_block(f"Generating for prompt: {text}"): |
| 120 | + for completion_index in range(request.num_completions): |
| 121 | + try: |
| 122 | + |
| 123 | + def do_it() -> Dict[str, Any]: |
| 124 | + generated_ids = model.generate(**inputs, **generation_args) |
| 125 | + # Remove the input prefix from outputs |
| 126 | + generated_ids_trimmed = [ |
| 127 | + out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) |
| 128 | + ] |
| 129 | + output_text = processor.batch_decode( |
| 130 | + generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False |
| 131 | + ) |
| 132 | + # There's only one batch element |
| 133 | + completion = output_text[0] |
| 134 | + # For simplicity, we split tokens by whitespace. |
| 135 | + # A more accurate tokenization would require a tokenizer for Qwen2, if desired. |
| 136 | + tokens = completion.split() |
| 137 | + return {"output": (completion, tokens)} |
| 138 | + |
| 139 | + cache_key = CachingClient.make_cache_key( |
| 140 | + raw_request={ |
| 141 | + "completion_index": completion_index, |
| 142 | + "model": request.model, |
| 143 | + "prompt": generate_uid_for_multimodal_prompt(request.multimodal_prompt), |
| 144 | + **generation_args, |
| 145 | + }, |
| 146 | + request=request, |
| 147 | + ) |
| 148 | + result, cached = self.cache.get(cache_key, wrap_request_time(do_it)) |
| 149 | + except RuntimeError as model_error: |
| 150 | + return RequestResult( |
| 151 | + success=False, cached=False, error=str(model_error), completions=[], embedding=[] |
| 152 | + ) |
| 153 | + |
| 154 | + text_out, tokens = result["output"] |
| 155 | + completions.append( |
| 156 | + GeneratedOutput( |
| 157 | + text=text_out, |
| 158 | + logprob=0, |
| 159 | + tokens=[Token(text=str(token), logprob=0) for token in tokens], |
| 160 | + ) |
| 161 | + ) |
| 162 | + hlog(f"Generated: {text_out}") |
| 163 | + |
| 164 | + request_time += result["request_time"] |
| 165 | + request_datetime = request_datetime or result.get("request_datetime") |
| 166 | + all_cached = all_cached and cached |
| 167 | + |
| 168 | + return RequestResult( |
| 169 | + success=True, |
| 170 | + cached=all_cached, |
| 171 | + request_time=request_time, |
| 172 | + request_datetime=request_datetime, |
| 173 | + completions=completions, |
| 174 | + embedding=[], |
| 175 | + ) |
0 commit comments