utils.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. import argparse
  2. import asyncio
  3. import contextlib
  4. import datetime
  5. import enum
  6. import gc
  7. import os
  8. import socket
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import threading
  13. import uuid
  14. import warnings
  15. from asyncio import FIRST_COMPLETED, ensure_future
  16. from collections import defaultdict
  17. from functools import lru_cache, partial, wraps
  18. from platform import uname
  19. from typing import (Any, AsyncGenerator, Awaitable, Callable, Dict, Generic,
  20. Hashable, List, Literal, Optional, OrderedDict, Set, Tuple,
  21. Type, TypeVar, Union, overload)
  22. from uuid import uuid4
  23. import numpy as np
  24. import numpy.typing as npt
  25. import psutil
  26. import torch
  27. import torch.types
  28. from loguru import logger
  29. from rich.progress import (BarColumn, MofNCompleteColumn, Progress,
  30. SpinnerColumn, TextColumn, TimeElapsedColumn)
  31. from typing_extensions import ParamSpec, TypeIs, assert_never
  32. from aphrodite.common.logger import enable_trace_function_call
  33. from aphrodite.distributed import get_tensor_model_parallel_rank
  34. # Exception strings for non-implemented encoder/decoder scenarios
  35. STR_NOT_IMPL_ENC_DEC_SWA = \
  36. "Sliding window attention for encoder/decoder models " + \
  37. "is not currently supported."
  38. STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE = \
  39. "Prefix caching for encoder/decoder models " + \
  40. "is not currently supported."
  41. STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL = \
  42. "Chunked prefill for encoder/decoder models " + \
  43. "is not currently supported."
  44. STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP = (
  45. "Models with logits_soft_cap "
  46. "require FlashInfer backend, which is "
  47. "currently not supported for encoder/decoder "
  48. "models.")
  49. STR_NOT_IMPL_ENC_DEC_LORA = ("LoRA is currently not currently "
  50. "supported with encoder/decoder "
  51. "models.")
  52. STR_NOT_IMPL_ENC_DEC_PP = ("Pipeline parallelism is not "
  53. "currently supported with "
  54. "encoder/decoder models.")
  55. STR_NOT_IMPL_ENC_DEC_MM = ("Multimodal is not currently "
  56. "supported with encoder/decoder "
  57. "models.")
  58. STR_NOT_IMPL_ENC_DEC_SPEC_DEC = ("Speculative decoding is not "
  59. "currently supported with encoder/"
  60. "decoder models.")
  61. STR_NOT_IMPL_ENC_DEC_CUDAGRAPH = ("CUDAGraph is not "
  62. "currently supported with encoder/"
  63. "decoder models.")
  64. STR_NOT_IMPL_ENC_DEC_BACKEND = ("XFormers is the only backend "
  65. "currently supported with encoder/"
  66. "decoder models.")
  67. STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER = ("Prompt adapters are not "
  68. "currently supported with encoder/"
  69. "decoder models.")
  70. # Efficiently import all enc/dec error strings
  71. # rather than having to import all of the above
  72. STR_NOT_IMPL_ENC_DEC_ERR_STRS = {
  73. "STR_NOT_IMPL_ENC_DEC_SWA": STR_NOT_IMPL_ENC_DEC_SWA,
  74. "STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE": STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE,
  75. "STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL":
  76. STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL,
  77. "STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP": STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP,
  78. "STR_NOT_IMPL_ENC_DEC_LORA": STR_NOT_IMPL_ENC_DEC_LORA,
  79. "STR_NOT_IMPL_ENC_DEC_PP": STR_NOT_IMPL_ENC_DEC_PP,
  80. "STR_NOT_IMPL_ENC_DEC_MM": STR_NOT_IMPL_ENC_DEC_MM,
  81. "STR_NOT_IMPL_ENC_DEC_SPEC_DEC": STR_NOT_IMPL_ENC_DEC_SPEC_DEC,
  82. "STR_NOT_IMPL_ENC_DEC_CUDA_GRAPH": STR_NOT_IMPL_ENC_DEC_CUDAGRAPH,
  83. "STR_NOT_IMPL_ENC_DEC_BACKEND": STR_NOT_IMPL_ENC_DEC_BACKEND,
  84. "STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER": STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER,
  85. }
  86. # Constants related to forcing the attention backend selection
  87. # String name of register which may be set in order to
  88. # force auto-selection of attention backend by Attention
  89. # wrapper
  90. STR_BACKEND_ENV_VAR: str = "APHRODITE_ATTENTION_BACKEND"
  91. # Possible string values of STR_BACKEND_ENV_VAR
  92. # register, corresponding to possible backends
  93. STR_FLASHINFER_ATTN_VAL: str = "FLASHINFER"
  94. STR_TORCH_SDPA_ATTN_VAL: str = "TORCH_SDPA"
  95. STR_ROCM_FLASH_ATTN_VAL: str = "ROCM_FLASH"
  96. STR_XFORMERS_ATTN_VAL: str = "XFORMERS"
  97. STR_FLASH_ATTN_VAL: str = "FLASH_ATTN"
  98. STR_INVALID_VAL: str = "INVALID"
  99. GiB_bytes = 1 << 30
  100. """The number of bytes in one gibibyte (GiB)."""
  101. STR_DTYPE_TO_TORCH_DTYPE = {
  102. "half": torch.half,
  103. "bfloat16": torch.bfloat16,
  104. "float": torch.float,
  105. "fp8": torch.uint8,
  106. "fp8_e4m3": torch.uint8,
  107. "fp8_e5m2": torch.uint8,
  108. }
  109. TORCH_DTYPE_TO_NUMPY_DTYPE = {
  110. torch.float16: np.float16,
  111. torch.float32: np.float32,
  112. torch.float64: np.float64,
  113. torch.uint8: np.uint8,
  114. torch.int32: np.int32,
  115. torch.int64: np.int64,
  116. }
  117. P = ParamSpec('P')
  118. K = TypeVar("K")
  119. T = TypeVar("T")
  120. U = TypeVar("U")
  121. class _Sentinel:
  122. ...
  123. ALL_PINNED_SENTINEL = _Sentinel()
  124. class Device(enum.Enum):
  125. GPU = enum.auto()
  126. CPU = enum.auto()
  127. class Counter:
  128. def __init__(self, start: int = 0) -> None:
  129. self.counter = start
  130. def __next__(self) -> int:
  131. i = self.counter
  132. self.counter += 1
  133. return i
  134. def reset(self) -> None:
  135. self.counter = 0
  136. class LRUCache(Generic[T]):
  137. def __init__(self, capacity: int):
  138. self.cache: OrderedDict[Hashable, T] = OrderedDict()
  139. self.pinned_items: Set[Hashable] = set()
  140. self.capacity = capacity
  141. def __contains__(self, key: Hashable) -> bool:
  142. return key in self.cache
  143. def __len__(self) -> int:
  144. return len(self.cache)
  145. def __getitem__(self, key: Hashable) -> T:
  146. value = self.cache[key] # Raise KeyError if not exists
  147. self.cache.move_to_end(key)
  148. return value
  149. def __setitem__(self, key: Hashable, value: T) -> None:
  150. self.put(key, value)
  151. def __delitem__(self, key: Hashable) -> None:
  152. self.pop(key)
  153. def touch(self, key: Hashable) -> None:
  154. self.cache.move_to_end(key)
  155. def get(self,
  156. key: Hashable,
  157. default_value: Optional[T] = None) -> Optional[T]:
  158. value: Optional[T]
  159. if key in self.cache:
  160. value = self.cache[key]
  161. self.cache.move_to_end(key)
  162. else:
  163. value = default_value
  164. return value
  165. def put(self, key: Hashable, value: T) -> None:
  166. self.cache[key] = value
  167. self.cache.move_to_end(key)
  168. self._remove_old_if_needed()
  169. def pin(self, key: Hashable) -> None:
  170. """
  171. Pins a key in the cache preventing it from being
  172. evicted in the LRU order.
  173. """
  174. if key not in self.cache:
  175. raise ValueError(f"Cannot pin key: {key} not in cache.")
  176. self.pinned_items.add(key)
  177. def _unpin(self, key: Hashable) -> None:
  178. self.pinned_items.remove(key)
  179. def _on_remove(self, key: Hashable, value: Optional[T]):
  180. pass
  181. def remove_oldest(self, remove_pinned=False):
  182. if not self.cache:
  183. return
  184. if not remove_pinned:
  185. # pop the oldest item in the cache that is not pinned
  186. lru_key = next(
  187. (key for key in self.cache if key not in self.pinned_items),
  188. ALL_PINNED_SENTINEL)
  189. if lru_key is ALL_PINNED_SENTINEL:
  190. raise RuntimeError("All items are pinned, "
  191. "cannot remove oldest from the cache.")
  192. else:
  193. lru_key = next(iter(self.cache))
  194. self.pop(lru_key)
  195. def _remove_old_if_needed(self) -> None:
  196. while len(self.cache) > self.capacity:
  197. self.remove_oldest()
  198. def pop(self,
  199. key: Hashable,
  200. default_value: Optional[T] = None) -> Optional[T]:
  201. run_on_remove = key in self.cache
  202. value: Optional[T] = self.cache.pop(key, default_value)
  203. # remove from pinned items
  204. if key in self.pinned_items:
  205. self._unpin(key)
  206. if run_on_remove:
  207. self._on_remove(key, value)
  208. return value
  209. def clear(self):
  210. while len(self.cache) > 0:
  211. self.remove_oldest(remove_pinned=True)
  212. self.cache.clear()
  213. class PyObjectCache:
  214. """Used to cache python objects to avoid object allocations
  215. across scheduler iterations.
  216. """
  217. def __init__(self, obj_builder):
  218. self._obj_builder = obj_builder
  219. self._index = 0
  220. self._obj_cache = []
  221. for _ in range(128):
  222. self._obj_cache.append(self._obj_builder())
  223. def _grow_cache(self):
  224. # Double the size of the cache
  225. num_objs = len(self._obj_cache)
  226. for _ in range(num_objs):
  227. self._obj_cache.append(self._obj_builder())
  228. def get_object(self):
  229. """Returns a pre-allocated cached object. If there is not enough
  230. objects, then the cache size will double.
  231. """
  232. if self._index >= len(self._obj_cache):
  233. self._grow_cache()
  234. assert self._index < len(self._obj_cache)
  235. obj = self._obj_cache[self._index]
  236. self._index += 1
  237. return obj
  238. def reset(self):
  239. """Makes all cached-objects available for the next scheduler iteration.
  240. """
  241. self._index = 0
  242. def is_hip() -> bool:
  243. return torch.version.hip is not None
  244. @lru_cache(maxsize=None)
  245. def is_cpu() -> bool:
  246. from importlib.metadata import PackageNotFoundError, version
  247. try:
  248. return "cpu" in version("aphrodite-engine")
  249. except PackageNotFoundError:
  250. return False
  251. @lru_cache(maxsize=None)
  252. def is_openvino() -> bool:
  253. from importlib.metadata import PackageNotFoundError, version
  254. try:
  255. return "openvino" in version("aphrodite-engine")
  256. except PackageNotFoundError:
  257. return False
  258. @lru_cache(maxsize=None)
  259. def is_neuron() -> bool:
  260. try:
  261. import transformers_neuronx
  262. except ImportError:
  263. transformers_neuronx = None
  264. return transformers_neuronx is not None
  265. @lru_cache(maxsize=None)
  266. def is_xpu() -> bool:
  267. from importlib.metadata import version
  268. is_xpu_flag = "xpu" in version("aphrodite-engine")
  269. # aphrodite is not build with xpu
  270. if not is_xpu_flag:
  271. return False
  272. try:
  273. import intel_extension_for_pytorch as ipex # noqa: F401
  274. _import_ipex = True
  275. except ImportError as e:
  276. logger.warning(f"Import Error for IPEX: {e.msg}")
  277. _import_ipex = False
  278. # ipex dependency is not ready
  279. if not _import_ipex:
  280. logger.warning("not found ipex lib")
  281. return False
  282. return hasattr(torch, "xpu") and torch.xpu.is_available()
  283. @lru_cache(maxsize=None)
  284. def get_max_shared_memory_bytes(gpu: int = 0) -> int:
  285. """Returns the maximum shared memory per thread block in bytes."""
  286. from aphrodite import _custom_ops as ops
  287. max_shared_mem = (
  288. ops.get_max_shared_memory_per_block_device_attribute(gpu))
  289. # value 0 will cause MAX_SEQ_LEN become negative and test_attention.py
  290. # will fail
  291. assert max_shared_mem > 0, "max_shared_mem can not be zero"
  292. return int(max_shared_mem)
  293. def get_cpu_memory() -> int:
  294. """Returns the total CPU memory of the node in bytes."""
  295. return psutil.virtual_memory().total
  296. def random_uuid() -> str:
  297. return str(uuid.uuid4().hex)
  298. @lru_cache(maxsize=None)
  299. def get_aphrodite_instance_id():
  300. """
  301. If the environment variable APHRODITE_INSTANCE_ID is set, return it.
  302. Otherwise, return a random UUID.
  303. Instance id represents an instance of the Aphrodite. All processes in the
  304. same instance should have the same instance id.
  305. """
  306. return os.environ.get("APHRODITE_INSTANCE_ID",
  307. f"aphrodite-instance-{random_uuid()}")
  308. @lru_cache(maxsize=None)
  309. def in_wsl() -> bool:
  310. # Reference: https://github.com/microsoft/WSL/issues/4071
  311. return "microsoft" in " ".join(uname()).lower()
  312. def make_async(func: Callable[P, T]) -> Callable[P, Awaitable[T]]:
  313. """Take a blocking function, and run it on in an executor thread.
  314. This function prevents the blocking function from blocking the
  315. asyncio event loop.
  316. The code in this function needs to be thread safe.
  317. """
  318. def _async_wrapper(*args: P.args, **kwargs: P.kwargs) -> asyncio.Future:
  319. loop = asyncio.get_event_loop()
  320. p_func = partial(func, *args, **kwargs)
  321. return loop.run_in_executor(executor=None, func=p_func)
  322. return _async_wrapper
  323. async def iterate_with_cancellation(
  324. iterator: AsyncGenerator[T, None],
  325. is_cancelled: Callable[[], Awaitable[bool]],
  326. ) -> AsyncGenerator[T, None]:
  327. """Convert async iterator into one that polls the provided function
  328. at least once per second to check for client cancellation.
  329. """
  330. # Can use anext() in python >= 3.10
  331. awaits = [ensure_future(iterator.__anext__())]
  332. while True:
  333. done, pending = await asyncio.wait(awaits, timeout=1)
  334. if await is_cancelled():
  335. with contextlib.suppress(BaseException):
  336. awaits[0].cancel()
  337. await iterator.aclose()
  338. raise asyncio.CancelledError("client cancelled")
  339. if done:
  340. try:
  341. item = await awaits[0]
  342. awaits[0] = ensure_future(iterator.__anext__())
  343. yield item
  344. except StopAsyncIteration:
  345. # we are done
  346. return
  347. async def merge_async_iterators(
  348. *iterators: AsyncGenerator[T, None],
  349. is_cancelled: Optional[Callable[[], Awaitable[bool]]] = None,
  350. ) -> AsyncGenerator[Tuple[int, T], None]:
  351. """Merge multiple asynchronous iterators into a single iterator.
  352. This method handle the case where some iterators finish before others.
  353. When it yields, it yields a tuple (i, item) where i is the index of the
  354. iterator that yields the item.
  355. It also optionally polls a provided function at least once per second
  356. to check for client cancellation.
  357. """
  358. # Can use anext() in python >= 3.10
  359. awaits = {
  360. ensure_future(pair[1].__anext__()): pair
  361. for pair in enumerate(iterators)
  362. }
  363. timeout = None if is_cancelled is None else 1
  364. try:
  365. while awaits:
  366. done, pending = await asyncio.wait(awaits.keys(),
  367. return_when=FIRST_COMPLETED,
  368. timeout=timeout)
  369. if is_cancelled is not None and await is_cancelled():
  370. raise asyncio.CancelledError("client cancelled")
  371. for d in done:
  372. pair = awaits.pop(d)
  373. try:
  374. item = await d
  375. i, it = pair
  376. awaits[ensure_future(it.__anext__())] = pair
  377. yield i, item
  378. except StopAsyncIteration:
  379. pass
  380. finally:
  381. # Cancel any remaining iterators
  382. for f, (_, it) in awaits.items():
  383. with contextlib.suppress(BaseException):
  384. f.cancel()
  385. await it.aclose()
  386. def get_ip() -> str:
  387. host_ip = os.environ.get("HOST_IP")
  388. if host_ip:
  389. return host_ip
  390. # IP is not set, try to get it from the network interface
  391. # try ipv4
  392. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  393. try:
  394. s.connect(("8.8.8.8", 80)) # Doesn't need to be reachable
  395. return s.getsockname()[0]
  396. except Exception:
  397. pass
  398. # try ipv6
  399. try:
  400. s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  401. # Google's public DNS server, see
  402. # https://developers.google.com/speed/public-dns/docs/using#addresses
  403. s.connect(("2001:4860:4860::8888", 80)) # Doesn't need to be reachable
  404. return s.getsockname()[0]
  405. except Exception:
  406. pass
  407. warnings.warn(
  408. "Failed to get the IP address, using 0.0.0.0 by default."
  409. "The value can be set by the environment variable HOST_IP.",
  410. stacklevel=2)
  411. return "0.0.0.0"
  412. def get_distributed_init_method(ip: str, port: int) -> str:
  413. # Brackets are not permitted in ipv4 addresses,
  414. # see https://github.com/python/cpython/issues/103848
  415. return f"tcp://[{ip}]:{port}" if ":" in ip else f"tcp://{ip}:{port}"
  416. def get_open_zmq_ipc_path() -> str:
  417. APHRODITE_RPC_BASE_PATH = os.getenv("APHRODITE_RPC_BASE_PATH",
  418. tempfile.gettempdir())
  419. base_rpc_path = APHRODITE_RPC_BASE_PATH
  420. return f"ipc://{base_rpc_path}/{uuid4()}"
  421. def get_open_port(port: Optional[int] = None) -> int:
  422. port = int(os.getenv("APHRODITE_PORT", 0)
  423. ) if "APHRODITE_PORT" in os.environ else None
  424. if port is not None:
  425. while True:
  426. try:
  427. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  428. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  429. s.bind(("", port))
  430. return port
  431. except OSError:
  432. port += 1 # Increment port number if already in use
  433. logger.info(f"Port {port - 1} is already in use, trying port "
  434. f"{port}")
  435. # try ipv4
  436. try:
  437. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  438. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  439. s.bind(("", 0))
  440. return s.getsockname()[1]
  441. except OSError:
  442. # try ipv6
  443. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
  444. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  445. s.bind(("", 0))
  446. return s.getsockname()[1]
  447. def update_environment_variables(envs: Dict[str, str]):
  448. for k, v in envs.items():
  449. if k in os.environ and os.environ[k] != v:
  450. logger.warning(f"Overwriting environment variable {k} "
  451. f"from '{os.environ[k]}' to '{v}'")
  452. os.environ[k] = v
  453. def chunk_list(lst: List[T], chunk_size: int):
  454. """Yield successive chunk_size chunks from lst."""
  455. for i in range(0, len(lst), chunk_size):
  456. yield lst[i:i + chunk_size]
  457. def cdiv(a: int, b: int) -> int:
  458. """Ceiling division."""
  459. return -(a // -b)
  460. def _generate_random_fp8(
  461. tensor: torch.Tensor,
  462. low: float,
  463. high: float,
  464. ) -> None:
  465. # NOTE: Due to NaN and Inf representation for fp8 data type,
  466. # it may occur Inf or NaN if we directly use torch.randint
  467. # to generate random data for fp8 data.
  468. # For example, s.11111.00 in fp8e5m2 format represents Inf.
  469. # | E4M3 | E5M2
  470. #-----|-------------|-------------------
  471. # Inf | N/A | s.11111.00
  472. # NaN | s.1111.111 | s.11111.{01,10,11}
  473. from aphrodite import _custom_ops as ops
  474. tensor_tmp = torch.empty_like(tensor, dtype=torch.float16)
  475. tensor_tmp.uniform_(low, high)
  476. ops.convert_fp8(tensor, tensor_tmp)
  477. del tensor_tmp
  478. def get_kv_cache_torch_dtype(
  479. cache_dtype: Optional[Union[str, torch.dtype]],
  480. model_dtype: Optional[Union[str, torch.dtype]] = None) -> torch.dtype:
  481. if isinstance(cache_dtype, str):
  482. if cache_dtype == "auto":
  483. if isinstance(model_dtype, str):
  484. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[model_dtype]
  485. elif isinstance(model_dtype, torch.dtype):
  486. torch_dtype = model_dtype
  487. else:
  488. raise ValueError(f"Invalid model dtype: {model_dtype}")
  489. elif cache_dtype in ["half", "bfloat16", "float"]:
  490. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype]
  491. elif cache_dtype == "fp8":
  492. torch_dtype = torch.uint8
  493. else:
  494. raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
  495. elif isinstance(cache_dtype, torch.dtype):
  496. torch_dtype = cache_dtype
  497. else:
  498. raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
  499. return torch_dtype
  500. def create_kv_caches_with_random_flash(
  501. num_blocks: int,
  502. block_size: int,
  503. num_layers: int,
  504. num_heads: int,
  505. head_size: int,
  506. cache_dtype: Optional[Union[str, torch.dtype]],
  507. model_dtype: Optional[Union[str, torch.dtype]] = None,
  508. seed: int = 0,
  509. device: Optional[str] = "cuda",
  510. ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
  511. torch.random.manual_seed(seed)
  512. if torch.cuda.is_available():
  513. torch.cuda.manual_seed(seed)
  514. torch_dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype)
  515. key_value_cache_shape = (num_blocks, 2, block_size, num_heads, head_size)
  516. scale = head_size**-0.5
  517. key_caches: List[torch.Tensor] = []
  518. value_caches: List[torch.Tensor] = []
  519. for _ in range(num_layers):
  520. key_value_cache = torch.empty(size=key_value_cache_shape,
  521. dtype=torch_dtype,
  522. device=device)
  523. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  524. key_value_cache.uniform_(-scale, scale)
  525. elif cache_dtype == 'fp8':
  526. _generate_random_fp8(key_value_cache, -scale, scale)
  527. else:
  528. raise ValueError(
  529. f"Does not support key cache of type {cache_dtype}")
  530. key_caches.append(key_value_cache[:, 0])
  531. value_caches.append(key_value_cache[:, 1])
  532. return key_caches, value_caches
  533. def create_kv_caches_with_random(
  534. num_blocks: int,
  535. block_size: int,
  536. num_layers: int,
  537. num_heads: int,
  538. head_size: int,
  539. cache_dtype: Optional[Union[str, torch.dtype]],
  540. model_dtype: Optional[Union[str, torch.dtype]] = None,
  541. seed: int = 0,
  542. device: Optional[str] = "cuda",
  543. ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
  544. if cache_dtype == "fp8" and head_size % 16:
  545. raise ValueError(
  546. f"Does not support key cache of type fp8 with head_size "
  547. f"{head_size}")
  548. torch.random.manual_seed(seed)
  549. if torch.cuda.is_available():
  550. torch.cuda.manual_seed(seed)
  551. torch_dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype)
  552. scale = head_size**-0.5
  553. x = 16 // torch.tensor([], dtype=torch_dtype).element_size()
  554. key_cache_shape = (num_blocks, num_heads, head_size // x, block_size, x)
  555. key_caches: List[torch.Tensor] = []
  556. for _ in range(num_layers):
  557. key_cache = torch.empty(size=key_cache_shape,
  558. dtype=torch_dtype,
  559. device=device)
  560. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  561. key_cache.uniform_(-scale, scale)
  562. elif cache_dtype == 'fp8':
  563. _generate_random_fp8(key_cache, -scale, scale)
  564. else:
  565. raise ValueError(
  566. f"Does not support key cache of type {cache_dtype}")
  567. key_caches.append(key_cache)
  568. value_cache_shape = (num_blocks, num_heads, head_size, block_size)
  569. value_caches: List[torch.Tensor] = []
  570. for _ in range(num_layers):
  571. value_cache = torch.empty(size=value_cache_shape,
  572. dtype=torch_dtype,
  573. device=device)
  574. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  575. value_cache.uniform_(-scale, scale)
  576. elif cache_dtype == 'fp8':
  577. _generate_random_fp8(value_cache, -scale, scale)
  578. else:
  579. raise ValueError(
  580. f"Does not support value cache of type {cache_dtype}")
  581. value_caches.append(value_cache)
  582. return key_caches, value_caches
  583. @lru_cache
  584. def print_warning_once(msg: str) -> None:
  585. logger.warning(msg)
  586. @lru_cache(maxsize=None)
  587. def is_pin_memory_available() -> bool:
  588. if in_wsl():
  589. # Pinning memory in WSL is not supported.
  590. # https://docs.nvidia.com/cuda/wsl-user-guide/index.html#known-limitations-for-linux-cuda-applications
  591. print_warning_once("Using 'pin_memory=False' as WSL is detected. "
  592. "This may slow down the performance.")
  593. return False
  594. elif is_xpu():
  595. print_warning_once("Pin memory is not supported on XPU.")
  596. return False
  597. elif is_neuron():
  598. print_warning_once("Pin memory is not supported on Neuron.")
  599. return False
  600. elif is_cpu() or is_openvino():
  601. return False
  602. return True
  603. class CudaMemoryProfiler:
  604. def __init__(self, device: Optional[torch.types.Device] = None):
  605. self.device = device
  606. def current_memory_usage(self) -> float:
  607. # Return the memory usage in bytes.
  608. if torch.cuda.is_available():
  609. torch.cuda.reset_peak_memory_stats(self.device)
  610. mem = torch.cuda.max_memory_allocated(self.device)
  611. elif is_xpu():
  612. torch.xpu.reset_peak_memory_stats(self.device) # type: ignore
  613. mem = torch.xpu.max_memory_allocated(self.device) # type: ignore
  614. return mem
  615. def __enter__(self):
  616. self.initial_memory = self.current_memory_usage()
  617. # This allows us to call methods of the context manager if needed
  618. return self
  619. def __exit__(self, exc_type, exc_val, exc_tb):
  620. self.final_memory = self.current_memory_usage()
  621. self.consumed_memory = self.final_memory - self.initial_memory
  622. # Force garbage collection
  623. gc.collect()
  624. def str_to_int_tuple(s: str) -> Tuple[int, ...]:
  625. """Convert a string to a tuple of integers."""
  626. try:
  627. return tuple(map(int, s.split(",")))
  628. except ValueError as e:
  629. raise ValueError(
  630. "String must be a series of integers separated by commas "
  631. f"(e.g., 1, 2, 3). Given input: {s}") from e
  632. def make_ndarray_with_pad(
  633. x: List[List[T]],
  634. pad: T,
  635. dtype: npt.DTypeLike,
  636. *,
  637. max_len: Optional[int] = None,
  638. ) -> npt.NDArray:
  639. """
  640. Make a padded array from 2D inputs.
  641. The padding is applied to the end of each inner list until it reaches
  642. `max_len`.
  643. """
  644. if max_len is None:
  645. # Unlike for most functions, map is faster than a genexpr over `len`
  646. max_len = max(map(len, x), default=0)
  647. padded_x = np.full((len(x), max_len), pad, dtype=dtype)
  648. for ind, blocktb in enumerate(x):
  649. assert len(blocktb) <= max_len
  650. padded_x[ind, :len(blocktb)] = blocktb
  651. return padded_x
  652. def make_tensor_with_pad(
  653. x: List[List[T]],
  654. pad: T,
  655. dtype: torch.dtype,
  656. *,
  657. max_len: Optional[int] = None,
  658. device: Optional[Union[str, torch.device]] = None,
  659. pin_memory: bool = False,
  660. ) -> torch.Tensor:
  661. """
  662. Make a padded tensor from 2D inputs.
  663. The padding is applied to the end of each inner list until it reaches
  664. `max_len`.
  665. """
  666. np_dtype = TORCH_DTYPE_TO_NUMPY_DTYPE[dtype]
  667. padded_x = make_ndarray_with_pad(x, pad, np_dtype, max_len=max_len)
  668. tensor = torch.from_numpy(padded_x).to(device)
  669. if pin_memory:
  670. tensor = tensor.pin_memory()
  671. return tensor
  672. def async_tensor_h2d(
  673. data: list,
  674. dtype: torch.dtype,
  675. target_device: Union[str, torch.device],
  676. pin_memory: bool,
  677. ) -> torch.Tensor:
  678. """Asynchronously create a tensor and copy it from host to device."""
  679. t = torch.tensor(data, dtype=dtype, pin_memory=pin_memory, device="cpu")
  680. return t.to(device=target_device, non_blocking=True)
  681. def maybe_expand_dim(tensor: torch.Tensor,
  682. target_dims: int,
  683. size: int = 1) -> torch.Tensor:
  684. """Expand the tensor to the target_dims."""
  685. if tensor.ndim < target_dims:
  686. tensor = tensor.view(-1, *([size] * (target_dims - tensor.ndim)))
  687. return tensor
  688. def get_dtype_size(dtype: torch.dtype) -> int:
  689. """Get the size of the data type in bytes."""
  690. return torch.tensor([], dtype=dtype).element_size()
  691. # `collections` helpers
  692. def is_list_of(
  693. value: object,
  694. typ: Type[T],
  695. *,
  696. check: Literal["first", "all"] = "first",
  697. ) -> TypeIs[List[T]]:
  698. if not isinstance(value, list):
  699. return False
  700. if check == "first":
  701. return len(value) == 0 or isinstance(value[0], typ)
  702. elif check == "all":
  703. return all(isinstance(v, typ) for v in value)
  704. assert_never(check)
  705. def merge_dicts(dict1: Dict[K, List[T]],
  706. dict2: Dict[K, List[T]]) -> Dict[K, List[T]]:
  707. """Merge 2 dicts that have key -> List of items.
  708. When a key conflicts, the values in dict1 is prioritized.
  709. """
  710. merged_dict: Dict[K, List[T]] = defaultdict(list)
  711. for key, value in dict1.items():
  712. merged_dict[key].extend(value)
  713. for key, value in dict2.items():
  714. merged_dict[key].extend(value)
  715. return dict(merged_dict)
  716. JSONTree = Union[Dict[str, "JSONTree[T]"], List["JSONTree[T]"],
  717. Tuple["JSONTree[T]", ...], T]
  718. """A nested JSON structure where the leaves need not be JSON-serializable."""
  719. @overload
  720. def json_map_leaves(
  721. func: Callable[[T], U],
  722. value: Dict[str, JSONTree[T]],
  723. ) -> Dict[str, JSONTree[U]]:
  724. ...
  725. @overload
  726. def json_map_leaves(
  727. func: Callable[[T], U],
  728. value: List[JSONTree[T]],
  729. ) -> List[JSONTree[U]]:
  730. ...
  731. @overload
  732. def json_map_leaves(
  733. func: Callable[[T], U],
  734. value: Tuple[JSONTree[T], ...],
  735. ) -> Tuple[JSONTree[U], ...]:
  736. ...
  737. @overload
  738. def json_map_leaves(
  739. func: Callable[[T], U],
  740. value: JSONTree[T],
  741. ) -> JSONTree[U]:
  742. ...
  743. def json_map_leaves(func: Callable[[T], U], value: JSONTree[T]) -> JSONTree[U]:
  744. if isinstance(value, dict):
  745. return {k: json_map_leaves(func, v) for k, v in value.items()}
  746. elif isinstance(value, list):
  747. return [json_map_leaves(func, v) for v in value]
  748. elif isinstance(value, tuple):
  749. return tuple(json_map_leaves(func, v) for v in value)
  750. else:
  751. return func(value)
  752. def flatten_2d_lists(lists: List[List[T]]) -> List[T]:
  753. """Flatten a list of lists to a single list."""
  754. return [item for sublist in lists for item in sublist]
  755. def init_cached_hf_modules() -> None:
  756. """
  757. Lazy initialization of the Hugging Face modules.
  758. """
  759. from transformers.dynamic_module_utils import init_hf_modules
  760. init_hf_modules()
  761. @lru_cache(maxsize=None)
  762. def find_library(lib_name: str) -> str:
  763. """
  764. Find the library file in the system.
  765. `lib_name` is full filename, with both prefix and suffix.
  766. This function resolves `lib_name` to the full path of the library.
  767. """
  768. # Adapted from https://github.com/openai/triton/blob/main/third_party/nvidia/backend/driver.py#L19 # noqa
  769. # According to https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
  770. # `/sbin/ldconfig` should exist in all Linux systems.
  771. # `/sbin/ldconfig` searches the library in the system
  772. libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode()
  773. # each line looks like the following:
  774. # libcuda.so.1 (libc6,x86-64) => /lib/x86_64-linux-gnu/libcuda.so.1
  775. locs = [line.split()[-1] for line in libs.splitlines() if lib_name in line]
  776. # `LD_LIBRARY_PATH` searches the library in the user-defined paths
  777. env_ld_library_path = os.getenv("LD_LIBRARY_PATH")
  778. if not locs and env_ld_library_path:
  779. locs = [
  780. os.path.join(dir, lib_name)
  781. for dir in env_ld_library_path.split(":")
  782. if os.path.exists(os.path.join(dir, lib_name))
  783. ]
  784. if not locs:
  785. raise ValueError(f"Cannot find {lib_name} in the system.")
  786. return locs[0]
  787. def find_nccl_library() -> str:
  788. """
  789. We either use the library file specified by the `APHRODITE_NCCL_SO_PATH`
  790. environment variable, or we find the library file brought by PyTorch.
  791. After importing `torch`, `libnccl.so.2` or `librccl.so.1` can be
  792. found by `ctypes` automatically.
  793. """
  794. so_file = os.environ.get("APHRODITE_NCCL_SO_PATH", "")
  795. # manually load the nccl library
  796. if so_file:
  797. logger.debug("Found nccl from environment variable "
  798. f"APHRODITE_NCCL_SO_PATH={so_file}")
  799. else:
  800. if torch.version.cuda is not None:
  801. so_file = "libnccl.so.2"
  802. elif torch.version.hip is not None:
  803. so_file = "librccl.so.1"
  804. else:
  805. raise ValueError("NCCL only supports CUDA and ROCm backends.")
  806. logger.debug(f"Found nccl from library {so_file}")
  807. return so_file
  808. def enable_trace_function_call_for_thread() -> None:
  809. if int(os.getenv("APHRODITE_TRACE_FUNCTION", "0")):
  810. tmp_dir = tempfile.gettempdir()
  811. filename = (f"APHRODITE_TRACE_FUNCTION_for_process_{os.getpid()}"
  812. f"_thread_{threading.get_ident()}_"
  813. f"at_{datetime.datetime.now()}.log").replace(" ", "_")
  814. log_path = os.path.join(tmp_dir, "aphrodite",
  815. get_aphrodite_instance_id(), filename)
  816. os.makedirs(os.path.dirname(log_path), exist_ok=True)
  817. enable_trace_function_call(log_path)
  818. def identity(value: T) -> T:
  819. return value
  820. F = TypeVar('F', bound=Callable[..., Any])
  821. def deprecate_kwargs(
  822. *kws: str,
  823. is_deprecated: Union[bool, Callable[[], bool]] = True,
  824. additional_message: Optional[str] = None) -> Callable[[F], F]:
  825. deprecated_kws = set(kws)
  826. if not callable(is_deprecated):
  827. is_deprecated = partial(identity, is_deprecated)
  828. def wrapper(fn: F) -> F:
  829. @wraps(fn)
  830. def inner(*args, **kwargs):
  831. if is_deprecated():
  832. deprecated_kwargs = kwargs.keys() & deprecated_kws
  833. if deprecated_kwargs:
  834. msg = (
  835. f"The keyword arguments {deprecated_kwargs} are "
  836. "deprecated and will be removed in a future update.")
  837. if additional_message is not None:
  838. msg += f" {additional_message}"
  839. warnings.warn(
  840. DeprecationWarning(msg),
  841. stacklevel=3, # The inner function takes up one level
  842. )
  843. return fn(*args, **kwargs)
  844. return inner # type: ignore
  845. return wrapper
  846. @lru_cache(maxsize=8)
  847. def _cuda_device_count_stateless(
  848. cuda_visible_devices: Optional[str] = None) -> int:
  849. # Note: cuda_visible_devices is not used, but we keep it as an argument for
  850. # LRU Cache purposes.
  851. # Code below is based on
  852. # https://github.com/pytorch/pytorch/blob/
  853. # c1cd946818442aca8c7f812b16d187ce1586c3bc/
  854. # torch/cuda/__init__.py#L831C1-L831C17
  855. import torch.cuda
  856. import torch.version
  857. if not torch.cuda._is_compiled():
  858. return 0
  859. if is_hip():
  860. # ROCm uses amdsmi instead of nvml for stateless device count
  861. # This requires a sufficiently modern version of Torch 2.4.0
  862. raw_count = torch.cuda._device_count_amdsmi() if (hasattr(
  863. torch.cuda, "_device_count_amdsmi")) else -1
  864. else:
  865. raw_count = torch.cuda._device_count_nvml()
  866. r = torch._C._cuda_getDeviceCount() if raw_count < 0 else raw_count
  867. return r
  868. def cuda_device_count_stateless() -> int:
  869. """Get number of CUDA devices, caching based on the value of
  870. CUDA_VISIBLE_DEVICES at the time of call.
  871. This should be used instead of torch.cuda.device_count()
  872. unless CUDA_VISIBLE_DEVICES has already been set to the desired
  873. value."""
  874. # This can be removed and simply replaced with torch.cuda.get_device_count
  875. # after https://github.com/pytorch/pytorch/pull/122815 is released.
  876. return _cuda_device_count_stateless(os.environ.get("CUDA_VISIBLE_DEVICES"))
  877. #From: https://stackoverflow.com/a/4104188/2749989
  878. def run_once(f):
  879. def wrapper(*args, **kwargs) -> Any:
  880. if not wrapper.has_run: # type: ignore[attr-defined]
  881. wrapper.has_run = True # type: ignore[attr-defined]
  882. return f(*args, **kwargs)
  883. wrapper.has_run = False # type: ignore[attr-defined]
  884. return wrapper
  885. class FlexibleArgumentParser(argparse.ArgumentParser):
  886. """ArgumentParser that allows both underscore and dash in names."""
  887. def parse_args(self, args=None, namespace=None):
  888. if args is None:
  889. args = sys.argv[1:]
  890. # Convert underscores to dashes and vice versa in argument names
  891. processed_args = []
  892. for arg in args:
  893. if arg.startswith('--'):
  894. if '=' in arg:
  895. key, value = arg.split('=', 1)
  896. key = '--' + key[len('--'):].replace('_', '-')
  897. processed_args.append(f'{key}={value}')
  898. else:
  899. processed_args.append('--' +
  900. arg[len('--'):].replace('_', '-'))
  901. else:
  902. processed_args.append(arg)
  903. return super().parse_args(processed_args, namespace)
  904. async def _run_task_with_lock(task: Callable, lock: asyncio.Lock, *args,
  905. **kwargs):
  906. """Utility function to run async task in a lock"""
  907. async with lock:
  908. return await task(*args, **kwargs)
  909. def progress_bar(iterable, desc="Processing"):
  910. show_progress = get_tensor_model_parallel_rank() == 0
  911. if show_progress:
  912. with Progress(
  913. SpinnerColumn(),
  914. TextColumn("[progress.description]{task.description}"),
  915. BarColumn(),
  916. MofNCompleteColumn(),
  917. TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
  918. TimeElapsedColumn(),
  919. ) as progress:
  920. task = progress.add_task(f"[cyan]{desc}", total=len(iterable))
  921. for item in iterable:
  922. yield item
  923. progress.update(task, advance=1)
  924. else:
  925. yield from iterable