Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

15.3 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team.
"""Checks symbols unsloth-zoo expects exist in vLLM >= 0.9.0 by GitHub fetch, without pip or GPU."""

from __future__ import annotations

import functools
import json
import os
import re
import urllib.error
import urllib.request

import pytest


# Derived from PyPI: a hand-kept list silently stops covering new minors.
_VLLM_MIN_VERSION = (0, 9, 0)

# Fallback must reach the frontier, or new guards are skipped while reporting green.
_VLLM_TAGS_FALLBACK = [
    "v0.9.0",
    "v0.9.1",
    "v0.9.2",
    "v0.10.0",
    "v0.10.1",
    "v0.10.2",
    "v0.11.0",
    "v0.11.1",
    "v0.11.2",
    "v0.12.0",
    "v0.13.0",
    "v0.14.0",
    "v0.14.1",
    "v0.15.0",
    "v0.15.1",
    "v0.16.0",
    "v0.17.0",
    "v0.17.1",
    "v0.18.0",
    "v0.18.1",
    "v0.19.0",
    "v0.19.1",
    "v0.20.0",
    "v0.20.1",
    "v0.20.2",
    "v0.21.0",
    "v0.22.0",
    "v0.22.1",
    "v0.23.0",
    "v0.24.0",
    "v0.25.0",
    "v0.25.1",
    "v0.26.0",
    "v0.27.0",
    "v0.27.1",
    "v0.28.0",
    "v0.29.0",
]


def _stable_release_tags() -> list[str]:
    """Stable releases only: all-numeric, no rc/dev/post or yanked; hotfixes may have four components."""
    try:
        with urllib.request.urlopen("https://pypi.org/pypi/vllm/json", timeout = 20) as r:
            releases = json.loads(r.read().decode("utf-8"))["releases"]
    except (urllib.error.URLError, TimeoutError, ValueError, KeyError):
        return list(_VLLM_TAGS_FALLBACK)

    versions = []
    for version, files in releases.items():
        if not files or all(f.get("yanked") for f in files):
            continue
        if re.fullmatch(r"\d+(?:\.\d+){2,}", version) is None:
            continue
        parts = tuple(int(g) for g in version.split("."))
        if parts >= _VLLM_MIN_VERSION:
            versions.append(parts)
    if not versions:
        return list(_VLLM_TAGS_FALLBACK)
    return ["v" + ".".join(str(p) for p in parts) for parts in sorted(versions)]


VLLM_TAGS = _stable_release_tags() + ["main"]


@functools.lru_cache(maxsize = None)
def _ref_resolves(repo: str, ref: str) -> bool:
    """Asks the ref itself: a renamed file would wrongly skip the tag; only an explicit 200 counts."""
    status = _api_status(f"repos/{repo}/commits/{ref}")
    if status is not None:
        return status == 200
    return _fetch_text(repo, ref, "README.md") is not None


def _tag_exists(tag: str) -> bool:
    return _ref_resolves("vllm-project/vllm", tag)


# vLLM 0.28 moved bitsandbytes to vllm-bnb-plugin, which re-exports the same names.
VLLM_BNB_IN_TREE = "vllm/model_executor/layers/quantization/bitsandbytes.py"
VLLM_BNB_PLUGIN_REPO = "vllm-project/vllm-bnb-plugin"
VLLM_BNB_PLUGIN_PATH = "vllm_bnb_plugin/bitsandbytes.py"


# A released tag, never `main`: see _plugin_ref.
VLLM_BNB_PLUGIN_FALLBACK_REF = "v0.0.3"


@functools.lru_cache(maxsize = None)
def _plugin_ref() -> str | None:
    """Never main: an unreleased fix would hide a broken published plugin; None is a skip, not a verdict."""
    version = None
    try:
        with urllib.request.urlopen("https://pypi.org/pypi/vllm-bnb-plugin/json", timeout = 20) as r:
            version = json.loads(r.read().decode("utf-8"))["info"]["version"]
    except (urllib.error.URLError, TimeoutError, ValueError, KeyError):
        pass
    for ref in (f"v{version}" if version else None, VLLM_BNB_PLUGIN_FALLBACK_REF):
        if ref and _ref_resolves(VLLM_BNB_PLUGIN_REPO, ref):
            return ref
    return None


# Only these two are required: zoo subclasses/replaces them; apply_bnb_4bit is hasattr-checked.
VLLM_BNB_SYMBOLS = (
    "BitsAndBytesConfig",
    "BitsAndBytesLinearMethod",
)


