vllm.utils ¶
Modules:
Name | Description |
---|---|
cache | |
deep_gemm | Compatibility wrapper for DeepGEMM API changes. |
flashinfer | Compatibility wrapper for FlashInfer API changes. |
func | Contains helpers that are applied to functions. |
gc_utils | |
jsontree | Helper functions to work with nested JSON structures. |
tensor_schema | |
MULTIMODAL_MODEL_MAX_NUM_BATCHED_TOKENS module-attribute
¶
POOLING_MODEL_MAX_NUM_BATCHED_TOKENS module-attribute
¶
STR_DTYPE_TO_TORCH_DTYPE module-attribute
¶
STR_DTYPE_TO_TORCH_DTYPE = {
"float32": float32,
"half": half,
"bfloat16": bfloat16,
"float": float,
"fp8": uint8,
"fp8_e4m3": uint8,
"fp8_e5m2": uint8,
"int8": int8,
"fp8_inc": float8_e4m3fn,
"fp8_ds_mla": uint8,
}
TORCH_DTYPE_TO_NUMPY_DTYPE module-attribute
¶
TORCH_DTYPE_TO_NUMPY_DTYPE = {
float16: float16,
float32: float32,
float64: float64,
uint8: uint8,
int32: int32,
int64: int64,
}
AsyncMicrobatchTokenizer ¶
Asynchronous tokenizer with micro-batching.
Pulls pending encode/decode requests from a queue and batches them up to reduce overhead. A single-thread ThreadPoolExecutor is used so the event loop stays responsive.
Source code in vllm/utils/__init__.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 |
|
_queues instance-attribute
¶
__call__ async
¶
Source code in vllm/utils/__init__.py
__del__ ¶
Source code in vllm/utils/__init__.py
__init__ ¶
Source code in vllm/utils/__init__.py
_batch_decode_loop async
¶
_batch_decode_loop(queue: Queue)
Batch incoming decode requests for efficiency.
Source code in vllm/utils/__init__.py
_batch_encode_loop async
¶
Batch incoming encode requests for efficiency.
Source code in vllm/utils/__init__.py
_get_queue ¶
_get_queue(
loop: AbstractEventLoop, key: tuple
) -> Queue[
tuple[str, dict, Future] | tuple[list[int], Future]
]
Get the request queue for the given operation key, creating a new queue and batcher task if needed.
Source code in vllm/utils/__init__.py
_queue_key ¶
Return a normalized key describing operation + kwargs.
add_special_tokens
: {True/False}truncation
: {True/False}- If
truncation
is False (max_length
is None), returns a key for a can_batch queue. - If
truncation
is True andmax_length
is None or equalstokenizer.model_max_length
, returns a key for a can_batch queue. - Otherwise, returns a key for a cannot_batch queue.
Examples:
- Decode: ("decode",)
- Encode typical: ("encode", add_special_tokens, bool_truncation, max_length_label)
- Fallback: ("encode", "other")
Source code in vllm/utils/__init__.py
decode async
¶
Source code in vllm/utils/__init__.py
AtomicCounter ¶
An atomic, thread-safe counter
Source code in vllm/utils/__init__.py
ClassRegistry ¶
Source code in vllm/utils/__init__.py
Counter ¶
Device ¶
DeviceMemoryProfiler ¶
Source code in vllm/utils/__init__.py
FlexibleArgumentParser ¶
Bases: ArgumentParser
ArgumentParser that allows both underscore and dash in names.
Source code in vllm/utils/__init__.py
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 |
|
_json_tip class-attribute
instance-attribute
¶
_json_tip: str = 'When passing JSON CLI arguments, the following sets of arguments are equivalent:\n --json-arg \'{"key1": "value1", "key2": {"key3": "value2"}}\'\n --json-arg.key1 value1 --json-arg.key2.key3 value2\n\nAdditionally, list elements can be passed individually using +:\n --json-arg \'{"key4": ["value3", "value4", "value5"]}\'\n --json-arg.key4+ value3 --json-arg.key4+=\'value4,value5\'\n\n'
__init__ ¶
Source code in vllm/utils/__init__.py
_pull_args_from_config ¶
Method to pull arguments specified in the config file into the command-line args variable.
The arguments in config file will be inserted between the argument list.
example:
$: vllm {serve,chat,complete} "facebook/opt-12B" --config config.yaml -tp 2
$: args = [
"serve,chat,complete",
"facebook/opt-12B",
'--config', 'config.yaml',
'-tp', '2'
]
$: args = [
"serve,chat,complete",
"facebook/opt-12B",
'--port', '12323',
'--tensor-parallel-size', '4',
'-tp', '2'
]
Please note how the config args are inserted after the sub command. this way the order of priorities is maintained when these are args parsed by super().
Source code in vllm/utils/__init__.py
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 |
|
add_argument ¶
add_argument_group ¶
check_port ¶
Source code in vllm/utils/__init__.py
format_help ¶
Source code in vllm/utils/__init__.py
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 |
|
load_config_file ¶
Loads a yaml file and returns the key value pairs as a flattened list with argparse like pattern
returns: processed_args: list[str] = [ '--port': '12323', '--tensor-parallel-size': '4' ]Source code in vllm/utils/__init__.py
parse_args ¶
Source code in vllm/utils/__init__.py
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 |
|
parse_known_args ¶
Source code in vllm/utils/__init__.py
LayerBlockType ¶
LazyDict ¶
Bases: Mapping[str, T]
, Generic[T]
Source code in vllm/utils/__init__.py
LazyLoader ¶
Bases: ModuleType
LazyLoader module borrowed from Tensorflow https://github.com/tensorflow/tensorflow/blob/main/tensorflow/python/util/lazy_loader.py with an addition of "module caching".
Lazily import a module, mainly to avoid pulling in large dependencies. Modules such as xgrammar
might do additional side effects, so we only want to use this when it is needed, delaying all eager effects
Source code in vllm/utils/__init__.py
__dir__ ¶
__getattr__ ¶
__init__ ¶
Source code in vllm/utils/__init__.py
_load ¶
_load() -> ModuleType
Source code in vllm/utils/__init__.py
MemoryProfilingResult dataclass
¶
Memory profiling result. All numbers are in bytes.
Source code in vllm/utils/__init__.py
after_profile class-attribute
instance-attribute
¶
after_profile: MemorySnapshot = field(
default_factory=MemorySnapshot
)
before_create class-attribute
instance-attribute
¶
before_create: MemorySnapshot = field(
default_factory=MemorySnapshot
)
before_profile class-attribute
instance-attribute
¶
before_profile: MemorySnapshot = field(
default_factory=MemorySnapshot
)
__init__ ¶
__init__(
non_kv_cache_memory: int = 0,
torch_peak_increase: int = 0,
non_torch_increase: int = 0,
weights_memory: float = 0,
before_create: MemorySnapshot = MemorySnapshot(),
before_profile: MemorySnapshot = MemorySnapshot(),
after_profile: MemorySnapshot = MemorySnapshot(),
profile_time: float = 0.0,
) -> None
__repr__ ¶
__repr__() -> str
Source code in vllm/utils/__init__.py
MemorySnapshot dataclass
¶
Memory snapshot.
Source code in vllm/utils/__init__.py
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 |
|
__init__ ¶
__init__(
torch_peak: int = 0,
free_memory: int = 0,
total_memory: int = 0,
cuda_memory: int = 0,
torch_memory: int = 0,
non_torch_memory: int = 0,
timestamp: float = 0.0,
auto_measure: bool = True,
) -> None
__post_init__ ¶
__sub__ ¶
__sub__(other: MemorySnapshot) -> MemorySnapshot
Source code in vllm/utils/__init__.py
measure ¶
Source code in vllm/utils/__init__.py
PlaceholderModule ¶
Bases: _PlaceholderBase
A placeholder object to use when a module does not exist.
This enables more informative errors when trying to access attributes of a module that does not exist.
Source code in vllm/utils/__init__.py
__getattr__ ¶
__getattr__(key: str)
Source code in vllm/utils/__init__.py
SortedHelpFormatter ¶
Bases: ArgumentDefaultsHelpFormatter
, RawDescriptionHelpFormatter
SortedHelpFormatter that sorts arguments by their option strings.
Source code in vllm/utils/__init__.py
_split_lines ¶
- Sentences split across lines have their single newlines removed.
- Paragraphs and explicit newlines are split into separate lines.
- Each line is wrapped to the specified width (width of terminal).
Source code in vllm/utils/__init__.py
StoreBoolean ¶
Bases: Action
Source code in vllm/utils/__init__.py
__call__ ¶
Source code in vllm/utils/__init__.py
_PlaceholderBase ¶
Disallows downstream usage of placeholder modules.
We need to explicitly override each dunder method because __getattr__
is not called when they are accessed.
Source code in vllm/utils/__init__.py
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 |
|
__abs__ ¶
__bool__ ¶
__call__ ¶
__ceil__ ¶
__enter__ ¶
__exit__ ¶
__floor__ ¶
__getattr__ ¶
The main class should implement this to throw an error for attribute accesses representing downstream usage.
__hash__ ¶
__index__ ¶
__invert__ ¶
__len__ ¶
__neg__ ¶
__pos__ ¶
__pow__ ¶
__setitem__ ¶
__trunc__ ¶
_PlaceholderModuleAttr ¶
Bases: _PlaceholderBase
Source code in vllm/utils/__init__.py
__init__ ¶
__init__(module: PlaceholderModule, attr_path: str) -> None
_StreamPlaceholder ¶
Source code in vllm/utils/__init__.py
_add_prefix ¶
Prepend each output line with process-specific prefix
Source code in vllm/utils/__init__.py
_cuda_device_count_stateless cached
¶
Source code in vllm/utils/__init__.py
_generate_random_fp8 ¶
Source code in vllm/utils/__init__.py
_get_open_port ¶
_get_open_port() -> int
Source code in vllm/utils/__init__.py
_get_precision_level ¶
_has_module cached
¶
Return True if module_name can be found in the current environment.
The result is cached so that subsequent queries for the same module incur no additional overhead.
Source code in vllm/utils/__init__.py
_is_torch_equal ¶
Source code in vllm/utils/__init__.py
_is_torch_equal_or_newer ¶
_maybe_force_spawn ¶
Check if we need to force the use of the spawn
multiprocessing start method.
Source code in vllm/utils/__init__.py
_run_task_with_lock async
¶
as_iter ¶
as_list ¶
async_tensor_h2d ¶
async_tensor_h2d(
data: list,
dtype: dtype,
target_device: str | device,
pin_memory: bool,
) -> Tensor
Asynchronously create a tensor and copy it from host to device.
Source code in vllm/utils/__init__.py
bind_kv_cache ¶
bind_kv_cache(
ctx: dict[str, Any],
kv_cache: list[list[Tensor]],
shared_kv_cache_layers: dict[str, str] | None = None,
) -> None
Source code in vllm/utils/__init__.py
cdiv ¶
check_use_alibi ¶
check_use_alibi(model_config: ModelConfig) -> bool
Source code in vllm/utils/__init__.py
chunk_list ¶
collect_from_async_generator async
¶
collect_from_async_generator(
iterator: AsyncGenerator[T, None],
) -> list[T]
Collect all items from an async generator into a list.
common_broadcastable_dtype ¶
common_broadcastable_dtype(dtypes: Collection[dtype])
Get the common dtype
where all of the other dtypes
can be cast to it without losing any information.
Source code in vllm/utils/__init__.py
cprofile ¶
Decorator to profile a Python method using cProfile.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_file | str | None | Path to save the profile result. If "1", None, or "", results will be printed to stdout. | None |
enabled | bool | Set to false to turn this into a no-op | True |
Source code in vllm/utils/__init__.py
cprofile_context ¶
cprofile_context(save_file: str | None = None)
Run a cprofile
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_file | str | None | path to save the profile result. "1" or None will result in printing to stdout. | None |
Source code in vllm/utils/__init__.py
create_kv_caches_with_random ¶
create_kv_caches_with_random(
num_blocks: int,
block_size: int,
num_layers: int,
num_heads: int,
head_size: int,
cache_dtype: str | dtype | None,
model_dtype: str | dtype | None = None,
seed: int | None = None,
device: str | None = "cuda",
) -> tuple[list[Tensor], list[Tensor]]
Source code in vllm/utils/__init__.py
create_kv_caches_with_random_flash ¶
create_kv_caches_with_random_flash(
num_blocks: int,
block_size: int,
num_layers: int,
num_heads: int,
head_size: int,
cache_dtype: str | dtype | None,
model_dtype: str | dtype | None = None,
seed: int | None = None,
device: str | None = "cuda",
cache_layout: str | None = "NHD",
) -> tuple[list[Tensor], list[Tensor]]
Source code in vllm/utils/__init__.py
cuda_device_count_stateless ¶
cuda_device_count_stateless() -> int
Get number of CUDA devices, caching based on the value of CUDA_VISIBLE_DEVICES at the time of call.
This should be used instead of torch.cuda.device_count() unless CUDA_VISIBLE_DEVICES has already been set to the desired value.
Source code in vllm/utils/__init__.py
cuda_get_device_properties ¶
Get specified CUDA device property values without initializing CUDA in the current process.
Source code in vllm/utils/__init__.py
current_stream ¶
current_stream() -> Stream
replace torch.cuda.current_stream()
with vllm.utils.current_stream()
. it turns out that torch.cuda.current_stream()
is quite expensive, as it will construct a new stream object at each call. here we patch torch.cuda.set_stream
to keep track of the current stream directly, so that we can avoid calling torch.cuda.current_stream()
.
the underlying hypothesis is that we do not call torch._C._cuda_setStream
from C/C++ code.
Source code in vllm/utils/__init__.py
decorate_logs ¶
decorate_logs(process_name: str | None = None) -> None
Adds a process-specific prefix to each line of output written to stdout and stderr.
This function is intended to be called before initializing the api_server, engine_core, or worker classes, so that all subsequent output from the process is prefixed with the process name and PID. This helps distinguish log output from different processes in multi-process environments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
process_name | str | None | Optional; the name of the process to use in the prefix. If not provided, the current process name from the multiprocessing context is used. | None |
Source code in vllm/utils/__init__.py
direct_register_custom_op ¶
direct_register_custom_op(
op_name: str,
op_func: Callable,
mutates_args: list[str] | None = None,
fake_impl: Callable | None = None,
target_lib: Library | None = None,
dispatch_key: str | None = None,
tags: tuple[Tag, ...] = (),
)
torch.library.custom_op
can have significant overhead because it needs to consider complicated dispatching logic. This function directly registers a custom op and dispatches it to the CUDA backend. See https://gist.github.com/youkaichao/ecbea9ec9fc79a45d2adce1784d7a9a5 for more details.
By default, the custom op is registered to the vLLM library. If you want to register it to a different library, you can pass the library object to the target_lib
argument.
IMPORTANT: the lifetime of the operator is tied to the lifetime of the library object. If you want to bind the operator to a different library, make sure the library object is alive when the operator is used.
Source code in vllm/utils/__init__.py
enable_trace_function_call_for_thread ¶
enable_trace_function_call_for_thread(
vllm_config: VllmConfig,
) -> None
Set up function tracing for the current thread, if enabled via the VLLM_TRACE_FUNCTION environment variable
Source code in vllm/utils/__init__.py
find_library cached
¶
Find the library file in the system. lib_name
is full filename, with both prefix and suffix. This function resolves lib_name
to the full path of the library.
Source code in vllm/utils/__init__.py
find_nccl_include_paths ¶
We either use the nccl.h specified by the VLLM_NCCL_INCLUDE_PATH
environment variable, or we find the library file brought by nvidia-nccl-cuXX. load_inline by default uses torch.utils.cpp_extension.include_paths
Source code in vllm/utils/__init__.py
find_nccl_library ¶
find_nccl_library() -> str
We either use the library file specified by the VLLM_NCCL_SO_PATH
environment variable, or we find the library file brought by PyTorch. After importing torch
, libnccl.so.2
or librccl.so.1
can be found by ctypes
automatically.
Source code in vllm/utils/__init__.py
find_process_using_port ¶
Source code in vllm/utils/__init__.py
flatten_2d_lists ¶
full_groupby ¶
full_groupby(
values: Iterable[_V" backlink-type="used-by" backlink-anchor="vllm.utils.full_groupby" optional hover>_V], *, key: Callable[[_V], _K]
)
Unlike itertools.groupby
, groups are not broken by non-contiguous data.
Source code in vllm/utils/__init__.py
get_cuda_view_from_cpu_tensor ¶
Get a CUDA view of a CPU tensor using Unified Virtual Addressing (UVA).
Source code in vllm/utils/__init__.py
get_distributed_init_method ¶
get_dtype_size ¶
get_exception_traceback ¶
get_hash_fn_by_name ¶
Get a hash function by name, or raise an error if the function is not found. Args: hash_fn_name: Name of the hash function. Returns: A hash function.
Source code in vllm/utils/__init__.py
get_ip ¶
get_ip() -> str
Source code in vllm/utils/__init__.py
get_kv_cache_torch_dtype ¶
get_kv_cache_torch_dtype(
cache_dtype: str | dtype | None,
model_dtype: str | dtype | None = None,
) -> dtype
Source code in vllm/utils/__init__.py
get_loopback_ip ¶
get_loopback_ip() -> str
Source code in vllm/utils/__init__.py
get_max_shared_memory_bytes cached
¶
Returns the maximum shared memory per thread block in bytes.
Source code in vllm/utils/__init__.py
get_mp_context ¶
Get a multiprocessing context with a particular method (spawn or fork). By default we follow the value of the VLLM_WORKER_MULTIPROC_METHOD to determine the multiprocessing method (default is fork). However, under certain conditions, we may enforce spawn and override the value of VLLM_WORKER_MULTIPROC_METHOD.
Source code in vllm/utils/__init__.py
get_open_port ¶
get_open_port() -> int
Get an open port for the vLLM process to listen on. An edge case to handle, is when we run data parallel, we need to avoid ports that are potentially used by the data parallel master process. Right now we reserve 10 ports for the data parallel master process. Currently it uses 2 ports.
Source code in vllm/utils/__init__.py
get_open_ports_list ¶
get_tcp_uri ¶
get_vllm_optional_dependencies cached
¶
Source code in vllm/utils/__init__.py
import_from_path ¶
Import a Python file according to its file path.
Based on the official recipe: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
Source code in vllm/utils/__init__.py
import_pynvml ¶
Historical comments:
libnvml.so is the library behind nvidia-smi, and pynvml is a Python wrapper around it. We use it to get GPU status without initializing CUDA context in the current process. Historically, there are two packages that provide pynvml: - nvidia-ml-py
(https://pypi.org/project/nvidia-ml-py/): The official wrapper. It is a dependency of vLLM, and is installed when users install vLLM. It provides a Python module named pynvml
. - pynvml
(https://pypi.org/project/pynvml/): An unofficial wrapper. Prior to version 12.0, it also provides a Python module pynvml
, and therefore conflicts with the official one. What's worse, the module is a Python package, and has higher priority than the official one which is a standalone Python file. This causes errors when both of them are installed. Starting from version 12.0, it migrates to a new module named pynvml_utils
to avoid the conflict. It is so confusing that many packages in the community use the unofficial one by mistake, and we have to handle this case. For example, nvcr.io/nvidia/pytorch:24.12-py3
uses the unofficial one, and it will cause errors, see the issue https://github.com/vllm-project/vllm/issues/12847 for example. After all the troubles, we decide to copy the official pynvml
module to our codebase, and use it directly.
Source code in vllm/utils/__init__.py
in_loop ¶
in_loop(event_loop: AbstractEventLoop) -> bool
init_cached_hf_modules ¶
is_list_of ¶
is_list_of(
value: object,
typ: type[T] | tuple[type[T], ...],
*,
check: Literal["first", "all"] = "first",
) -> TypeIs[list[T]]
Source code in vllm/utils/__init__.py
is_lossless_cast ¶
Test whether it is lossless to cast a tensor from src_dtype
to tgt_dtype
.
Source code in vllm/utils/__init__.py
is_torch_equal ¶
Check if the installed torch version is == the target version.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target | str | a version string, like "2.6.0". | required |
Returns:
Type | Description |
---|---|
bool | Whether the condition meets. |
Source code in vllm/utils/__init__.py
is_torch_equal_or_newer ¶
Check if the installed torch version is >= the target version.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target | str | a version string, like "2.6.0". | required |
Returns:
Type | Description |
---|---|
bool | Whether the condition meets. |
Source code in vllm/utils/__init__.py
is_uva_available cached
¶
is_uva_available() -> bool
Check if Unified Virtual Addressing (UVA) is available.
is_valid_ipv6_address ¶
join_host_port ¶
kill_process_tree ¶
kill_process_tree(pid: int)
Kills all descendant processes of the given pid by sending SIGKILL.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pid | int | Process ID of the parent process | required |
Source code in vllm/utils/__init__.py
length_from_prompt_token_ids_or_embeds ¶
length_from_prompt_token_ids_or_embeds(
prompt_token_ids: list[int] | None,
prompt_embeds: Tensor | None,
) -> int
Calculate the request length (in number of tokens) give either prompt_token_ids or prompt_embeds.
Source code in vllm/utils/__init__.py
make_ndarray_with_pad ¶
make_ndarray_with_pad(
x: list[list[T]],
pad: T,
dtype: DTypeLike,
*,
max_len: int | None = None,
) -> NDArray
Make a padded array from 2D inputs.
The padding is applied to the end of each inner list until it reaches max_len
.
Source code in vllm/utils/__init__.py
make_tensor_with_pad ¶
make_tensor_with_pad(
x: list[list[T]],
pad: T,
dtype: dtype,
*,
max_len: int | None = None,
device: str | device | None = None,
pin_memory: bool = False,
) -> Tensor
Make a padded tensor from 2D inputs.
The padding is applied to the end of each inner list until it reaches max_len
.
Source code in vllm/utils/__init__.py
make_zmq_path ¶
Make a ZMQ path from its parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scheme | str | The ZMQ transport scheme (e.g. tcp, ipc, inproc). | required |
host | str | The host - can be an IPv4 address, IPv6 address, or hostname. | required |
port | int | None | Optional port number, only used for TCP sockets. | None |
Returns:
Type | Description |
---|---|
str | A properly formatted ZMQ path string. |
Source code in vllm/utils/__init__.py
make_zmq_socket ¶
make_zmq_socket(
ctx: Context | Context,
path: str,
socket_type: Any,
bind: bool | None = None,
identity: bytes | None = None,
linger: int | None = None,
) -> Socket | Socket
Make a ZMQ socket with the proper bind/connect semantics.
Source code in vllm/utils/__init__.py
memory_profiling ¶
memory_profiling(
baseline_snapshot: MemorySnapshot, weights_memory: int
) -> Generator[MemoryProfilingResult, None, None]
Memory profiling context manager. baseline_snapshot: the memory snapshot before the current vLLM instance. weights_memory: memory used by PyTorch when loading the model weights. Note that, before loading the model weights, we also initialize the device and distributed environment, which may consume some memory. This part is not included in the weights_memory because PyTorch does not control it.
The memory in one GPU can be classified into 3 categories: 1. memory used by anything other than the current vLLM instance. 2. memory used by torch in the current vLLM instance. 3. memory used in the current vLLM instance, but not by torch.
A quantitive example:
Before creating the current vLLM instance
category 1: 1 GiB category 2: 0 GiB category 3: 0 GiB
After creating the current vLLM instance and loading the model, (i.e. before profiling): category 1: 1 GiB category 2: 2 GiB (model weights take 2 GiB) category 3: 0.5 GiB (memory used by NCCL)
During profiling (peak): category 1: 1 GiB category 2: 4 GiB (peak activation tensors take 2 GiB) category 3: 1 GiB (memory used by NCCL + buffers for some attention backends)
After profiling
category 1: 1 GiB category 2: 3 GiB (after garbage-collecting activation tensors) category 3: 1 GiB (memory used by NCCL + buffers for some attention backends)
In this case, non-kv cache takes 5 GiB in total, including: a. 2 GiB used by the model weights (category 2) b. 2 GiB reserved for the peak activation tensors (category 2) c. 1 GiB used by non-torch components (category 3)
The memory used for loading weights (a.) is directly given from the argument weights_memory
.
The increase of torch.cuda.memory_stats()["allocated_bytes.all.peak"]
during profiling gives (b.).
The increase of non_torch_memory
from creating the current vLLM instance until after profiling to get (c.).
Source code in vllm/utils/__init__.py
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 |
|
merge_async_iterators async
¶
merge_async_iterators(
*iterators: AsyncGenerator[T, None],
) -> AsyncGenerator[tuple[int, T], None]
Merge multiple asynchronous iterators into a single iterator.
This method handle the case where some iterators finish before others. When it yields, it yields a tuple (i, item) where i is the index of the iterator that yields the item.
Source code in vllm/utils/__init__.py
prev_power_of_2 ¶
resolve_obj_by_qualname ¶
Resolve an object by its fully-qualified class name.
Source code in vllm/utils/__init__.py
round_down ¶
round_up ¶
run_in_loop ¶
run_in_loop(
loop: AbstractEventLoop, function: Callable, *args
)
run_method ¶
run_method(
obj: Any,
method: str | bytes | Callable,
args: tuple[Any],
kwargs: dict[str, Any],
) -> Any
Run a method of an object with the given arguments and keyword arguments. If the method is string, it will be converted to a method using getattr. If the method is serialized bytes and will be deserialized using cloudpickle. If the method is a callable, it will be called directly.
Source code in vllm/utils/__init__.py
set_default_torch_num_threads ¶
set_default_torch_num_threads(num_threads: int)
Sets the default number of threads for PyTorch to the given value.
Source code in vllm/utils/__init__.py
set_env_var ¶
set_process_title ¶
Set the current process title to a specific name with an optional suffix.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name | str | The title to assign to the current process. | required |
suffix | str | An optional suffix to append to the base name. | '' |
prefix | str | A prefix to prepend to the front separated by | VLLM_PROCESS_NAME_PREFIX |
Source code in vllm/utils/__init__.py
set_ulimit ¶
Source code in vllm/utils/__init__.py
sha256 ¶
Hash any picklable Python object using SHA-256.
The input is serialized using pickle before hashing, which allows arbitrary Python objects to be used. Note that this function does not use a hash seed—if you need one, prepend it explicitly to the input.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input | Any | Any picklable Python object. | required |
Returns:
Type | Description |
---|---|
bytes | Bytes representing the SHA-256 hash of the serialized input. |
Source code in vllm/utils/__init__.py
sha256_cbor ¶
Hash objects using CBOR serialization and SHA-256.
This option is useful for non-Python-dependent serialization and hashing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input | Any | Object to be serialized and hashed. Supported types include basic Python types and complex structures like lists, tuples, and dictionaries. Custom classes must implement CBOR serialization methods. | required |
Returns:
Type | Description |
---|---|
bytes | Bytes representing the SHA-256 hash of the CBOR serialized input. |
Source code in vllm/utils/__init__.py
split_host_port ¶
Source code in vllm/utils/__init__.py
split_zmq_path ¶
Split a zmq path into its parts.
Source code in vllm/utils/__init__.py
swap_dict_values ¶
Helper function to swap values for two keys
Source code in vllm/utils/__init__.py
test_loopback_bind ¶
unique_filepath ¶
unique_filepath returns a unique path by trying to include an integer in increasing order.
fn should be a callable that returns a path that includes the passed int at a fixed location.
Note: This function has a TOCTOU race condition. Caller should use atomic operations (e.g., open with 'x' mode) when creating the file to ensure thread safety.
Source code in vllm/utils/__init__.py
update_environment_variables ¶
Source code in vllm/utils/__init__.py
warn_for_unimplemented_methods ¶
A replacement for abc.ABC
. When we use abc.ABC
, subclasses will fail to instantiate if they do not implement all abstract methods. Here, we only require raise NotImplementedError
in the base class, and log a warning if the method is not implemented in the subclass.
Source code in vllm/utils/__init__.py
weak_bind ¶
Make an instance method that weakly references its associated instance and no-ops once that instance is collected.
Source code in vllm/utils/__init__.py
weak_ref_tensor ¶
Create a weak reference to a tensor. The new tensor will share the same data as the original tensor, but will not keep the original tensor alive.
Source code in vllm/utils/__init__.py
weak_ref_tensors ¶
weak_ref_tensors(
tensors: Tensor
| list[Tensor]
| tuple[Tensor]
| IntermediateTensors,
) -> Tensor | list[Any] | tuple[Any] | Any
Convenience function to create weak references to tensors, for single tensor, list of tensors or tuple of tensors.
Source code in vllm/utils/__init__.py
zmq_socket_ctx ¶
zmq_socket_ctx(
path: str,
socket_type: Any,
bind: bool | None = None,
linger: int = 0,
identity: bytes | None = None,
) -> Iterator[Socket]
Context manager for a ZMQ socket