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.

11.2 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""API video loads use local_files_only=True; network helpers are sentinels that raise if called."""

from __future__ import annotations

import inspect
import types

import pytest

import utils.hf_xet_fallback as xet
from core.inference import video as video_mod
from core.inference.video import VideoBackend
from core.inference.video_families import detect_video_family

WAN_GGUF = "unsloth/Wan2.2-TI2V-5B-GGUF"
WAN_BASE = "Wan-AI/Wan2.2-TI2V-5B-Diffusers"
WAN_FILE = "wan2.2-ti2v-5b-Q4_K_M.gguf"


class _Calls:
    """Every Hub call the load made, and how it made it."""

    def __init__(self):
        self.model_info: list[str] = []
        self.downloads: list[tuple[str, str, bool]] = []


def _install_sentinels(monkeypatch, calls, tmp_path, *, offline):
    """Offline, probes and downloads lacking local_files_only=True raise; online they only record."""
    import huggingface_hub

    def _model_info(self, repo_id, **_kwargs):
        calls.model_info.append(repo_id)
        if offline:
            raise AssertionError(f"model_info({repo_id!r}) reached the Hub on an offline load")
        return types.SimpleNamespace(siblings = [], sha = "deadbeef")

    def _download(
        repo_id,
        filename,
        token = None,
        **kwargs,
    ):
        local_files_only = bool(kwargs.get("local_files_only"))
        calls.downloads.append((repo_id, filename, local_files_only))
        if offline and not local_files_only:
            raise AssertionError(
                f"{repo_id}/{filename} was fetched without local_files_only on an offline load"
            )
        path = tmp_path / filename
        path.parent.mkdir(parents = True, exist_ok = True)
        path.write_bytes(b"")
        return str(path)

    monkeypatch.setattr(huggingface_hub.HfApi, "model_info", _model_info, raising = False)
    monkeypatch.setattr(xet, "hf_hub_download_with_xet_fallback", _download)
    monkeypatch.setattr(
        huggingface_hub,
        "hf_hub_download",
        lambda **kwargs: _download(
            kwargs.get("repo_id"), kwargs.get("filename"), kwargs.get("token"), **kwargs
        ),
        raising = False,
    )


def _backend(monkeypatch, calls_seen):
    """A backend whose family detection is pinned and whose pipeline build is a capture."""
    backend = VideoBackend()
    backend._load_token = 1
    backend._loading = video_mod._VideoLoadingState(repo_id = WAN_GGUF, base_repo = WAN_BASE)
    fam = detect_video_family(WAN_BASE)
    assert fam is not None and not fam.modular_workflow
    monkeypatch.setattr(video_mod, "_detect_load_family", lambda *_a, **_k: fam)
    monkeypatch.setattr(backend, "load_pipeline", lambda **kwargs: calls_seen.update(kwargs))
    return backend


def test_an_api_initiated_load_opens_the_cache_and_downloads_nothing(monkeypatch, tmp_path):
    """Every load-path helper stays off the Hub, or asks it only for cached files."""
    calls = _Calls()
    _install_sentinels(monkeypatch, calls, tmp_path, offline = True)
    seen: dict = {}
    backend = _backend(monkeypatch, seen)

    backend._run_load(
        repo_id = WAN_GGUF,
        gguf_filename = WAN_FILE,
        local_files_only = True,
        _load_token = 1,
    )

    # _run_load swallows failures onto load_progress, so the state is the result.
    assert backend._loading is None, getattr(backend._loading, "error", None)
    assert seen.get("local_files_only") is True
    assert calls.model_info == []
    assert calls.downloads == [(WAN_GGUF, WAN_FILE, True)]
    assert seen.get("_base_local_dir") is None


def test_a_user_initiated_load_still_calls_every_one_of_them(monkeypatch, tmp_path):
    """The pre-PR path, unchanged: the UI load asks the Hub for sizes and pulls the checkpoint."""
    calls = _Calls()
    _install_sentinels(monkeypatch, calls, tmp_path, offline = False)
    seen: dict = {}
    backend = _backend(monkeypatch, seen)

    backend._run_load(
        repo_id = WAN_GGUF,
        gguf_filename = WAN_FILE,
        _load_token = 1,
    )

    assert backend._loading is None, getattr(backend._loading, "error", None)
    assert seen.get("local_files_only") in (False, None)
    # The byte estimate probes the checkpoint repo and the base; the base prefetch probes it again. The base's sizes
    # are read from its byte-identical unsloth mirror, so the listing never leaves unsloth/*.
    from core.inference.diffusion_families import mirror_repo

    assert WAN_GGUF in calls.model_info and mirror_repo(WAN_BASE) in calls.model_info
    assert WAN_BASE not in calls.model_info
    # And the checkpoint is FETCHED, not looked up.
    assert calls.downloads == [(WAN_GGUF, WAN_FILE, False)]


def test_the_native_h3_path_binds_the_flag_instead_of_swallowing_it(monkeypatch):
    """``_run_load_h3_native`` used to take ``**_``, so the flag arrived and vanished -- and its
    four-file bundle, its sizing metadata and its sd-cli install all downloaded anyway."""
    assert (
        inspect.signature(VideoBackend._run_load_h3_native).parameters["local_files_only"].default
        is False
    )

    from core.inference.video_minimax_h3 import H3_GGUF_REPO

    fam = detect_video_family("MiniMaxAI/MiniMax-H3")
    monkeypatch.setattr(video_mod, "_detect_load_family", lambda *_a, **_k: fam)
    backend = VideoBackend()
    backend._load_token = 1
    backend._loading = video_mod._VideoLoadingState(repo_id = H3_GGUF_REPO, base_repo = fam.base_repo)
    seen: dict = {}
    monkeypatch.setattr(backend, "_run_load_h3_native", lambda **kwargs: seen.update(kwargs))

    backend._run_load(
        repo_id = H3_GGUF_REPO,
        gguf_filename = "MiniMax-H3-Q4_K_M.gguf",
        local_files_only = True,
        _load_token = 1,
    )
    assert seen.get("local_files_only") is True


def test_load_pipeline_carries_the_flag_into_the_native_path(monkeypatch):
    """load_pipeline is reachable without _run_load (tests, and the keep-warm path), so the
    dispatch has to pass the flag rather than let the parameter default re-enable downloads."""
    from core.inference.video_minimax_h3 import H3_GGUF_REPO

    backend = VideoBackend()
    seen: dict = {}
    monkeypatch.setattr(backend, "_run_load_h3_native", lambda **kwargs: seen.update(kwargs))
    monkeypatch.setattr(
        backend,
        "validate_load_request",
        lambda *a, **k: detect_video_family("MiniMaxAI/MiniMax-H3"),
    )

    backend.load_pipeline(
        H3_GGUF_REPO,
        gguf_filename = "MiniMax-H3-Q4_K_M.gguf",
        model_kind = "gguf",
        local_files_only = True,
    )
    assert seen.get("local_files_only") is True


def test_an_offline_denoiser_probe_reads_the_cache_instead_of_the_hub(monkeypatch):
    """Offline, the replacement-denoiser probe reads the cache: refusing the load would break the
    offline case, and a blind yes drops shards the cache still needs."""
    from core.inference.diffusion import DiffusionBackend

    fam = detect_video_family("MiniMaxAI/MiniMax-H3")

    monkeypatch.setattr(DiffusionBackend, "_hub_file_is_cached", staticmethod(lambda *a, **k: True))
    assert (
        VideoBackend._denoiser_prequant_cached_repo(fam, "int8", "MiniMaxAI/MiniMax-H3", "fl2va")
        == "unsloth/MiniMax-H3-FP8"
    )

    monkeypatch.setattr(
        DiffusionBackend, "_hub_file_is_cached", staticmethod(lambda *a, **k: False)
    )
    assert (
        VideoBackend._denoiser_prequant_cached_repo(fam, "int8", "MiniMaxAI/MiniMax-H3", "fl2va")
        is None
    )


def test_the_estimate_and_the_base_prefetch_stand_down_offline(monkeypatch):
    """Both are pure Hub metadata, and both already have a "could not tell" answer the callers
    handle, so offline they take it rather than inventing a probe."""

    class _Boom:
        def __init__(self, *_a, **_k):
            pass

        def model_info(self, *_a, **_k):
            raise AssertionError("the Hub was asked about an offline load")

    import huggingface_hub

    monkeypatch.setattr(huggingface_hub, "HfApi", _Boom)
    backend = VideoBackend()
    assert (
        backend._estimate_download_bytes(
            WAN_GGUF, WAN_FILE, WAN_BASE, None, "gguf", local_files_only = True
        )
        is None
    )
    assert backend._predownload_base(WAN_BASE, None, "gguf", local_files_only = True) is None


def test_the_xet_wrapper_resolves_offline_without_the_shared_backend(monkeypatch, tmp_path):
    """``local_files_only`` must not depend on which unsloth_zoo is installed: the degraded stub
    drops unknown keywords, so a forwarded flag would silently become a download."""
    monkeypatch.setattr(
        xet,
        "_shared_hf_hub_download_with_xet_fallback",
        lambda *a, **k: pytest.fail("the shared transport ran for an offline request"),
    )
    seen: dict = {}

    def _hf_hub_download(**kwargs):
        seen.update(kwargs)
        path = tmp_path / "file.bin"
        path.write_bytes(b"")
        return str(path)

    import huggingface_hub

    monkeypatch.setattr(huggingface_hub, "hf_hub_download", _hf_hub_download)
    out = xet.hf_hub_download_with_xet_fallback(
        "org/repo", "file.bin", None, cache_dir = str(tmp_path), local_files_only = True
    )
    assert out == str(tmp_path / "file.bin")
    assert seen["local_files_only"] is True


def test_the_xet_wrapper_is_unchanged_for_every_existing_caller(monkeypatch, tmp_path):
    """Default False: the online path still goes through the shared transport, and the flag is not
    even forwarded, so an older shared backend cannot trip over it."""
    seen: dict = {}

    def _shared(*args, **kwargs):
        seen["args"] = args
        seen["kwargs"] = kwargs
        return str(tmp_path / "file.bin")

    monkeypatch.setattr(xet, "_shared_hf_hub_download_with_xet_fallback", _shared)
    xet.hf_hub_download_with_xet_fallback("org/repo", "file.bin", None, cache_dir = str(tmp_path))
    assert seen["args"] == ("org/repo", "file.bin", None)
    assert "local_files_only" not in seen["kwargs"]


def _keywords_of(module_path: str, function: str, callee: str) -> set[str]:
    """Reads call keywords from source, since the branch needs a live H3 pipeline to drive."""
    import ast
    import pathlib

    # Anchor on the package: CI runs pytest from the repo root.
    backend_root = pathlib.Path(video_mod.__file__).resolve().parents[2]
    tree = ast.parse((backend_root / module_path).read_text(encoding = "utf-8"))
    for node in ast.walk(tree):
        if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) or node.name != function:
            continue
        for call in ast.walk(node):
            if isinstance(call, ast.Call) and getattr(call.func, "id", None) == callee:
                return {kw.arg for kw in call.keywords if kw.arg}
    raise AssertionError(f"no call to {callee}() inside {function}()")


def test_the_hosted_prequantized_denoiser_is_not_fetched_by_a_load_nobody_asked_for():
    # auto is re-decided against live free memory here, so local_files_only must be passed.
    assert "local_files_only" in _keywords_of(
        "core/inference/video.py", "_load_h3_modular_pipeline", "load_prequantized_transformer"
    )
    assert "local_files_only" in _keywords_of(
        "core/inference/diffusion.py", "_load_dense_quant_pipeline", "load_prequantized_transformer"
    )