@functools.lru_cache(maxsize = None)
def _api_status(path: str) -> int | None:
    """GitHub API HTTP status for a path; None when unreachable or rate limited, not a verdict."""
    req = urllib.request.Request(f"https://api.github.com/{path}", method = "HEAD")
    token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
    if token:
        req.add_header("Authorization", f"Bearer {token}")
    try:
        with urllib.request.urlopen(req, timeout = 15) as r:
            return r.status
    except urllib.error.HTTPError as e:
        return e.code if e.code == 404 else None
    except (urllib.error.URLError, TimeoutError):
        return None


@functools.lru_cache(maxsize = None)
def _fetch_text(repo: str, ref: str, path: str) -> str | None:
    """Fetch a file's text from GitHub, None on 404; cached because uncached fetches get rate limited."""
    url = f"https://raw.githubusercontent.com/{repo}/{ref}/{path}"
    req = urllib.request.Request(url)
    token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
    if token:
        req.add_header("Authorization", f"Bearer {token}")
    try:
        with urllib.request.urlopen(req, timeout = 15) as r:
            return r.read().decode("utf-8", errors = "replace")
    except urllib.error.HTTPError as e:
        if e.code == 404:
            return None
        pytest.skip(f"GitHub fetch failed ({e.code}) for {url}")
    except (urllib.error.URLError, TimeoutError) as e:
        pytest.skip(f"GitHub fetch failed ({e}) for {url}")


@pytest.fixture(autouse = True)
def _skip_when_the_tag_is_absent(request):
    """A PyPI release with no git tag 404s on every path; that is not a
    compatibility failure, so skip it rather than report our code broken."""
    if "tag" not in request.fixturenames:
        return
    tag = request.getfixturevalue("tag")
    if not _tag_exists(tag):
        pytest.skip(f"vLLM repo carries no tag {tag}")


def _has_def(
    src: str,
    name: str,
    kind: str = "any",
) -> bool:
    """Grep for `class Name`/`def name`/`Name = ...`; avoids ast.parse so one bad line doesn't false-fail."""
    if kind in ("any", "class") and re.search(rf"^class\s+{re.escape(name)}\b", src, re.MULTILINE):
        return True
    if kind in ("any", "func") and re.search(
        rf"^(?:async\s+)?def\s+{re.escape(name)}\b", src, re.MULTILINE
    ):
        return True
    if kind == "any" and re.search(rf"^{re.escape(name)}\s*[:=]", src, re.MULTILINE):
        return True
    return False


@pytest.mark.parametrize("tag", VLLM_TAGS)
def test_vllm_lora_request_hard_imports(tag: str):
    """LoRARequest, get_adapter_absolute_path, PEFTHelper -- hard-imported by unsloth-zoo's vllm_lora_worker_manager."""
    src = _fetch_text("vllm-project/vllm", tag, "vllm/lora/request.py")
    assert src is not None, f"vllm/lora/request.py missing in {tag}"
    assert _has_def(
        src, "LoRARequest", "class"
    ), f"vllm/lora/request.py:LoRARequest missing in {tag} (unsloth-zoo HARD-imports it)"

    src_utils = _fetch_text("vllm-project/vllm", tag, "vllm/lora/utils.py")
    assert src_utils is not None, f"vllm/lora/utils.py missing in {tag}"
    assert _has_def(
        src_utils, "get_adapter_absolute_path", "func"
    ), f"vllm/lora/utils.py:get_adapter_absolute_path missing in {tag}"

    src_peft = _fetch_text("vllm-project/vllm", tag, "vllm/lora/peft_helper.py")
    assert src_peft is not None, f"vllm/lora/peft_helper.py missing in {tag}"
    assert _has_def(
        src_peft, "PEFTHelper", "class"
    ), f"vllm/lora/peft_helper.py:PEFTHelper missing in {tag}"


@pytest.mark.parametrize("tag", VLLM_TAGS)
def test_vllm_config_lora_config(tag: str):
    """vllm.config.LoRAConfig -- hard-imported at module top of unsloth_zoo.vllm_lora_worker_manager."""
    candidates = [
        "vllm/config/__init__.py",
        "vllm/config.py",
        "vllm/config/lora.py",
    ]
    found = False
    for path in candidates:
        src = _fetch_text("vllm-project/vllm", tag, path)
        if src is None:
            continue
        if _has_def(src, "LoRAConfig", "class") or "LoRAConfig" in src:
            found = True
            break
    assert found, f"vllm.config.LoRAConfig missing in {tag} (checked {candidates})"


