Skip to content

vllm.env_override

_apply_inductor_pattern_matcher_patch()

Allow custom ops and functionalization wrappers with unsupported dtypes.

Source code in vllm/env_override.py
def _apply_inductor_pattern_matcher_patch() -> None:
    """Allow custom ops and functionalization wrappers with unsupported dtypes."""
    from torch._inductor import pattern_matcher
    from torch._inductor.lowering import fallback_node_due_to_unsupported_type

    def fallback_for_builtin(node, allow_cpu_inputs=True):
        return (
            isinstance(node.target, torch._ops.OpOverload)
            and torch._library.utils.is_builtin(node.target)
            and fallback_node_due_to_unsupported_type(node, allow_cpu_inputs)
        )

    pattern_matcher.fallback_node_due_to_unsupported_type = fallback_for_builtin

_get_torch_cuda_version()

Peripheral function to _maybe_set_cuda_compatibility_path().

Source code in vllm/env_override.py
def _get_torch_cuda_version():
    """Peripheral function to _maybe_set_cuda_compatibility_path()."""
    return _get_torch_version_attr("cuda")

_get_torch_root()

Locate the installed torch package without importing it.

Source code in vllm/env_override.py
def _get_torch_root():
    """Locate the installed torch package without importing it."""
    spec = importlib.util.find_spec("torch")
    if not spec:
        return None
    if spec.origin:
        return os.path.dirname(spec.origin)
    if spec.submodule_search_locations:
        return spec.submodule_search_locations[0]
    return None

_get_torch_version_attr(attr)

Read an attribute of torch.version without importing torch.

PyTorch version must not be determined by importing directly because it will trigger the CUDA initialization, losing the chance to set the LD_LIBRARY_PATH beforehand.

Source code in vllm/env_override.py
def _get_torch_version_attr(attr):
    """Read an attribute of torch.version without importing torch.

    PyTorch version must not be determined by importing directly
    because it will trigger the CUDA initialization, losing the
    chance to set the LD_LIBRARY_PATH beforehand.
    """
    try:
        torch_root = _get_torch_root()
        if not torch_root:
            return None
        version_path = os.path.join(torch_root, "version.py")
        if not os.path.exists(version_path):
            return None
        # Load the version module without importing torch
        ver_spec = importlib.util.spec_from_file_location("torch.version", version_path)
        if not ver_spec or not ver_spec.loader:
            return None
        module = importlib.util.module_from_spec(ver_spec)
        # Avoid registering in sys.modules to not confuse future imports
        ver_spec.loader.exec_module(module)
        return getattr(module, attr, None)
    except Exception:
        return None

_maybe_promote_torch_symbols_for_rocm()

Put libtorch_cpu.so in the global symbol scope on ROCm, for GPU profiling.

Must run before 'import torch'. libkineto advertises itself to rocprofiler-sdk by exporting rocprofiler_configure from libtorch_cpu.so, and rocprofiler-sdk looks for that symbol exactly once, from a lazy initializer that runs during 'import torch'. CPython loads extension modules RTLD_LOCAL, so unless something has already placed the symbol in the global scope the lookup misses and no client is ever registered.

The failure is silent and total: no queue interception, so roctracer yields no GPU records, while torch.profiler still writes a complete CPU-only trace and reports success.

Best effort. If the library cannot be loaded early we leave the process exactly as it would have been, losing only GPU tracing.

Source code in vllm/env_override.py
def _maybe_promote_torch_symbols_for_rocm():
    """Put libtorch_cpu.so in the global symbol scope on ROCm, for GPU profiling.

    Must run before 'import torch'. libkineto advertises itself to
    rocprofiler-sdk by exporting rocprofiler_configure from libtorch_cpu.so,
    and rocprofiler-sdk looks for that symbol exactly once, from a lazy
    initializer that runs *during* 'import torch'. CPython loads extension
    modules RTLD_LOCAL, so unless something has already placed the symbol in
    the global scope the lookup misses and no client is ever registered.

    The failure is silent and total: no queue interception, so roctracer
    yields no GPU records, while torch.profiler still writes a complete
    CPU-only trace and reports success.

    Best effort. If the library cannot be loaded early we leave the process
    exactly as it would have been, losing only GPU tracing.
    """
    if _get_torch_version_attr("hip") is None:
        return
    try:
        import ctypes
        import glob

        torch_root = _get_torch_root()
        if not torch_root:
            return
        lib = os.path.join(torch_root, "lib", "libtorch_cpu.so")
        if not os.path.exists(lib):
            return
        try:
            ctypes.CDLL(lib, mode=ctypes.RTLD_GLOBAL)
        except OSError:
            # Some ROCm wheel layouts leave a stale RUNPATH in libtorch_cpu.so,
            # so a dependency that resolves once torch has set things up does
            # not resolve for a standalone load. Satisfy it by search, then
            # retry; give up quietly if it is not where we expect.
            site_root = os.path.dirname(torch_root)
            deps = glob.glob(
                os.path.join(
                    site_root, "_rocm_sdk_*", "lib", "*", "lib", "librocm-openblas.so.*"
                )
            )
            if not deps:
                return
            ctypes.CDLL(deps[0], mode=ctypes.RTLD_LOCAL)
            ctypes.CDLL(lib, mode=ctypes.RTLD_GLOBAL)
    except Exception:
        return

