utils.py 40 KB

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