@pytest.mark.parametrize("tag", VLLM_TAGS)
def test_vllm_lora_models_either_path(tag: str):
    """The LoRA model/manager symbols must resolve via EITHER vllm.lora.models OR the post-#30253 split path."""
    needed = {
        "LoRAModel": ("class", None),
        "LoRAModelManager": ("class", None),
        "LRUCacheLoRAModelManager": ("class", None),
        "create_lora_manager": ("func", None),
    }
    old_candidates = ["vllm/lora/models.py", "vllm/lora/models/__init__.py"]
    old_src = next(
        (s for s in (_fetch_text("vllm-project/vllm", tag, p) for p in old_candidates) if s),
        None,
    )
    if old_src is not None:
        if all(_has_def(old_src, n, k) for n, (k, _) in needed.items()):
            return

    lora_model_src = _fetch_text("vllm-project/vllm", tag, "vllm/lora/lora_model.py")
    model_mgr_src = _fetch_text("vllm-project/vllm", tag, "vllm/lora/model_manager.py")

    if lora_model_src is None and model_mgr_src is None:
        pytest.fail(
            f"{tag}: neither legacy vllm/lora/models.py nor split "
            f"vllm/lora/{{lora_model,model_manager}}.py found; "
            f"unsloth-zoo's try/except will fail-closed at import"
        )

    combined = (lora_model_src or "") + "\n" + (model_mgr_src or "")
    missing = [n for n, (k, _) in needed.items() if not _has_def(combined, n, k)]
    if missing:
        pytest.fail(
            f"{tag}: post-#30253 path missing symbols {missing}. "
            f"unsloth-zoo's try/except for vllm.lora.models will fall "
            f"through to the new path and crash."
        )


@pytest.mark.parametrize("tag", VLLM_TAGS)
def test_vllm_worker_lora_manager_class(tag: str):
    """vllm.lora.worker_manager.WorkerLoRAManager -- unsloth-zoo subclasses it; signature drives old_init vs new_init."""
    src = _fetch_text("vllm-project/vllm", tag, "vllm/lora/worker_manager.py")
    if src is None:
        alt = _fetch_text("vllm-project/vllm", tag, "vllm/v1/worker/lora_model_runner_mixin.py")
        if alt and ("WorkerLoRAManager" in alt or "LoRAModelRunnerMixin" in alt):
            return
        pytest.fail(
            f"{tag}: vllm/lora/worker_manager.py and "
            f"vllm/v1/worker/lora_model_runner_mixin.py both missing"
        )
    assert (
        _has_def(src, "WorkerLoRAManager", "class") or "WorkerLoRAManager" in src
    ), f"{tag}: vllm.lora.worker_manager.WorkerLoRAManager not in source"


@pytest.mark.parametrize("tag", VLLM_TAGS)
def test_lora_request_no_removed_kwargs(tag: str):
    """vLLM renamed lora_local_path -> lora_path -> lora_dir; assert LoRARequest still accepts lora_dir or lora_path."""
    src = _fetch_text("vllm-project/vllm", tag, "vllm/lora/request.py")
    assert src is not None
    has_dir = bool(re.search(r"\blora_dir\b", src))
    has_path = bool(re.search(r"\blora_path\b", src))
    assert has_dir or has_path, f"{tag}: vllm.lora.request has neither lora_dir nor lora_path"


# unsloth-zoo refuses standby on vllm 0.10.x (bad_alloc) and 0.14.x (illegal address).
def _vllm_zoo_local_path() -> str | None:
    """Return the on-runner path to unsloth_zoo.vllm_utils source, or None."""
    try:
        import importlib.util
        spec = importlib.util.find_spec("unsloth_zoo.vllm_utils")
        if spec and spec.origin:
            return spec.origin
    except Exception:
        pass
    return None


def test_unsloth_zoo_standby_guards_present():
    """Sanity: the two hard-error windows exist in unsloth_zoo.vllm_utils; catches a revert that drops them."""
    path = _vllm_zoo_local_path()
    if path is None:
        pytest.skip("unsloth_zoo not installed on runner")
    src = open(path, encoding = "utf-8").read()
    has_10x_guard = re.search(r"0\.10\.0", src) and re.search(r"standby", src, re.IGNORECASE)
    has_14x_guard = re.search(r"0\.14\.0", src) and re.search(r"standby", src, re.IGNORECASE)
    assert has_10x_guard or has_14x_guard, (
        "unsloth_zoo.vllm_utils dropped the UNSLOTH_VLLM_STANDBY "
        "version-gate against vLLM 0.10.x / 0.14.x; that re-introduces the "
        "std::bad_alloc and cudaErrorIllegalAddress crashes the team fixed "
        "in unsloth-zoo commits 664e52ea / fa82dcc2."
    )


