utils.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. import asyncio
  2. import datetime
  3. import enum
  4. import gc
  5. import os
  6. import socket
  7. import subprocess
  8. import sys
  9. import tempfile
  10. import threading
  11. import uuid
  12. import warnings
  13. from collections import defaultdict
  14. from functools import lru_cache, partial, wraps
  15. from platform import uname
  16. from typing import (Any, AsyncIterator, Awaitable, Callable, Dict, Generic,
  17. Hashable, List, Optional, OrderedDict, Tuple, TypeVar,
  18. Union)
  19. import numpy as np
  20. import psutil
  21. import torch
  22. from loguru import logger
  23. from aphrodite.common.logger import enable_trace_function_call
  24. T = TypeVar("T")
  25. STR_DTYPE_TO_TORCH_DTYPE = {
  26. "half": torch.half,
  27. "bfloat16": torch.bfloat16,
  28. "float": torch.float,
  29. "fp8": torch.uint8,
  30. "fp8_e4m3": torch.uint8,
  31. "fp8_e5m2": torch.uint8,
  32. }
  33. class Device(enum.Enum):
  34. GPU = enum.auto()
  35. CPU = enum.auto()
  36. class Counter:
  37. def __init__(self, start: int = 0) -> None:
  38. self.counter = start
  39. def __next__(self) -> int:
  40. i = self.counter
  41. self.counter += 1
  42. return i
  43. def reset(self) -> None:
  44. self.counter = 0
  45. class LRUCache(Generic[T]):
  46. def __init__(self, capacity: int):
  47. self.cache: OrderedDict[Hashable, T] = OrderedDict()
  48. self.capacity = capacity
  49. def __contains__(self, key: Hashable) -> bool:
  50. return key in self.cache
  51. def __len__(self) -> int:
  52. return len(self.cache)
  53. def __getitem__(self, key: Hashable) -> Optional[T]:
  54. return self.get(key)
  55. def __setitem__(self, key: Hashable, value: T) -> None:
  56. self.put(key, value)
  57. def __delitem__(self, key: Hashable) -> None:
  58. self.pop(key)
  59. def touch(self, key: Hashable) -> None:
  60. self.cache.move_to_end(key)
  61. def get(self,
  62. key: Hashable,
  63. default_value: Optional[T] = None) -> Optional[T]:
  64. if key in self.cache:
  65. value: Optional[T] = self.cache[key]
  66. self.cache.move_to_end(key)
  67. else:
  68. value = default_value
  69. return value
  70. def put(self, key: Hashable, value: T) -> None:
  71. self.cache[key] = value
  72. self.cache.move_to_end(key)
  73. self._remove_old_if_needed()
  74. def _on_remove(self, key: Hashable, value: Optional[T]):
  75. pass
  76. def remove_oldest(self):
  77. if not self.cache:
  78. return
  79. key, value = self.cache.popitem(last=False)
  80. self._on_remove(key, value)
  81. def _remove_old_if_needed(self) -> None:
  82. while len(self.cache) > self.capacity:
  83. self.remove_oldest()
  84. def pop(self,
  85. key: Hashable,
  86. default_value: Optional[T] = None) -> Optional[T]:
  87. run_on_remove = key in self.cache
  88. value: Optional[T] = self.cache.pop(key, default_value)
  89. if run_on_remove:
  90. self._on_remove(key, value)
  91. return value
  92. def clear(self):
  93. while len(self.cache) > 0:
  94. self.remove_oldest()
  95. self.cache.clear()
  96. def is_hip() -> bool:
  97. return torch.version.hip is not None
  98. @lru_cache(maxsize=None)
  99. def is_cpu() -> bool:
  100. from importlib.metadata import PackageNotFoundError, version
  101. try:
  102. return "cpu" in version("aphrodite-engine")
  103. except PackageNotFoundError:
  104. return False
  105. @lru_cache(maxsize=None)
  106. def is_neuron() -> bool:
  107. try:
  108. import transformers_neuronx
  109. except ImportError:
  110. transformers_neuronx = None
  111. return transformers_neuronx is not None
  112. @lru_cache(maxsize=None)
  113. def is_tpu() -> bool:
  114. try:
  115. import libtpu
  116. except ImportError:
  117. libtpu = None
  118. return libtpu is not None
  119. @lru_cache(maxsize=None)
  120. def is_xpu() -> bool:
  121. from importlib.metadata import version
  122. is_xpu_flag = "xpu" in version("aphrodite-engine")
  123. # aphrodite is not build with xpu
  124. if not is_xpu_flag:
  125. return False
  126. try:
  127. import intel_extension_for_pytorch as ipex # noqa: F401
  128. _import_ipex = True
  129. except ImportError as e:
  130. logger.warning(f"Import Error for IPEX: {e.msg}")
  131. _import_ipex = False
  132. # ipex dependency is not ready
  133. if not _import_ipex:
  134. logger.warning("not found ipex lib")
  135. return False
  136. return hasattr(torch, "xpu") and torch.xpu.is_available()
  137. @lru_cache(maxsize=None)
  138. def get_max_shared_memory_bytes(gpu: int = 0) -> int:
  139. """Returns the maximum shared memory per thread block in bytes."""
  140. # NOTE: This import statement should be executed lazily since
  141. # the Neuron-X backend does not have the `cuda_utils` module.
  142. from aphrodite import _custom_ops as ops
  143. max_shared_mem = (
  144. ops.get_max_shared_memory_per_block_device_attribute(gpu))
  145. # value 0 will cause MAX_SEQ_LEN become negative and test_attention.py
  146. # will fail
  147. assert max_shared_mem > 0, "max_shared_mem can not be zero"
  148. return int(max_shared_mem)
  149. def get_cpu_memory() -> int:
  150. """Returns the total CPU memory of the node in bytes."""
  151. return psutil.virtual_memory().total
  152. def random_uuid() -> str:
  153. return str(uuid.uuid4().hex)
  154. @lru_cache(maxsize=None)
  155. def get_aphrodite_instance_id():
  156. """
  157. If the environment variable APHRODITE_INSTANCE_ID is set, return it.
  158. Otherwise, return a random UUID.
  159. Instance id represents an instance of the Aphrodite. All processes in the
  160. same instance should have the same instance id.
  161. """
  162. return os.environ.get("APHRODITE_INSTANCE_ID",
  163. f"aphrodite-instance-{random_uuid()}")
  164. @lru_cache(maxsize=None)
  165. def in_wsl() -> bool:
  166. # Reference: https://github.com/microsoft/WSL/issues/4071
  167. return "microsoft" in " ".join(uname()).lower()
  168. def make_async(func: Callable[..., T]) -> Callable[..., Awaitable[T]]:
  169. """Take a blocking function, and run it on in an executor thread.
  170. This function prevents the blocking function from blocking the
  171. asyncio event loop.
  172. The code in this function needs to be thread safe.
  173. """
  174. def _async_wrapper(*args, **kwargs) -> asyncio.Future:
  175. loop = asyncio.get_event_loop()
  176. p_func = partial(func, *args, **kwargs)
  177. return loop.run_in_executor(executor=None, func=p_func)
  178. return _async_wrapper
  179. def merge_async_iterators(
  180. *iterators: AsyncIterator[T]) -> AsyncIterator[Tuple[int, T]]:
  181. """Merge multiple asynchronous iterators into a single iterator.
  182. This method handle the case where some iterators finish before others.
  183. When it yields, it yields a tuple (i, item) where i is the index of the
  184. iterator that yields the item.
  185. """
  186. queue: asyncio.Queue[Union[Tuple[int, T], Exception]] = asyncio.Queue()
  187. finished = [False] * len(iterators)
  188. async def producer(i: int, iterator: AsyncIterator[T]):
  189. try:
  190. async for item in iterator:
  191. await queue.put((i, item))
  192. except Exception as e:
  193. await queue.put(e)
  194. finished[i] = True
  195. _tasks = [
  196. asyncio.create_task(producer(i, iterator))
  197. for i, iterator in enumerate(iterators)
  198. ]
  199. async def consumer():
  200. try:
  201. while not all(finished) or not queue.empty():
  202. item = await queue.get()
  203. if isinstance(item, Exception):
  204. raise item
  205. yield item
  206. except (Exception, asyncio.CancelledError) as e:
  207. for task in _tasks:
  208. if sys.version_info >= (3, 9):
  209. # msg parameter only supported in Python 3.9+
  210. task.cancel(e)
  211. else:
  212. task.cancel()
  213. raise e
  214. await asyncio.gather(*_tasks)
  215. return consumer()
  216. def get_ip() -> str:
  217. host_ip = os.environ.get("HOST_IP")
  218. if host_ip:
  219. return host_ip
  220. # IP is not set, try to get it from the network interface
  221. # try ipv4
  222. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  223. try:
  224. s.connect(("8.8.8.8", 80)) # Doesn't need to be reachable
  225. return s.getsockname()[0]
  226. except Exception:
  227. pass
  228. # try ipv6
  229. try:
  230. s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  231. # Google's public DNS server, see
  232. # https://developers.google.com/speed/public-dns/docs/using#addresses
  233. s.connect(("2001:4860:4860::8888", 80)) # Doesn't need to be reachable
  234. return s.getsockname()[0]
  235. except Exception:
  236. pass
  237. warnings.warn(
  238. "Failed to get the IP address, using 0.0.0.0 by default."
  239. "The value can be set by the environment variable HOST_IP.",
  240. stacklevel=2)
  241. return "0.0.0.0"
  242. def get_distributed_init_method(ip: str, port: int) -> str:
  243. # Brackets are not permitted in ipv4 addresses,
  244. # see https://github.com/python/cpython/issues/103848
  245. return f"tcp://[{ip}]:{port}" if ":" in ip else f"tcp://{ip}:{port}"
  246. def get_open_port() -> int:
  247. # try ipv4
  248. try:
  249. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  250. s.bind(("", 0))
  251. return s.getsockname()[1]
  252. except OSError:
  253. # try ipv6
  254. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
  255. s.bind(("", 0))
  256. return s.getsockname()[1]
  257. def update_environment_variables(envs: Dict[str, str]):
  258. for k, v in envs.items():
  259. if k in os.environ and os.environ[k] != v:
  260. logger.warning(f"Overwriting environment variable {k} "
  261. f"from '{os.environ[k]}' to '{v}'")
  262. os.environ[k] = v
  263. def chunk_list(lst, chunk_size):
  264. """Yield successive chunk_size chunks from lst."""
  265. return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
  266. def cdiv(a: int, b: int) -> int:
  267. """Ceiling division."""
  268. return -(a // -b)
  269. def _generate_random_fp8(
  270. tensor: torch.tensor,
  271. low: float,
  272. high: float,
  273. ) -> None:
  274. # NOTE: Due to NaN and Inf representation for fp8 data type,
  275. # it may occur Inf or NaN if we directly use torch.randint
  276. # to generate random data for fp8 data.
  277. # For example, s.11111.00 in fp8e5m2 format represents Inf.
  278. # | E4M3 | E5M2
  279. #-----|-------------|-------------------
  280. # Inf | N/A | s.11111.00
  281. # NaN | s.1111.111 | s.11111.{01,10,11}
  282. from aphrodite import _custom_ops as ops
  283. tensor_tmp = torch.empty_like(tensor, dtype=torch.float16)
  284. tensor_tmp.uniform_(low, high)
  285. ops.convert_fp8(tensor, tensor_tmp)
  286. del tensor_tmp
  287. def get_kv_cache_torch_dtype(
  288. cache_dtype: Optional[Union[str, torch.dtype]],
  289. model_dtype: Optional[Union[str, torch.dtype]] = None) -> torch.dtype:
  290. if isinstance(cache_dtype, str):
  291. if cache_dtype == "auto":
  292. if isinstance(model_dtype, str):
  293. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[model_dtype]
  294. elif isinstance(model_dtype, torch.dtype):
  295. torch_dtype = model_dtype
  296. else:
  297. raise ValueError(f"Invalid model dtype: {model_dtype}")
  298. elif cache_dtype in ["half", "bfloat16", "float"]:
  299. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype]
  300. elif cache_dtype == "fp8":
  301. torch_dtype = torch.uint8
  302. else:
  303. raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
  304. elif isinstance(cache_dtype, torch.dtype):
  305. torch_dtype = cache_dtype
  306. else:
  307. raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
  308. return torch_dtype
  309. def create_kv_caches_with_random_flash(
  310. num_blocks: int,
  311. block_size: int,
  312. num_layers: int,
  313. num_heads: int,
  314. head_size: int,
  315. cache_dtype: Optional[Union[str, torch.dtype]],
  316. model_dtype: Optional[Union[str, torch.dtype]] = None,
  317. seed: int = 0,
  318. device: Optional[str] = "cuda",
  319. ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
  320. assert cache_dtype != "fp8"
  321. torch.random.manual_seed(seed)
  322. if torch.cuda.is_available():
  323. torch.cuda.manual_seed(seed)
  324. torch_dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype)
  325. key_value_cache_shape = (num_blocks, 2, block_size, num_heads, head_size)
  326. scale = head_size**-0.5
  327. key_caches, value_caches = [], []
  328. for _ in range(num_layers):
  329. key_value_cache = torch.empty(size=key_value_cache_shape,
  330. dtype=torch_dtype,
  331. device=device)
  332. key_value_cache.uniform_(-scale, scale)
  333. key_caches.append(key_value_cache[:, 0])
  334. value_caches.append(key_value_cache[:, 1])
  335. return key_caches, value_caches
  336. def create_kv_caches_with_random(
  337. num_blocks: int,
  338. block_size: int,
  339. num_layers: int,
  340. num_heads: int,
  341. head_size: int,
  342. cache_dtype: Optional[Union[str, torch.dtype]],
  343. model_dtype: Optional[Union[str, torch.dtype]] = None,
  344. seed: int = 0,
  345. device: Optional[str] = "cuda",
  346. ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
  347. torch.random.manual_seed(seed)
  348. if torch.cuda.is_available():
  349. torch.cuda.manual_seed(seed)
  350. torch_dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype)
  351. scale = head_size**-0.5
  352. x = 16 // torch.tensor([], dtype=torch_dtype).element_size()
  353. key_cache_shape = (num_blocks, num_heads, head_size // x, block_size, x)
  354. key_caches = []
  355. for _ in range(num_layers):
  356. key_cache = torch.empty(size=key_cache_shape,
  357. dtype=torch_dtype,
  358. device=device)
  359. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  360. key_cache.uniform_(-scale, scale)
  361. elif cache_dtype == 'fp8':
  362. _generate_random_fp8(key_cache, -scale, scale)
  363. else:
  364. raise ValueError(
  365. f"Does not support key cache of type {cache_dtype}")
  366. key_caches.append(key_cache)
  367. value_cache_shape = (num_blocks, num_heads, head_size, block_size)
  368. value_caches = []
  369. for _ in range(num_layers):
  370. value_cache = torch.empty(size=value_cache_shape,
  371. dtype=torch_dtype,
  372. device=device)
  373. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  374. value_cache.uniform_(-scale, scale)
  375. elif cache_dtype == 'fp8':
  376. _generate_random_fp8(value_cache, -scale, scale)
  377. else:
  378. raise ValueError(
  379. f"Does not support value cache of type {cache_dtype}")
  380. value_caches.append(value_cache)
  381. return key_caches, value_caches
  382. @lru_cache
  383. def print_warning_once(msg: str) -> None:
  384. logger.warning(msg)
  385. @lru_cache(maxsize=None)
  386. def is_pin_memory_available() -> bool:
  387. if in_wsl():
  388. # Pinning memory in WSL is not supported.
  389. # https://docs.nvidia.com/cuda/wsl-user-guide/index.html#known-limitations-for-linux-cuda-applications
  390. print_warning_once("Using 'pin_memory=False' as WSL is detected. "
  391. "This may slow down the performance.")
  392. return False
  393. elif is_xpu():
  394. print_warning_once("Pin memory is not supported on XPU.")
  395. return False
  396. elif is_neuron():
  397. print_warning_once("Pin memory is not supported on Neuron.")
  398. return False
  399. elif is_cpu():
  400. return False
  401. return True
  402. class CudaMemoryProfiler:
  403. def __init__(self, device=None):
  404. self.device = device
  405. def current_memory_usage(self) -> float:
  406. # Return the memory usage in bytes.
  407. if torch.cuda.is_available():
  408. torch.cuda.reset_peak_memory_stats(self.device)
  409. mem = torch.cuda.max_memory_allocated(self.device)
  410. elif is_xpu():
  411. torch.xpu.reset_peak_memory_stats(self.device)
  412. mem = torch.xpu.max_memory_allocated(self.device)
  413. return mem
  414. def __enter__(self):
  415. self.initial_memory = self.current_memory_usage()
  416. # This allows us to call methods of the context manager if needed
  417. return self
  418. def __exit__(self, exc_type, exc_val, exc_tb):
  419. self.final_memory = self.current_memory_usage()
  420. self.consumed_memory = self.final_memory - self.initial_memory
  421. # Force garbage collection
  422. gc.collect()
  423. def str_to_int_tuple(s: str) -> Tuple[int, ...]:
  424. """Convert a string to a tuple of integers."""
  425. try:
  426. return tuple(map(int, s.split(",")))
  427. except ValueError as e:
  428. raise ValueError(
  429. "String must be a series of integers separated by commas "
  430. f"(e.g., 1, 2, 3). Given input: {s}") from e
  431. def make_tensor_with_pad(
  432. x: List[List[int]],
  433. max_len: int,
  434. pad: int,
  435. dtype: torch.dtype,
  436. device: Optional[Union[str, torch.device]],
  437. ) -> torch.Tensor:
  438. """Make a padded tensor of a 2D inputs.
  439. The padding is applied to the end of each inner list until it reaches
  440. `max_len`.
  441. """
  442. padded_x = np.zeros([len(x), max_len], dtype=np.int32) + pad
  443. for ind, blocktb in enumerate(x):
  444. assert len(blocktb) <= max_len
  445. padded_x[ind, :len(blocktb)] = blocktb
  446. return torch.tensor(padded_x, dtype=dtype, device=device)
  447. def async_tensor_h2d(
  448. data: list,
  449. dtype: torch.dtype,
  450. target_device: Union[str, torch.device],
  451. pin_memory: bool,
  452. ) -> torch.Tensor:
  453. """Asynchronously create a tensor and copy it from host to device."""
  454. t = torch.tensor(data, dtype=dtype, pin_memory=pin_memory, device="cpu")
  455. return t.to(device=target_device, non_blocking=True)
  456. def maybe_expand_dim(tensor: torch.Tensor,
  457. target_dims: int,
  458. size: int = 1) -> torch.Tensor:
  459. """Expand the tensor to the target_dims."""
  460. if tensor.ndim < target_dims:
  461. tensor = tensor.view(-1, *([size] * (target_dims - tensor.ndim)))
  462. return tensor
  463. def get_dtype_size(dtype: torch.dtype) -> int:
  464. """Get the size of the data type in bytes."""
  465. return torch.tensor([], dtype=dtype).element_size()
  466. def merge_dicts(dict1: Dict[Any, List[Any]],
  467. dict2: Dict[Any, List[Any]]) -> Dict[Any, List[Any]]:
  468. """Merge 2 dicts that have key -> List of items.
  469. When a key conflicts, the values in dict1 is prioritized.
  470. """
  471. merged_dict = defaultdict(list)
  472. for key, value in dict1.items():
  473. merged_dict[key].extend(value)
  474. for key, value in dict2.items():
  475. merged_dict[key].extend(value)
  476. return dict(merged_dict)
  477. def init_cached_hf_modules():
  478. """
  479. Lazy initialization of the Hugging Face modules.
  480. """
  481. from transformers.dynamic_module_utils import init_hf_modules
  482. init_hf_modules()
  483. @lru_cache(maxsize=None)
  484. def find_library(lib_name: str) -> str:
  485. """
  486. Find the library file in the system.
  487. `lib_name` is full filename, with both prefix and suffix.
  488. This function resolves `lib_name` to the full path of the library.
  489. """
  490. # Adapted from https://github.com/openai/triton/blob/main/third_party/nvidia/backend/driver.py#L19 # noqa
  491. # According to https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
  492. # `/sbin/ldconfig` should exist in all Linux systems.
  493. # `/sbin/ldconfig` searches the library in the system
  494. libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode()
  495. # each line looks like the following:
  496. # libcuda.so.1 (libc6,x86-64) => /lib/x86_64-linux-gnu/libcuda.so.1
  497. locs = [line.split()[-1] for line in libs.splitlines() if lib_name in line]
  498. # `LD_LIBRARY_PATH` searches the library in the user-defined paths
  499. env_ld_library_path = os.getenv("LD_LIBRARY_PATH")
  500. if not locs and env_ld_library_path:
  501. locs = [
  502. os.path.join(dir, lib_name)
  503. for dir in env_ld_library_path.split(":")
  504. if os.path.exists(os.path.join(dir, lib_name))
  505. ]
  506. if not locs:
  507. raise ValueError(f"Cannot find {lib_name} in the system.")
  508. return locs[0]
  509. def find_nccl_library():
  510. """
  511. We either use the library file specified by the `APHRODITE_NCCL_SO_PATH`
  512. environment variable, or we find the library file brought by PyTorch.
  513. After importing `torch`, `libnccl.so.2` or `librccl.so.1` can be
  514. found by `ctypes` automatically.
  515. """
  516. so_file = os.environ.get("APHRODITE_NCCL_SO_PATH", "")
  517. # manually load the nccl library
  518. if so_file:
  519. logger.info("Found nccl from environment variable "
  520. f"APHRODITE_NCCL_SO_PATH={so_file}")
  521. else:
  522. if torch.version.cuda is not None:
  523. so_file = "libnccl.so.2"
  524. elif torch.version.hip is not None:
  525. so_file = "librccl.so.1"
  526. else:
  527. raise ValueError("NCCL only supports CUDA and ROCm backends.")
  528. logger.info(f"Found nccl from library {so_file}")
  529. return so_file
  530. def enable_trace_function_call_for_thread() -> None:
  531. if int(os.getenv("APHRODITE_TRACE_FUNCTION", "0")):
  532. tmp_dir = tempfile.gettempdir()
  533. filename = (f"APHRODITE_TRACE_FUNCTION_for_process_{os.getpid()}"
  534. f"_thread_{threading.get_ident()}_"
  535. f"at_{datetime.datetime.now()}.log").replace(" ", "_")
  536. log_path = os.path.join(tmp_dir, "aphrodite",
  537. get_aphrodite_instance_id(), filename)
  538. os.makedirs(os.path.dirname(log_path), exist_ok=True)
  539. enable_trace_function_call(log_path)
  540. def identity(value: T) -> T:
  541. return value
  542. F = TypeVar('F', bound=Callable[..., Any])
  543. def deprecate_kwargs(
  544. *kws: str,
  545. is_deprecated: Union[bool, Callable[[], bool]] = True,
  546. additional_message: Optional[str] = None) -> Callable[[F], F]:
  547. deprecated_kws = set(kws)
  548. if not callable(is_deprecated):
  549. is_deprecated = partial(identity, is_deprecated)
  550. def wrapper(fn: F) -> F:
  551. @wraps(fn)
  552. def inner(*args, **kwargs):
  553. if is_deprecated():
  554. deprecated_kwargs = kwargs.keys() & deprecated_kws
  555. if deprecated_kwargs:
  556. msg = (
  557. f"The keyword arguments {deprecated_kwargs} are "
  558. "deprecated and will be removed in a future update.")
  559. if additional_message is not None:
  560. msg += f" {additional_message}"
  561. warnings.warn(
  562. DeprecationWarning(msg),
  563. stacklevel=3, # The inner function takes up one level
  564. )
  565. return fn(*args, **kwargs)
  566. return inner # type: ignore
  567. return wrapper
  568. @lru_cache(maxsize=8)
  569. def _cuda_device_count_stateless(
  570. cuda_visible_devices: Optional[str] = None) -> int:
  571. # Note: cuda_visible_devices is not used, but we keep it as an argument for
  572. # LRU Cache purposes.
  573. # Code below is based on
  574. # https://github.com/pytorch/pytorch/blob/
  575. # c1cd946818442aca8c7f812b16d187ce1586c3bc/
  576. # torch/cuda/__init__.py#L831C1-L831C17
  577. import torch.cuda
  578. import torch.version
  579. if not torch.cuda._is_compiled():
  580. return 0
  581. # bypass _device_count_nvml() if rocm (not supported)
  582. nvml_count = -1 if torch.version.hip else torch.cuda._device_count_nvml()
  583. r = torch._C._cuda_getDeviceCount() if nvml_count < 0 else nvml_count
  584. return r
  585. def cuda_device_count_stateless() -> int:
  586. """Get number of CUDA devices, caching based on the value of
  587. CUDA_VISIBLE_DEVICES at the time of call.
  588. This should be used instead of torch.cuda.device_count()
  589. unless CUDA_VISIBLE_DEVICES has already been set to the desired
  590. value."""
  591. # This can be removed and simply replaced with torch.cuda.get_device_count
  592. # after https://github.com/pytorch/pytorch/pull/122815 is released.
  593. return _cuda_device_count_stateless(os.environ.get("CUDA_VISIBLE_DEVICES"))