utils.py 37 KB

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