utils.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. import argparse
  2. import asyncio
  3. import contextlib
  4. import datetime
  5. import enum
  6. import gc
  7. import math
  8. import os
  9. import socket
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import threading
  14. import uuid
  15. import warnings
  16. from asyncio import FIRST_COMPLETED, ensure_future
  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, Iterable, List, Literal, Optional, OrderedDict,
  21. Set, Tuple, 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. @lru_cache(maxsize=None)
  313. def in_windows() -> bool:
  314. return sys.platform.startswith("win32")
  315. def make_async(func: Callable[P, T]) -> Callable[P, Awaitable[T]]:
  316. """Take a blocking function, and run it on in an executor thread.
  317. This function prevents the blocking function from blocking the
  318. asyncio event loop.
  319. The code in this function needs to be thread safe.
  320. """
  321. def _async_wrapper(*args: P.args, **kwargs: P.kwargs) -> asyncio.Future:
  322. loop = asyncio.get_event_loop()
  323. p_func = partial(func, *args, **kwargs)
  324. return loop.run_in_executor(executor=None, func=p_func)
  325. return _async_wrapper
  326. async def iterate_with_cancellation(
  327. iterator: AsyncGenerator[T, None],
  328. is_cancelled: Callable[[], Awaitable[bool]],
  329. ) -> AsyncGenerator[T, None]:
  330. """Convert async iterator into one that polls the provided function
  331. at least once per second to check for client cancellation.
  332. """
  333. # Can use anext() in python >= 3.10
  334. awaits = [ensure_future(iterator.__anext__())]
  335. while True:
  336. done, pending = await asyncio.wait(awaits, timeout=1)
  337. if await is_cancelled():
  338. with contextlib.suppress(BaseException):
  339. awaits[0].cancel()
  340. await iterator.aclose()
  341. raise asyncio.CancelledError("client cancelled")
  342. if done:
  343. try:
  344. item = await awaits[0]
  345. awaits[0] = ensure_future(iterator.__anext__())
  346. yield item
  347. except StopAsyncIteration:
  348. # we are done
  349. return
  350. async def merge_async_iterators(
  351. *iterators: AsyncGenerator[T, None],
  352. is_cancelled: Optional[Callable[[], Awaitable[bool]]] = None,
  353. ) -> AsyncGenerator[Tuple[int, T], None]:
  354. """Merge multiple asynchronous iterators into a single iterator.
  355. This method handle the case where some iterators finish before others.
  356. When it yields, it yields a tuple (i, item) where i is the index of the
  357. iterator that yields the item.
  358. It also optionally polls a provided function at least once per second
  359. to check for client cancellation.
  360. """
  361. # Can use anext() in python >= 3.10
  362. awaits = {
  363. ensure_future(pair[1].__anext__()): pair
  364. for pair in enumerate(iterators)
  365. }
  366. timeout = None if is_cancelled is None else 1
  367. try:
  368. while awaits:
  369. done, pending = await asyncio.wait(awaits.keys(),
  370. return_when=FIRST_COMPLETED,
  371. timeout=timeout)
  372. if is_cancelled is not None and await is_cancelled():
  373. raise asyncio.CancelledError("client cancelled")
  374. for d in done:
  375. pair = awaits.pop(d)
  376. try:
  377. item = await d
  378. i, it = pair
  379. awaits[ensure_future(it.__anext__())] = pair
  380. yield i, item
  381. except StopAsyncIteration:
  382. pass
  383. finally:
  384. # Cancel any remaining iterators
  385. for f, (_, it) in awaits.items():
  386. with contextlib.suppress(BaseException):
  387. f.cancel()
  388. await it.aclose()
  389. def get_ip() -> str:
  390. host_ip = os.environ.get("HOST_IP")
  391. if host_ip:
  392. return host_ip
  393. # IP is not set, try to get it from the network interface
  394. # try ipv4
  395. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  396. try:
  397. s.connect(("8.8.8.8", 80)) # Doesn't need to be reachable
  398. return s.getsockname()[0]
  399. except Exception:
  400. pass
  401. # try ipv6
  402. try:
  403. s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  404. # Google's public DNS server, see
  405. # https://developers.google.com/speed/public-dns/docs/using#addresses
  406. s.connect(("2001:4860:4860::8888", 80)) # Doesn't need to be reachable
  407. return s.getsockname()[0]
  408. except Exception:
  409. pass
  410. warnings.warn(
  411. "Failed to get the IP address, using 0.0.0.0 by default."
  412. "The value can be set by the environment variable HOST_IP.",
  413. stacklevel=2)
  414. return "0.0.0.0"
  415. def get_distributed_init_method(ip: str, port: int) -> str:
  416. # Brackets are not permitted in ipv4 addresses,
  417. # see https://github.com/python/cpython/issues/103848
  418. return f"tcp://[{ip}]:{port}" if ":" in ip else f"tcp://{ip}:{port}"
  419. def get_open_zmq_ipc_path() -> str:
  420. if not in_windows():
  421. APHRODITE_RPC_BASE_PATH = os.getenv("APHRODITE_RPC_BASE_PATH",
  422. tempfile.gettempdir())
  423. base_rpc_path = APHRODITE_RPC_BASE_PATH
  424. return f"ipc://{base_rpc_path}/{uuid4()}"
  425. else:
  426. # windows doesn't support ipc://
  427. # use tcp:// instead
  428. return f"tcp://127.0.0.1:{get_open_port()}"
  429. def get_open_port(port: Optional[int] = None) -> int:
  430. port = int(os.getenv("APHRODITE_PORT", 0)
  431. ) if "APHRODITE_PORT" in os.environ else None
  432. if port is not None:
  433. while True:
  434. try:
  435. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  436. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  437. s.bind(("", port))
  438. return port
  439. except OSError:
  440. port += 1 # Increment port number if already in use
  441. logger.info(f"Port {port - 1} is already in use, trying port "
  442. f"{port}")
  443. # try ipv4
  444. try:
  445. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  446. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  447. s.bind(("", 0))
  448. return s.getsockname()[1]
  449. except OSError:
  450. # try ipv6
  451. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
  452. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  453. s.bind(("", 0))
  454. return s.getsockname()[1]
  455. def update_environment_variables(envs: Dict[str, str]):
  456. for k, v in envs.items():
  457. if k in os.environ and os.environ[k] != v:
  458. logger.warning(f"Overwriting environment variable {k} "
  459. f"from '{os.environ[k]}' to '{v}'")
  460. os.environ[k] = v
  461. def chunk_list(lst: List[T], chunk_size: int):
  462. """Yield successive chunk_size chunks from lst."""
  463. for i in range(0, len(lst), chunk_size):
  464. yield lst[i:i + chunk_size]
  465. def cdiv(a: int, b: int) -> int:
  466. """Ceiling division."""
  467. return -(a // -b)
  468. def _generate_random_fp8(
  469. tensor: torch.Tensor,
  470. low: float,
  471. high: float,
  472. ) -> None:
  473. # NOTE: Due to NaN and Inf representation for fp8 data type,
  474. # it may occur Inf or NaN if we directly use torch.randint
  475. # to generate random data for fp8 data.
  476. # For example, s.11111.00 in fp8e5m2 format represents Inf.
  477. # | E4M3 | E5M2
  478. #-----|-------------|-------------------
  479. # Inf | N/A | s.11111.00
  480. # NaN | s.1111.111 | s.11111.{01,10,11}
  481. from aphrodite import _custom_ops as ops
  482. tensor_tmp = torch.empty_like(tensor, dtype=torch.float16)
  483. tensor_tmp.uniform_(low, high)
  484. ops.convert_fp8(tensor, tensor_tmp)
  485. del tensor_tmp
  486. def get_kv_cache_torch_dtype(
  487. cache_dtype: Optional[Union[str, torch.dtype]],
  488. model_dtype: Optional[Union[str, torch.dtype]] = None) -> torch.dtype:
  489. if isinstance(cache_dtype, str):
  490. if cache_dtype == "auto":
  491. if isinstance(model_dtype, str):
  492. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[model_dtype]
  493. elif isinstance(model_dtype, torch.dtype):
  494. torch_dtype = model_dtype
  495. else:
  496. raise ValueError(f"Invalid model dtype: {model_dtype}")
  497. elif cache_dtype in ["half", "bfloat16", "float"]:
  498. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype]
  499. elif cache_dtype == "fp8":
  500. torch_dtype = torch.uint8
  501. else:
  502. raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
  503. elif isinstance(cache_dtype, torch.dtype):
  504. torch_dtype = cache_dtype
  505. else:
  506. raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
  507. return torch_dtype
  508. def create_kv_caches_with_random_flash(
  509. num_blocks: int,
  510. block_size: int,
  511. num_layers: int,
  512. num_heads: int,
  513. head_size: int,
  514. cache_dtype: Optional[Union[str, torch.dtype]],
  515. model_dtype: Optional[Union[str, torch.dtype]] = None,
  516. seed: int = 0,
  517. device: Optional[str] = "cuda",
  518. ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
  519. torch.random.manual_seed(seed)
  520. if torch.cuda.is_available():
  521. torch.cuda.manual_seed(seed)
  522. torch_dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype)
  523. key_value_cache_shape = (num_blocks, 2, block_size, num_heads, head_size)
  524. scale = head_size**-0.5
  525. key_caches: List[torch.Tensor] = []
  526. value_caches: List[torch.Tensor] = []
  527. for _ in range(num_layers):
  528. key_value_cache = torch.empty(size=key_value_cache_shape,
  529. dtype=torch_dtype,
  530. device=device)
  531. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  532. key_value_cache.uniform_(-scale, scale)
  533. elif cache_dtype == 'fp8':
  534. _generate_random_fp8(key_value_cache, -scale, scale)
  535. else:
  536. raise ValueError(
  537. f"Does not support key cache of type {cache_dtype}")
  538. key_caches.append(key_value_cache[:, 0])
  539. value_caches.append(key_value_cache[:, 1])
  540. return key_caches, value_caches
  541. def create_kv_caches_with_random(
  542. num_blocks: int,
  543. block_size: int,
  544. num_layers: int,
  545. num_heads: int,
  546. head_size: int,
  547. cache_dtype: Optional[Union[str, torch.dtype]],
  548. model_dtype: Optional[Union[str, torch.dtype]] = None,
  549. seed: int = 0,
  550. device: Optional[str] = "cuda",
  551. ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
  552. if cache_dtype == "fp8" and head_size % 16:
  553. raise ValueError(
  554. f"Does not support key cache of type fp8 with head_size "
  555. f"{head_size}")
  556. torch.random.manual_seed(seed)
  557. if torch.cuda.is_available():
  558. torch.cuda.manual_seed(seed)
  559. torch_dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype)
  560. scale = head_size**-0.5
  561. x = 16 // torch.tensor([], dtype=torch_dtype).element_size()
  562. key_cache_shape = (num_blocks, num_heads, head_size // x, block_size, x)
  563. key_caches: List[torch.Tensor] = []
  564. for _ in range(num_layers):
  565. key_cache = torch.empty(size=key_cache_shape,
  566. dtype=torch_dtype,
  567. device=device)
  568. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  569. key_cache.uniform_(-scale, scale)
  570. elif cache_dtype == 'fp8':
  571. _generate_random_fp8(key_cache, -scale, scale)
  572. else:
  573. raise ValueError(
  574. f"Does not support key cache of type {cache_dtype}")
  575. key_caches.append(key_cache)
  576. value_cache_shape = (num_blocks, num_heads, head_size, block_size)
  577. value_caches: List[torch.Tensor] = []
  578. for _ in range(num_layers):
  579. value_cache = torch.empty(size=value_cache_shape,
  580. dtype=torch_dtype,
  581. device=device)
  582. if cache_dtype in ["auto", "half", "bfloat16", "float"]:
  583. value_cache.uniform_(-scale, scale)
  584. elif cache_dtype == 'fp8':
  585. _generate_random_fp8(value_cache, -scale, scale)
  586. else:
  587. raise ValueError(
  588. f"Does not support value cache of type {cache_dtype}")
  589. value_caches.append(value_cache)
  590. return key_caches, value_caches
  591. @lru_cache
  592. def print_warning_once(msg: str) -> None:
  593. logger.warning(msg)
  594. @lru_cache(maxsize=None)
  595. def is_pin_memory_available() -> bool:
  596. if in_wsl():
  597. # Pinning memory in WSL is not supported.
  598. # https://docs.nvidia.com/cuda/wsl-user-guide/index.html#known-limitations-for-linux-cuda-applications
  599. print_warning_once("Using 'pin_memory=False' as WSL is detected. "
  600. "This may slow down the performance.")
  601. return False
  602. elif is_xpu():
  603. print_warning_once("Pin memory is not supported on XPU.")
  604. return False
  605. elif is_neuron():
  606. print_warning_once("Pin memory is not supported on Neuron.")
  607. return False
  608. elif is_cpu() or is_openvino():
  609. return False
  610. return True
  611. class CudaMemoryProfiler:
  612. def __init__(self, device: Optional[torch.types.Device] = None):
  613. self.device = device
  614. def current_memory_usage(self) -> float:
  615. # Return the memory usage in bytes.
  616. if torch.cuda.is_available():
  617. torch.cuda.reset_peak_memory_stats(self.device)
  618. mem = torch.cuda.max_memory_allocated(self.device)
  619. elif is_xpu():
  620. torch.xpu.reset_peak_memory_stats(self.device) # type: ignore
  621. mem = torch.xpu.max_memory_allocated(self.device) # type: ignore
  622. return mem
  623. def __enter__(self):
  624. self.initial_memory = self.current_memory_usage()
  625. # This allows us to call methods of the context manager if needed
  626. return self
  627. def __exit__(self, exc_type, exc_val, exc_tb):
  628. self.final_memory = self.current_memory_usage()
  629. self.consumed_memory = self.final_memory - self.initial_memory
  630. # Force garbage collection
  631. gc.collect()
  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. JSONTree = Union[Dict[str, "JSONTree[T]"], List["JSONTree[T]"],
  706. Tuple["JSONTree[T]", ...], T]
  707. """A nested JSON structure where the leaves need not be JSON-serializable."""
  708. @overload
  709. def json_map_leaves(
  710. func: Callable[[T], U],
  711. value: Dict[str, JSONTree[T]],
  712. ) -> Dict[str, JSONTree[U]]:
  713. ...
  714. @overload
  715. def json_map_leaves(
  716. func: Callable[[T], U],
  717. value: List[JSONTree[T]],
  718. ) -> List[JSONTree[U]]:
  719. ...
  720. @overload
  721. def json_map_leaves(
  722. func: Callable[[T], U],
  723. value: Tuple[JSONTree[T], ...],
  724. ) -> Tuple[JSONTree[U], ...]:
  725. ...
  726. @overload
  727. def json_map_leaves(
  728. func: Callable[[T], U],
  729. value: JSONTree[T],
  730. ) -> JSONTree[U]:
  731. ...
  732. def json_map_leaves(func: Callable[[T], U], value: JSONTree[T]) -> JSONTree[U]:
  733. if isinstance(value, dict):
  734. return {k: json_map_leaves(func, v) for k, v in value.items()}
  735. elif isinstance(value, list):
  736. return [json_map_leaves(func, v) for v in value]
  737. elif isinstance(value, tuple):
  738. return tuple(json_map_leaves(func, v) for v in value)
  739. else:
  740. return func(value)
  741. def flatten_2d_lists(lists: List[List[T]]) -> List[T]:
  742. """Flatten a list of lists to a single list."""
  743. return [item for sublist in lists for item in sublist]
  744. def init_cached_hf_modules() -> None:
  745. """
  746. Lazy initialization of the Hugging Face modules.
  747. """
  748. from transformers.dynamic_module_utils import init_hf_modules
  749. init_hf_modules()
  750. @lru_cache(maxsize=None)
  751. def find_library(lib_name: str) -> str:
  752. """
  753. Find the library file in the system.
  754. `lib_name` is full filename, with both prefix and suffix.
  755. This function resolves `lib_name` to the full path of the library.
  756. """
  757. # Adapted from https://github.com/openai/triton/blob/main/third_party/nvidia/backend/driver.py#L19 # noqa
  758. # According to https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
  759. # `/sbin/ldconfig` should exist in all Linux systems.
  760. # `/sbin/ldconfig` searches the library in the system
  761. libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode()
  762. # each line looks like the following:
  763. # libcuda.so.1 (libc6,x86-64) => /lib/x86_64-linux-gnu/libcuda.so.1
  764. locs = [line.split()[-1] for line in libs.splitlines() if lib_name in line]
  765. # `LD_LIBRARY_PATH` searches the library in the user-defined paths
  766. env_ld_library_path = os.getenv("LD_LIBRARY_PATH")
  767. if not locs and env_ld_library_path:
  768. locs = [
  769. os.path.join(dir, lib_name)
  770. for dir in env_ld_library_path.split(":")
  771. if os.path.exists(os.path.join(dir, lib_name))
  772. ]
  773. if not locs:
  774. raise ValueError(f"Cannot find {lib_name} in the system.")
  775. return locs[0]
  776. def find_nccl_library() -> str:
  777. """
  778. We either use the library file specified by the `APHRODITE_NCCL_SO_PATH`
  779. environment variable, or we find the library file brought by PyTorch.
  780. After importing `torch`, `libnccl.so.2` or `librccl.so.1` can be
  781. found by `ctypes` automatically.
  782. """
  783. so_file = os.environ.get("APHRODITE_NCCL_SO_PATH", "")
  784. # manually load the nccl library
  785. if so_file:
  786. logger.debug("Found nccl from environment variable "
  787. f"APHRODITE_NCCL_SO_PATH={so_file}")
  788. else:
  789. if torch.version.cuda is not None:
  790. so_file = "libnccl.so.2"
  791. elif torch.version.hip is not None:
  792. so_file = "librccl.so.1"
  793. else:
  794. raise ValueError("NCCL only supports CUDA and ROCm backends.")
  795. logger.debug(f"Found nccl from library {so_file}")
  796. return so_file
  797. def enable_trace_function_call_for_thread() -> None:
  798. if int(os.getenv("APHRODITE_TRACE_FUNCTION", "0")):
  799. tmp_dir = tempfile.gettempdir()
  800. filename = (f"APHRODITE_TRACE_FUNCTION_for_process_{os.getpid()}"
  801. f"_thread_{threading.get_ident()}_"
  802. f"at_{datetime.datetime.now()}.log").replace(" ", "_")
  803. log_path = os.path.join(tmp_dir, "aphrodite",
  804. get_aphrodite_instance_id(), filename)
  805. os.makedirs(os.path.dirname(log_path), exist_ok=True)
  806. enable_trace_function_call(log_path)
  807. def identity(value: T) -> T:
  808. return value
  809. F = TypeVar('F', bound=Callable[..., Any])
  810. def deprecate_kwargs(
  811. *kws: str,
  812. is_deprecated: Union[bool, Callable[[], bool]] = True,
  813. additional_message: Optional[str] = None) -> Callable[[F], F]:
  814. deprecated_kws = set(kws)
  815. if not callable(is_deprecated):
  816. is_deprecated = partial(identity, is_deprecated)
  817. def wrapper(fn: F) -> F:
  818. @wraps(fn)
  819. def inner(*args, **kwargs):
  820. if is_deprecated():
  821. deprecated_kwargs = kwargs.keys() & deprecated_kws
  822. if deprecated_kwargs:
  823. msg = (
  824. f"The keyword arguments {deprecated_kwargs} are "
  825. "deprecated and will be removed in a future update.")
  826. if additional_message is not None:
  827. msg += f" {additional_message}"
  828. warnings.warn(
  829. DeprecationWarning(msg),
  830. stacklevel=3, # The inner function takes up one level
  831. )
  832. return fn(*args, **kwargs)
  833. return inner # type: ignore
  834. return wrapper
  835. @lru_cache(maxsize=8)
  836. def _cuda_device_count_stateless(
  837. cuda_visible_devices: Optional[str] = None) -> int:
  838. # Note: cuda_visible_devices is not used, but we keep it as an argument for
  839. # LRU Cache purposes.
  840. # Code below is based on
  841. # https://github.com/pytorch/pytorch/blob/
  842. # c1cd946818442aca8c7f812b16d187ce1586c3bc/
  843. # torch/cuda/__init__.py#L831C1-L831C17
  844. import torch.cuda
  845. import torch.version
  846. if not torch.cuda._is_compiled():
  847. return 0
  848. if is_hip():
  849. # ROCm uses amdsmi instead of nvml for stateless device count
  850. # This requires a sufficiently modern version of Torch 2.4.0
  851. raw_count = torch.cuda._device_count_amdsmi() if (hasattr(
  852. torch.cuda, "_device_count_amdsmi")) else -1
  853. else:
  854. raw_count = torch.cuda._device_count_nvml()
  855. r = torch._C._cuda_getDeviceCount() if raw_count < 0 else raw_count
  856. return r
  857. def cuda_device_count_stateless() -> int:
  858. """Get number of CUDA devices, caching based on the value of
  859. CUDA_VISIBLE_DEVICES at the time of call.
  860. This should be used instead of torch.cuda.device_count()
  861. unless CUDA_VISIBLE_DEVICES has already been set to the desired
  862. value."""
  863. # This can be removed and simply replaced with torch.cuda.get_device_count
  864. # after https://github.com/pytorch/pytorch/pull/122815 is released.
  865. return _cuda_device_count_stateless(os.environ.get("CUDA_VISIBLE_DEVICES"))
  866. #From: https://stackoverflow.com/a/4104188/2749989
  867. def run_once(f):
  868. def wrapper(*args, **kwargs) -> Any:
  869. if not wrapper.has_run: # type: ignore[attr-defined]
  870. wrapper.has_run = True # type: ignore[attr-defined]
  871. return f(*args, **kwargs)
  872. wrapper.has_run = False # type: ignore[attr-defined]
  873. return wrapper
  874. class FlexibleArgumentParser(argparse.ArgumentParser):
  875. """ArgumentParser that allows both underscore and dash in names."""
  876. def parse_args(self, args=None, namespace=None):
  877. if args is None:
  878. args = sys.argv[1:]
  879. # Convert underscores to dashes and vice versa in argument names
  880. processed_args = []
  881. for arg in args:
  882. if arg.startswith('--'):
  883. if '=' in arg:
  884. key, value = arg.split('=', 1)
  885. key = '--' + key[len('--'):].replace('_', '-')
  886. processed_args.append(f'{key}={value}')
  887. else:
  888. processed_args.append('--' +
  889. arg[len('--'):].replace('_', '-'))
  890. else:
  891. processed_args.append(arg)
  892. return super().parse_args(processed_args, namespace)
  893. async def _run_task_with_lock(task: Callable, lock: asyncio.Lock, *args,
  894. **kwargs):
  895. """Utility function to run async task in a lock"""
  896. async with lock:
  897. return await task(*args, **kwargs)
  898. def progress_bar(iterable, desc="Processing"):
  899. show_progress = get_tensor_model_parallel_rank() == 0
  900. if show_progress:
  901. with Progress(
  902. SpinnerColumn(),
  903. TextColumn("[progress.description]{task.description}"),
  904. BarColumn(),
  905. MofNCompleteColumn(),
  906. TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
  907. TimeElapsedColumn(),
  908. ) as progress:
  909. task = progress.add_task(f"[cyan]{desc}", total=len(iterable))
  910. for item in iterable:
  911. yield item
  912. progress.update(task, advance=1)
  913. else:
  914. yield from iterable
  915. def tensor_progress_bar(iterable:Iterable[Tuple[str, torch.Tensor]],
  916. final_bytes:int, desc="Processing"):
  917. show_progress = get_tensor_model_parallel_rank() == 0
  918. units = 1024 ** (int(math.log2(final_bytes)) // 10)
  919. if show_progress:
  920. with Progress(
  921. SpinnerColumn(),
  922. TextColumn("[progress.description]{task.description}"),
  923. BarColumn(),
  924. # MofNCompleteColumn(),
  925. TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
  926. TextColumn("{task.completed:.2f}/{task.total:.2f} GiB"),
  927. TimeElapsedColumn(),
  928. ) as progress:
  929. task = progress.add_task(f"[cyan]{desc}", total=final_bytes/units)
  930. for item in iterable:
  931. steps = item[1].element_size() * item[1].nelement() / units
  932. yield item
  933. progress.update(task, advance=steps)
  934. else:
  935. yield from iterable