utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import functools
  2. import os
  3. import signal
  4. import subprocess
  5. import sys
  6. import time
  7. import warnings
  8. from contextlib import contextmanager
  9. from pathlib import Path
  10. from typing import Any, Callable, Dict, List, Optional
  11. import openai
  12. import requests
  13. from openai.types.completion import Completion
  14. from transformers import AutoTokenizer
  15. from typing_extensions import ParamSpec
  16. from aphrodite.common.utils import (FlexibleArgumentParser, get_open_port,
  17. is_hip)
  18. from aphrodite.distributed import (ensure_model_parallel_initialized,
  19. init_distributed_environment)
  20. from aphrodite.endpoints.openai.args import make_arg_parser
  21. from aphrodite.engine.args_tools import AsyncEngineArgs
  22. from aphrodite.modeling.model_loader.loader import DefaultModelLoader
  23. from aphrodite.platforms import current_platform
  24. from tests.models.utils import TextTextLogprobs
  25. if current_platform.is_rocm():
  26. from amdsmi import (amdsmi_get_gpu_vram_usage,
  27. amdsmi_get_processor_handles, amdsmi_init,
  28. amdsmi_shut_down)
  29. @contextmanager
  30. def _nvml():
  31. try:
  32. amdsmi_init()
  33. yield
  34. finally:
  35. amdsmi_shut_down()
  36. elif current_platform.is_cuda():
  37. from pynvml import (nvmlDeviceGetHandleByIndex, nvmlDeviceGetMemoryInfo,
  38. nvmlInit, nvmlShutdown)
  39. @contextmanager
  40. def _nvml():
  41. try:
  42. nvmlInit()
  43. yield
  44. finally:
  45. nvmlShutdown()
  46. else:
  47. @contextmanager
  48. def _nvml():
  49. yield
  50. APHRODITE_PATH = Path(__file__).parent.parent
  51. """Path to root of the Aphrodite repository."""
  52. class RemoteOpenAIServer:
  53. DUMMY_API_KEY = "token-abc123"
  54. def __init__(self,
  55. model: str,
  56. aphrodite_serve_args: List[str],
  57. *,
  58. env_dict: Optional[Dict[str, str]] = None,
  59. auto_port: bool = True,
  60. max_wait_seconds: Optional[float] = None) -> None:
  61. if auto_port:
  62. if "-p" in aphrodite_serve_args or "--port" in aphrodite_serve_args:
  63. raise ValueError("You have manually specified the port "
  64. "when `auto_port=True`.")
  65. # Don't mutate the input args
  66. aphrodite_serve_args = aphrodite_serve_args + [
  67. "--port", str(get_open_port())
  68. ]
  69. parser = FlexibleArgumentParser(
  70. description="Aphrodite's remote OpenAI server.")
  71. parser = make_arg_parser(parser)
  72. args = parser.parse_args(["--model", model, *aphrodite_serve_args])
  73. self.host = str(args.host or 'localhost')
  74. self.port = int(args.port)
  75. # download the model before starting the server to avoid timeout
  76. is_local = os.path.isdir(model)
  77. if not is_local:
  78. engine_args = AsyncEngineArgs.from_cli_args(args)
  79. engine_config = engine_args.create_engine_config()
  80. dummy_loader = DefaultModelLoader(engine_config.load_config)
  81. dummy_loader._prepare_weights(engine_config.model_config.model,
  82. engine_config.model_config.revision,
  83. fall_back_to_pt=True)
  84. env = os.environ.copy()
  85. # the current process might initialize cuda,
  86. # to be safe, we should use spawn method
  87. env['APHRODITE_WORKER_MULTIPROC_METHOD'] = 'spawn'
  88. if env_dict is not None:
  89. env.update(env_dict)
  90. self.proc = subprocess.Popen(
  91. ["aphrodite", "run", model, *aphrodite_serve_args],
  92. env=env,
  93. stdout=sys.stdout,
  94. stderr=sys.stderr,
  95. )
  96. max_wait_seconds = max_wait_seconds or 240
  97. self._wait_for_server(url=self.url_for("health"),
  98. timeout=max_wait_seconds)
  99. def __enter__(self):
  100. return self
  101. def __exit__(self, exc_type, exc_value, traceback):
  102. self.proc.terminate()
  103. try:
  104. self.proc.wait(3)
  105. except subprocess.TimeoutExpired:
  106. # force kill if needed
  107. self.proc.kill()
  108. def _wait_for_server(self, *, url: str, timeout: float):
  109. # run health check
  110. start = time.time()
  111. while True:
  112. try:
  113. if requests.get(url).status_code == 200:
  114. break
  115. except Exception as err:
  116. result = self.proc.poll()
  117. if result is not None and result != 0:
  118. raise RuntimeError("Server exited unexpectedly.") from err
  119. time.sleep(0.5)
  120. if time.time() - start > timeout:
  121. raise RuntimeError(
  122. "Server failed to start in time.") from err
  123. @property
  124. def url_root(self) -> str:
  125. return f"http://{self.host}:{self.port}"
  126. def url_for(self, *parts: str) -> str:
  127. return self.url_root + "/" + "/".join(parts)
  128. def get_client(self):
  129. return openai.OpenAI(
  130. base_url=self.url_for("v1"),
  131. api_key=self.DUMMY_API_KEY,
  132. )
  133. def get_async_client(self):
  134. return openai.AsyncOpenAI(
  135. base_url=self.url_for("v1"),
  136. api_key=self.DUMMY_API_KEY,
  137. max_retries=0,
  138. )
  139. def compare_two_settings(model: str,
  140. arg1: List[str],
  141. arg2: List[str],
  142. env1: Optional[Dict[str, str]] = None,
  143. env2: Optional[Dict[str, str]] = None,
  144. max_wait_seconds: Optional[float] = None) -> None:
  145. """
  146. Launch API server with two different sets of arguments/environments
  147. and compare the results of the API calls.
  148. Args:
  149. model: The model to test.
  150. arg1: The first set of arguments to pass to the API server.
  151. arg2: The second set of arguments to pass to the API server.
  152. env1: The first set of environment variables to pass to the API server.
  153. env2: The second set of environment variables to pass to the API server.
  154. """
  155. tokenizer = AutoTokenizer.from_pretrained(model)
  156. prompt = "Hello, my name is"
  157. token_ids = tokenizer(prompt)["input_ids"]
  158. results = []
  159. for args, env in ((arg1, env1), (arg2, env2)):
  160. with RemoteOpenAIServer(model,
  161. args,
  162. env_dict=env,
  163. max_wait_seconds=max_wait_seconds) as server:
  164. client = server.get_client()
  165. # test models list
  166. models = client.models.list()
  167. models = models.data
  168. served_model = models[0]
  169. results.append({
  170. "test": "models_list",
  171. "id": served_model.id,
  172. "root": served_model.root,
  173. })
  174. # test with text prompt
  175. completion = client.completions.create(model=model,
  176. prompt=prompt,
  177. max_tokens=5,
  178. temperature=0.0)
  179. results.append({
  180. "test": "single_completion",
  181. "text": completion.choices[0].text,
  182. "finish_reason": completion.choices[0].finish_reason,
  183. "usage": completion.usage,
  184. })
  185. # test using token IDs
  186. completion = client.completions.create(
  187. model=model,
  188. prompt=token_ids,
  189. max_tokens=5,
  190. temperature=0.0,
  191. )
  192. results.append({
  193. "test": "token_ids",
  194. "text": completion.choices[0].text,
  195. "finish_reason": completion.choices[0].finish_reason,
  196. "usage": completion.usage,
  197. })
  198. # test seeded random sampling
  199. completion = client.completions.create(model=model,
  200. prompt=prompt,
  201. max_tokens=5,
  202. seed=33,
  203. temperature=1.0)
  204. results.append({
  205. "test": "seeded_sampling",
  206. "text": completion.choices[0].text,
  207. "finish_reason": completion.choices[0].finish_reason,
  208. "usage": completion.usage,
  209. })
  210. # test seeded random sampling with multiple prompts
  211. completion = client.completions.create(model=model,
  212. prompt=[prompt, prompt],
  213. max_tokens=5,
  214. seed=33,
  215. temperature=1.0)
  216. results.append({
  217. "test":
  218. "seeded_sampling",
  219. "text": [choice.text for choice in completion.choices],
  220. "finish_reason":
  221. [choice.finish_reason for choice in completion.choices],
  222. "usage":
  223. completion.usage,
  224. })
  225. # test simple list
  226. batch = client.completions.create(
  227. model=model,
  228. prompt=[prompt, prompt],
  229. max_tokens=5,
  230. temperature=0.0,
  231. )
  232. results.append({
  233. "test": "simple_list",
  234. "text0": batch.choices[0].text,
  235. "text1": batch.choices[1].text,
  236. })
  237. # test streaming
  238. batch = client.completions.create(
  239. model=model,
  240. prompt=[prompt, prompt],
  241. max_tokens=5,
  242. temperature=0.0,
  243. stream=True,
  244. )
  245. texts = [""] * 2
  246. for chunk in batch:
  247. assert len(chunk.choices) == 1
  248. choice = chunk.choices[0]
  249. texts[choice.index] += choice.text
  250. results.append({
  251. "test": "streaming",
  252. "texts": texts,
  253. })
  254. n = len(results) // 2
  255. arg1_results = results[:n]
  256. arg2_results = results[n:]
  257. for arg1_result, arg2_result in zip(arg1_results, arg2_results):
  258. assert arg1_result == arg2_result, (
  259. f"Results for {model=} are not the same with {arg1=} and {arg2=}. "
  260. f"{arg1_result=} != {arg2_result=}")
  261. def init_test_distributed_environment(
  262. tp_size: int,
  263. pp_size: int,
  264. rank: int,
  265. distributed_init_port: str,
  266. local_rank: int = -1,
  267. ) -> None:
  268. distributed_init_method = f"tcp://localhost:{distributed_init_port}"
  269. init_distributed_environment(
  270. world_size=pp_size * tp_size,
  271. rank=rank,
  272. distributed_init_method=distributed_init_method,
  273. local_rank=local_rank)
  274. ensure_model_parallel_initialized(tp_size, pp_size)
  275. def multi_process_parallel(
  276. tp_size: int,
  277. pp_size: int,
  278. test_target: Any,
  279. ) -> None:
  280. import ray
  281. # Using ray helps debugging the error when it failed
  282. # as compared to multiprocessing.
  283. # NOTE: We need to set working_dir for distributed tests,
  284. # otherwise we may get import errors on ray workers
  285. ray.init(runtime_env={"working_dir": APHRODITE_PATH})
  286. distributed_init_port = get_open_port()
  287. refs = []
  288. for rank in range(tp_size * pp_size):
  289. refs.append(
  290. test_target.remote(tp_size, pp_size, rank, distributed_init_port))
  291. ray.get(refs)
  292. ray.shutdown()
  293. @contextmanager
  294. def error_on_warning():
  295. """
  296. Within the scope of this context manager, tests will fail if any warning
  297. is emitted.
  298. """
  299. with warnings.catch_warnings():
  300. warnings.simplefilter("error")
  301. yield
  302. def get_physical_device_indices(devices):
  303. visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
  304. if visible_devices is None:
  305. return devices
  306. visible_indices = [int(x) for x in visible_devices.split(",")]
  307. index_mapping = {i: physical for i, physical in enumerate(visible_indices)}
  308. return [index_mapping[i] for i in devices if i in index_mapping]
  309. @_nvml()
  310. def wait_for_gpu_memory_to_clear(devices: List[int],
  311. threshold_bytes: int,
  312. timeout_s: float = 120) -> None:
  313. # Use nvml instead of pytorch to reduce measurement error from torch cuda
  314. # context.
  315. devices = get_physical_device_indices(devices)
  316. start_time = time.time()
  317. while True:
  318. output: Dict[int, str] = {}
  319. output_raw: Dict[int, float] = {}
  320. for device in devices:
  321. if is_hip():
  322. dev_handle = amdsmi_get_processor_handles()[device]
  323. mem_info = amdsmi_get_gpu_vram_usage(dev_handle)
  324. gb_used = mem_info["vram_used"] / 2**10
  325. else:
  326. dev_handle = nvmlDeviceGetHandleByIndex(device)
  327. mem_info = nvmlDeviceGetMemoryInfo(dev_handle)
  328. gb_used = mem_info.used / 2**30
  329. output_raw[device] = gb_used
  330. output[device] = f'{gb_used:.02f}'
  331. print('gpu memory used (GB): ', end='')
  332. for k, v in output.items():
  333. print(f'{k}={v}; ', end='')
  334. print('')
  335. dur_s = time.time() - start_time
  336. if all(v <= (threshold_bytes / 2**30) for v in output_raw.values()):
  337. print(f'Done waiting for free GPU memory on devices {devices=} '
  338. f'({threshold_bytes/2**30=}) {dur_s=:.02f}')
  339. break
  340. if dur_s >= timeout_s:
  341. raise ValueError(f'Memory of devices {devices=} not free after '
  342. f'{dur_s=:.02f} ({threshold_bytes/2**30=})')
  343. time.sleep(5)
  344. _P = ParamSpec("_P")
  345. def fork_new_process_for_each_test(
  346. f: Callable[_P, None]) -> Callable[_P, None]:
  347. """Decorator to fork a new process for each test function.
  348. """
  349. @functools.wraps(f)
  350. def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None:
  351. # Make the process the leader of its own process group
  352. # to avoid sending SIGTERM to the parent process
  353. os.setpgrp()
  354. from _pytest.outcomes import Skipped
  355. pid = os.fork()
  356. print(f"Fork a new process to run a test {pid}")
  357. if pid == 0:
  358. try:
  359. f(*args, **kwargs)
  360. except Skipped as e:
  361. # convert Skipped to exit code 0
  362. print(str(e))
  363. os._exit(0)
  364. except Exception:
  365. import traceback
  366. traceback.print_exc()
  367. os._exit(1)
  368. else:
  369. os._exit(0)
  370. else:
  371. pgid = os.getpgid(pid)
  372. _pid, _exitcode = os.waitpid(pid, 0)
  373. # ignore SIGTERM signal itself
  374. old_signal_handler = signal.signal(signal.SIGTERM, signal.SIG_IGN)
  375. # kill all child processes
  376. os.killpg(pgid, signal.SIGTERM)
  377. # restore the signal handler
  378. signal.signal(signal.SIGTERM, old_signal_handler)
  379. assert _exitcode == 0, (f"function {f} failed when called with"
  380. f" args {args} and kwargs {kwargs}")
  381. return wrapper
  382. async def completions_with_server_args(
  383. prompts: List[str],
  384. model_name: str,
  385. server_cli_args: List[str],
  386. num_logprobs: Optional[int],
  387. max_wait_seconds: int = 240,
  388. ) -> Completion:
  389. '''Construct a remote OpenAI server, obtain an async client to the
  390. server & invoke the completions API to obtain completions.
  391. Args:
  392. prompts: test prompts
  393. model_name: model to spin up on the Aphrodite server
  394. server_cli_args: CLI args for starting the server
  395. num_logprobs: Number of logprobs to report (or `None`)
  396. max_wait_seconds: timeout interval for bringing up server.
  397. Default: 240sec
  398. Returns:
  399. OpenAI Completion instance
  400. '''
  401. outputs = None
  402. with RemoteOpenAIServer(model_name,
  403. server_cli_args,
  404. max_wait_seconds=max_wait_seconds) as server:
  405. client = server.get_async_client()
  406. outputs = await client.completions.create(model=model_name,
  407. prompt=prompts,
  408. temperature=0,
  409. stream=False,
  410. max_tokens=5,
  411. logprobs=num_logprobs)
  412. assert outputs is not None
  413. return outputs
  414. def get_client_text_generations(completions: Completion) -> List[str]:
  415. '''Extract generated tokens from the output of a
  416. request made to an Open-AI-protocol completions endpoint.
  417. '''
  418. return [x.text for x in completions.choices]
  419. def get_client_text_logprob_generations(
  420. completions: Completion) -> List[TextTextLogprobs]:
  421. '''Operates on the output of a request made to an Open-AI-protocol
  422. completions endpoint; obtains top-rank logprobs for each token in
  423. each :class:`SequenceGroup`
  424. '''
  425. text_generations = get_client_text_generations(completions)
  426. text = ''.join(text_generations)
  427. return [(text_generations, text,
  428. (None if x.logprobs is None else x.logprobs.top_logprobs))
  429. for x in completions.choices]