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.

Give the torchcodec placeholder a real __spec__ (#11325)

Daniel Han08e2278d65a2
diff --git a/.github/workflows/notebooks-ci.yml b/.github/workflows/notebooks-ci.yml
index 3226ae0b6e2..f2b0452da6c 100644
--- a/.github/workflows/notebooks-ci.yml
+++ b/.github/workflows/notebooks-ci.yml
@@ -31,7 +31,11 @@ on:
- 'scripts/data/colab_os_info.gpu.txt'
- 'scripts/data/colab_to_cpu_pin.json'
- 'tests/notebooks/**'
+ # Every helper the smoke steps import, or a change to one of them merges without the
+ # matrix that runs it ever starting. test_smoke_install_contract.py derives this list
+ # from the steps themselves, so a new helper fails that test until it is listed here.
- 'tests/_zoo_aggressive_cuda_spoof.py'
+ - 'tests/_torchcodec_stub.py'
- '.github/workflows/notebooks-ci.yml'
schedule:
# Daily 06:17 UTC. Catches Colab preinstall bumps (the upstream image
@@ -735,10 +739,11 @@ jobs:
awk '/^from unsloth import/ { print "import sys; sys.exit(0)"; exit } { print }' "$PY" > _smoke.py
PYTHONPATH=unsloth/tests python -u - <<'PY'
import _zoo_aggressive_cuda_spoof as _s; _s.apply()
- # Stub torchcodec for cells that import it — no CPU wheel exists.
- import sys, types
- if "torchcodec" not in sys.modules:
- sys.modules["torchcodec"] = types.ModuleType("torchcodec")
+ # Stub torchcodec for cells that import it — no CPU wheel exists. Through the
+ # shared helper, which installs a tiny placeholder DISTRIBUTION rather than poking
+ # sys.modules: transformers asks find_spec and then reads the distribution version
+ # at import time, and a sys.modules entry answers at most the first of those.
+ import _torchcodec_stub as _t; _t.install()
exec(open("_smoke.py").read(), {"__name__": "__main__"})
PY
@@ -746,9 +751,7 @@ jobs:
timeout-minutes: 5
run: |
PYTHONPATH=unsloth/tests python -u - <<'PY'
- import sys, types
- if "torchcodec" not in sys.modules:
- sys.modules["torchcodec"] = types.ModuleType("torchcodec")
+ import _torchcodec_stub as _t; _t.install()
import _zoo_aggressive_cuda_spoof as _s; _s.apply()
import unsloth, peft, torch, torchao, transformers, tokenizers
print("OK: imports pass under CUDA spoof")
diff --git a/tests/_torchcodec_stub.py b/tests/_torchcodec_stub.py
new file mode 100644
index 00000000000..97a22d20917
--- /dev/null
+++ b/tests/_torchcodec_stub.py
@@ -0,0 +1,89 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""A torchcodec placeholder for the Colab-shaped smoke job, which has no CPU wheel to install.
+
+Installed as a real (tiny) distribution on sys.path rather than as an entry poked into
+sys.modules, because both of the obvious sys.modules shapes fail against the transformers the
+Colab image pins:
+
+ * `types.ModuleType("torchcodec")` leaves `__spec__` None, and `importlib.util.find_spec`
+ RAISES for a module sitting in sys.modules with no spec instead of returning None. That is
+ `ValueError: torchcodec.__spec__ is None`, which is how the smoke matrix was failing.
+
+ * the same module carrying a hand-made ModuleSpec answers find_spec, but then
+ `is_torchcodec_available()` is True -- transformers 5.16.1 calls `_is_package_available`
+ without `return_version`, so it never looks at distribution metadata and reports presence
+ from the spec alone -- and `audio_utils` line 61 immediately does
+ `version.parse(importlib.metadata.version("torchcodec"))` at import time. With no
+ distribution installed that is PackageNotFoundError: one import failure traded for another.
+
+A distribution on disk answers both questions honestly. It also answers a third one the right
+way: the version is deliberately below the 0.3.0 floor `load_audio` requires, so the "auto"
+backend resolves to librosa and nothing ever asks this placeholder to decode anything.
+"""
+
+from __future__ import annotations
+
+import importlib
+import importlib.util
+import sys
+import tempfile
+from pathlib import Path
+
+NAME = "torchcodec"
+# Deliberately below transformers' 0.3.0 torchcodec floor; see the module docstring.
+VERSION = "0.0.0"
+
+_METADATA = f"""Metadata-Version: 2.1
+Name: {NAME}
+Version: {VERSION}
+Summary: Placeholder installed by the Unsloth notebooks smoke job; no CPU wheel is published.
+"""
+
+
+def install(target_dir: "str | Path | None" = None) -> "str | None":
+ """Put the placeholder on sys.path unless a real torchcodec is already importable.
+
+ Returns the directory it was written to, or None when a real one was found.
+ """
+ if _already_present():
+ # A genuine torchcodec, or a placeholder an earlier step already installed. Either way
+ # replacing it would be the opposite of what this is for.
+ return None
+
+ root = (
+ Path(target_dir)
+ if target_dir
+ else Path(tempfile.mkdtemp(prefix = "unsloth-torchcodec-stub-"))
+ )
+ package = root / NAME
+ package.mkdir(parents = True, exist_ok = True)
+ (package / "__init__.py").write_text(
+ f'"""Placeholder; the real torchcodec publishes no CPU wheel."""\n\n__version__ = "{VERSION}"\n',
+ encoding = "utf-8",
+ )
+ dist_info = root / f"{NAME}-{VERSION}.dist-info"
+ dist_info.mkdir(parents = True, exist_ok = True)
+ (dist_info / "METADATA").write_text(_METADATA, encoding = "utf-8")
+ # Names who put it there, so anyone reading the venv can tell this from a real install.
+ (dist_info / "INSTALLER").write_text("unsloth-notebooks-smoke\n", encoding = "utf-8")
+ (dist_info / "RECORD").write_text("", encoding = "utf-8")
+
+ sys.path.insert(0, str(root))
+ # The path entry is new, so the finders' directory caches have to be dropped or the
+ # package stays invisible to find_spec for the rest of the process.
+ importlib.invalidate_caches()
+ return str(root)
+
+
+def _already_present() -> bool:
+ """Whether importing torchcodec would find something without our help."""
+ if NAME in sys.modules:
+ return True
+ try:
+ return importlib.util.find_spec(NAME) is not None
+ except (ImportError, ValueError):
+ # ValueError is the spec-less sys.modules entry this file exists to avoid; treat a
+ # broken pre-existing entry as present rather than shadowing it with a second one.
+ return True
diff --git a/tests/notebooks/test_smoke_install_contract.py b/tests/notebooks/test_smoke_install_contract.py
index 73756c6c673..edf6c4ed17d 100644
--- a/tests/notebooks/test_smoke_install_contract.py
+++ b/tests/notebooks/test_smoke_install_contract.py
@@ -20,6 +20,7 @@ Neither is noticeable otherwise: a leg over `timeout-minutes` is scored
from __future__ import annotations
import json
+import os
import re
import sys
from pathlib import Path
@@ -369,3 +370,208 @@ def test_the_skip_list_is_closed_under_the_freezes_dependencies():
f"each of these is skipped while a retained pin still requires it, so pip "
f"downloads it anyway and the skip saves nothing: {leaks}"
)
+
+
+# --- the torchcodec placeholder --------------------------------------------------------
+
+
+def _probe_in_a_venv_without_torchcodec(mode: str) -> str:
+ """Run the two things transformers does at import time, in a subprocess whose sys.path has
+ no real torchcodec, and return what it printed.
+
+ A subprocess because the question is about interpreter state (sys.modules, sys.path,
+ distribution metadata) that a stub cannot be un-installed from cleanly, and because this
+ repo's own venv HAS torchcodec, which would answer both probes for the wrong reason.
+ """
+ import subprocess
+ import textwrap
+
+ script = textwrap.dedent(
+ """
+ import importlib.metadata, importlib.util, sys
+ mode, tests_dir = sys.argv[1], sys.argv[2]
+ sys.path.insert(0, tests_dir)
+ if mode == "bare":
+ import types
+ sys.modules["torchcodec"] = types.ModuleType("torchcodec")
+ elif mode == "spec":
+ import importlib.machinery, types
+ m = types.ModuleType("torchcodec")
+ m.__spec__ = importlib.machinery.ModuleSpec("torchcodec", None)
+ sys.modules["torchcodec"] = m
+ elif mode == "dist":
+ import _torchcodec_stub as t
+ t.install()
+ # is_torchcodec_available() -> _is_package_available(name)[0]; transformers 5.16.1
+ # passes no return_version, so presence is decided by the spec alone.
+ try:
+ available = importlib.util.find_spec("torchcodec") is not None
+ except Exception as e:
+ print("AVAILABLE_RAISED", type(e).__name__); raise SystemExit(0)
+ print("AVAILABLE", available)
+ if available:
+ # audio_utils.py:61, at import time.
+ try:
+ print("VERSION", importlib.metadata.version("torchcodec"))
+ except Exception as e:
+ print("VERSION_RAISED", type(e).__name__)
+ """
+ )
+ # -S skips site-packages, so a real torchcodec on THIS interpreter cannot answer the
+ # probes for the wrong reason. That is what the runner looks like, and it lets the test
+ # run everywhere instead of skipping wherever the wheel happens to be installed.
+ out = subprocess.run(
+ [sys.executable, "-S", "-c", script, mode, str(REPO / "tests")],
+ capture_output = True,
+ text = True,
+ env = {"PATH": os.environ.get("PATH", ""), "PYTHONNOUSERSITE": "1"},
+ cwd = str(REPO),
+ )
+ return out.stdout
+
+
+ "mode, expected",
+ [
+ # The shape on main: __spec__ is None and find_spec raises rather than returning None.
+ ("bare", "AVAILABLE_RAISED ValueError"),
+ # A hand-made ModuleSpec gets past find_spec and straight into the metadata lookup
+ # that audio_utils does at import time, which is the second failure and the reason
+ # the placeholder is a distribution rather than a sys.modules entry.
+ ("spec", "VERSION_RAISED PackageNotFoundError"),
+ # The placeholder: both probes answer.
+ ("dist", "VERSION 0.0.0"),
+ ],
+ ids = ["bare ModuleType", "ModuleType with a spec", "the placeholder distribution"],
+)
+def test_the_placeholder_survives_both_probes_transformers_makes(mode, expected):
+ """transformers asks two questions while importing audio_utils, and a stub has to answer
+ both. is_torchcodec_available() reads find_spec, and line 61 then reads the distribution
+ version. Answering only the first turns ValueError into PackageNotFoundError.
+ """
+ printed = _probe_in_a_venv_without_torchcodec(mode)
+ assert (
+ "AVAILABLE_RAISED ValueError" in printed or "AVAILABLE" in printed
+ ), f"the probe subprocess produced nothing usable for {mode!r}: {printed!r}"
+ assert expected in printed, printed
+
+
+def _load_stub_helper():
+ """Load tests/_torchcodec_stub.py by path, without touching sys.path.
+
+ `sys.path.insert(0, REPO / "tests")` is process-wide and permanent, and `tests/` holds a
+ `utils/` package that then shadows studio/backend's `utils` for every test that runs
+ afterwards in the same worker. That is how this file turned
+ tests/test_studio_root_resilience.py red with
+ `ModuleNotFoundError: No module named 'utils.native_path_leases'` while being green itself.
+ """
+ import importlib.util
+
+ path = REPO / "tests" / "_torchcodec_stub.py"
+ spec = importlib.util.spec_from_file_location("_unsloth_torchcodec_stub_under_test", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_the_placeholder_version_stays_under_the_backend_floor():
+ """load_audio resolves "auto" to torchcodec only at >= 0.3.0, so a placeholder claiming a
+ newer version would be chosen as the decoder and then fail on the first real call. Below
+ the floor it is visible, importable and never selected."""
+ _torchcodec_stub = _load_stub_helper()
+
+ floor = (0, 3, 0)
+ actual = tuple(int(part) for part in _torchcodec_stub.VERSION.split("."))
+ assert actual < floor, (
+ f"the placeholder claims {_torchcodec_stub.VERSION}, at or above transformers' "
+ "0.3.0 torchcodec floor, so load_audio(backend='auto') would select it"
+ )
+
+
+def test_the_placeholder_never_displaces_a_real_torchcodec():
+ """A machine that does have the wheel must keep it: the placeholder is for the CPU runner,
+ and shadowing a genuine install would be the opposite of what it is for."""
+ import types
+
+ _torchcodec_stub = _load_stub_helper()
+
+ real = types.ModuleType(_torchcodec_stub.NAME)
+ saved = sys.modules.get(_torchcodec_stub.NAME)
+ sys.modules[_torchcodec_stub.NAME] = real
+ try:
+ assert _torchcodec_stub.install() is None, "it wrote a placeholder over a live module"
+ assert sys.modules[_torchcodec_stub.NAME] is real
+ finally:
+ if saved is None:
+ sys.modules.pop(_torchcodec_stub.NAME, None)
+ else:
+ sys.modules[_torchcodec_stub.NAME] = saved
+
+
+def test_both_smoke_steps_stub_torchcodec_through_the_shared_helper():
+ """Two steps stub it, and they used to carry their own copy of the bare-ModuleType form.
+ One fixed copy is how this comes back."""
+ shell = _shell(_job())
+ assert "_torchcodec_stub" in shell, "the smoke job no longer uses the shared placeholder"
+ assert shell.count("import _torchcodec_stub") == 2, (
+ "both the install-cell step and the import-verification step must install the "
+ f"placeholder; found {shell.count('import _torchcodec_stub')} site(s)"
+ )
+ assert 'types.ModuleType("torchcodec")' not in shell, (
+ "a hand-rolled torchcodec stub is back in the workflow; its __spec__ is None and "
+ "importlib.util.find_spec raises on it"
+ )
+
+
+def test_every_helper_the_smoke_steps_import_is_a_path_trigger():
+ """A helper the job executes is part of the job. `tests/_torchcodec_stub.py` was added as a
+ shared stub and imported by both smoke steps while the workflow's `pull_request.paths`
+ still listed only its sibling, so a PR touching nothing else would have merged a broken
+ helper without the smoke matrix or this file ever running.
+
+ Derived from the steps rather than hand-listed, so the next shared helper is caught by
+ this test instead of by a silent green run.
+ """
+ shell = _shell(_job())
+ imported = set(re.findall(r"import\s+(_\w+)", shell))
+ assert imported, "no helper imports found in the smoke steps; this guard checks nothing"
+
+ doc = yaml.safe_load(WORKFLOW.read_text(encoding = "utf-8"))
+ # `on` is the YAML 1.1 boolean True once parsed, which is why this is not doc["on"].
+ triggers = doc[True] if True in doc else doc["on"]
+ paths = set(triggers["pull_request"]["paths"])
+
+ for helper in sorted(imported):
+ candidate = REPO / "tests" / f"{helper}.py"
+ if not candidate.is_file():
+ continue # a stdlib or third-party name that merely starts with an underscore
+ entry = f"tests/{helper}.py"
+ assert entry in paths, (
+ f"{entry} is imported by a smoke step but is not in the workflow's "
+ f"pull_request.paths, so a PR changing only that file would not run this job"
+ )
+
+
+def test_loading_the_stub_helper_leaves_sys_path_alone():
+ """`tests/` holds a `utils/` package, so a module that puts that directory at the FRONT of
+ sys.path shadows studio/backend's `utils` for every test after it in the same worker. This
+ file did exactly that to reach the helper, and the casualty was another file entirely:
+ tests/test_studio_root_resilience.py, red with
+ `ModuleNotFoundError: No module named 'utils.native_path_leases'`.
+
+ The claim is that loading the helper changes nothing, not that `tests/` is absent from
+ sys.path: pytest's own prepend import mode puts the basedir of every collected test module
+ there, so absence was never true to begin with and asserting it failed in CI for a reason
+ that had nothing to do with this file.
+ """
+ before = list(sys.path)
+ _load_stub_helper()
+ assert sys.path == before, (
+ "loading the helper mutated sys.path: "
+ f"added {[p for p in sys.path if p not in before]!r}"
+ )
+
+ # Assembled rather than written out, so the needle does not match this line itself.
+ needle = "sys.path" + ".insert(0, str(REPO / " + chr(34) + "tests" + chr(34) + "))"
+ source = Path(__file__).read_text(encoding = "utf-8")
+ assert needle not in source, "a sys.path insert of the tests dir is back in this file"