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.

Stub the trainer's heavy imports in the audio-probe test so Backend CI collects again (#8740)

Daniel Han5ebcc4faba26
diff --git a/studio/backend/tests/test_audio_type_inconclusive.py b/studio/backend/tests/test_audio_type_inconclusive.py
index 7afc4924a06..a2a88afea78 100644
--- a/studio/backend/tests/test_audio_type_inconclusive.py
+++ b/studio/backend/tests/test_audio_type_inconclusive.py
@@ -11,14 +11,77 @@ mapping", which names a column-mapping problem rather than the read that failed.
from __future__ import annotations
+import importlib
import sys
+import types
from pathlib import Path
from types import SimpleNamespace
+from unittest.mock import MagicMock
import pytest
-from core.training.trainer import _AUDIO_SNIFF_ROWS as _SNIFF_ROWS
-from core.training.trainer import UnslothTrainer
+
+_STUBBED: list[str] = []
+
+
+def _stub_if_missing(name, attrs):
+ """Register a stub module for a dep the backend pytest job does not install.
+
+ Same helper and reason as test_trainer_stdout_quiet.py: core.training.trainer imports
+ unsloth (and through it unsloth_zoo) and trl at module scope, while the pytest matrix in
+ studio-backend-ci.yml installs studio.txt plus torch and transformers and deliberately
+ stops there, because the repo-cpu-tests job beside it is the one that installs
+ unsloth_zoo, for the REPO-ROOT tests/ tree. Unstubbed, this module fails COLLECTION and
+ takes the whole job down. A real install is left alone. __spec__ = None keeps the
+ trainer's own _ensure_real_packages namespace-shadow guard a no-op on the stub.
+ """
+ if name in sys.modules:
+ return
+ try:
+ importlib.import_module(name)
+ return
+ except Exception: # noqa: BLE001 - unusable here either way, so stub it
+ pass
+ _STUBBED.append(name)
+ mod = types.ModuleType(name)
+ mod.__spec__ = None
+ for attr in attrs:
+ setattr(mod, attr, MagicMock())
+ sys.modules[name] = mod
+ parent, _, child = name.rpartition(".")
+ if parent and parent in sys.modules:
+ setattr(sys.modules[parent], child, mod)
+
+
+_stub_if_missing("unsloth", ("FastLanguageModel", "FastVisionModel", "is_bfloat16_supported"))
+_stub_if_missing("unsloth.chat_templates", ("get_chat_template",))
+_stub_if_missing("trl", ("SFTTrainer", "SFTConfig"))
+
+from core.training.trainer import _AUDIO_SNIFF_ROWS as _SNIFF_ROWS # noqa: E402
+from core.training.trainer import UnslothTrainer # noqa: E402
+
+# Drop the stubs now that the trainer holds its own references, because they outlive this module
+# otherwise and the whole suite then runs against them. utils.hardware.hardware._shared_policy
+# branches on `"unsloth" in sys.modules` and reaches for unsloth.dataset_num_proc, which a
+# spec-less non-package stub cannot provide, so it returns None and every shared-policy case in
+# test_dataset_map_num_proc.py skips instead of running. core.training.trainer itself stays in
+# sys.modules: the tests below monkeypatch it by dotted name, which would re-import it, and this
+# is the job where the real unsloth is not installed. A real install stubs nothing, so this is a
+# no-op there.
+for _name in reversed(_STUBBED):
+ sys.modules.pop(_name, None)
+
+import transformers # noqa: E402
+
+# transformers 5 rebuilds sys.modules["transformers"] as a fresh lazy facade the first time an
+# attribute resolves through a submodule import, so an object bound by an earlier `import
+# transformers` is not the one `from transformers import AutoProcessor` reads, and a stub on the
+# stale one is invisible to the trainer, which then makes a real network call. Resolving both
+# names once here settles that before any test patches them. Only visible with unsloth stubbed:
+# a real `import unsloth` resolves them long before collection reaches this module.
+transformers.AutoProcessor # noqa: B018
+transformers.AutoTokenizer # noqa: B018
+transformers = sys.modules["transformers"]
_BACKEND = Path(__file__).resolve().parents[1]
_load_and_format_dataset = UnslothTrainer.load_and_format_dataset
@@ -83,6 +146,21 @@ def _run(
)
+def test_the_stubs_do_not_outlive_this_module():
+ """A leaked stub silently disables coverage in modules collected after this one.
+
+ utils.hardware.hardware._shared_policy takes `"unsloth" in sys.modules` as proof the real
+ package is usable; against a stub it returns None and test_dataset_map_num_proc.py skips its
+ shared-policy cases rather than failing, so nothing else would report this.
+ """
+ from utils.hardware import hardware as hw
+
+ for name in _STUBBED:
+ assert name not in sys.modules, name
+ if _STUBBED:
+ assert hw._shared_policy() is not None, "the stub is still hiding the policy module"
+
+
def test_an_inconclusive_probe_on_an_audio_dataset_is_refused(monkeypatch):
trainer = _trainer(audio_type = None, known = False, dataset_audio = True)
assert _run(trainer, monkeypatch) is None
@@ -230,8 +308,6 @@ def test_a_transient_probe_failure_is_rechecked_after_the_tokenizer_loads(monkey
def from_pretrained(cls, *a, **kw):
return object()
- import transformers
-
monkeypatch.setattr(transformers, "AutoProcessor", _Proc, raising = False)
monkeypatch.setattr(transformers, "AutoTokenizer", _Proc, raising = False)
@@ -256,8 +332,6 @@ def test_a_probe_that_stays_inconclusive_is_not_overwritten(monkeypatch):
def from_pretrained(cls, *a, **kw):
return object()
- import transformers
-
monkeypatch.setattr(transformers, "AutoTokenizer", _Proc, raising = False)
trainer = UnslothTrainer()
@@ -322,8 +396,6 @@ def test_the_retry_reloads_the_processor_when_it_discovers_whisper(monkeypatch):
loaded.append("tokenizer")
return object()
- import transformers
-
monkeypatch.setattr(transformers, "AutoProcessor", _Processor, raising = False)
monkeypatch.setattr(transformers, "AutoTokenizer", _Tokenizer, raising = False)
@@ -352,8 +424,6 @@ def test_the_retry_does_not_reload_when_the_answer_is_unchanged(monkeypatch):
loaded.append("tokenizer")
return object()
- import transformers
-
monkeypatch.setattr(transformers, "AutoTokenizer", _Tokenizer, raising = False)
trainer = UnslothTrainer()
@@ -415,8 +485,6 @@ def test_the_first_tokenizer_load_failing_still_reaches_the_retry(monkeypatch):
raise OSError("Can't load tokenizer for 'org/spark'")
return object()
- import transformers
-
monkeypatch.setattr(transformers, "AutoTokenizer", _Tokenizer, raising = False)
trainer = UnslothTrainer()
@@ -441,8 +509,6 @@ def test_a_load_failure_with_a_definitive_type_is_not_swallowed(monkeypatch):
def from_pretrained(cls, *a, **kw):
raise OSError("Can't load tokenizer for 'org/broken'")
- import transformers
-
monkeypatch.setattr(transformers, "AutoTokenizer", _Tokenizer, raising = False)
trainer = UnslothTrainer()
diff --git a/studio/backend/tests/test_backend_tests_stub_heavy_imports.py b/studio/backend/tests/test_backend_tests_stub_heavy_imports.py
index 89ab18258bb..128b254eb4b 100644
--- a/studio/backend/tests/test_backend_tests_stub_heavy_imports.py
+++ b/studio/backend/tests/test_backend_tests_stub_heavy_imports.py
@@ -1,105 +1,218 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""No test module in this tree may import the LLM trainer without stubbing its heavy deps first.
-
-``core/training/trainer.py`` imports ``unsloth`` (and through it ``unsloth_zoo``) and ``trl`` at
-module scope. The ``pytest`` matrix in ``.github/workflows/studio-backend-ci.yml`` installs
-studio.txt plus torch and transformers and deliberately stops there. The heavier
-``repo-cpu-tests`` job beside it does install ``unsloth_zoo``, but it runs the REPO-ROOT
-``tests/`` tree, not this one, so nothing here can lean on that.
-
-The consequence is worse than one skipped test: an unstubbed module fails COLLECTION, and a
-collection error takes down the entire job on all four Python versions. That is what happened
-when ``test_trainer_stdout_quiet.py`` landed, and every open PR went red until it was fixed.
-
-Three modules import the trainer today and each stubs first. This asserts the rule so a fourth
-cannot arrive without it, and it is a source check rather than a runtime one because on a box
-where the real packages ARE installed the import succeeds and proves nothing.
+"""No test module in this tree may import a backend module that needs unsloth without stubbing first.
+
+``core/training/trainer.py`` and ``core/inference/inference.py`` import ``unsloth`` (and through
+it ``unsloth_zoo``) and ``trl`` at module scope. The ``pytest`` matrix in
+``.github/workflows/studio-backend-ci.yml`` installs studio.txt plus torch and transformers and
+deliberately stops there: the ``repo-cpu-tests`` job beside it is the one that installs
+``unsloth_zoo``, and it runs the REPO-ROOT ``tests/`` tree, not this one.
+
+An unstubbed module fails COLLECTION, which takes the entire job down on all four Python
+versions, as ``test_trainer_stdout_quiet.py`` and then ``test_audio_type_inconclusive.py`` did.
+
+The earlier version of this guard hardcoded ``core.training.trainer``, so a test reaching the
+same ``import unsloth`` through any other backend module was invisible to it. The set is now
+derived from the backend sources: every module importing a heavy package at module scope, closed
+transitively over the backend's own module-scope imports. Source check rather than runtime,
+because where the real packages ARE installed the import succeeds and proves nothing.
"""
from __future__ import annotations
import ast
+import warnings
+from functools import lru_cache
from pathlib import Path
_TESTS_DIR = Path(__file__).resolve().parent
+_BACKEND = _TESTS_DIR.parent
+
+# Top-level packages the backend pytest job does not install. `unsloth` is the one that raises
+# (its _gpu_init insists on unsloth_zoo); the other two are unimportable there for the same reason.
+_HEAVY_PACKAGES = ("unsloth", "unsloth_zoo", "trl")
-# The import that pulls the heavy chain in. Matched on the module path, so
-# `from core.training import trainer` and `import core.training.trainer` both count.
-_TRAINER_MODULE = "core.training.trainer"
-# What a module must stub before that import. Naming `unsloth` is enough to prove intent: a
-# module that stubs it and forgets `trl` fails loudly at collection on CI, whereas a module that
-# stubs nothing is the silent case this guard exists to catch.
+# Outside the backend's own import graph (unsloth_compiled_cache is a gitignored artifact dir).
+_SKIP_TOP_LEVEL = frozenset({"tests", "vendor", "unsloth_compiled_cache"})
+
+# Naming `unsloth` is enough to prove intent: a module that stubs it and forgets `trl` fails
+# loudly at collection, whereas one that stubs nothing is the silent case this guard catches.
_REQUIRED_STUB = "unsloth"
-def _imports_trainer_at_module_scope(tree: ast.Module) -> bool:
- for node in tree.body: # module scope only: an import inside a test function is already lazy
- if isinstance(node, ast.Import):
- if any(a.name == _TRAINER_MODULE for a in node.names):
- return True
- elif isinstance(node, ast.ImportFrom):
- mod = node.module or ""
- if mod == _TRAINER_MODULE:
- return True
- if mod == "core.training" and any(a.name == "trainer" for a in node.names):
- return True
- return False
+def _parse(source: str) -> ast.Module:
+ """``ast.parse`` without re-reporting warnings the file's own import already emits.
+ Every test module is parsed here, and a few carry an invalid escape sequence in a docstring,
+ which would otherwise add a SyntaxWarning per run that belongs to those files, not to this
+ guard.
+ """
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", SyntaxWarning)
+ return ast.parse(source)
-def _stubs_before_that_import(source: str, tree: ast.Module) -> bool:
- """Whether a stub call naming ``unsloth`` appears at module scope BEFORE the trainer import.
- Order is the whole point. A stub registered afterwards is registered after the real import
- has already been attempted and raised, so it changes nothing."""
- trainer_line = None
- for node in tree.body:
- if isinstance(node, (ast.Import, ast.ImportFrom)) and _imports_trainer_at_module_scope(
- ast.Module(body = [node], type_ignores = [])
- ):
- trainer_line = node.lineno
- break
- if trainer_line is None:
- return True
- head = "\n".join(source.splitlines()[: trainer_line - 1])
- return _REQUIRED_STUB in head and ("stub" in head or "sys.modules" in head)
+def _module_name(path: Path) -> str:
+ rel = path.relative_to(_BACKEND)
+ parts = list(rel.parts)
+ parts[-1] = parts[-1][: -len(".py")]
+ if parts[-1] == "__init__":
+ parts.pop()
+ return ".".join(parts)
-def test_no_test_module_imports_the_trainer_unstubbed():
- offenders = []
- for path in sorted(_TESTS_DIR.glob("test_*.py")):
- source = path.read_text(encoding = "utf-8")
- if _TRAINER_MODULE not in source and "core.training import trainer" not in source:
+def _module_scope_imports(tree: ast.Module, package: str) -> set[str]:
+ """Absolute dotted names imported at module scope only.
+
+ An import inside a function or a ``try`` is already lazy or guarded and cannot break
+ collection, so only ``tree.body`` is walked. Both the module and the module.attr form of a
+ ``from X import Y`` are recorded, since either can be the one naming the module.
+ """
+ names: set[str] = set()
+ for node in tree.body:
+ if isinstance(node, ast.Import):
+ names.update(alias.name for alias in node.names)
+ elif isinstance(node, ast.ImportFrom):
+ base = node.module or ""
+ if node.level: # relative: resolve against the containing package
+ anchor = package.split(".") if package else []
+ anchor = anchor[: len(anchor) - (node.level - 1)]
+ base = ".".join([*anchor, base]) if base else ".".join(anchor)
+ if not base:
+ continue
+ names.add(base)
+ names.update(f"{base}.{alias.name}" for alias in node.names)
+ return names
+
+
+def _needs_heavy(names: set[str]) -> bool:
+ return any(n == h or n.startswith(f"{h}.") for n in names for h in _HEAVY_PACKAGES)
+
+
+@lru_cache(maxsize = 1)
+def _heavy_backend_modules() -> frozenset[str]:
+ """Backend modules unimportable unless unsloth/unsloth_zoo/trl are installed.
+
+ Seeded with the direct module-scope importers, then closed over the backend's own
+ module-scope imports so a module that merely re-exports one is caught too.
+ """
+ imports: dict[str, set[str]] = {}
+ for path in sorted(_BACKEND.rglob("*.py")):
+ rel = path.relative_to(_BACKEND)
+ if rel.parts[0] in _SKIP_TOP_LEVEL:
continue
try:
- tree = ast.parse(source)
- except SyntaxError: # not this guard's job to report
+ tree = _parse(path.read_text(encoding = "utf-8"))
+ except (SyntaxError, UnicodeDecodeError): # not this guard's job to report
continue
- if not _imports_trainer_at_module_scope(tree):
+ name = _module_name(path)
+ package = name if path.name == "__init__.py" else name.rpartition(".")[0]
+ imports[name] = _module_scope_imports(tree, package)
+
+ tainted = {name for name, names in imports.items() if _needs_heavy(names)}
+ changed = True
+ while changed:
+ changed = False
+ for name, names in imports.items():
+ if name not in tainted and names & tainted:
+ tainted.add(name)
+ changed = True
+ return frozenset(tainted)
+
+
+def _first_heavy_import_line(tree: ast.Module, heavy: frozenset[str]) -> int | None:
+ """Line of the first module-scope import of a heavy backend module, or None."""
+ for node in tree.body:
+ if not isinstance(node, (ast.Import, ast.ImportFrom)):
continue
- if not _stubs_before_that_import(source, tree):
- offenders.append(path.name)
+ if _module_scope_imports(ast.Module(body = [node], type_ignores = []), "") & heavy:
+ return node.lineno
+ return None
+
+def _stubs_before(source: str, line: int | None) -> bool:
+ """Whether a stub call naming ``unsloth`` appears at module scope BEFORE ``line``.
+
+ Order is the whole point: a stub registered afterwards lands after the real import has
+ already been attempted and raised."""
+ if line is None:
+ return True
+ head = "\n".join(source.splitlines()[: line - 1])
+ return _REQUIRED_STUB in head and ("stub" in head or "sys.modules" in head)
+
+
+def _is_offender(source: str, heavy: frozenset[str]) -> bool:
+ """Whether ``source`` imports a heavy backend module at module scope unstubbed.
+
+ Every candidate is parsed. A textual prefilter on the dotted module names looks like a
+ cheap skip but is wrong: ``from core.training import trainer`` never spells the contiguous
+ string ``core.training.trainer``, so the file it was meant to skip is the collection-killing
+ one, and the guard reported no offender while the job died.
+ """
+ try:
+ tree = _parse(source)
+ except SyntaxError: # not this guard's job to report
+ return False
+ return not _stubs_before(source, _first_heavy_import_line(tree, heavy))
+
+
+def _offenders() -> list[str]:
+ heavy = _heavy_backend_modules()
+ return [
+ path.name
+ for path in sorted(_TESTS_DIR.glob("test_*.py"))
+ if _is_offender(path.read_text(encoding = "utf-8"), heavy)
+ ]
+
+
+def test_the_heavy_module_set_is_derived_from_the_backend_sources():
+ """A derivation that quietly returned nothing would make the guard below pass on anything."""
+ heavy = _heavy_backend_modules()
+ assert "core.training.trainer" in heavy
+ # The one the hardcoded version of this guard could never have seen.
+ assert "core.inference.inference" in heavy
+ assert not any(name.startswith("tests.") for name in heavy)
+
+
+def test_no_test_module_imports_an_unsloth_backed_module_unstubbed():
+ offenders = _offenders()
assert not offenders, (
- f"{len(offenders)} test module(s) import {_TRAINER_MODULE} at module scope without "
- f"stubbing its heavy deps first, so they fail COLLECTION on the backend pytest matrix "
- f"(which installs neither unsloth nor trl) and take the whole job down: {offenders}. "
- f"Copy the _stub_if_missing block from test_trainer_stdout_quiet.py, above the import."
+ f"{len(offenders)} test module(s) import a backend module that needs unsloth at module "
+ f"scope without stubbing its heavy deps first, so they fail COLLECTION on the backend "
+ f"pytest matrix (which installs neither unsloth nor trl) and take the whole job down: "
+ f"{offenders}. Copy the _stub_if_missing block from test_trainer_stdout_quiet.py, above "
+ f"the import."
)
-def test_the_guard_would_catch_an_unstubbed_module(tmp_path):
+def test_the_guard_would_catch_an_unstubbed_module():
"""The guard above passes trivially if its matching is wrong, so pin both answers here."""
- unstubbed = tmp_path / "test_unstubbed.py"
- unstubbed.write_text("from core.training import trainer as t\n", encoding = "utf-8")
- tree = ast.parse(unstubbed.read_text(encoding = "utf-8"))
- assert _imports_trainer_at_module_scope(tree)
- assert not _stubs_before_that_import(unstubbed.read_text(encoding = "utf-8"), tree)
-
- stubbed_source = '_stub_if_missing("unsloth", ())\n' "from core.training import trainer as t\n"
- assert _stubs_before_that_import(stubbed_source, ast.parse(stubbed_source))
+ heavy = _heavy_backend_modules()
+
+ for source in (
+ # Split form: the source never spells "core.training.trainer", so a textual prefilter
+ # dropped it while it still killed collection. Asserted through _is_offender, the same
+ # entry point _offenders uses, so no filter can be reintroduced in front of it.
+ "from core.training import trainer as t\n",
+ "from core.training.trainer import UnslothTrainer\n",
+ "import core.training.trainer\n",
+ # The shape the hardcoded guard was blind to.
+ "from core.inference.inference import InferenceEngine\n",
+ "from core.inference import inference\n",
+ ):
+ assert _first_heavy_import_line(ast.parse(source), heavy) == 1, source
+ assert not _stubs_before(source, 1), source
+ assert _is_offender(source, heavy), source
+
+ stubbed = '_stub_if_missing("unsloth", ())\nfrom core.training import trainer as t\n'
+ assert _stubs_before(stubbed, _first_heavy_import_line(ast.parse(stubbed), heavy))
+ assert not _is_offender(stubbed, heavy)
# And a stub that lands too late does not count.
- too_late = "from core.training import trainer as t\n" '_stub_if_missing("unsloth", ())\n'
- assert not _stubs_before_that_import(too_late, ast.parse(too_late))
+ too_late = 'from core.training import trainer as t\n_stub_if_missing("unsloth", ())\n'
+ assert not _stubs_before(too_late, _first_heavy_import_line(ast.parse(too_late), heavy))
+
+ # An import inside a function is lazy already, so it is not an offence.
+ lazy = "def test_x():\n from core.training.trainer import UnslothTrainer\n"
+ assert _first_heavy_import_line(ast.parse(lazy), heavy) is None
diff --git a/studio/backend/tests/test_external_hosted_tool_passthrough.py b/studio/backend/tests/test_external_hosted_tool_passthrough.py
index f524a7c68f2..02888e98201 100644
--- a/studio/backend/tests/test_external_hosted_tool_passthrough.py
+++ b/studio/backend/tests/test_external_hosted_tool_passthrough.py
@@ -210,10 +210,13 @@ def test_a_self_hosted_provider_still_runs_studios_own_web_search(monkeypatch, p
def test_a_local_only_selection_takes_the_loop_on_a_hosted_provider(monkeypatch, overrides):
"""Shape 3: one Studio-only name (or MCP) is unambiguous, so the feature
works on hosted providers too."""
+ # ``_select_request_tools`` imports this from ``core.inference.tools`` inside the function
+ # body, so it is never an attribute of ``routes.inference``: patching the route set a dead
+ # name, and ``raising = False`` hid that while the real function spawned stdio MCP servers
+ # and wrote discovery cache and cool-off state. Default ``raising`` catches a future move.
monkeypatch.setattr(
- "routes.inference.get_enabled_mcp_tools",
+ "core.inference.tools.get_enabled_mcp_tools",
lambda: _noop_mcp(),
- raising = False,
)
inf = _install(monkeypatch, "openai")
with pytest.raises(LoopEntered):
diff --git a/studio/backend/tests/test_external_tool_stream_abuse.py b/studio/backend/tests/test_external_tool_stream_abuse.py
index 7e82f79d78b..f34f80a6164 100644
--- a/studio/backend/tests/test_external_tool_stream_abuse.py
+++ b/studio/backend/tests/test_external_tool_stream_abuse.py
@@ -894,6 +894,12 @@ def test_no_asyncio_task_is_orphaned_when_the_loop_is_closed_mid_tool(executed,
cancel_event = threading.Event()
async def _drive():
+ # Tasks already running belong to this harness, not the tool loop, so the census is taken
+ # against them. On 3.10/3.11 ``asyncio.wait_for`` wraps its coroutine in a SECOND task, so
+ # ``all_tasks()`` below also returns the ``wait_for()`` task driving this one, never done
+ # because it is awaiting the census. 3.12 reimplemented ``wait_for`` on ``asyncio.timeout``
+ # and awaits directly, which is why this read green there and red on the older two.
+ harness = asyncio.all_tasks()
agen = stream_with_studio_tools(
transport,
run = ToolLoopRun(messages = [{"role": "user", "content": "hi"}], session_id = "s1"),
@@ -909,10 +915,12 @@ def test_no_asyncio_task_is_orphaned_when_the_loop_is_closed_mid_tool(executed,
await agen.aclose()
# Give the drain a tick to join its worker before the task census.
await asyncio.sleep(0)
+ # ``not task.done()``, not "no tasks exist": a finished task was joined and is no leak,
+ # what must not survive is one still running with nobody left to await it.
return [
task
for task in asyncio.all_tasks()
- if task is not asyncio.current_task() and not task.done()
+ if task not in harness and task is not asyncio.current_task() and not task.done()
]
pending = asyncio.run(asyncio.wait_for(_drive(), timeout = 30.0))
diff --git a/studio/backend/tests/test_trainer_stdout_quiet.py b/studio/backend/tests/test_trainer_stdout_quiet.py
index ebb1acb5c27..4fde10ca3e7 100644
--- a/studio/backend/tests/test_trainer_stdout_quiet.py
+++ b/studio/backend/tests/test_trainer_stdout_quiet.py
@@ -30,6 +30,9 @@ from unittest.mock import MagicMock # noqa: E402
import pytest # noqa: E402
+_STUBBED: list[str] = []
+
+
def _stub_if_missing(name, attrs):
"""Register a stub module for a dep the backend pytest job does not install.
@@ -50,6 +53,7 @@ def _stub_if_missing(name, attrs):
return
except Exception: # noqa: BLE001 - any import failure means "not usable here", so stub it
pass
+ _STUBBED.append(name)
mod = types.ModuleType(name)
mod.__spec__ = None
for attr in attrs:
@@ -66,6 +70,15 @@ _stub_if_missing("trl", ("SFTTrainer", "SFTConfig"))
from core.training import trainer as tmod # noqa: E402
+# Drop the stubs now that tmod is bound, because they outlive this module otherwise and the rest
+# of the suite then runs against them. utils.hardware.hardware._shared_policy branches on
+# `"unsloth" in sys.modules` and then reaches for unsloth.dataset_num_proc, which a spec-less
+# non-package stub cannot provide, so it returns None and every shared-policy case in
+# test_dataset_map_num_proc.py skips instead of running. A real install stubs nothing, so this is
+# a no-op there.
+for _name in reversed(_STUBBED):
+ sys.modules.pop(_name, None)
+
_VERBOSE_ENV = (
"UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS",
"UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS",
diff --git a/studio/backend/tests/test_training_preflight.py b/studio/backend/tests/test_training_preflight.py
index eaa19985460..0c99fc3cdfc 100644
--- a/studio/backend/tests/test_training_preflight.py
+++ b/studio/backend/tests/test_training_preflight.py
@@ -5,6 +5,7 @@
empty-chat-template crash) before train(). The real methods are bound onto a light
fake self so the production logic runs against controlled batches."""
+import contextlib
import importlib
import json
import os
@@ -23,6 +24,9 @@ import pytest
torch = pytest.importorskip("torch")
+_STUBBED: list[str] = []
+
+
def _stub_if_missing(name, attrs):
"""Register a stub module for a dep the CPU backend CI job does not install.
@@ -39,6 +43,7 @@ def _stub_if_missing(name, attrs):
return
except Exception:
pass
+ _STUBBED.append(name)
mod = types.ModuleType(name)
mod.__spec__ = None
for attr in attrs:
@@ -49,11 +54,35 @@ def _stub_if_missing(name, attrs):
setattr(sys.modules[parent], child, mod)
-_stub_if_missing("unsloth", ("FastLanguageModel", "FastVisionModel", "is_bfloat16_supported"))
-_stub_if_missing("unsloth.chat_templates", ("get_chat_template",))
-_stub_if_missing("trl", ("SFTTrainer", "SFTConfig"))
+_STUB_SPECS = (
+ ("unsloth", ("FastLanguageModel", "FastVisionModel", "is_bfloat16_supported")),
+ ("unsloth.chat_templates", ("get_chat_template",)),
+ ("trl", ("SFTTrainer", "SFTConfig")),
+)
+
+
+def _stubbed():
+ """Hold the stubs for the duration of an import of the trainer, then drop them again.
+
+ Leaving them in sys.modules outlives this module and the rest of the suite then runs against
+ them: utils.hardware.hardware._shared_policy branches on `"unsloth" in sys.modules` and then
+ reaches for unsloth.dataset_num_proc, which a spec-less non-package stub cannot provide, so it
+ returns None and every shared-policy case in test_dataset_map_num_proc.py skips instead of
+ running. _load_trainer_module re-imports the trainer per test, so scoping beats a one-shot
+ cleanup after the import below. A real install stubs nothing, so this is a no-op there.
+ """
+ for name, attrs in _STUB_SPECS:
+ _stub_if_missing(name, attrs)
+ try:
+ yield
+ finally:
+ while _STUBBED:
+ sys.modules.pop(_STUBBED.pop(), None)
-from core.training.trainer import UnslothTrainer # noqa: E402
+
+with _stubbed():
+ from core.training.trainer import UnslothTrainer # noqa: E402
_preflight = UnslothTrainer._preflight_first_batch
_renders_empty = UnslothTrainer._chat_template_renders_empty
@@ -714,10 +743,11 @@ def _load_trainer_module(
):
_set_training_platform(monkeypatch, package, backend)
_clear_trainer_module(package)
- if package in sys.modules:
- importlib.reload(sys.modules[package])
- trainer_mod = importlib.import_module(f"{package}.trainer")
- training_mod = importlib.import_module(f"{package}.training")
+ with _stubbed():
+ if package in sys.modules:
+ importlib.reload(sys.modules[package])
+ trainer_mod = importlib.import_module(f"{package}.trainer")
+ training_mod = importlib.import_module(f"{package}.training")
monkeypatch.setattr(
training_mod._MLXTrainerAdapter,
"_activate_transformers_for_model",
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 043c8e002d1..1521ec6fa9d 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -531,6 +531,44 @@ def _load_gguf(backend, tmp_path):
)
+def _stub_apply_memory_plan(
+ monkeypatch,
+ video_mod,
+ *,
+ policy = "model",
+ vae_tiling = True,
+) -> list:
+ """Stand in for ``apply_memory_plan``, recording the placement kwargs of every call.
+
+ The keywords are spelled out rather than ``**kwargs`` on purpose: a double that swallows the
+ signature keeps passing once the load hands over an argument it never reads, which is how
+ ``placement_device`` (#8645) became a TypeError on CI.
+ """
+ calls = []
+
+ def _fake(
+ pipe,
+ plan,
+ *,
+ device = None,
+ placement_device = None,
+ logger = None,
+ ):
+ calls.append({"device": device, "placement_device": placement_device})
+ return (policy, vae_tiling)
+
+ monkeypatch.setattr(video_mod, "apply_memory_plan", _fake)
+ return calls
+
+
+def _assert_placement_follows_the_target(calls, video_mod):
+ """Placement gets the INDEXED device off the resolved target, the policy string stays bare."""
+ target = video_mod.resolve_diffusion_device_target()
+ assert calls, "apply_memory_plan was never called"
+ assert calls[0]["placement_device"] == target.torch_device
+ assert calls[0]["device"] == target.device
+
+
def test_resolve_kind():
assert resolve_video_model_kind("x.gguf", None) == "gguf"
assert resolve_video_model_kind("x.safetensors", None) == "single_file"
@@ -1790,11 +1828,7 @@ def test_dense_quant_skipped_under_offload(fake_runtime, monkeypatch):
"plan_diffusion_memory",
lambda **kwargs: dataclasses.replace(real_plan(**kwargs), offload_policy = "model"),
)
- monkeypatch.setattr(
- video_mod,
- "apply_memory_plan",
- lambda pipe, plan, device = None, logger = None: ("model", True),
- )
+ placements = _stub_apply_memory_plan(monkeypatch, video_mod)
backend = VideoBackend()
status = backend.load_pipeline(
@@ -1802,6 +1836,7 @@ def test_dense_quant_skipped_under_offload(fake_runtime, monkeypatch):
model_kind = "pipeline",
transformer_quant = "int8",
)
+ _assert_placement_follows_the_target(placements, video_mod)
assert status["offload_policy"] == "model"
assert quantised == []
assert status["transformer_quant"] is None
@@ -1813,6 +1848,36 @@ def test_dense_quant_skipped_under_offload(fake_runtime, monkeypatch):
assert resolved["status"] == "fell_back"
+def test_the_video_load_places_on_the_selected_card_not_a_bare_device(fake_runtime, monkeypatch):
+ # #8645 at the video seam: ``enable_model_cpu_offload`` reads the ordinal off the device and
+ # falls back to ``_offload_gpu_id = 0`` without one, so the load passes the INDEXED string as
+ # ``placement_device``; ``device`` stays bare because the memory/speed/attention policies
+ # compare it against "cuda". The two must not be swapped.
+ import dataclasses
+
+ import core.inference.video as video_mod
+
+ real_target = VideoBackend._device_target
+
+ def _selected(self, ordinal = None):
+ return dataclasses.replace(real_target(self, ordinal), ordinal = 1)
+
+ monkeypatch.setattr(VideoBackend, "_device_target", _selected)
+ real_plan = video_mod.plan_diffusion_memory
+ monkeypatch.setattr(
+ video_mod,
+ "plan_diffusion_memory",
+ lambda **kwargs: dataclasses.replace(real_plan(**kwargs), offload_policy = "model"),
+ )
+ placements = _stub_apply_memory_plan(monkeypatch, video_mod)
+
+ VideoBackend().load_pipeline("Lightricks/LTX-2", model_kind = "pipeline")
+
+ assert placements, "apply_memory_plan was never called"
+ assert placements[0]["placement_device"] == "cpu:1"
+ assert placements[0]["device"] == "cpu"
+
+
def test_explicit_dense_quant_refuses_under_offload(fake_runtime, monkeypatch):
# Strict default (no escape hatch): an explicit int8 the offload plan cannot honor stops the
# load, rather than denoising at bf16 while the Precision dropdown still reads INT8.
@@ -6680,9 +6745,7 @@ def test_dense_quant_replan_uses_the_scaled_text_encoder(fake_runtime, monkeypat
return dataclasses.replace(real(**kwargs), offload_policy = "model")
monkeypatch.setattr(video_mod, "plan_diffusion_memory", _spy)
- monkeypatch.setattr(
- video_mod, "apply_memory_plan", lambda pipe, plan, device = None, logger = None: ("model", True)
- )
+ placements = _stub_apply_memory_plan(monkeypatch, video_mod)
VideoBackend().load_pipeline(
"Lightricks/LTX-2",
@@ -6690,6 +6753,7 @@ def test_dense_quant_replan_uses_the_scaled_text_encoder(fake_runtime, monkeypat
transformer_quant = "int8",
text_encoder_quant = "fp8",
)
+ _assert_placement_follows_the_target(placements, video_mod)
assert len(calls) == 2, "the dense-quant re-plan did not run"
assert calls[1]["model_dense_mib"] == int(
(transformer_gb * _QUANT_STEADY_FACTOR["int8"] + text_encoder_gb * scale + vae_gb)