|
19 | 19 |
|
20 | 20 | import contextlib |
21 | 21 | import gc |
| 22 | +import json |
22 | 23 | import os |
| 24 | +import subprocess |
| 25 | +import sys |
| 26 | +import time |
23 | 27 | from typing import Any, List, Optional, Tuple, TypeVar, Union |
24 | 28 |
|
| 29 | +import httpx |
25 | 30 | import numpy as np |
| 31 | +import openai |
26 | 32 | import pytest |
| 33 | +import requests |
27 | 34 | import torch |
28 | 35 | from modelscope import snapshot_download # type: ignore[import-untyped] |
29 | 36 | from PIL import Image |
|
33 | 40 | from transformers.models.auto.auto_factory import _BaseAutoModelClass |
34 | 41 | from vllm import LLM, SamplingParams |
35 | 42 | from vllm.config.model import TaskOption, _get_and_verify_dtype |
| 43 | +from vllm.engine.arg_utils import AsyncEngineArgs |
| 44 | +from vllm.entrypoints.cli.serve import ServeSubcommand |
36 | 45 | from vllm.inputs import TextPrompt |
| 46 | +from vllm.model_executor.model_loader import get_model_loader |
37 | 47 | from vllm.outputs import RequestOutput |
| 48 | +from vllm.platforms import current_platform |
38 | 49 | from vllm.transformers_utils.utils import maybe_model_redirect |
| 50 | +from vllm.utils import FlexibleArgumentParser, get_open_port |
39 | 51 |
|
40 | 52 | from tests.e2e.model_utils import (TokensTextLogprobs, |
41 | 53 | TokensTextLogprobsPromptLogprobs) |
@@ -76,6 +88,181 @@ def cleanup_dist_env_and_memory(shutdown_ray: bool = False): |
76 | 88 | torch.npu.reset_peak_memory_stats() |
77 | 89 |
|
78 | 90 |
|
| 91 | +class RemoteOpenAIServer: |
| 92 | + DUMMY_API_KEY = "token-abc123" # vLLM's OpenAI server does not need API key |
| 93 | + |
| 94 | + def _start_server(self, model: str, vllm_serve_args: list[str], |
| 95 | + env_dict: Optional[dict[str, str]]) -> None: |
| 96 | + """Subclasses override this method to customize server process launch |
| 97 | + """ |
| 98 | + env = os.environ.copy() |
| 99 | + # the current process might initialize npu, |
| 100 | + # to be safe, we should use spawn method |
| 101 | + env['VLLM_WORKER_MULTIPROC_METHOD'] = 'spawn' |
| 102 | + if env_dict is not None: |
| 103 | + env.update(env_dict) |
| 104 | + self.proc: subprocess.Popen = subprocess.Popen( |
| 105 | + ["vllm", "serve", model, *vllm_serve_args], |
| 106 | + env=env, |
| 107 | + stdout=sys.stdout, |
| 108 | + stderr=sys.stderr, |
| 109 | + ) |
| 110 | + |
| 111 | + def __init__(self, |
| 112 | + model: str, |
| 113 | + server_host: str, |
| 114 | + server_port: int, |
| 115 | + vllm_serve_args: list[str], |
| 116 | + *, |
| 117 | + env_dict: Optional[dict[str, str]] = None, |
| 118 | + seed: Optional[int] = 0, |
| 119 | + auto_port: bool = True, |
| 120 | + max_wait_seconds: Optional[float] = None, |
| 121 | + override_hf_configs: Optional[dict[str, Any]] = None) -> None: |
| 122 | + if auto_port: |
| 123 | + if "-p" in vllm_serve_args or "--port" in vllm_serve_args: |
| 124 | + raise ValueError("You have manually specified the port " |
| 125 | + "when `auto_port=True`.") |
| 126 | + |
| 127 | + # No need for a port if using unix sockets |
| 128 | + if "--uds" not in vllm_serve_args: |
| 129 | + # Don't mutate the input args |
| 130 | + vllm_serve_args = vllm_serve_args + [ |
| 131 | + "--port", str(get_open_port()) |
| 132 | + ] |
| 133 | + if seed is not None: |
| 134 | + if "--seed" in vllm_serve_args: |
| 135 | + raise ValueError("You have manually specified the seed " |
| 136 | + f"when `seed={seed}`.") |
| 137 | + |
| 138 | + vllm_serve_args = vllm_serve_args + ["--seed", str(seed)] |
| 139 | + |
| 140 | + if override_hf_configs is not None: |
| 141 | + vllm_serve_args = vllm_serve_args + [ |
| 142 | + "--hf-overrides", |
| 143 | + json.dumps(override_hf_configs) |
| 144 | + ] |
| 145 | + |
| 146 | + parser = FlexibleArgumentParser( |
| 147 | + description="vLLM's remote OpenAI server.") |
| 148 | + subparsers = parser.add_subparsers(required=False, dest="subparser") |
| 149 | + parser = ServeSubcommand().subparser_init(subparsers) |
| 150 | + args = parser.parse_args([*vllm_serve_args]) |
| 151 | + self.uds = args.uds |
| 152 | + if args.uds: |
| 153 | + self.host = None |
| 154 | + self.port = None |
| 155 | + else: |
| 156 | + self.host = str(server_host) |
| 157 | + self.port = int(server_port) |
| 158 | + |
| 159 | + self.show_hidden_metrics = \ |
| 160 | + args.show_hidden_metrics_for_version is not None |
| 161 | + |
| 162 | + # download the model before starting the server to avoid timeout |
| 163 | + is_local = os.path.isdir(model) |
| 164 | + if not is_local: |
| 165 | + engine_args = AsyncEngineArgs.from_cli_args(args) |
| 166 | + model_config = engine_args.create_model_config() |
| 167 | + load_config = engine_args.create_load_config() |
| 168 | + |
| 169 | + model_loader = get_model_loader(load_config) |
| 170 | + model_loader.download_model(model_config) |
| 171 | + |
| 172 | + self._start_server(model, vllm_serve_args, env_dict) |
| 173 | + max_wait_seconds = max_wait_seconds or 7200 |
| 174 | + self._wait_for_server(url=self.url_for("health"), |
| 175 | + timeout=max_wait_seconds) |
| 176 | + |
| 177 | + def __enter__(self): |
| 178 | + return self |
| 179 | + |
| 180 | + def __exit__(self, exc_type, exc_value, traceback): |
| 181 | + self.proc.terminate() |
| 182 | + try: |
| 183 | + self.proc.wait(8) |
| 184 | + except subprocess.TimeoutExpired: |
| 185 | + # force kill if needed |
| 186 | + self.proc.kill() |
| 187 | + |
| 188 | + def _poll(self) -> Optional[int]: |
| 189 | + """Subclasses override this method to customize process polling""" |
| 190 | + return self.proc.poll() |
| 191 | + |
| 192 | + def hang_until_terminated(self) -> None: |
| 193 | + """ |
| 194 | + Wait until the server process terminates. |
| 195 | + This is for headless mode, where the api server |
| 196 | + process only exists in the leader node. |
| 197 | + """ |
| 198 | + if self.uds: |
| 199 | + client = httpx.Client(transport=httpx.HTTPTransport(uds=self.uds)) |
| 200 | + else: |
| 201 | + client = requests |
| 202 | + |
| 203 | + try: |
| 204 | + while True: |
| 205 | + try: |
| 206 | + resp = client.get(self.url_for("health"), timeout=5) |
| 207 | + if resp.status_code != 200: |
| 208 | + break |
| 209 | + time.sleep(5) |
| 210 | + except Exception: |
| 211 | + break |
| 212 | + finally: |
| 213 | + if isinstance(client, httpx.Client): |
| 214 | + client.close() |
| 215 | + |
| 216 | + def _wait_for_server(self, *, url: str, timeout: float): |
| 217 | + # run health check |
| 218 | + start = time.time() |
| 219 | + client = (httpx.Client(transport=httpx.HTTPTransport( |
| 220 | + uds=self.uds)) if self.uds else requests) |
| 221 | + while True: |
| 222 | + try: |
| 223 | + if client.get(url).status_code == 200: |
| 224 | + break |
| 225 | + except Exception: |
| 226 | + # this exception can only be raised by requests.get, |
| 227 | + # which means the server is not ready yet. |
| 228 | + # the stack trace is not useful, so we suppress it |
| 229 | + # by using `raise from None`. |
| 230 | + result = self._poll() |
| 231 | + if result is not None and result != 0: |
| 232 | + raise RuntimeError("Server exited unexpectedly.") from None |
| 233 | + |
| 234 | + time.sleep(1) |
| 235 | + if time.time() - start > timeout: |
| 236 | + raise RuntimeError( |
| 237 | + "Server failed to start in time.") from None |
| 238 | + |
| 239 | + @property |
| 240 | + def url_root(self) -> str: |
| 241 | + return (f"http://{self.uds.split('/')[-1]}" |
| 242 | + if self.uds else f"http://{self.host}:{self.port}") |
| 243 | + |
| 244 | + def url_for(self, *parts: str) -> str: |
| 245 | + return self.url_root + "/" + "/".join(parts) |
| 246 | + |
| 247 | + def get_client(self, **kwargs): |
| 248 | + if "timeout" not in kwargs: |
| 249 | + kwargs["timeout"] = 600 |
| 250 | + return openai.OpenAI( |
| 251 | + base_url=self.url_for("v1"), |
| 252 | + api_key=self.DUMMY_API_KEY, |
| 253 | + max_retries=0, |
| 254 | + **kwargs, |
| 255 | + ) |
| 256 | + |
| 257 | + def get_async_client(self, **kwargs): |
| 258 | + if "timeout" not in kwargs: |
| 259 | + kwargs["timeout"] = 600 |
| 260 | + return openai.AsyncOpenAI(base_url=self.url_for("v1"), |
| 261 | + api_key=self.DUMMY_API_KEY, |
| 262 | + max_retries=0, |
| 263 | + **kwargs) |
| 264 | + |
| 265 | + |
79 | 266 | class VllmRunner: |
80 | 267 |
|
81 | 268 | def __init__( |
@@ -289,7 +476,6 @@ def __exit__(self, exc_type, exc_value, traceback): |
289 | 476 | class HfRunner: |
290 | 477 |
|
291 | 478 | def get_default_device(self): |
292 | | - from vllm.platforms import current_platform |
293 | 479 |
|
294 | 480 | return ("cpu" |
295 | 481 | if current_platform.is_cpu() else current_platform.device_type) |
|
0 commit comments