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.

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

"""unsloth export and list-checkpoints must seed the cache env before importing the backend."""

import json
import os
import subprocess
import sys
import textwrap
from pathlib import Path

import pytest

REPO_ROOT = Path(__file__).resolve().parents[2]

# Own interpreter: the seeding is process-global, so in-process results depend on test order.
PROBE = textwrap.dedent(
    """
    import json, os, sys, types

    import typer
    from typer.testing import CliRunner

    command_name = sys.argv[1]
    recorded = {}

    # Stand in for the heavy backend (unsloth, torch) so the probe stays
    # import-light. The CLI's own import statement, and therefore everything that
    # has to happen before it, is untouched.
    class ExportBackend:
        def __init__(self):
            recorded["compile_location"] = os.environ.get("UNSLOTH_COMPILE_LOCATION")

        def load_checkpoint(self, **kwargs):
            return True, "loaded"

        def export_merged_model(self, **kwargs):
            return True, "exported", kwargs["save_directory"]

        def scan_checkpoints(self, **kwargs):
            return []

    # Each stub keeps the REAL directory on __path__ instead of []. The point is to skip
    # the heavy studio.backend.core.export import, not to make the whole studio tree
    # unimportable: unsloth_cli/__init__ eagerly imports commands.start, which pulls
    # studio.backend.utils.coding_agents, and an empty __path__ turned that into
    # ModuleNotFoundError. Submodules still load from disk; the package __init__ files
    # are the thing that never runs, which is what kept this probe light to begin with.
    repo_root = sys.argv[2]
    for name, relative in (
        ("studio", "studio"),
        ("studio.backend", "studio/backend"),
        ("studio.backend.core", "studio/backend/core"),
    ):
        module = types.ModuleType(name)
        module.__path__ = [os.path.join(repo_root, *relative.split("/"))]
        sys.modules[name] = module
    export_module = types.ModuleType("studio.backend.core.export")
    export_module.ExportBackend = ExportBackend
    sys.modules["studio.backend.core.export"] = export_module

    from unsloth_cli.commands import export as export_command

    app = typer.Typer()
    if command_name == "export":
        app.command()(export_command.export)
        args = ["checkpoint", "exported"]
    else:
        app.command()(export_command.list_checkpoints)
        args = []
    result = CliRunner().invoke(app, args)
    recorded["exit_code"] = result.exit_code
    print("PROBE " + json.dumps(recorded))
    """
)


@pytest.mark.parametrize("command_name", ["export", "list-checkpoints"])
def test_export_commands_seed_compile_location(tmp_path, command_name):
    unsloth_home = tmp_path / "unsloth"
    workdir = tmp_path / "cwd"
    workdir.mkdir()

    env = dict(os.environ)
    env.pop("UNSLOTH_COMPILE_LOCATION", None)
    # Both outrank UNSLOTH_HOME, and conftest.py sets a session-scoped UNSLOTH_STUDIO_HOME.
    for key in ("UNSLOTH_STUDIO_HOME", "STUDIO_HOME", "UNSLOTH_PORTABLE"):
        env.pop(key, None)
    env.update(
        HOME = str(tmp_path / "home"),
        UNSLOTH_HOME = str(unsloth_home),
        PYTHONPATH = str(REPO_ROOT),
    )
    completed = subprocess.run(
        [sys.executable, "-c", PROBE, command_name, str(REPO_ROOT)],
        cwd = str(workdir),
        env = env,
        capture_output = True,
        text = True,
        timeout = 300,
    )
    assert completed.returncode == 0, completed.stderr
    line = next(l for l in completed.stdout.splitlines() if l.startswith("PROBE "))
    recorded = json.loads(line[len("PROBE ") :])

    assert recorded["exit_code"] == 0, recorded
    location = recorded["compile_location"]
    assert location, "UNSLOTH_COMPILE_LOCATION was unset when the export backend was imported"
    assert Path(location).is_absolute()
    assert Path(location) == unsloth_home / "studio" / "compiled_cache"
    assert not (workdir / "unsloth_compiled_cache").exists()


def test_node_discovery_does_not_build_the_cache_tree(tmp_path):
    """Node discovery is a read, so it must not go through setup_cache_env(), which creates dirs."""
    home = tmp_path / "home"
    (home / ".unsloth" / "studio").mkdir(parents = True)
    probe = (
        "import json, os, sys\n"
        f"sys.path.insert(0, {str(REPO_ROOT)!r})\n"
        "from pathlib import Path\n"
        "home = Path(os.environ['HOME'])\n"
        "before = {str(p) for p in home.rglob('*') if p.is_dir()}\n"
        "from unsloth_cli.commands import start\n"
        "start._managed_node_tools()\n"
        "after = {str(p) for p in home.rglob('*') if p.is_dir()}\n"
        "print('PROBE ' + json.dumps(sorted(after - before)))\n"
    )
    completed = subprocess.run(
        [sys.executable, "-c", probe],
        cwd = str(tmp_path),
        env = {"HOME": str(home), "PATH": os.environ.get("PATH", "/usr/bin:/bin")},
        capture_output = True,
        text = True,
        timeout = 300,
    )
    assert completed.returncode == 0, completed.stderr
    line = next(l for l in completed.stdout.splitlines() if l.startswith("PROBE "))
    assert json.loads(line[len("PROBE ") :]) == []