vllm.utils
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 = {
"half": half,
"bfloat16": bfloat16,
"float": float,
"fp8": uint8,
"fp8_e4m3": uint8,
"fp8_e5m2": uint8,
"int8": int8,
}
STR_DUAL_CHUNK_FLASH_ATTN_VAL
module-attribute
¶
STR_DUAL_CHUNK_FLASH_ATTN_VAL: str = "DUAL_CHUNK_FLASH_ATTN"
STR_NOT_IMPL_ENC_DEC_BACKEND
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_BACKEND = "XFormers and Flash-Attention are the only backends currently supported with encoder/decoder models."
STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL = (
"Chunked prefill for encoder/decoder models "
+ "is not currently supported."
)
STR_NOT_IMPL_ENC_DEC_ERR_STRS
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_ERR_STRS = {
"STR_NOT_IMPL_ENC_DEC_SWA": STR_NOT_IMPL_ENC_DEC_SWA,
"STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE": STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE,
"STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL": STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL,
"STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP": STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP,
"STR_NOT_IMPL_ENC_DEC_LORA": STR_NOT_IMPL_ENC_DEC_LORA,
"STR_NOT_IMPL_ENC_DEC_PP": STR_NOT_IMPL_ENC_DEC_PP,
"STR_NOT_IMPL_ENC_DEC_MM": STR_NOT_IMPL_ENC_DEC_MM,
"STR_NOT_IMPL_ENC_DEC_SPEC_DEC": STR_NOT_IMPL_ENC_DEC_SPEC_DEC,
"STR_NOT_IMPL_ENC_DEC_BACKEND": STR_NOT_IMPL_ENC_DEC_BACKEND,
"STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER": STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER,
}
STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP = "Models with logits_soft_cap require FlashInfer backend, which is currently not supported for encoder/decoder models."
STR_NOT_IMPL_ENC_DEC_LORA
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_MM
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_PP
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_PP = "Pipeline parallelism is not currently supported with encoder/decoder models."
STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE = (
"Prefix caching for encoder/decoder models "
+ "is not currently supported."
)
STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER = "Prompt adapters are not currently supported with encoder/decoder models."
STR_NOT_IMPL_ENC_DEC_SPEC_DEC
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_SPEC_DEC = "Speculative decoding is not currently supported with encoder/decoder models."
STR_NOT_IMPL_ENC_DEC_SWA
module-attribute
¶
STR_NOT_IMPL_ENC_DEC_SWA = (
"Sliding window attention for encoder/decoder models "
+ "is not currently supported."
)
TORCH_DTYPE_TO_NUMPY_DTYPE
module-attribute
¶
TORCH_DTYPE_TO_NUMPY_DTYPE = {
float16: float16,
float32: float32,
float64: float64,
uint8: uint8,
int32: int32,
int64: int64,
}
AtomicCounter
¶
An atomic, thread-safe counter
Source code in vllm/utils.py
CacheInfo
¶
ClassRegistry
¶
Source code in vllm/utils.py
Counter
¶
Device
¶
DeviceMemoryProfiler
¶
Source code in vllm/utils.py
FlexibleArgumentParser
¶
Bases: ArgumentParser
ArgumentParser that allows both underscore and dash in names.
Source code in vllm/utils.py
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 |
|
__init__
¶
_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.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.py
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 |
|
add_argument
¶
add_argument_group
¶
check_port
¶
Source code in vllm/utils.py
parse_args
¶
Source code in vllm/utils.py
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 |
|
parse_known_args
¶
Source code in vllm/utils.py
LRUCache
¶
Bases: LRUCache[_K, _V]
, Generic[_K, _V]
Source code in vllm/utils.py
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 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 |
|
__delitem__
¶
__delitem__(key: _K) -> None
Source code in vllm/utils.py
__getitem__
¶
__init__
¶
_on_remove
¶
_remove_old_if_needed
¶
clear
¶
pin
¶
pin(key: _K) -> None
Pins a key in the cache preventing it from being evicted in the LRU order.
popitem
¶
popitem(remove_pinned: bool = False)
Remove and return the (key, value)
pair least recently used.
Source code in vllm/utils.py
put
¶
stat
¶
Gets the cumulative number of hits and queries against this cache.
If delta=True
, instead gets these statistics
since the last call that also passed delta=True
.
Source code in vllm/utils.py
LayerBlockType
¶
LazyDict
¶
Bases: Mapping[str, T]
, Generic[T]
Source code in vllm/utils.py
LazyLoader
¶
Bases: ModuleType
LazyLoader module borrowed from Tensorflow https://github.com/tensorflow/tensorflow/blob/main/tensorflow/python/util/lazy_loader.py with a 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.py
__dir__
¶
__getattr__
¶
__init__
¶
Source code in vllm/utils.py
_load
¶
_load() -> ModuleType
Source code in vllm/utils.py
MemoryProfilingResult
dataclass
¶
Memory profiling result. All numbers are in bytes.
Source code in vllm/utils.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.py
MemorySnapshot
dataclass
¶
Memory snapshot.
Source code in vllm/utils.py
__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.py
measure
¶
Source code in vllm/utils.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 exists.
Source code in vllm/utils.py
__getattr__
¶
__getattr__(key: str)
Source code in vllm/utils.py
PyObjectCache
¶
Used to cache python objects to avoid object allocations across scheduler iterations.
Source code in vllm/utils.py
SortedHelpFormatter
¶
Bases: ArgumentDefaultsHelpFormatter
, RawDescriptionHelpFormatter
SortedHelpFormatter that sorts arguments by their option strings.
Source code in vllm/utils.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.py
StoreBoolean
¶
Bases: Action
Source code in vllm/utils.py
__call__
¶
Source code in vllm/utils.py
_MappingOrderCacheView
¶
Source code in vllm/utils.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.py
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 2139 2140 2141 2142 2143 |
|
__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.py
__init__
¶
__init__(module: PlaceholderModule, attr_path: str) -> None
_cuda_device_count_stateless
cached
¶
Source code in vllm/utils.py
_generate_random_fp8
¶
Source code in vllm/utils.py
_get_open_port
¶
_get_open_port() -> int
Source code in vllm/utils.py
_get_precision_level
¶
_maybe_force_spawn
¶
Check if we need to force the use of the spawn
multiprocessing start
method.
Source code in vllm/utils.py
_next_task
¶
_next_task(
iterator: AsyncGenerator[T, None],
loop: AbstractEventLoop,
) -> Task
_run_task_with_lock
async
¶
async_tensor_h2d
¶
async_tensor_h2d(
data: list,
dtype: dtype,
target_device: Union[str, device],
pin_memory: bool,
) -> Tensor
Asynchronously create a tensor and copy it from host to device.
Source code in vllm/utils.py
bind_kv_cache
¶
Source code in vllm/utils.py
cdiv
¶
check_use_alibi
¶
check_use_alibi(model_config: ModelConfig) -> bool
Source code in vllm/utils.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.py
cprofile
¶
Decorator to profile a Python method using cProfile.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_file
|
Optional[str]
|
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.py
cprofile_context
¶
Run a cprofile
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_file
|
Optional[str]
|
path to save the profile result. "1" or None will result in printing to stdout. |
None
|
Source code in vllm/utils.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: Optional[Union[str, dtype]],
model_dtype: Optional[Union[str, dtype]] = None,
seed: Optional[int] = None,
device: Optional[str] = "cuda",
) -> tuple[list[Tensor], list[Tensor]]
Source code in vllm/utils.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: Optional[Union[str, dtype]],
model_dtype: Optional[Union[str, dtype]] = None,
seed: Optional[int] = None,
device: Optional[str] = "cuda",
cache_layout: Optional[str] = "NHD",
) -> tuple[list[Tensor], list[Tensor]]
Source code in vllm/utils.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.py
cuda_get_device_properties
¶
Get specified CUDA device property values without initializing CUDA in the current process.
Source code in vllm/utils.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.py
deprecate_args
¶
deprecate_args(
start_index: int,
is_deprecated: Union[bool, Callable[[], bool]] = True,
additional_message: Optional[str] = None,
) -> Callable[[F], F]
Source code in vllm/utils.py
deprecate_kwargs
¶
deprecate_kwargs(
*kws: str,
is_deprecated: Union[bool, Callable[[], bool]] = True,
additional_message: Optional[str] = None,
) -> Callable[[F], F]
Source code in vllm/utils.py
direct_register_custom_op
¶
direct_register_custom_op(
op_name: str,
op_func: Callable,
mutates_args: list[str],
fake_impl: Optional[Callable] = None,
target_lib: Optional[Library] = None,
dispatch_key: str = "CUDA",
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.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.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.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.py
find_process_using_port
¶
Source code in vllm/utils.py
flatten_2d_lists
¶
full_groupby
¶
Unlike itertools.groupby
, groups are not broken by
non-contiguous data.
Source code in vllm/utils.py
get_allowed_kwarg_only_overrides
¶
get_allowed_kwarg_only_overrides(
callable: Callable[..., object],
overrides: Optional[Mapping[str, object]],
*,
requires_kw_only: bool = True,
allow_var_kwargs: bool = False,
) -> dict[str, Any]
Given a callable which has one or more keyword only params and a dict mapping param names to values, drop values that can be not be kwarg expanded to overwrite one or more keyword-only args. This is used in a few places to handle custom processor overrides for multimodal models, e.g., for profiling when processor options provided by the user may affect the number of mm tokens per instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
callable
|
Callable[..., object]
|
Callable which takes 0 or more keyword only arguments. If None is provided, all overrides names are allowed. |
required |
overrides
|
Optional[Mapping[str, object]]
|
Potential overrides to be used when invoking the callable. |
required |
allow_var_kwargs
|
bool
|
Allows overrides that are expandable for var kwargs. |
False
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Dictionary containing the kwargs to be leveraged which may be used |
dict[str, Any]
|
to overwrite one or more keyword only arguments when invoking the |
dict[str, Any]
|
callable. |
Source code in vllm/utils.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.py
get_distributed_init_method
¶
get_dtype_size
¶
get_exception_traceback
¶
get_ip
¶
get_ip() -> str
Source code in vllm/utils.py
get_kv_cache_torch_dtype
¶
get_kv_cache_torch_dtype(
cache_dtype: Optional[Union[str, dtype]],
model_dtype: Optional[Union[str, dtype]] = None,
) -> dtype
Source code in vllm/utils.py
get_max_shared_memory_bytes
cached
¶
Returns the maximum shared memory per thread block in bytes.
Source code in vllm/utils.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.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.py
get_tcp_uri
¶
get_vllm_optional_dependencies
cached
¶
Source code in vllm/utils.py
identity
¶
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.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.py
init_cached_hf_modules
¶
is_in_ray_actor
¶
Check if we are in a Ray actor.
is_list_of
¶
is_list_of(
value: object,
typ: Union[type[T], tuple[type[T], ...]],
*,
check: Literal["first", "all"] = "first",
) -> TypeIs[list[T]]
Source code in vllm/utils.py
is_lossless_cast
¶
Test whether it is lossless to cast a tensor from
src_dtype
to tgt_dtype
.
Source code in vllm/utils.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.py
is_uva_available
cached
¶
is_uva_available() -> bool
Check if Unified Virtual Addressing (UVA) is available.
is_valid_ipv6_address
¶
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.py
make_async
¶
make_async(
func: Callable[P, T],
executor: Optional[Executor] = None,
) -> Callable[P, Awaitable[T]]
Take a blocking function, and run it on in an executor thread.
This function prevents the blocking function from blocking the asyncio event loop. The code in this function needs to be thread safe.
Source code in vllm/utils.py
make_ndarray_with_pad
¶
make_ndarray_with_pad(
x: list[list[T]],
pad: T,
dtype: DTypeLike,
*,
max_len: Optional[int] = 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.py
make_tensor_with_pad
¶
make_tensor_with_pad(
x: list[list[T]],
pad: T,
dtype: dtype,
*,
max_len: Optional[int] = None,
device: Optional[Union[str, device]] = 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.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
|
Optional[int]
|
Optional port number, only used for TCP sockets. |
None
|
Returns:
Type | Description |
---|---|
str
|
A properly formatted ZMQ path string. |
Source code in vllm/utils.py
make_zmq_socket
¶
make_zmq_socket(
ctx: Union[Context, Context],
path: str,
socket_type: Any,
bind: Optional[bool] = None,
identity: Optional[bytes] = None,
linger: Optional[int] = None,
) -> Union[Socket, Socket]
Make a ZMQ socket with the proper bind/connect semantics.
Source code in vllm/utils.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.py
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 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 |
|
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.py
resolve_mm_processor_kwargs
¶
resolve_mm_processor_kwargs(
init_kwargs: Optional[Mapping[str, object]],
inference_kwargs: Optional[Mapping[str, object]],
callable: Callable[..., object],
*,
requires_kw_only: bool = True,
allow_var_kwargs: bool = False,
) -> dict[str, Any]
Applies filtering to eliminate invalid mm_processor_kwargs, i.e., those who are not explicit keywords to the given callable (of one is given; otherwise no filtering is done), then merges the kwarg dicts, giving priority to inference_kwargs if there are any collisions.
In the case that no kwarg overrides are provided, returns an empty dict so that it can still be kwarg expanded into the callable later on.
If allow_var_kwargs=True, allows for things that can be expanded into kwargs as long as they aren't naming collision for var_kwargs or potential positional arguments.
Source code in vllm/utils.py
resolve_obj_by_qualname
¶
Resolve an object by its fully qualified name.
round_down
¶
round_up
¶
run_method
¶
run_method(
obj: Any,
method: Union[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.py
run_once
¶
Source code in vllm/utils.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.py
set_ulimit
¶
Source code in vllm/utils.py
sha256
¶
sha256(input) -> int
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 picklable Python object. |
required |
Returns:
Type | Description |
---|---|
int
|
An integer representing the SHA-256 hash of the serialized input. |
Source code in vllm/utils.py
split_zmq_path
¶
Split a zmq path into its parts.
Source code in vllm/utils.py
supports_kw
¶
supports_kw(
callable: Callable[..., object],
kw_name: str,
*,
requires_kw_only: bool = False,
allow_var_kwargs: bool = True,
) -> bool
Check if a keyword is a valid kwarg for a callable; if requires_kw_only disallows kwargs names that can also be positional arguments.
Source code in vllm/utils.py
swap_dict_values
¶
Helper function to swap values for two keys
Source code in vllm/utils.py
update_environment_variables
¶
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.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.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.py
weak_ref_tensors
¶
weak_ref_tensors(
tensors: Union[Tensor, list[Tensor], tuple[Tensor]],
) -> Union[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.py
zmq_socket_ctx
¶
zmq_socket_ctx(
path: str,
socket_type: Any,
bind: Optional[bool] = None,
linger: int = 0,
identity: Optional[bytes] = None,
) -> Iterator[Socket]
Context manager for a ZMQ socket