utils.py 38 KB

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