_maybe_set_cuda_compatibility_path()

Set LD_LIBRARY_PATH for CUDA forward compatibility if enabled.

Must run before 'import torch' since torch loads CUDA shared libraries at import time and the dynamic linker only consults LD_LIBRARY_PATH when a library is first loaded.

CUDA forward compatibility is only supported on select professional and datacenter NVIDIA GPUs. Consumer GPUs (GeForce, RTX) do not support it and will get Error 803 if compat libs are loaded.

Source code in vllm/env_override.py
def _maybe_set_cuda_compatibility_path():
    """Set LD_LIBRARY_PATH for CUDA forward compatibility if enabled.

    Must run before 'import torch' since torch loads CUDA shared libraries
    at import time and the dynamic linker only consults LD_LIBRARY_PATH when
    a library is first loaded.

    CUDA forward compatibility is only supported on select professional and
    datacenter NVIDIA GPUs. Consumer GPUs (GeForce, RTX) do not support it
    and will get Error 803 if compat libs are loaded.
    """
    enable = os.environ.get("VLLM_ENABLE_CUDA_COMPATIBILITY", "0").strip().lower() in (
        "1",
        "true",
    )
    if not enable:
        return

    cuda_compat_path = os.environ.get("VLLM_CUDA_COMPATIBILITY_PATH", "")
    if not cuda_compat_path or not os.path.isdir(cuda_compat_path):
        conda_prefix = os.environ.get("CONDA_PREFIX", "")
        conda_compat = os.path.join(conda_prefix, "cuda-compat")
        if conda_prefix and os.path.isdir(conda_compat):
            cuda_compat_path = conda_compat
    if not cuda_compat_path or not os.path.isdir(cuda_compat_path):
        torch_cuda_version = _get_torch_cuda_version()
        if torch_cuda_version:
            default_path = f"/usr/local/cuda-{torch_cuda_version}/compat"
            if os.path.isdir(default_path):
                cuda_compat_path = default_path
    if not cuda_compat_path or not os.path.isdir(cuda_compat_path):
        return

    norm_path = os.path.normpath(cuda_compat_path)
    existing = os.environ.get("LD_LIBRARY_PATH", "")
    ld_paths = existing.split(os.pathsep) if existing else []

    if ld_paths and ld_paths[0] and os.path.normpath(ld_paths[0]) == norm_path:
        return  # Already at the front

    new_paths = [norm_path] + [
        p for p in ld_paths if not p or os.path.normpath(p) != norm_path
    ]
    os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(new_paths)

_patch_inductor_operator_str_if_needed()

Shorten the implicit-fallback message for vllm ops on torch < 2.13.

Defers application until torch._inductor.exc is imported, so that importing vllm does not import torch._inductor.

Source code in vllm/env_override.py
def _patch_inductor_operator_str_if_needed():
    """Shorten the implicit-fallback message for vllm ops on torch < 2.13.

    Defers application until torch._inductor.exc is imported, so that
    importing vllm does not import torch._inductor.
    """
    if is_torch_equal_or_newer("2.13.0.dev"):
        return

    import sys

    target_name = "torch._inductor.exc"
    if target_name in sys.modules:
        _apply_inductor_operator_str_patch()
        return

    import importlib.abc

    class _OperatorStrPatchFinder(importlib.abc.MetaPathFinder):
        def find_spec(self, fullname, path, target=None):
            if fullname != target_name:
                return None
            sys.meta_path.remove(self)
            spec = importlib.util.find_spec(fullname)
            if spec is None or spec.loader is None:
                return None
            original_exec = spec.loader.exec_module

            def _exec_then_patch(module):
                original_exec(module)
                _apply_inductor_operator_str_patch()

            spec.loader.exec_module = _exec_then_patch  # type: ignore[method-assign]
            return spec

    sys.meta_path.insert(0, _OperatorStrPatchFinder())

_patch_inductor_pattern_matcher()

Apply the backport when Inductor imports its pattern matcher.

Source code in vllm/env_override.py
def _patch_inductor_pattern_matcher() -> None:
    """Apply the backport when Inductor imports its pattern matcher."""
    import sys

    target_name = "torch._inductor.pattern_matcher"
    if target_name in sys.modules:
        _apply_inductor_pattern_matcher_patch()
        return

    import importlib.abc

    class _PatternMatcherPatchFinder(importlib.abc.MetaPathFinder):
        def find_spec(self, fullname, path, target=None):
            if fullname != target_name:
                return None
            sys.meta_path.remove(self)
            spec = importlib.util.find_spec(fullname)
            if spec is None or spec.loader is None:
                return None
            original_exec = spec.loader.exec_module

            def _exec_then_patch(module):
                original_exec(module)
                _apply_inductor_pattern_matcher_patch()

            spec.loader.exec_module = _exec_then_patch  # type: ignore[method-assign]
            return spec

    sys.meta_path.insert(0, _PatternMatcherPatchFinder())