utils.py 20 KB

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