vllm.utils ¶
Modules:
Name | Description |
---|---|
asyncio | Contains helpers related to asynchronous code. |
cache | |
collections | Contains helpers that are applied to collections. |
deep_gemm | Compatibility wrapper for DeepGEMM API changes. |
flashinfer | Compatibility wrapper for FlashInfer API changes. |
functools | Contains helpers that are applied to functions. |
gc_utils | |
import_utils | Contains helpers related to importing modules. |
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,
}
AtomicCounter ¶
An atomic, thread-safe counter
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
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 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 |
|
_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
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 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 |
|
add_argument ¶
add_argument_group ¶
check_port ¶
Source code in vllm/utils/__init__.py
format_help ¶
Source code in vllm/utils/__init__.py
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 |
|
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
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 |
|
parse_known_args ¶
Source code in vllm/utils/__init__.py
LayerBlockType ¶
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
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 |
|
__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
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
_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
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
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
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 ¶
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
init_cached_hf_modules ¶
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
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 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 |
|
prev_power_of_2 ¶
round_down ¶
round_up ¶
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
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