|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +import sys |
| 6 | +import time |
| 7 | +import traceback |
| 8 | +from dataclasses import dataclass, field |
| 9 | +from typing import List, Optional, Union |
| 10 | + |
| 11 | +import aiohttp |
| 12 | +import huggingface_hub.constants |
| 13 | +from tqdm.asyncio import tqdm |
| 14 | +from transformers import (AutoTokenizer, PreTrainedTokenizer, |
| 15 | + PreTrainedTokenizerFast) |
| 16 | + |
| 17 | +AIOHTTP_TIMEOUT = aiohttp.ClientTimeout(total=6 * 60 * 60) |
| 18 | + |
| 19 | + |
| 20 | +@dataclass |
| 21 | +class RequestFuncInput: |
| 22 | + prompt: str |
| 23 | + api_url: str |
| 24 | + prompt_len: int |
| 25 | + output_len: int |
| 26 | + model: str |
| 27 | + model_name: Optional[str] = None |
| 28 | + best_of: int = 1 |
| 29 | + logprobs: Optional[int] = None |
| 30 | + extra_body: Optional[dict] = None |
| 31 | + multi_modal_content: Optional[dict] = None |
| 32 | + ignore_eos: bool = False |
| 33 | + |
| 34 | + |
| 35 | +@dataclass |
| 36 | +class RequestFuncOutput: |
| 37 | + generated_text: str = "" |
| 38 | + success: bool = False |
| 39 | + latency: float = 0.0 |
| 40 | + output_tokens: int = 0 |
| 41 | + ttft: float = 0.0 # Time to first token |
| 42 | + itl: List[float] = field( |
| 43 | + default_factory=list) # List of inter-token latencies |
| 44 | + tpot: float = 0.0 # avg next-token latencies |
| 45 | + prompt_len: int = 0 |
| 46 | + error: str = "" |
| 47 | + |
| 48 | + |
| 49 | +async def async_request_openai_completions( |
| 50 | + request_func_input: RequestFuncInput, |
| 51 | + pbar: Optional[tqdm] = None, |
| 52 | +) -> RequestFuncOutput: |
| 53 | + api_url = request_func_input.api_url |
| 54 | + assert api_url.endswith( |
| 55 | + ("completions", "profile") |
| 56 | + ), "OpenAI Completions API URL must end with 'completions' or 'profile'." |
| 57 | + |
| 58 | + async with aiohttp.ClientSession(trust_env=True, |
| 59 | + timeout=AIOHTTP_TIMEOUT) as session: |
| 60 | + payload = { |
| 61 | + "model": request_func_input.model_name \ |
| 62 | + if request_func_input.model_name else request_func_input.model, |
| 63 | + "prompt": request_func_input.prompt, |
| 64 | + "temperature": 0.0, |
| 65 | + "best_of": request_func_input.best_of, |
| 66 | + "max_tokens": request_func_input.output_len, |
| 67 | + "logprobs": request_func_input.logprobs, |
| 68 | + "stream": True, |
| 69 | + "stream_options": { |
| 70 | + "include_usage": True, |
| 71 | + }, |
| 72 | + } |
| 73 | + if request_func_input.ignore_eos: |
| 74 | + payload["ignore_eos"] = request_func_input.ignore_eos |
| 75 | + if request_func_input.extra_body: |
| 76 | + payload.update(request_func_input.extra_body) |
| 77 | + headers = { |
| 78 | + "Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}" |
| 79 | + } |
| 80 | + |
| 81 | + output = RequestFuncOutput() |
| 82 | + output.prompt_len = request_func_input.prompt_len |
| 83 | + |
| 84 | + generated_text = "" |
| 85 | + st = time.perf_counter() |
| 86 | + most_recent_timestamp = st |
| 87 | + try: |
| 88 | + async with session.post(url=api_url, json=payload, |
| 89 | + headers=headers) as response: |
| 90 | + if response.status == 200: |
| 91 | + first_chunk_received = False |
| 92 | + async for chunk_bytes in response.content: |
| 93 | + chunk_bytes = chunk_bytes.strip() |
| 94 | + if not chunk_bytes: |
| 95 | + continue |
| 96 | + |
| 97 | + chunk = chunk_bytes.decode("utf-8").removeprefix( |
| 98 | + "data: ") |
| 99 | + if chunk != "[DONE]": |
| 100 | + data = json.loads(chunk) |
| 101 | + |
| 102 | + # NOTE: Some completion API might have a last |
| 103 | + # usage summary response without a token so we |
| 104 | + # want to check a token was generated |
| 105 | + if choices := data.get("choices"): |
| 106 | + # Note that text could be empty here |
| 107 | + # e.g. for special tokens |
| 108 | + text = choices[0].get("text") |
| 109 | + timestamp = time.perf_counter() |
| 110 | + # First token |
| 111 | + if not first_chunk_received: |
| 112 | + first_chunk_received = True |
| 113 | + ttft = time.perf_counter() - st |
| 114 | + output.ttft = ttft |
| 115 | + |
| 116 | + # Decoding phase |
| 117 | + else: |
| 118 | + output.itl.append(timestamp - |
| 119 | + most_recent_timestamp) |
| 120 | + |
| 121 | + most_recent_timestamp = timestamp |
| 122 | + generated_text += text or "" |
| 123 | + elif usage := data.get("usage"): |
| 124 | + output.output_tokens = usage.get( |
| 125 | + "completion_tokens") |
| 126 | + if first_chunk_received: |
| 127 | + output.success = True |
| 128 | + else: |
| 129 | + output.success = False |
| 130 | + output.error = ( |
| 131 | + "Never received a valid chunk to calculate TTFT." |
| 132 | + "This response will be marked as failed!") |
| 133 | + output.generated_text = generated_text |
| 134 | + output.latency = most_recent_timestamp - st |
| 135 | + else: |
| 136 | + output.error = response.reason or "" |
| 137 | + output.success = False |
| 138 | + except Exception: |
| 139 | + output.success = False |
| 140 | + exc_info = sys.exc_info() |
| 141 | + output.error = "".join(traceback.format_exception(*exc_info)) |
| 142 | + |
| 143 | + if pbar: |
| 144 | + pbar.update(1) |
| 145 | + return output |
| 146 | + |
| 147 | + |
| 148 | +def get_model(pretrained_model_name_or_path: str) -> str: |
| 149 | + if os.getenv('VLLM_USE_MODELSCOPE', 'False').lower() == 'true': |
| 150 | + from modelscope import snapshot_download |
| 151 | + |
| 152 | + model_path = snapshot_download( |
| 153 | + model_id=pretrained_model_name_or_path, |
| 154 | + local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE, |
| 155 | + ignore_file_pattern=[".*.pt", ".*.safetensors", ".*.bin"]) |
| 156 | + |
| 157 | + return model_path |
| 158 | + return pretrained_model_name_or_path |
| 159 | + |
| 160 | +def get_tokenizer( |
| 161 | + pretrained_model_name_or_path: str, |
| 162 | + tokenizer_mode: str = "auto", |
| 163 | + trust_remote_code: bool = False, |
| 164 | + **kwargs, |
| 165 | +) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]: |
| 166 | + if pretrained_model_name_or_path is not None and not os.path.exists( |
| 167 | + pretrained_model_name_or_path): |
| 168 | + pretrained_model_name_or_path = get_model( |
| 169 | + pretrained_model_name_or_path) |
| 170 | + if tokenizer_mode == "slow": |
| 171 | + if kwargs.get("use_fast", False): |
| 172 | + raise ValueError( |
| 173 | + "Cannot use the fast tokenizer in slow tokenizer mode.") |
| 174 | + kwargs["use_fast"] = False |
| 175 | + if tokenizer_mode == "mistral": |
| 176 | + try: |
| 177 | + from vllm.transformers_utils.tokenizer import MistralTokenizer |
| 178 | + except ImportError as e: |
| 179 | + raise ImportError("MistralTokenizer requires vllm package.\n" |
| 180 | + "Please install it with `pip install vllm` " |
| 181 | + "to use mistral tokenizer mode.") from e |
| 182 | + return MistralTokenizer.from_pretrained( |
| 183 | + str(pretrained_model_name_or_path)) |
| 184 | + else: |
| 185 | + return AutoTokenizer.from_pretrained( |
| 186 | + pretrained_model_name_or_path, |
| 187 | + trust_remote_code=trust_remote_code, |
| 188 | + **kwargs, |
| 189 | + ) |
| 190 | + |
| 191 | +ASYNC_REQUEST_FUNCS = { |
| 192 | + "vllm": async_request_openai_completions, |
| 193 | +} |
0 commit comments