@pytest.mark.parametrize("tag", VLLM_TAGS)
def test_vllm_bitsandbytes_symbols_have_a_home(tag: str):
    """unsloth_zoo's bnb symbols must exist in the vLLM tree or the plugin; vLLM 0.28 moved them out."""
    in_tree = _fetch_text("vllm-project/vllm", tag, VLLM_BNB_IN_TREE)
    if in_tree is not None:
        missing = [s for s in VLLM_BNB_SYMBOLS if not _has_def(in_tree, s)]
        assert not missing, f"{tag}: in-tree bitsandbytes is missing {missing}"
        return

    # Out of tree from 0.28 and versioned separately, so use the published release.
    plugin_ref = _plugin_ref()
    if plugin_ref is None:
        pytest.skip(
            f"no released {VLLM_BNB_PLUGIN_REPO} ref resolved; nothing reproducible to check"
        )
    plugin = _fetch_text(VLLM_BNB_PLUGIN_REPO, plugin_ref, VLLM_BNB_PLUGIN_PATH)
    assert plugin is not None, (
        f"{tag}: bitsandbytes is absent in tree AND {VLLM_BNB_PLUGIN_PATH} could "
        f"not be fetched from {VLLM_BNB_PLUGIN_REPO}@{plugin_ref}; nowhere to "
        f"resolve the bnb linear method from, so load_in_4bit + fast_inference "
        f"has no path on this version"
    )
    missing = [s for s in VLLM_BNB_SYMBOLS if s not in plugin]
    assert not missing, (
        f"{tag}: bitsandbytes moved out of tree and {VLLM_BNB_PLUGIN_REPO}@"
        f"{plugin_ref} no longer re-exports {missing}"
    )


VLLM_WEIGHTS_MAPPER_PATH = "vllm/model_executor/models/utils.py"
VLLM_UNSTACK_HELPERS = ("get_rename_mapper", "get_unstacked_mapper")


@pytest.mark.parametrize("tag", VLLM_TAGS)
def test_weights_mapper_unstack_helper_is_named_as_expected(tag: str):
    """vLLM 0.29 renamed get_unstacked_mapper to get_rename_mapper; probe both or LoRA names fuse."""
    src = _fetch_text("vllm-project/vllm", tag, VLLM_WEIGHTS_MAPPER_PATH)
    if src is None:
        pytest.skip(f"{tag}: {VLLM_WEIGHTS_MAPPER_PATH} not present")
    if "orig_to_new_stacked" not in src:
        pytest.skip(f"{tag}: WeightsMapper has no stacked maps, nothing to strip")
    # Indented, so not _has_def, which anchors at column 0.
    assert any(
        re.search(rf"^\s*def\s+{name}\b", src, re.MULTILINE) for name in VLLM_UNSTACK_HELPERS
    ), (
        f"{tag}: WeightsMapper folds fused weights via orig_to_new_stacked but "
        f"exposes none of {VLLM_UNSTACK_HELPERS}; unsloth_zoo's "
        f"_drop_stacked_weight_maps falls back to clearing the field, so add "
        f"the new spelling there"
    )


VLLM_QUANT_REGISTRY_PATH = "vllm/model_executor/layers/quantization/__init__.py"


@pytest.mark.parametrize("tag", VLLM_TAGS)
def test_out_of_tree_quant_registry_is_still_a_dict(tag: str):
    """unsloth_zoo rewrites the registered bnb config through this dict, since
    a plugin registers the class object and a module swap never reaches it."""
    src = _fetch_text("vllm-project/vllm", tag, VLLM_QUANT_REGISTRY_PATH)
    if src is None:
        pytest.skip(f"{tag}: {VLLM_QUANT_REGISTRY_PATH} not present")
    # A read-only mapping would keep the name check green while item assignment breaks.
    assert re.search(
        r"^_CUSTOMIZED_METHOD_TO_QUANT_CONFIG\s*(?::[^=\n]+)?=\s*(?:\{|dict\()",
        src,
        re.MULTILINE,
    ), (
        f"{tag}: the out-of-tree quantization registry was renamed or is no "
        f"longer a plain mutable dict; unsloth_zoo._set_registered_quant_config "
        f"assigns into it by key"
    )