utils.py 38 KB

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