Skip to content

vllm.utils.torch_utils

Classes:

  • LayerName –

    Wraps a module name string for use as a torch opaque type.

Functions:

LayerName

Bases: OpaqueBase

Wraps a module name string for use as a torch opaque type.

This is registered as a hoisted opaque object so that torch.compile lifts it as a graph input instead of baking it as a constant. This avoids per-layer recompilation for custom ops that accept layer name strings (attention, MOE, KV cache, etc.).

_cgroup_cpu_limit()

Effective CPU quota of this process's cgroup, None if unlimited.

Resolves the process's own cgroup from /proc/self/cgroup and takes the tightest cpu.max (v2) or cfs quota (v1) along the hierarchy.

_encode_layer_name(layer_name)

Wrap a str layer name as LayerName when enabled.

_resolve_layer_name(layer_name)

Unwrap a LayerName to str, or return str unchanged.

async_tensor_h2d(data, device=None, dtype=None, out=None)

Copy list/numpy array/tensor async from host to device.

aux_stream()

Ensures aux_stream is initialized only once.

available_cpu_count()

CPUs actually usable by this process: scheduling affinity capped by the cgroup CPU quota (unlike os.cpu_count(), which is quota-blind).

canonicalize_singleton_dim_strides(t)

Fix degenerate strides on size=1 dimensions for CUDA TMA compatibility.

PyTorch allows any stride on a size=1 dim (is_contiguous() is always True there), so a size=1 dim may have stride=1 (2 bytes for bf16) instead of the canonical product(shape[i+1:]). CUDA TMA on H100+ requires all non-outermost strides to be ≥16-byte aligned; stride=1 triggers cudaErrorIllegalInstruction. Zero-copy: patches stride metadata only via as_strided; returns t unchanged if all size=1 strides are already canonical.

common_broadcastable_dtype(dtypes)

Get the common dtype where all of the other dtypes can be cast to it without losing any information.

current_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.

direct_register_custom_op(op_name, op_func, mutates_args=None, fake_impl=None, target_lib=None, dispatch_key=None, tags=())

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.

eager_bypass_custom_op(op_name, op_func, target_lib=None)

Wrap a registered custom op so that only Dynamo tracing goes through the dispatcher, where the op is needed as a graph boundary; eager calls go straight to op_func. Use it on host-bound hot paths such as per-linear GEMM calls, where dispatch costs several µs per call.

get_accelerator_view_from_cpu_tensor(cpu_tensor)

Get an accelerator view of a CPU tensor via Unified Virtual Addressing.

get_dtype_size(dtype)

Get the size of the data type in bytes.

get_kv_cache_quant_algo_string(quant_cfg)

Get the KV cache quantization algorithm string from the quantization config.

Maps various FP8 format names to vLLM's standard cache dtype strings. Returns None if no kv_cache_quant_algo is specified. Returns "auto" if the value is not recognized/supported.

guard_cuda_initialization()

Avoid unexpected CUDA initialization.

is_lossless_cast(src_dtype, tgt_dtype)

Test whether it is lossless to cast a tensor from src_dtype to tgt_dtype.

is_meta_module(module)

Return True if module contains any meta parameters or buffers.

is_non_overlapping_and_dense(t)

Check if the tensor's elements cover one gapless, non-overlapping byte range, in any dimension order (i.e. a permuted view of a contiguous tensor); is_contiguous() additionally requires row-major order.

is_strictly_contiguous(t)

Check if tensor is contiguous AND has no degenerate strides.

A degenerate stride occurs when a dimension has size 1 but the stride doesn't match the canonical contiguous layout. This can cause issues in some CUDA kernels that rely on stride values for memory access.

For a C-contiguous tensor of shape (d0, d1, ..., dn), the expected strides are: stride[i] = product(shape[i+1:]) for all i, with stride[-1]=1.

Example with torch.Size([16, 1, 8, 32]): - Canonical strides: (256, 256, 32, 1) - Degenerate strides: (256, 1, 32, 1) # dim=1 has size=1, allowing # non-canonical stride in dim=0

make_ndarray_with_pad(x, pad, dtype, *, max_len=None)

Make a padded array from 2D inputs.

The padding is applied to the end of each inner list until it reaches max_len.

nvfp4_kv_cache_full_dim(head_size)

Packed last dim for NVFP4 KV cache: fp4 data + fp8 block scales.

nvfp4_split_data_scale(kv_side)

Split one side (K or V) of an NVFP4 KV cache into data and scale.

The input is a 4D uint8 tensor whose last dimension is full_dim = data_dim + scale_dim. The physical layout within each side is [data | scale], both packed contiguously.

The caller is responsible for slicing K and V from the combined cache first (e.g. kv_cache.split(num_kv_heads, dim=1)).

Parameters:

  • kv_side

    (Tensor) –

    4D uint8 tensor (B, H, N, full_dim).

Returns:

  • Tensor –

    (data, scale) where data is uint8 and scale is

  • Tensor –

    float8_e4m3fn, both views of the same storage.

resolve_kv_cache_dtype_string(kv_cache_dtype, model_config)

Resolve 'auto' kv_cache_dtype to the actual string value from model config. Returns the resolved cache_dtype string.

set_default_torch_dtype(dtype)

Sets the default torch dtype to the given dtype.

set_default_torch_num_threads(num_threads=None)

Sets the default number of threads for PyTorch to the given value.

None means using the value of the environment variable OMP_NUM_THREADS (or 1 if that is not available).

set_torch_threads_for_runtime()

Set torch intra-op threads to 1 for steady-state serving.

Any multi-threaded torch CPU op in the engine hot loop leaves the OMP workers spin-waiting after each parallel region, stealing cycles from the step's serial code (and burning cgroup CPU quota in containers). No steady-state CPU op benefits from intra-op parallelism. Respects an externally-set OMP_NUM_THREADS.

startup_omp_num_threads(num_local_procs)

Thread count for a worker process's startup work (weight loading).

Weight loading does CPU-parallel work, so workers benefit from more than one thread, but only a bounded share of the CPUs this node's workers may actually use: torch's default is the host core count, which ignores both scheduling affinity and any cgroup CPU quota, and doesn't account for the other workers sharing the node.

token_ids_to_tensor(token_ids, dtype=torch.int64)

CPU tensor of token ids. A TokenBuffer is copied as one block rather than read token by token; the copy keeps the buffer resizable.

weak_ref_tensor(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. This ignores 0-size tensors as those don't allocate any memory.

weak_ref_tensors(tensors)

Convenience function to create weak references to tensors, for single tensor, possibly nested list/tuple of tensors, or IntermediateTensors. Ints and LayerNames are returned as is.