utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. import asyncio
  2. import datetime
  3. import enum
  4. import gc
  5. import glob
  6. import os
  7. import socket
  8. import subprocess
  9. import tempfile
  10. import threading
  11. import uuid
  12. import warnings
  13. from collections import defaultdict
  14. from functools import lru_cache, partial
  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 psutil
  20. import torch
  21. from loguru import logger
  22. from packaging.version import Version, parse
  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. }
  31. class Device(enum.Enum):
  32. GPU = enum.auto()
  33. CPU = enum.auto()
  34. class Counter:
  35. def __init__(self, start: int = 0) -> None:
  36. self.counter = start
  37. def __next__(self) -> int:
  38. i = self.counter
  39. self.counter += 1
  40. return i
  41. def reset(self) -> None:
  42. self.counter = 0
  43. class LRUCache(Generic[T]):
  44. def __init__(self, capacity: int):
  45. self.cache: OrderedDict[Hashable, T] = OrderedDict()
  46. self.capacity = capacity
  47. def __contains__(self, key: Hashable) -> bool:
  48. return key in self.cache
  49. def __len__(self) -> int:
  50. return len(self.cache)
  51. def __getitem__(self, key: Hashable) -> Optional[T]:
  52. return self.get(key)
  53. def __setitem__(self, key: Hashable, value: T) -> None:
  54. self.put(key, value)
  55. def __delitem__(self, key: Hashable) -> None:
  56. self.pop(key)
  57. def touch(self, key: Hashable) -> None:
  58. self.cache.move_to_end(key)
  59. def get(self,
  60. key: Hashable,
  61. default_value: Optional[T] = None) -> Optional[T]:
  62. if key in self.cache:
  63. value: Optional[T] = self.cache[key]
  64. self.cache.move_to_end(key)
  65. else:
  66. value = default_value
  67. return value
  68. def put(self, key: Hashable, value: T) -> None:
  69. self.cache[key] = value
  70. self.cache.move_to_end(key)
  71. self._remove_old_if_needed()
  72. def _on_remove(self, key: Hashable, value: Optional[T]):
  73. pass
  74. def remove_oldest(self):
  75. if not self.cache:
  76. return
  77. key, value = self.cache.popitem(last=False)
  78. self._on_remove(key, value)
  79. def _remove_old_if_needed(self) -> None:
  80. while len(self.cache) > self.capacity:
  81. self.remove_oldest()
  82. def pop(self,
  83. key: Hashable,
  84. default_value: Optional[T] = None) -> Optional[T]:
  85. run_on_remove = key in self.cache
  86. value: Optional[T] = self.cache.pop(key, default_value)
  87. if run_on_remove:
  88. self._on_remove(key, value)
  89. return value
  90. def clear(self):
  91. while len(self.cache) > 0:
  92. self.remove_oldest()
  93. self.cache.clear()
  94. def is_hip() -> bool:
  95. return torch.version.hip is not None
  96. @lru_cache(maxsize=None)
  97. def is_cpu() -> bool:
  98. from importlib.metadata import PackageNotFoundError, version
  99. try:
  100. return "cpu" in version("aphrodite-engine")
  101. except PackageNotFoundError:
  102. return False
  103. @lru_cache(maxsize=None)
  104. def is_neuron() -> bool:
  105. try:
  106. import transformers_neuronx
  107. except ImportError:
  108. transformers_neuronx = None
  109. return transformers_neuronx is not None
  110. @lru_cache(maxsize=None)
  111. def get_max_shared_memory_bytes(gpu: int = 0) -> int:
  112. """Returns the maximum shared memory per thread block in bytes."""
  113. # NOTE: This import statement should be executed lazily since
  114. # the Neuron-X backend does not have the `cuda_utils` module.
  115. from aphrodite._C import cuda_utils
  116. max_shared_mem = (
  117. cuda_utils.get_max_shared_memory_per_block_device_attribute(gpu))
  118. # value 0 will cause MAX_SEQ_LEN become negative and test_attention.py
  119. # will fail
  120. assert max_shared_mem > 0, "max_shared_mem can not be zero"
  121. return int(max_shared_mem)
  122. def get_cpu_memory() -> int:
  123. """Returns the total CPU memory of the node in bytes."""
  124. return psutil.virtual_memory().total
  125. def random_uuid() -> str:
  126. return str(uuid.uuid4().hex)
  127. @lru_cache(maxsize=None)
  128. def get_aphrodite_instance_id():
  129. """
  130. If the environment variable APHRODITE_INSTANCE_ID is set, return it.
  131. Otherwise, return a random UUID.
  132. Instance id represents an instance of the Aphrodite. All processes in the
  133. same instance should have the same instance id.
  134. """
  135. return os.environ.get("APHRODITE_INSTANCE_ID",
  136. f"aphrodite-instance-{random_uuid()}")
  137. @lru_cache(maxsize=None)
  138. def in_wsl() -> bool:
  139. # Reference: https://github.com/microsoft/WSL/issues/4071
  140. return "microsoft" in " ".join(uname()).lower()
  141. def make_async(func: Callable[..., T]) -> Callable[..., Awaitable[T]]:
  142. """Take a blocking function, and run it on in an executor thread.
  143. This function prevents the blocking function from blocking the
  144. asyncio event loop.
  145. The code in this function needs to be thread safe.
  146. """
  147. def _async_wrapper(*args, **kwargs) -> asyncio.Future:
  148. loop = asyncio.get_event_loop()
  149. p_func = partial(func, *args, **kwargs)
  150. return loop.run_in_executor(executor=None, func=p_func)
  151. return _async_wrapper
  152. def merge_async_iterators(
  153. *iterators: AsyncIterator[T]) -> AsyncIterator[Tuple[int, T]]:
  154. """Merge multiple asynchronous iterators into a single iterator.
  155. This method handle the case where some iterators finish before others.
  156. When it yields, it yields a tuple (i, item) where i is the index of the
  157. iterator that yields the item.
  158. """
  159. queue: asyncio.Queue[Union[Tuple[int, T], Exception]] = asyncio.Queue()
  160. finished = [False] * len(iterators)
  161. async def producer(i: int, iterator: AsyncIterator[T]):
  162. try:
  163. async for item in iterator:
  164. await queue.put((i, item))
  165. except Exception as e:
  166. await queue.put(e)
  167. finished[i] = True
  168. _tasks = [
  169. asyncio.create_task(producer(i, iterator))
  170. for i, iterator in enumerate(iterators)
  171. ]
  172. async def consumer():
  173. while not all(finished) or not queue.empty():
  174. item = await queue.get()
  175. if isinstance(item, Exception):
  176. raise item
  177. yield item
  178. await asyncio.gather(*_tasks)
  179. return consumer()
  180. def get_ip() -> str:
  181. host_ip = os.environ.get("HOST_IP")
  182. if host_ip:
  183. return host_ip
  184. # IP is not set, try to get it from the network interface
  185. # try ipv4
  186. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  187. try:
  188. s.connect(("8.8.8.8", 80)) # Doesn't need to be reachable
  189. return s.getsockname()[0]
  190. except Exception:
  191. pass
  192. # try ipv6
  193. try:
  194. s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  195. # Google's public DNS server, see
  196. # https://developers.google.com/speed/public-dns/docs/using#addresses
  197. s.connect(("2001:4860:4860::8888", 80)) # Doesn't need to be reachable
  198. return s.getsockname()[0]
  199. except Exception:
  200. pass
  201. warnings.warn(
  202. "Failed to get the IP address, using 0.0.0.0 by default."
  203. "The value can be set by the environment variable HOST_IP.",
  204. stacklevel=2)
  205. return "0.0.0.0"
  206. def get_distributed_init_method(ip: str, port: int) -> str:
  207. # Brackets are not permitted in ipv4 addresses,
  208. # see https://github.com/python/cpython/issues/103848
  209. return f"tcp://[{ip}]:{port}" if ":" in ip else f"tcp://{ip}:{port}"
  210. def get_open_port() -> int:
  211. # try ipv4
  212. try:
  213. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  214. s.bind(("", 0))
  215. return s.getsockname()[1]
  216. except OSError:
  217. # try ipv6
  218. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
  219. s.bind(("", 0))
  220. return s.getsockname()[1]
  221. def update_environment_variables(envs: Dict[str, str]):
  222. for k, v in envs.items():
  223. if k in os.environ and os.environ[k] != v:
  224. logger.warning(f"Overwriting environment variable {k} "
  225. f"from '{os.environ[k]}' to '{v}'")
  226. os.environ[k] = v
  227. def chunk_list(lst, chunk_size):
  228. """Yield successive chunk_size chunks from lst."""
  229. return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
  230. def cdiv(a: int, b: int) -> int:
  231. """Ceiling division."""
  232. return -(a // -b)
  233. @lru_cache(maxsize=None)
  234. def get_nvcc_cuda_version() -> Optional[Version]:
  235. cuda_home = os.environ.get('CUDA_HOME')
  236. if not cuda_home:
  237. cuda_home = '/usr/local/cuda'
  238. if os.path.isfile(cuda_home + '/bin/nvcc'):
  239. logger.info(f'CUDA_HOME is not found in the environment. '
  240. f'Using {cuda_home} as CUDA_HOME.')
  241. else:
  242. logger.warning(
  243. f'Not found nvcc in {cuda_home}. Skip cuda version check!')
  244. return None
  245. nvcc_output = subprocess.check_output([cuda_home + "/bin/nvcc", "-V"],
  246. universal_newlines=True)
  247. output = nvcc_output.split()
  248. release_idx = output.index("release") + 1
  249. nvcc_cuda_version = parse(output[release_idx].split(",")[0])
  250. return nvcc_cuda_version
  251. def _generate_random_fp8(
  252. tensor: torch.tensor,
  253. low: float,
  254. high: float,
  255. ) -> None:
  256. # NOTE: Due to NaN and Inf representation for fp8 data type,
  257. # it may occur Inf or NaN if we directly use torch.randint
  258. # to generate random data for fp8 data.
  259. # For example, s.11111.00 in fp8e5m2 format represents Inf.
  260. # | E4M3 | E5M2
  261. #-----|-------------|-------------------
  262. # Inf | N/A | s.11111.00
  263. # NaN | s.1111.111 | s.11111.{01,10,11}
  264. from aphrodite._C import cache_ops
  265. tensor_tmp = torch.empty_like(tensor, dtype=torch.float16)
  266. tensor_tmp.uniform_(low, high)
  267. cache_ops.convert_fp8(tensor_tmp, tensor)
  268. del tensor_tmp
  269. def create_kv_caches_with_random(
  270. num_blocks: int,
  271. block_size: int,
  272. num_layers: int,
  273. num_heads: int,
  274. head_size: int,
  275. cache_dtype: Optional[Union[str, torch.dtype]],
  276. model_dtype: Optional[Union[str, torch.dtype]] = None,
  277. seed: int = 0,
  278. device: Optional[str] = "cuda",
  279. ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
  280. torch.random.manual_seed(seed)
  281. if torch.cuda.is_available():
  282. torch.cuda.manual_seed(seed)
  283. if isinstance(cache_dtype, str):
  284. if cache_dtype == "auto":
  285. if isinstance(model_dtype, str):
  286. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[model_dtype]
  287. elif isinstance(model_dtype, torch.dtype):
  288. torch_dtype = model_dtype
  289. else:
  290. raise ValueError(f"Invalid model dtype: {model_dtype}")
  291. elif cache_dtype in ["half", "bfloat16", "float"]:
  292. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype]
  293. elif cache_dtype == "fp8":
  294. torch_dtype = torch.uint8
  295. else:
  296. raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
  297. elif isinstance(cache_dtype, torch.dtype):
  298. torch_dtype = cache_dtype
  299. else:
  300. raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
  301. scale = head_size**-0.5
  302. x = 16 // torch.tensor([], dtype=torch_dtype).element_size()
  303. key_cache_shape = (num_blocks, num_heads, head_size // x, block_size, x)
  304. key_caches = []
  305. for _ in range(num_layers):
  306. key_cache = torch.empty(size=key_cache_shape,
  307. dtype=torch_dtype,
  308. device=device)
  309. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  310. key_cache.uniform_(-scale, scale)
  311. elif cache_dtype == 'fp8':
  312. _generate_random_fp8(key_cache, -scale, scale)
  313. else:
  314. raise ValueError(
  315. f"Does not support key cache of type {cache_dtype}")
  316. key_caches.append(key_cache)
  317. value_cache_shape = (num_blocks, num_heads, head_size, block_size)
  318. value_caches = []
  319. for _ in range(num_layers):
  320. value_cache = torch.empty(size=value_cache_shape,
  321. dtype=torch_dtype,
  322. device=device)
  323. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  324. value_cache.uniform_(-scale, scale)
  325. elif cache_dtype == 'fp8':
  326. _generate_random_fp8(value_cache, -scale, scale)
  327. else:
  328. raise ValueError(
  329. f"Does not support value cache of type {cache_dtype}")
  330. value_caches.append(value_cache)
  331. return key_caches, value_caches
  332. @lru_cache
  333. def print_warning_once(msg: str) -> None:
  334. logger.warning(msg)
  335. @lru_cache(maxsize=None)
  336. def is_pin_memory_available() -> bool:
  337. if in_wsl():
  338. # Pinning memory in WSL is not supported.
  339. # https://docs.nvidia.com/cuda/wsl-user-guide/index.html#known-limitations-for-linux-cuda-applications
  340. print_warning_once("Using 'pin_memory=False' as WSL is detected. "
  341. "This may slow down the performance.")
  342. return False
  343. elif is_neuron():
  344. print_warning_once("Pin memory is not supported on Neuron.")
  345. return False
  346. elif is_cpu():
  347. return False
  348. return True
  349. class CudaMemoryProfiler:
  350. def __init__(self, device=None):
  351. self.device = device
  352. def current_memory_usage(self) -> float:
  353. # Return the memory usage in bytes.
  354. torch.cuda.reset_peak_memory_stats(self.device)
  355. mem = torch.cuda.max_memory_allocated(self.device)
  356. return mem
  357. def __enter__(self):
  358. self.initial_memory = self.current_memory_usage()
  359. # This allows us to call methods of the context manager if needed
  360. return self
  361. def __exit__(self, exc_type, exc_val, exc_tb):
  362. self.final_memory = self.current_memory_usage()
  363. self.consumed_memory = self.final_memory - self.initial_memory
  364. # Force garbage collection
  365. gc.collect()
  366. def str_to_int_tuple(s: str) -> Tuple[int, ...]:
  367. """Convert a string to a tuple of integers."""
  368. try:
  369. return tuple(map(int, s.split(",")))
  370. except ValueError as e:
  371. raise ValueError(
  372. "String must be a series of integers separated by commas "
  373. f"(e.g., 1, 2, 3). Given input: {s}") from e
  374. def pad_to_max_length(x: List[int], max_len: int, pad: int) -> List[int]:
  375. assert len(x) <= max_len
  376. return x + [pad] * (max_len - len(x))
  377. def make_tensor_with_pad(
  378. x: List[List[int]],
  379. max_len: int,
  380. pad: int,
  381. dtype: torch.dtype,
  382. device: Optional[Union[str, torch.device]],
  383. ) -> torch.Tensor:
  384. """Make a padded tensor of a 2D inputs.
  385. The padding is applied to the end of each inner list until it reaches
  386. `max_len`.
  387. """
  388. padded_x = [pad_to_max_length(x_i, max_len, pad) for x_i in x]
  389. return torch.tensor(padded_x, dtype=dtype, device=device)
  390. def async_tensor_h2d(
  391. data: list,
  392. dtype: torch.dtype,
  393. target_device: Union[str, torch.device],
  394. pin_memory: bool,
  395. ) -> torch.Tensor:
  396. """Asynchronously create a tensor and copy it from host to device."""
  397. t = torch.tensor(data, dtype=dtype, pin_memory=pin_memory, device="cpu")
  398. return t.to(device=target_device, non_blocking=True)
  399. def maybe_expand_dim(tensor: torch.Tensor,
  400. target_dims: int,
  401. size: int = 1) -> torch.Tensor:
  402. """Expand the tensor to the target_dims."""
  403. if tensor.ndim < target_dims:
  404. tensor = tensor.view(-1, *([size] * (target_dims - tensor.ndim)))
  405. return tensor
  406. def merge_dicts(dict1: Dict[Any, List[Any]],
  407. dict2: Dict[Any, List[Any]]) -> Dict[Any, List[Any]]:
  408. """Merge 2 dicts that have key -> List of items.
  409. When a key conflicts, the values in dict1 is prioritized.
  410. """
  411. merged_dict = defaultdict(list)
  412. for key, value in dict1.items():
  413. merged_dict[key].extend(value)
  414. for key, value in dict2.items():
  415. merged_dict[key].extend(value)
  416. return dict(merged_dict)
  417. def init_cached_hf_modules():
  418. """
  419. Lazy initialization of the Hugging Face modules.
  420. """
  421. from transformers.dynamic_module_utils import init_hf_modules
  422. init_hf_modules()
  423. def nccl_integrity_check(filepath):
  424. """
  425. when the library is corrupted, we cannot catch
  426. the exception in python. it will crash the process.
  427. instead, we use the exit code of `ldd` to check
  428. if the library is corrupted. if not, we will return
  429. the version of the library.
  430. """
  431. exit_code = os.system(f"ldd {filepath} 2>&1 > /dev/null")
  432. if exit_code != 0:
  433. raise RuntimeError(f"Failed to load NCCL library from {filepath} .")
  434. import ctypes
  435. nccl = ctypes.CDLL(filepath)
  436. version = ctypes.c_int()
  437. nccl.ncclGetVersion.restype = ctypes.c_int
  438. nccl.ncclGetVersion.argtypes = [ctypes.POINTER(ctypes.c_int)]
  439. result = nccl.ncclGetVersion(ctypes.byref(version))
  440. assert result == 0
  441. return version.value
  442. @lru_cache(maxsize=None)
  443. def find_library(lib_name: str) -> str:
  444. """
  445. Find the library file in the system.
  446. `lib_name` is full filename, with both prefix and suffix.
  447. This function resolves `lib_name` to the full path of the library.
  448. """
  449. # Adapted from https://github.com/openai/triton/blob/main/third_party/nvidia/backend/driver.py#L19 # noqa
  450. # According to https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
  451. # `/sbin/ldconfig` should exist in all Linux systems.
  452. # `/sbin/ldconfig` searches the library in the system
  453. libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode()
  454. # each line looks like the following:
  455. # libcuda.so.1 (libc6,x86-64) => /lib/x86_64-linux-gnu/libcuda.so.1
  456. locs = [line.split()[-1] for line in libs.splitlines() if lib_name in line]
  457. # `LD_LIBRARY_PATH` searches the library in the user-defined paths
  458. env_ld_library_path = os.getenv("LD_LIBRARY_PATH")
  459. if not locs and env_ld_library_path:
  460. locs = [
  461. os.path.join(dir, lib_name)
  462. for dir in env_ld_library_path.split(":")
  463. if os.path.exists(os.path.join(dir, lib_name))
  464. ]
  465. if not locs:
  466. raise ValueError(f"Cannot find {lib_name} in the system.")
  467. return locs[0]
  468. def find_nccl_library():
  469. so_file = os.environ.get("APHRODITE_NCCL_SO_PATH", "")
  470. aphrodite_nccl_path = None
  471. if torch.version.cuda is not None:
  472. cuda_major = torch.version.cuda.split(".")[0]
  473. path = os.path.expanduser(
  474. f"~/.config/aphrodite/nccl/cu{cuda_major}/libnccl.so.*")
  475. files = glob.glob(path)
  476. aphrodite_nccl_path = files[0] if files else None
  477. # manually load the nccl library
  478. if so_file:
  479. logger.info("Found nccl from environment variable "
  480. f"APHRODITE_NCCL_SO_PATH={so_file}")
  481. else:
  482. if torch.version.cuda is not None:
  483. so_file = aphrodite_nccl_path or find_library("libnccl.so.2")
  484. elif torch.version.hip is not None:
  485. so_file = find_library("librccl.so.1")
  486. else:
  487. raise ValueError("NCCL only supports CUDA and ROCm backends.")
  488. logger.info(f"Found nccl from library {so_file}")
  489. return so_file
  490. def enable_trace_function_call_for_thread() -> None:
  491. if int(os.getenv("APHRODITE_TRACE_FUNCTION", "0")):
  492. tmp_dir = tempfile.gettempdir()
  493. filename = (f"APHRODITE_TRACE_FUNCTION_for_process_{os.getpid()}"
  494. f"_thread_{threading.get_ident()}_"
  495. f"at_{datetime.datetime.now()}.log").replace(" ", "_")
  496. log_path = os.path.join(tmp_dir, "aphrodite",
  497. get_aphrodite_instance_id(), filename)
  498. os.makedirs(os.path.dirname(log_path), exist_ok=True)
  499. enable_trace_function_call(log_path)