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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
torchcodec: cover torch 2.11 in the compatibility guard and pin per torch minor (#7474)
Daniel Handa4f0b9194d6
diff --git a/.github/workflows/security-audit.yml b/.github/workflows/security-audit.ymlindex c3a493192fd..fb64de15879 100644--- a/.github/workflows/security-audit.yml+++ b/.github/workflows/security-audit.yml@@ -267,11 +267,29 @@ jobs:d = tomllib.load(f)core = d["project"]["dependencies"]extras = d["project"]["optional-dependencies"]["huggingfacenotorch"]+ # extras-no-deps.txt no longer pins torchcodec, so the audit set would lose it.+ audio = d["project"]["optional-dependencies"]["audio-torch211"]print("# Auto-generated from pyproject.toml by security-audit.yml.")- print("# core deps + huggingfacenotorch extras.")- for spec in core + extras:+ print("# core deps + huggingfacenotorch extras + audio-torch211.")+ for spec in core + extras + audio:print(spec)PY+ for extra in audio-torch210 audio-torch290 audio-torch280; do+ python - "$extra" <<'PY' > "audit-reqs/$extra.txt"+ import sys, tomllib+ extra = sys.argv[1]+ with open("pyproject.toml", "rb") as f:+ d = tomllib.load(f)+ # The older lines _select_torchcodec_spec installs on torch 2.10, 2.9 and 2.8, all of+ # which the flavor and default-ROCm repairs still resolve. One file each: their+ # ranges are disjoint, so they cannot share a resolve with each other or with+ # audio-torch211's >=0.11.+ print("# Auto-generated from pyproject.toml by security-audit.yml.")+ print(f"# {extra}.")+ for spec in d["project"]["optional-dependencies"][extra]:+ print(spec)+ PY+ donefor f in studio.txt extras.txt extras-no-deps.txt \no-torch-runtime.txt overrides.txt triton-kernels.txt; dopython <<PY > "audit-reqs/$f"@@ -312,8 +330,8 @@ jobs:wheelCONSTRAINTS: > logs-pip-audit.txt- for f in unsloth-deps studio extras extras-no-deps \- no-torch-runtime overrides triton-kernels; do+ for f in unsloth-deps audio-torch210 audio-torch290 audio-torch280 studio extras \+ extras-no-deps no-torch-runtime overrides triton-kernels; doif ! grep -qE '^[^#[:space:]]' "audit-reqs/$f.txt"; thenecho "[security-audit] $f.txt has no PyPI specs after git+ filter, skipping" \| tee -a logs-pip-audit.txt@@ -332,7 +350,7 @@ jobs:echo "## pip-audit (Python)"echoecho '### Coverage'- echo '- unsloth core + `huggingfacenotorch` extras (pyproject.toml)'+ echo '- unsloth core + `huggingfacenotorch` + every `audio-torch2xx` extra (pyproject.toml)'echo '- studio/backend/requirements/{studio,extras,extras-no-deps,no-torch-runtime,overrides,triton-kernels}.txt'echo '- `git+` specs are stripped before audit (out of scope: we audit PyPI archives)'echo@@ -457,6 +475,9 @@ jobs:--lockfile=studio/frontend/package-lock.json \--lockfile=studio/src-tauri/Cargo.lock \--lockfile=requirements.txt:audit-reqs/unsloth-deps.txt \+ --lockfile=requirements.txt:audit-reqs/audio-torch210.txt \+ --lockfile=requirements.txt:audit-reqs/audio-torch290.txt \+ --lockfile=requirements.txt:audit-reqs/audio-torch280.txt \--lockfile=requirements.txt:audit-reqs/studio.txt \--lockfile=requirements.txt:audit-reqs/no-torch-runtime.txt \--lockfile=requirements.txt:audit-reqs/overrides.txt \@@ -804,10 +825,19 @@ jobs:files: 'unsloth-deps no-torch-runtime'- name: 'pip scan-packages :: studio'id: studio- files: 'studio overrides extras-no-deps'+ files: 'studio overrides extras-no-deps audio-torch210'- name: 'pip scan-packages :: extras'id: extrasfiles: 'extras'+ # scan_packages.py keeps the first requirement per normalised package name, so the+ # torchcodec lines have to be scanned apart or only one of them is ever fetched.+ # They are one package each, so the shards are cheap.+ - name: 'pip scan-packages :: audio-torch290'+ id: audio-torch290+ files: 'audio-torch290'+ - name: 'pip scan-packages :: audio-torch280'+ id: audio-torch280+ files: 'audio-torch280'steps:# Egress block on every shard. Each shard pulls hundreds of# PyPI archives -- if a malicious wheel ever phones home from@@ -859,11 +889,29 @@ jobs:d = tomllib.load(f)core = d["project"]["dependencies"]extras = d["project"]["optional-dependencies"]["huggingfacenotorch"]+ # extras-no-deps.txt no longer pins torchcodec, so the audit set would lose it.+ audio = d["project"]["optional-dependencies"]["audio-torch211"]print("# Auto-generated from pyproject.toml by security-audit.yml.")- print("# core deps + huggingfacenotorch extras.")- for spec in core + extras:+ print("# core deps + huggingfacenotorch extras + audio-torch211.")+ for spec in core + extras + audio:print(spec)PY+ for extra in audio-torch210 audio-torch290 audio-torch280; do+ python - "$extra" <<'PY' > "audit-reqs/$extra.txt"+ import sys, tomllib+ extra = sys.argv[1]+ with open("pyproject.toml", "rb") as f:+ d = tomllib.load(f)+ # The older lines _select_torchcodec_spec installs on torch 2.10, 2.9 and 2.8, all of+ # which the flavor and default-ROCm repairs still resolve. One file each: their+ # ranges are disjoint, so they cannot share a resolve with each other or with+ # audio-torch211's >=0.11.+ print("# Auto-generated from pyproject.toml by security-audit.yml.")+ print(f"# {extra}.")+ for spec in d["project"]["optional-dependencies"][extra]:+ print(spec)+ PY+ donefor f in studio.txt extras.txt extras-no-deps.txt \no-torch-runtime.txt overrides.txt triton-kernels.txt; dopython <<PY > "audit-reqs/$f"diff --git a/pyproject.toml b/pyproject.tomlindex e5aa22a4872..af08bb3b1a9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -214,14 +214,20 @@ huggingfacenotorch = [# nothing to resolve and pip fails the whole install rather than skipping audio.# Gate on the platforms that have a wheel, matching# PLATFORM_LACKS_TORCHCODEC_WHEEL in studio/install_python_stack.py.+# The only audio-torch2xx whose line has a Linux aarch64 wheel: torchcodec added+# manylinux_2_28_aarch64 at 0.11.0, so this extra carries it and the older ones below,+# which top out at 0.10, still cannot. Mirrors _torchcodec_platform_floor.+audio-torch211 = [+ "torchcodec>=0.11.0,<0.12.0 ; python_version >= '3.10' and python_version < '3.15' and (((sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) or (sys_platform == 'linux' and platform_machine == 'aarch64') or (sys_platform == 'darwin' and platform_machine == 'arm64'))",+]audio-torch210 = [- "torchcodec>=0.10.0,<0.11.0 ; python_version >= '3.10' and (((sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) or (sys_platform == 'darwin' and platform_machine == 'arm64'))",+ "torchcodec>=0.10.0,<0.11.0 ; python_version >= '3.10' and python_version < '3.15' and (((sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) or (sys_platform == 'darwin' and platform_machine == 'arm64'))",]audio-torch290 = [- "torchcodec>=0.8.0,<0.10.0 ; python_version >= '3.10' and (((sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) or (sys_platform == 'darwin' and platform_machine == 'arm64'))",+ "torchcodec>=0.8.0,<0.10.0 ; python_version >= '3.10' and python_version < '3.15' and (((sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) or (sys_platform == 'darwin' and platform_machine == 'arm64'))",]audio-torch280 = [- "torchcodec>=0.6.0,<0.8.0 ; python_version >= '3.9' and (((sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) or (sys_platform == 'darwin' and platform_machine == 'arm64'))",+ "torchcodec>=0.6.0,<0.8.0 ; python_version >= '3.9' and python_version < '3.14' and (((sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) or (sys_platform == 'darwin' and platform_machine == 'arm64'))",]huggingface = ["unsloth[huggingfacenotorch]",diff --git a/studio/backend/requirements/extras-no-deps.txt b/studio/backend/requirements/extras-no-deps.txtindex fcc4152981b..1b61721f43e 100644--- a/studio/backend/requirements/extras-no-deps.txt+++ b/studio/backend/requirements/extras-no-deps.txt@@ -2,7 +2,8 @@descript-audio-codec==1.0.0descript-audiotools==0.7.2julius==0.2.8-torchcodec==0.10.0+# torchcodec is NOT pinned here: its wheels are per-torch-minor and markers cannot see+# the installed torch. install_python_stack._select_torchcodec_spec picks the line.snac==1.2.1# peft 0.19.0 causes export subprocess shutdown issues in Unsloth;diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex e45b80c0c55..ca60fcd4686 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -57,12 +57,18 @@ IS_LINUX = sys.platform.startswith("linux")# amd-smi auto-elevates on Windows (UAC/DiskPart); RunAsInvoker keeps probes un-elevated.if IS_WINDOWS:os.environ.setdefault("__COMPAT_LAYER", "RunAsInvoker")-# torchcodec ships wheels only for manylinux_2_28_x86_64, macosx_12_0_arm64 and win_amd64.-PLATFORM_LACKS_TORCHCODEC_WHEEL = (- (IS_LINUX and platform.machine() in {"aarch64", "arm64"})- or (IS_WINDOWS and platform.machine().lower() in {"arm64", "aarch64"})- or IS_MAC_INTEL+# Platforms that HAVE a torchcodec wheel (manylinux_2_28 x86_64/aarch64, macosx arm64,+# win_amd64); elsewhere the audio extras are filtered out or extras-no-deps fails. Stated+# as the allowlist, like the pyproject markers this mirrors: the denylist spelling missed+# every Linux arch past Arm. aarch64 arrived at 0.11.0, which is the row torch 2.11 selects,+# so omitting it would deny audio to the hosts that row serves. Whether a platform ever+# published, not when -- that is _torchcodec_platform_floor's job.+_PLATFORM_HAS_TORCHCODEC_WHEEL = (+ (IS_LINUX and platform.machine() in {"x86_64", "AMD64", "aarch64", "arm64"})+ or (IS_WINDOWS and platform.machine().lower() in {"amd64", "x86_64"})+ or IS_MAC_ARM)+PLATFORM_LACKS_TORCHCODEC_WHEEL = not _PLATFORM_HAS_TORCHCODEC_WHEELdef _is_windows_arm64() -> bool:@@ -353,6 +359,227 @@ def _select_torchao_spec(torch_version: str | None) -> str:return _TORCHAO_DEFAULT_SPEC+# torchcodec up to 0.11 is built against one torch minor and declares no+# `Requires-Dist: torch`, so pip cannot catch a mismatch. 0.12+ is ABI-stable against torch+# >=2.11, hence the open floor. Mirrors pyproject's audio-torch2xx and import_fixes.+_TORCHCODEC_DEFAULT_SPEC = "torchcodec>=0.10.0,<0.11.0"+_TORCHCODEC_ABI_STABLE_SPEC = "torchcodec>=0.12.0"+_TORCHCODEC_TORCH_SPECS: dict[int, str] = {+ 12: _TORCHCODEC_ABI_STABLE_SPEC,+ 11: "torchcodec>=0.11.0,<0.12.0",+ 10: "torchcodec>=0.10.0,<0.11.0",+ 9: "torchcodec>=0.8.0,<0.10.0",+ 8: "torchcodec>=0.6.0,<0.8.0",+ 7: "torchcodec>=0.3.0,<0.6.0",+ 6: "torchcodec>=0.2.0,<0.3.0",+ 5: "torchcodec>=0.1.0,<0.2.0",+}+_TORCHCODEC_MAX_KNOWN_MINOR = max(_TORCHCODEC_TORCH_SPECS)++# Not every platform was published from 0.1. Read off the live PyPI index:+#+# win_amd64 first at 0.7.0 (0.1 .. 0.6 are Linux/macOS only)+# manylinux aarch64 first at 0.11.0+# manylinux x86_64 from the start+# macosx arm64 from the start, min macOS moves 11.0 -> 14.0 at 0.12.0+#+# A window whose releases have no wheel here aborts the install rather than skipping audio,+# and it is reachable: cu118 tops out at torch 2.7, so an older-driver Windows box selects+# `>=0.3.0,<0.6.0`, and no release in that window ships win_amd64.+_TORCHCODEC_MIN_WHEEL_VERSION = (0, 1, 0)+_TORCHCODEC_MIN_WHEEL_WINDOWS = (0, 7, 0)+_TORCHCODEC_MIN_WHEEL_LINUX_AARCH64 = (0, 11, 0)+# 0.12.0 raised its macOS floor; a Mac below this cannot use the ABI-stable line at all.+_TORCHCODEC_MACOS_14_ONLY_FROM = (0, 12, 0)+++def _torchcodec_platform_floor() -> "tuple[int, int, int] | None":+ """Earliest torchcodec release with a wheel for THIS host, or None when there is none."""+ machine = platform.machine().lower()+ if IS_WINDOWS:+ return _TORCHCODEC_MIN_WHEEL_WINDOWS if machine in {"amd64", "x86_64"} else None+ if IS_LINUX:+ if machine in {"x86_64", "amd64"}:+ return _TORCHCODEC_MIN_WHEEL_VERSION+ if machine in {"aarch64", "arm64"}:+ return _TORCHCODEC_MIN_WHEEL_LINUX_AARCH64+ return None # ppc64le, s390x, riscv64: no wheel at any version+ if IS_MAC_ARM:+ return _TORCHCODEC_MIN_WHEEL_VERSION+ return None # Intel Mac+++def _macos_release_major() -> "int | None":+ """Major macOS version, or None off macOS / when it cannot be read."""+ if not IS_MACOS:+ return None+ try:+ release = platform.mac_ver()[0]+ return int(release.split(".", 1)[0]) if release else None+ except (ValueError, IndexError):+ return None+++# The supported Python range moves three times across the lines we select from.+# Transcribed from upstream's published table (README / PyPI):+#+# 0.1 >=3.9, <=3.12+# 0.2 .. 0.7 >=3.9, <=3.13+# 0.8 >=3.10, <=3.13+# 0.9 + >=3.10, <=3.14+#+# Entries are (first release of the run, min python, max python); a run ends where the next+# begins. A separate axis from the platform floor: a host can have a wheel for its+# architecture and none for its interpreter. Reachable at torch 2.5 on Python 3.13, whose+# only line is 0.1, which stops at 3.12.+_TORCHCODEC_PYTHON_WINDOWS: "tuple[tuple[tuple[int, int, int], tuple[int, int], tuple[int, int]], ...]" = (+ ((0, 1, 0), (3, 9), (3, 12)),+ ((0, 2, 0), (3, 9), (3, 13)),+ ((0, 8, 0), (3, 10), (3, 13)),+ ((0, 9, 0), (3, 10), (3, 14)),+)+++def _torchcodec_python_is_supported(+ floor: "tuple[int, ...]", ceiling: "tuple[int, ...] | None"+) -> bool:+ """Does any release in [floor, ceiling) ship a wheel for the running interpreter?"""+ running = sys.version_info[:2]+ for index, (start, py_min, py_max) in enumerate(_TORCHCODEC_PYTHON_WINDOWS):+ end = (+ _TORCHCODEC_PYTHON_WINDOWS[index + 1][0]+ if index + 1 < len(_TORCHCODEC_PYTHON_WINDOWS)+ else None+ )+ if ceiling is not None and start >= ceiling:+ continue # run begins above the window+ if end is not None and end <= floor:+ continue # run ends below the window+ if py_min <= running <= py_max:+ return True+ return False+++# download.pytorch.org carries torchcodec only from 0.3 up; 0.1 and 0.2 were published to+# PyPI alone. So the two oldest rows (torch 2.5 -> 0.1, 2.6 -> 0.2) cannot be pinned at all,+# and pinning them would turn a working-or-not install into a guaranteed skip on exactly the+# oldest venvs. They keep today's unpinned behavior.+_TORCHCODEC_MIN_ON_TORCH_INDEX = (0, 3, 0)+++def _cuda_major_for_npp(torch_version: "str | None", index_url: str) -> str:+ """`"12"`, `"13"`, or `""` when this codec install needs no NPP runtime.++ The resident torch's LOCAL TAG first, the index URL only as a fallback. Matching+ `/cuNNN$` on the URL failed for a supported UNSLOTH_TORCH_INDEX_URL ending in+ `/simple?token=...`, so a `+cu128` host skipped NPP and the codec then failed to import+ without a system CUDA toolkit. The tag is also the better source: _torchcodec_index_url+ only returns an index once it has seen a `cpu` or `cuNNN` tag, so the tag is always there.+ """+ local = str(torch_version or "").partition("+")[2].strip().lower()+ match = re.fullmatch(r"cu(\d+)", local)+ if match:+ return match.group(1)[:2]+ # No usable local tag: a torch from PyPI carries none. Fall back to the leaf, which+ # still answers for the public download.pytorch.org form.+ match = re.search(r"/cu(\d+)/?$", index_url or "")+ return match.group(1)[:2] if match else ""+++def _torchcodec_index_url(torch_version: "str | None", spec: str = "") -> "str | None":+ """The torchcodec index serving the resident torch's build, or None to stay unpinned.++ torchcodec is published per accelerator exactly the way torch is: PyPI carries one+ default flavor and the rest live at download.pytorch.org/whl/<tag>. Upstream's install+ docs say to pass --index-url and "make sure to install the corresponding PyTorch version+ as well", so a cu126 or cu128 venv that takes PyPI's default gets a codec built against a+ different CUDA and libtorchcodec cannot dlopen. docker/Dockerfile already pins cu128 by+ hand for this reason.++ Only an EXPLICIT local tag pins. An untagged torch is PyPI's own build, whose counterpart+ is PyPI's default torchcodec -- already the right pairing. That is the opposite reading+ from _torch_flavor_tag, which maps untagged to "cpu" for the Windows repair path; here an+ untagged Linux torch is a CUDA build, so pinning cpu would install the wrong one.+ rocm and xpu publish no torchcodec under that name, so they stay unpinned rather than+ being sent to an index that cannot serve them.+ """+ if not torch_version:+ return None+ if spec:+ _, ceiling = _torchcodec_spec_bounds(spec)+ if ceiling is not None and ceiling <= _TORCHCODEC_MIN_ON_TORCH_INDEX:+ return None # window sits entirely below what any torch index publishes+ local = str(torch_version).partition("+")[2].strip().lower()+ if local == "cpu" or re.fullmatch(r"cu\d+", local):+ # An explicit pin wins, as it does for the torch repair helpers: synthesising the+ # public URL from the local tag sent authenticated, corporate and air-gapped mirrors+ # to download.pytorch.org, and the --index-url also makes _install_env_for_cmd drop+ # the inherited index config, so the install fails outright there. _PYTORCH_WHL_BASE+ # rather than a literal, since UNSLOTH_PYTORCH_MIRROR redirects every other index+ # this module builds.+ return _explicit_torch_index_url() or f"{_PYTORCH_WHL_BASE}/{local}"+ return None+++def _torchcodec_spec_bounds(spec: str) -> "tuple[tuple[int, ...], tuple[int, ...] | None]":+ """`torchcodec>=0.6.0,<0.8.0` -> ((0,6,0), (0,8,0)); an open floor gives (floor, None)."""++ def _v(text: str) -> tuple[int, ...]:+ return tuple(int(p) for p in re.findall(r"\d+", text)[:3])++ body = spec.split("torchcodec", 1)[1]+ floor_match = re.search(r">=\s*([0-9.]+)", body)+ ceiling_match = re.search(r"<\s*([0-9.]+)", body)+ floor = _v(floor_match.group(1)) if floor_match else (0,)+ ceiling = _v(ceiling_match.group(1)) if ceiling_match else None+ return floor, ceiling+++def _torchcodec_spec_is_installable(spec: str) -> bool:+ """Does this host have a wheel for any release the spec admits?++ Asked before the install rather than discovered by it, because the install step exits on+ failure. Answering no means the audio extra is skipped, which is what a host with no wheel+ got before this step existed.+ """+ host_floor = _torchcodec_platform_floor()+ if host_floor is None:+ return False+ floor, ceiling = _torchcodec_spec_bounds(spec)+ # The window has to reach the first release this platform actually published.+ if ceiling is not None and host_floor >= ceiling:+ return False+ if not _torchcodec_python_is_supported(max(floor, host_floor), ceiling):+ return False+ if IS_MAC_ARM and (_macos_release_major() or 0) < 14:+ # 0.12+ is macosx_14_0 only. Reachable when the window starts at or above it.+ effective_floor = max(floor, host_floor)+ if effective_floor >= _TORCHCODEC_MACOS_14_ONLY_FROM:+ return False+ return True+++def _select_torchcodec_spec(torch_version: "str | None") -> str:+ """Map an installed torch version (e.g. '2.11.0+cu128') to the torchcodec spec built+ against it. Falls back to _TORCHCODEC_DEFAULT_SPEC for torch <=2.4, a non-2.x major, or+ an unparseable/missing version. Pure function."""+ if not torch_version:+ return _TORCHCODEC_DEFAULT_SPEC+ release = str(torch_version).split("+", 1)[0] # drop +cu128/+rocm7.2/+cpu+ parts = release.split(".")+ try:+ # '11rc1' -> '11', matching _select_torchao_spec.+ minor_str = re.sub(r"[^0-9].*", "", parts[1]) if len(parts) > 1 else ""+ major, minor = int(parts[0]), int(minor_str)+ except (IndexError, ValueError):+ return _TORCHCODEC_DEFAULT_SPEC+ if major != 2:+ return _TORCHCODEC_DEFAULT_SPEC+ # Clamp to the ABI-stable floor, never the 0.11 row: 0.11 is locked to torch 2.11 exactly.+ minor = min(minor, _TORCHCODEC_MAX_KNOWN_MINOR)+ return _TORCHCODEC_TORCH_SPECS.get(minor, _TORCHCODEC_DEFAULT_SPEC)++# Memoized `import torch` classification of the target venv, reset by pip_install() and# pip_install_try(), the only things here that change what is installed. None means# "not probed yet".@@ -6935,7 +7162,8 @@ def pip_install(# wheel. `unsloth studio update --local` does not pass# --no-torch, so the NO_TORCH filter above does not fire; do# the targeted skip independently so the audio extras step- # does not take down the whole update.+ # does not take down the whole update. Nothing feeds torchcodec+ # now; this stays for any file that reintroduces it.actual_req = _filter_requirements(actual_req, {"torchcodec"})temp_reqs.append(actual_req)req_args_pip: list[str] = []@@ -7110,8 +7338,9 @@ def install_python_stack() -> int:# reinstall path too, not just the two calls below# Clean-machine CI overlays only unsloth, not the full local source pair.ci_source_overlay = os.environ.get("UNSLOTH_CI_SOURCE_OVERLAY", "")- # +1 for the anyio repair check (step 8b), +1 for the diffusers pin (step 11b, every platform)- base_total = 12 if IS_WINDOWS else 13+ # Three lettered steps on top of the numbered ones: anyio repair (8b), diffusers pin+ # (11b), torchcodec (13b, which reports progress on every branch including its skips).+ base_total = 13 if IS_WINDOWS else 14if IS_MACOS:base_total -= 1 # triton step is skipped on macOSif not IS_MACOS and not NO_TORCH:@@ -7549,6 +7778,93 @@ def install_python_stack() -> int:# beside a physical GPU.torch_flavor_tag = _expected_torch_flavor_tag()+ # 13b. torchcodec, pinned to the venv's torch minor (_select_torchcodec_spec), which+ # extras-no-deps.txt cannot do because markers cannot see torch. Must run after the+ # repair above: that can move torch onto another minor, staling an earlier choice.+ # The runtime probe reports nothing on a timeout (the wedged-driver host it exists to+ # tolerate), so read the installed metadata before giving up: guessing here means+ # downgrading a matching codec onto the default and recreating the mismatch.+ _codec_torch_ver = None+ if not NO_TORCH and not PLATFORM_LACKS_TORCHCODEC_WHEEL:+ _codec_torch_ver = _probe_installed_torch_version() or _installed_distribution_version(+ "torch"+ )+ if NO_TORCH:+ _progress("torchcodec (skipped, no torch)")+ elif PLATFORM_LACKS_TORCHCODEC_WHEEL:+ _progress("torchcodec (skipped, no wheel for this platform)")+ elif not _codec_torch_ver:+ _progress("torchcodec (skipped, torch version unknown)")+ _note("could not read the installed torch version -- leaving torchcodec alone")+ elif not _torchcodec_spec_is_installable(_select_torchcodec_spec(_codec_torch_ver)):+ # This platform published no wheel in the window this torch selects. Skipping is what+ # such a host got before this step existed; attempting it would end the install.+ _progress("torchcodec (skipped, no wheel for this torch on this platform)")+ _note(+ f"torch {_codec_torch_ver} wants {_select_torchcodec_spec(_codec_torch_ver)}, "+ "which publishes no wheel here -- leaving audio decoding disabled"+ )+ else:+ _progress("torchcodec")+ _codec_spec = _select_torchcodec_spec(_codec_torch_ver)+ # Pin the index to the resident torch's build. The version alone is not enough:+ # torchcodec ships a separate wheel per accelerator, and the right version from the+ # wrong index is a codec that cannot load.+ _codec_index = _torchcodec_index_url(_codec_torch_ver, _codec_spec)+ _codec_args = ("--no-deps", "--no-cache-dir")+ _codec_rebuild = False+ if _codec_index:+ _codec_args += ("--index-url", _codec_index)+ # A codec already inside the window satisfies the requirement, so pip and uv+ # skip it and the pin never fetches anything -- leaving in place exactly the+ # wrong-accelerator wheel this pin exists to replace. Provenance is readable+ # from the version: the torch indexes carry a +cuNNN / +cpu local tag and PyPI+ # forbids one, so a local tag that is missing or different means another build.+ _codec_have = _installed_distribution_version("torchcodec") or ""+ _codec_want = str(_codec_torch_ver).partition("+")[2].strip().lower()+ if _codec_have and _codec_have.partition("+")[2].strip().lower() != _codec_want:+ _codec_args += ("--force-reinstall",)+ _codec_rebuild = True+ _safe_print(+ f" torch {_codec_torch_ver} detected -- installing {_codec_spec}"+ # Redacted for display only; the installer below still gets the exact URL.+ # An authenticated mirror puts its credentials in the userinfo or a query+ # token, and this line is printed straight to the terminal and CI log rather+ # than through _redact_install_output, which only covers captured pip output.+ + (f" from {_strip_index_url_credentials(_codec_index)}" if _codec_index else "")+ + (" (replacing a build from another index)" if _codec_rebuild else "")+ )+ # pip_install_try, not pip_install: audio is an optional extra, and pip_install's+ # failure path is run(check=True), i.e. exit. Letting an audio wheel end a Studio+ # install inverts the rule the extras-no-deps filter above exists to enforce, and+ # the index can refuse for reasons no local table predicts -- a yanked release, an+ # offline mirror, a platform tag added or dropped upstream after this shipped.+ if not pip_install_try(+ "Installing torchcodec",+ *_codec_args,+ _codec_spec,+ ):+ _note(+ f"could not install {_codec_spec} -- audio decoding stays disabled, "+ "the rest of the install is unaffected"+ )+ elif _codec_index and _cuda_major_for_npp(_codec_torch_ver, _codec_index):+ # torchcodec's CUDA build dlopens libnppicc and libnppc, and NPP is NOT in+ # torch's own dependency set, so a --no-deps install from a cuNNN index reports+ # success and then fails to import, disabling audio for a reason nothing here+ # would otherwise name. docker/Dockerfile installs nvidia-npp-cu12 beside the+ # same wheel for exactly this. cu13x wheels want nvidia-npp-cu13.+ _npp_major = _cuda_major_for_npp(_codec_torch_ver, _codec_index)+ if not pip_install_try(+ "Installing torchcodec CUDA runtime (NPP)",+ "--no-cache-dir",+ f"nvidia-npp-cu{_npp_major}",+ ):+ _note(+ f"could not install nvidia-npp-cu{_npp_major} -- torchcodec may fail to "+ "import on a host without the CUDA toolkit, leaving audio disabled"+ )+# 14. Final check (silent; third-party conflicts are expected)subprocess.run([sys.executable, "-m", "pip", "check"],diff --git a/tests/python/test_torchcodec_torch_compat.py b/tests/python/test_torchcodec_torch_compat.pyindex 238259a78cc..7e2df0cc5e3 100644--- a/tests/python/test_torchcodec_torch_compat.py+++ b/tests/python/test_torchcodec_torch_compat.py@@ -4,19 +4,22 @@"""torch / torchcodec ABI guardrails (unslothai/unsloth#7225)."""from __future__ import annotations-import importlib.utilimport reimport sysimport typesfrom pathlib import Path-import pytest-REPO_ROOT = Path(__file__).resolve().parents[2]PYPROJECT = REPO_ROOT / "pyproject.toml"IMPORT_FIXES_PATH = REPO_ROOT / "unsloth" / "import_fixes.py"+EXTRAS_NO_DEPS_TXT = REPO_ROOT / "studio" / "backend" / "requirements" / "extras-no-deps.txt"+SECURITY_AUDIT_YML = REPO_ROOT / ".github" / "workflows" / "security-audit.yml"+COLAB_TORCH211 = {"torch": "2.11.0+cu128", "torchcodec": "0.11.0+cu128"}+TORCHCODEC_WHEEL = (+ "https://download.pytorch.org/whl/torchcodec-0.13.0-cp312-cp312-manylinux_2_28_x86_64.whl"+)def _tomllib():@@ -26,6 +29,18 @@ def _tomllib():return pytest.importorskip("tomli")[email protected](autouse = True)+def _no_inherited_index_config(monkeypatch):+ """Nearly every test here reads the index configuration, so a developer's own+ UNSLOTH_TORCH_INDEX_URL must not be what decides which URL the suite asserts."""+ for name in (+ "UNSLOTH_TORCH_INDEX_URL",+ "UNSLOTH_TORCH_INDEX_FAMILY",+ "UNSLOTH_PYTORCH_MIRROR",+ ):+ monkeypatch.delenv(name, raising = False)++def _load_import_fixes_module():spec = importlib.util.spec_from_file_location("unsloth_import_fixes_under_test",@@ -77,160 +92,1039 @@ def test_torchcodec_exclusive_upper_bound():assert fixes._torchcodec_exclusive_upper("0.9") == "<0.10.0"-def test_torch290_rejects_torchcodec_07(monkeypatch):+# One row per (torch, torchcodec) pair the runtime guard has an opinion about: the+# substrings the warning must carry, and the ones it must not. `None` for `contains` means+# the guard has to stay silent -- the pair is supported and a warning would be noise.+_GUARD_CASES = [+ # Inside the lockstep table: each torch minor takes its own codec line and no other.+ ("2.9.0+cu128", "0.7.0", (), ("audio-torch210",)),+ ("2.8.0+cu128", "0.7.0", None, ()),+ # Untagged torch needs no index pin, so the convenient extra stays on offer...+ ("2.10.0", "0.11.0", ("torchcodec 0.11.0", "audio-torch210", "<0.11.0"), ("<11.0",)),+ # ...while a tagged one cannot carry an index in an extra, so it gets the pin alone.+ (+ "2.10.0+cu128",+ "0.11.0",+ ("--index-url https://download.pytorch.org/whl/cu128", "<0.11.0"),+ ("audio-torch210",),+ ),+ ("2.10.0+cu128", "0.10.0+cu128", None, ()),+ # The guard must not be silent on the torch minor where the mismatch happens.+ (+ "2.11.0",+ "0.10.0+cu128",+ ("torchcodec 0.10.0+cu128", "audio-torch211", ">=0.11", "<0.12.0"),+ ("audio-torch210",),+ ),+ ("2.11.0+cu128", "0.11.1+cu128", None, ()),+ # The ABI-stable floor starts at torch 2.11: 2.10 keeps the exact pairing.+ ("2.10.0", "0.15.0", ("audio-torch210",), ()),+ # A torch minor older than the matrix keeps the original no-opinion behaviour.+ ("2.4.0", "0.0.3", None, ()),+]++# torchcodec 0.12+ targets torch >=2.11, so it is not locked to one minor.+_GUARD_CASES += [+ (torch_version, codec_version, None, ())+ for torch_version in ("2.11.0+cu128", "2.12.0", "2.13.0+cu130")+ for codec_version in ("0.12.0", "0.15.0+cu130")+]++# 0.11 is pinned to torch 2.11 exactly, so 2.12/2.13 with a pre-0.12 codec still warns, and+# no audio-torch2xx extra exists for those minors, so none is offered.+_GUARD_CASES += [+ (torch_version, codec_version, ("torchcodec>=0.12.0",), ("unsloth[audio-torch",))+ for torch_version in ("2.12.1+cu130", "2.13.0")+ for codec_version in ("0.11.1", "0.10.0")+]+++ "torch_version, codec_version, contains, absent",+ _GUARD_CASES,+ ids = [f"torch{t}-codec{c}" for t, c, _, _ in _GUARD_CASES],+)+def test_the_runtime_guard_reports_exactly_the_pairs_the_matrix_forbids(+ monkeypatch, torch_version, codec_version, contains, absent+):import importlib.metadatafixes = _load_import_fixes_module()- _stub_torch(monkeypatch, "2.9.0+cu128")- monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.7.0")+ _stub_torch(monkeypatch, torch_version)+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: codec_version)hint = fixes._torchcodec_version_mismatch_hint()- assert hint is not None- assert "audio-torch210" not in hint+ if contains is None:+ assert hint is None, f"{torch_version} + torchcodec {codec_version} is supported upstream"+ return+ assert hint is not None, f"{torch_version} + torchcodec {codec_version} must not go unreported"+ for text in contains:+ assert text in hint, f"{text!r} missing from {hint!r}"+ for text in absent:+ assert text not in hint, f"{text!r} should not appear in {hint!r}"-def test_torch280_accepts_torchcodec_07(monkeypatch):- import importlib.metadata+def test_import_fixes_loads_on_python39_syntax():+ """Regression: module must import on 3.9 (postponed annotations for str | None)."""+ fixes = _load_import_fixes_module()+ assert callable(fixes._torchcodec_version_mismatch_hint)+++def _load_install_python_stack():+ studio_dir = REPO_ROOT / "studio"+ if str(studio_dir) not in sys.path:+ sys.path.insert(0, str(studio_dir))+ import install_python_stack++ return install_python_stack+++def test_pyproject_declares_torch211_audio_extra_with_python_gate():+ text = PYPROJECT.read_text(encoding = "utf-8")+ match = re.search(r"^audio-torch211 = \[(.*?)^\]", text, re.MULTILINE | re.DOTALL)+ assert match is not None, "pyproject must declare an audio-torch211 extra"+ assert "torchcodec>=0.11.0,<0.12.0" in match.group(1)+ assert "python_version >= '3.10'" in match.group(1)+++def test_security_audit_covers_every_installable_torchcodec_line():+ """extras-no-deps.txt used to pin torchcodec flat, so 0.10 was the only line that ever+ installed and the only one audited. `_select_torchcodec_spec` now picks per torch minor,+ and the repairs still resolve torch 2.10, 2.9 and 2.8, so each of those lines needs an+ input of its own: the ranges are disjoint and cannot share a resolve."""+ text = SECURITY_AUDIT_YML.read_text(encoding = "utf-8")+ ips = _load_install_python_stack()+ tomllib = _tomllib()+ extras = tomllib.loads(PYPROJECT.read_text(encoding = "utf-8"))["project"][+ "optional-dependencies"+ ]++ audited = ["audio-torch211", "audio-torch210", "audio-torch290", "audio-torch280"]+ # Both halves of the workflow build the inputs; one is the advisory audit, one is+ # scan_packages. 211 is folded into unsloth-deps.txt, the rest get a file each.+ assert text.count('optional-dependencies"]["audio-torch211"]') == 2+ assert text.count("for extra in audio-torch210 audio-torch290 audio-torch280; do") == 2+ for extra in audited[1:]:+ assert f"audit-reqs/{extra}.txt" in text, extra+ assert f" {extra} " in text or f" {extra};" in text or f" {extra}'" in text, extra++ # scan_packages.py keeps one requirement per package name, so two disjoint torchcodec+ # ranges in one shard collapse to the first. They have to be scanned apart.+ shards = re.findall(r"files: '([^']+)'", text)+ for shard in shards:+ assert (+ sum(1 for extra in audited if extra in shard.split()) <= 1+ ), f"shard {shard!r} would have its torchcodec lines deduplicated to one"+ scanned = {extra for shard in shards for extra in audited if extra in shard.split()}+ assert scanned == {"audio-torch210", "audio-torch290", "audio-torch280"}++ # Whatever the selector installs on a reachable torch minor has to be in that set.+ for torch_minor in ("2.10", "2.9", "2.8"):+ spec = ips._select_torchcodec_spec(f"{torch_minor}.0")+ assert any(+ spec in dep for extra in audited for dep in extras[extra]+ ), f"torch {torch_minor} installs {spec}, which no audited extra declares"+++def test_extras_no_deps_has_no_unconditional_torchcodec_pin():+ """A flat pin cannot serve both torch lines, so the installer picks the spec."""+ lines = [+ line.strip()+ for line in EXTRAS_NO_DEPS_TXT.read_text(encoding = "utf-8").splitlines()+ if line.strip() and not line.strip().startswith("#")+ ]+ assert not any(line.lower().startswith("torchcodec") for line in lines), (+ "extras-no-deps.txt must not pin torchcodec unconditionally; "+ "install_python_stack._select_torchcodec_spec picks it per torch minor"+ )+++def test_select_torchcodec_spec_tracks_torch_minor():+ ips = _load_install_python_stack()+ assert ips._select_torchcodec_spec("2.11.0+cu128") == "torchcodec>=0.11.0,<0.12.0"+ assert ips._select_torchcodec_spec("2.10.0+cu130") == "torchcodec>=0.10.0,<0.11.0"+ assert ips._select_torchcodec_spec("2.9.1+cu128") == "torchcodec>=0.8.0,<0.10.0"+ assert ips._select_torchcodec_spec("2.8.0+cu126") == "torchcodec>=0.6.0,<0.8.0"+++def test_select_torchcodec_spec_never_caps_newer_torch_to_the_011_line():+ """0.11 is locked to torch 2.11 exactly, so torch >2.11 takes the open floor."""+ ips = _load_install_python_stack()+ for version in ("2.12.0", "2.12.1+cu132", "2.13.0+cu130", "2.99.0"):+ spec = ips._select_torchcodec_spec(version)+ assert spec == ips._TORCHCODEC_ABI_STABLE_SPEC, version+ assert "<" not in spec, version+++def test_select_torchcodec_spec_falls_back_on_unknown_torch():+ ips = _load_install_python_stack()+ for value in (None, "", "not-a-version", "3.0.0", "2.rc1"):+ assert ips._select_torchcodec_spec(value) == ips._TORCHCODEC_DEFAULT_SPEC+++def test_select_torchcodec_spec_matches_pyproject_audio_extras():+ """The installer's specs and the pip extras must not drift apart."""+ ips = _load_install_python_stack()+ text = PYPROJECT.read_text(encoding = "utf-8")+ for torch_version, extra in (+ ("2.11.0", "audio-torch211"),+ ("2.10.0", "audio-torch210"),+ ("2.9.0", "audio-torch290"),+ ("2.8.0", "audio-torch280"),+ ):+ match = re.search(rf"^{extra} = \[(.*?)^\]", text, re.MULTILINE | re.DOTALL)+ assert match is not None, extra+ assert ips._select_torchcodec_spec(torch_version) in match.group(1), extra+++# The published torchcodec compatibility table, transcribed from upstream. Sources agree:+# https://github.com/meta-pytorch/torchcodec (README, "older versions" section)+# https://pypi.org/project/torchcodec/ (same table in the project description)+# Kept as a literal on purpose. Every other check here compares our three tables against each+# OTHER, which passes just as happily when all three are wrong in the same way -- that is how+# `2.6: {0.2, 0.3}` and `2.5: {0.1, 0.2}` survived: upstream pairs 0.3 with torch 2.7 and 0.2+# with torch 2.6, so the installer's window picked a release built against the NEXT torch.+# torch 2.4 -> 0.0.3 is deliberately omitted below: the installer floors at 2.5 and returns+# _TORCHCODEC_DEFAULT_SPEC underneath it.+_UPSTREAM_TORCH_TO_TORCHCODEC_MINORS = {+ "2.11": {"0.11"},+ "2.10": {"0.10"},+ "2.9": {"0.8", "0.9"},+ "2.8": {"0.6", "0.7"},+ "2.7": {"0.3", "0.4", "0.5"},+ "2.6": {"0.2"},+ "2.5": {"0.1"},+}+++# What each download.pytorch.org index actually publishes, read off the live listings:+# the torch 2.x minors it serves, and the inclusive range of torchcodec minors.+# Note cu130 starts at codec 0.8, and no index carries 0.1 or 0.2 -- those are PyPI-only.+_INDEX_INVENTORY = {+ "cpu": {"torch": range(5, 15), "codec": (3, 16)},+ "cu118": {"torch": range(5, 8), "codec": (3, 5)},+ "cu126": {"torch": range(6, 15), "codec": (3, 16)},+ "cu128": {"torch": range(7, 12), "codec": (3, 11)},+ "cu130": {"torch": range(9, 15), "codec": (8, 16)},+}+++def test_torchcodec_index_follows_the_resident_torch_build():+ """torchcodec ships one wheel per accelerator, so the right version from the wrong index+ is a codec that cannot dlopen. Upstream's install docs say to pass --index-url and match+ it to the torch build; docker/Dockerfile pins cu128 by hand for exactly this reason."""+ ips = _load_install_python_stack()+ base = "https://download.pytorch.org/whl/"+ assert ips._torchcodec_index_url("2.11.0+cu128") == base + "cu128"+ assert ips._torchcodec_index_url("2.11.0+cu126") == base + "cu126"+ assert ips._torchcodec_index_url("2.14.0+cu130") == base + "cu130"+ assert ips._torchcodec_index_url("2.11.0+cpu") == base + "cpu"++ # Untagged is PyPI's own torch, whose counterpart is PyPI's default torchcodec. Pinning+ # cpu here would be wrong: on Linux an untagged torch is a CUDA build.+ assert ips._torchcodec_index_url("2.11.0") is None+ # No torchcodec is published under these, so unpinned beats an index that cannot serve.+ assert ips._torchcodec_index_url("2.9.0+rocm6.4") is None+ assert ips._torchcodec_index_url("2.10.0+xpu") is None+ assert ips._torchcodec_index_url(None) is None+ assert ips._torchcodec_index_url("") is None+++def test_pinning_the_index_never_starves_a_reachable_torch():+ """A pin that removed audio from a supported host would trade one bug for another.+ Every torch build that pins must find its selected codec on that same index. This holds+ because torch and torchcodec are cut together: cu128 stops at torch 2.11 and its+ torchcodec stops at 0.11, the exact pair the matrix maps 2.11 to; cu130 starts at torch+ 2.9 and its torchcodec starts at 0.8, the pair for 2.9.++ The one gap is deliberate and handled in the helper rather than here: no index carries+ torchcodec 0.1 or 0.2, so torch 2.5 and 2.6 must not pin at all.+ """+ from packaging.specifiers import SpecifierSet++ ips = _load_install_python_stack()+ for tag, inv in _INDEX_INVENTORY.items():+ low, high = inv["codec"]+ for minor in inv["torch"]:+ version = f"2.{minor}.0+{tag}"+ spec = ips._select_torchcodec_spec(version)+ specifier = SpecifierSet(spec.split("torchcodec", 1)[1])+ served = [f"0.{m}.0" for m in range(low, high + 1) if specifier.contains(f"0.{m}.0")]+ index = ips._torchcodec_index_url(version, spec)+ if index is None:+ # Only the PyPI-only rows may decline to pin.+ assert minor in (5, 6), f"torch 2.{minor}+{tag} unexpectedly refused to pin"+ continue+ assert index.endswith("/" + tag)+ assert served, (+ f"torch 2.{minor} pins the {tag} index and selects {spec}, but that index "+ f"publishes only torchcodec 0.{low}-0.{high}"+ )+++def test_the_two_pypi_only_rows_stay_unpinned():+ """torchcodec 0.1 and 0.2 were never published to download.pytorch.org, so pinning torch+ 2.5 / 2.6 would guarantee a skip on the oldest venvs instead of leaving them as they are."""+ ips = _load_install_python_stack()+ for minor in (5, 6):+ version = f"2.{minor}.0+cu126"+ assert ips._torchcodec_index_url(version, ips._select_torchcodec_spec(version)) is None+ # 2.7 selects >=0.3.0,<0.6.0, which the indexes do carry, so it pins.+ assert (+ ips._torchcodec_index_url("2.7.0+cu118", ips._select_torchcodec_spec("2.7.0")) is not None+ )+++# extra -> the first interpreter that must NOT select it, one that must, and whether its+# codec line ships a Linux aarch64 wheel.+#+# torchcodec publishes no sdist, so an extra left open above its last cp tag, or on a host+# with no wheel, makes pip fail the whole install instead of skipping audio -- and the+# cu*/rocm*/intel torch 2.10 extras pull it in. requires-python is open-ended (>=3.9), so a+# newer interpreter reaches these extras too; the marker has to stop it, and it has to match+# install_python_stack.py.+#+# The Python ceilings come from the same upstream table _TORCHCODEC_PYTHON_WINDOWS encodes:+# the 0.6/0.7 line stops at 3.13, everything from 0.9 up runs to 3.14. aarch64 is per-extra+# rather than blanket: torchcodec had no aarch64 wheel until 0.11.0, and every release since+# has kept it, so audio-torch211 must ALLOW aarch64 while the older extras, which top out at+# 0.10, must still exclude it.+_AUDIO_EXTRA_GATES = {+ "audio-torch211": ("3.15", "3.14", True),+ "audio-torch210": ("3.15", "3.14", False),+ "audio-torch290": ("3.15", "3.14", False),+ "audio-torch280": ("3.14", "3.13", False),+}++# Windows ARM64 and Intel Mac have no wheel at any torchcodec version.+_WHEELED_HOSTS = (+ {"sys_platform": "linux", "platform_machine": "x86_64"},+ {"sys_platform": "win32", "platform_machine": "AMD64"},+ {"sys_platform": "darwin", "platform_machine": "arm64"},+)+_WHEELLESS_HOSTS = (+ {"sys_platform": "win32", "platform_machine": "ARM64"},+ {"sys_platform": "darwin", "platform_machine": "x86_64"},+)+++def _audio_extras():+ extras = _tomllib().loads(PYPROJECT.read_text(encoding = "utf-8"))["project"][+ "optional-dependencies"+ ]+ return {n: d for n, d in extras.items() if n.startswith("audio-torch")}+++def test_every_audio_extra_has_a_gate_of_its_own():+ """A new extra added without a row here would go through the gates below untested."""+ assert set(_audio_extras()) == set(_AUDIO_EXTRA_GATES)++[email protected]("extra", sorted(_AUDIO_EXTRA_GATES))+def test_an_audio_extra_is_gated_to_the_hosts_and_pythons_its_wheels_cover(extra):+ markers = pytest.importorskip("packaging.markers")+ too_new, supported, allows_aarch64 = _AUDIO_EXTRA_GATES[extra]+ deps = _audio_extras()[extra]+ assert deps, extra++ for dep in deps:+ _, _, marker_text = dep.partition(";")+ assert marker_text.strip(), f"{extra}: {dep!r} has no marker"+ marker = markers.Marker(marker_text.strip())++ base = {"python_version": "3.12", "platform_system": "Linux", "os_name": "posix"}+ for case in _WHEELED_HOSTS:+ assert marker.evaluate({**base, **case}), f"{extra} must install on {case}"+ for case in _WHEELLESS_HOSTS:+ assert not marker.evaluate(+ {**base, **case}+ ), f"{extra} has no wheel for {case} and must not be resolved there"+ aarch64 = marker.evaluate({**base, "sys_platform": "linux", "platform_machine": "aarch64"})+ assert aarch64 == allows_aarch64, (+ f"{extra} {'must not exclude' if allows_aarch64 else 'must not be resolved on'} "+ "Linux aarch64"+ )++ linux = {**_WHEELED_HOSTS[0], "platform_system": "Linux", "os_name": "posix"}+ assert not marker.evaluate(+ {**linux, "python_version": too_new}+ ), f"{extra} still selects torchcodec on Python {too_new}, which has no wheel"+ assert marker.evaluate(+ {**linux, "python_version": supported}+ ), f"{extra} stopped selecting torchcodec on Python {supported}, which does"+++def test_compat_matrix_matches_the_published_upstream_table():+ """Pin the runtime guard to upstream, not merely to our own other copies of it."""fixes = _load_import_fixes_module()- _stub_torch(monkeypatch, "2.8.0+cu128")- monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.7.0")+ assert fixes._TORCH_TORCHCODEC_MINORS == _UPSTREAM_TORCH_TO_TORCHCODEC_MINORS+++def test_installer_never_selects_a_torchcodec_built_against_another_torch():+ """The window handed to pip must not contain a release upstream pairs with a different+ torch: pip takes the HIGHEST match, so a window one minor too wide installs the mismatch+ this whole module exists to prevent.++ This also ties the installer to the runtime guard's own matrix, since+ test_compat_matrix_matches_the_published_upstream_table pins that matrix to the literal+ below."""+ from packaging.specifiers import SpecifierSet++ ips = _load_install_python_stack()+ probes = [f"0.{n}.0" for n in range(0, 16)]+ for torch_minor, allowed in _UPSTREAM_TORCH_TO_TORCHCODEC_MINORS.items():+ spec = ips._select_torchcodec_spec(f"{torch_minor}.0")+ specifier = SpecifierSet(spec.split("torchcodec", 1)[1])+ admitted = {p.rsplit(".", 1)[0] for p in probes if specifier.contains(p)}+ assert admitted == allowed, (+ f"torch {torch_minor}: {spec} admits {sorted(admitted)}, "+ f"upstream builds only {sorted(allowed)} against it"+ )+ highest = max(+ (p for p in probes if specifier.contains(p)),+ key = lambda v: tuple(int(x) for x in v.split(".")),+ )+ assert (+ highest.rsplit(".", 1)[0] in allowed+ ), f"torch {torch_minor}: pip would resolve {spec} to {highest}"+- assert fixes._torchcodec_version_mismatch_hint() is None+def test_validator_and_runtime_guard_agree_on_the_whole_matrix(monkeypatch):+ """The two checkers must not disagree; half a rule is how they drift.+ The ABI rule has two halves -- exempt 0.12+ above the floor, and reject pre-0.12 past+ it -- and porting only the first left the validator silent on torch 2.12 with+ torchcodec 0.11, which the runtime guard reports. Comparing them pair by pair is what+ stops the next half-port.+ """+ from scripts import notebook_validator as nv-def test_torch210_rejects_torchcodec_011(monkeypatch):+ fixes = _load_import_fixes_module()+ pairs = [+ ("2.13.0", "0.10.0"),+ ("2.12.0", "0.11.1"),+ ("2.12.0", "0.12.0"),+ ("2.11.0", "0.10.0"),+ ("2.11.0", "0.11.0"),+ ("2.11.0", "0.15.0"),+ ("2.10.0", "0.10.0"),+ ("2.10.0", "0.12.0"),+ ("2.9.0", "0.8.0"),+ ("2.4.0", "0.1.0"),+ ]+ for torch_v, codec_v in pairs:+ validator_flags = bool(+ nv.rule_inst_004_torchcodec_torch(+ "", {"torch": torch_v, "torchcodec": codec_v}, "nb.ipynb", 0+ )+ )+ guard_flags = _guard_reports(fixes, monkeypatch, torch_v, codec_v)+ assert validator_flags == guard_flags, (+ f"torch {torch_v} + torchcodec {codec_v}: "+ f"validator={'reports' if validator_flags else 'silent'}, "+ f"guard={'reports' if guard_flags else 'silent'}"+ )+++def _guard_reports(fixes, monkeypatch, torch_version: str, codec_version: str) -> bool:+ """Run the runtime guard against one pair, stubbed the way the cases above stub it."""import importlib.metadata+ _stub_torch(monkeypatch, torch_version)+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: codec_version)+ return fixes._torchcodec_version_mismatch_hint() is not None+++def test_the_installer_never_installs_what_the_guard_rejects(monkeypatch):+ """End-to-end invariant across all three checkers, past the table as well as inside it.++ test_select_torchcodec_spec_matches_compat_matrix ties the installer to the matrix, but+ it iterates the rows that EXIST, so a torch minor past the last row is not covered -- and+ that is exactly where the ABI half-port hid. This asks the question that actually matters+ instead: for every torch minor the installer will see, is every codec its own spec admits+ accepted by the runtime guard?+ """+ from packaging.specifiers import SpecifierSet+fixes = _load_import_fixes_module()- _stub_torch(monkeypatch, "2.10.0+cu128")+ ips = _load_install_python_stack()+ probes = [f"0.{n}.0" for n in range(0, 20)]++ for minor in range(5, 15): # torch 2.5 .. 2.14, i.e. past the last lockstep row+ torch_v = f"2.{minor}.0"+ specifier = SpecifierSet(ips._select_torchcodec_spec(torch_v).split("torchcodec", 1)[1])+ admitted = [p for p in probes if specifier.contains(p)]+ assert admitted, f"torch {torch_v}: installer spec admits nothing"+ for codec_v in admitted:+ assert not _guard_reports(fixes, monkeypatch, torch_v, codec_v), (+ f"installer would put torchcodec {codec_v} on torch {torch_v}, "+ f"which the runtime guard then reports as incompatible"+ )+++# ----------------------------------------------------------------------------------+# Wheel availability. The step that installs the selected spec is fatal on failure, so+# "does this spec have a wheel here" decides whether this branch can break an install,+# not merely whether audio works. Verified against the live PyPI index; kept as a table+# so the suite stays deterministic and offline.+# ----------------------------------------------------------------------------------++# torchcodec version -> platforms it publishes. Read off pypi.org/pypi/torchcodec/json.+# The three transitions that matter:+# win_amd64 absent before 0.7.0+# manylinux aarch64 absent before 0.11.0+# macosx arm64 minimum macOS 11.0 through 0.11.1, then 14.0 from 0.12.0+_TORCHCODEC_WHEEL_HISTORY = {+ "0.1.0": {"linux_x86_64", "macos_arm64_11"},+ "0.2.0": {"linux_x86_64", "macos_arm64_11"},+ "0.3.0": {"linux_x86_64", "macos_arm64_11"},+ "0.4.0": {"linux_x86_64", "macos_arm64_11"},+ "0.5": {"linux_x86_64", "macos_arm64_11"},+ "0.6.0": {"linux_x86_64", "macos_arm64_11"},+ "0.7.0": {"linux_x86_64", "macos_arm64_11", "win_amd64"},+ "0.8.0": {"linux_x86_64", "macos_arm64_11", "win_amd64"},+ "0.9.0": {"linux_x86_64", "macos_arm64_11", "win_amd64"},+ "0.10.0": {"linux_x86_64", "macos_arm64_11", "win_amd64"},+ "0.11.0": {"linux_x86_64", "linux_aarch64", "macos_arm64_11", "win_amd64"},+ "0.11.1": {"linux_x86_64", "linux_aarch64", "macos_arm64_11", "win_amd64"},+ "0.12.0": {"linux_x86_64", "linux_aarch64", "macos_arm64_14", "win_amd64"},+ "0.15.0": {"linux_x86_64", "linux_aarch64", "macos_arm64_14", "win_amd64"},+}++# label -> (IS_LINUX, IS_WINDOWS, IS_MACOS, IS_MAC_ARM, IS_MAC_INTEL), machine, macos major+_SIM_HOSTS = {+ "linux-x86_64": ((True, False, False, False, False), "x86_64", None),+ "linux-aarch64": ((True, False, False, False, False), "aarch64", None),+ "linux-ppc64le": ((True, False, False, False, False), "ppc64le", None),+ "windows-amd64": ((False, True, False, False, False), "AMD64", None),+ "windows-arm64": ((False, True, False, False, False), "ARM64", None),+ "macos-arm64-14": ((False, False, True, True, False), "arm64", 14),+ "macos-arm64-13": ((False, False, True, True, False), "arm64", 13),+ "macos-intel": ((False, False, True, False, True), "x86_64", None),+}+++def _host_key(label):+ if label.startswith("linux"):+ machine = _SIM_HOSTS[label][1]+ return f"linux_{machine}" if machine in ("x86_64", "aarch64") else None+ if label == "windows-amd64":+ return "win_amd64"+ if label.startswith("macos-arm64"):+ return "macos_arm64"+ return None+++def _release_python_window(vt):+ """Upstream's published Python range for a release, independent of architecture."""+ if vt < (0, 2, 0):+ return (3, 9), (3, 12)+ if vt < (0, 8, 0):+ return (3, 9), (3, 13)+ if vt < (0, 9, 0):+ return (3, 10), (3, 13)+ return (3, 10), (3, 14)+++def _wheel_exists_in_window(label, floor, ceiling, python):+ """Does any release the window admits publish a wheel for this host AND interpreter?"""+ key = _host_key(label)+ if key is None:+ return False+ macos_major = _SIM_HOSTS[label][2]+ for ver, plats in _TORCHCODEC_WHEEL_HISTORY.items():+ vt = tuple(int(p) for p in ver.split("."))+ vt = vt + (0,) * (3 - len(vt))+ if vt < floor or (ceiling is not None and vt >= ceiling):+ continue+ py_min, py_max = _release_python_window(vt)+ if not py_min <= python <= py_max:+ continue+ if key == "macos_arm64":+ for p in plats:+ if p.startswith("macos_arm64_") and macos_major >= int(p.rsplit("_", 1)[1]):+ return True+ elif key in plats:+ return True+ return False+++def _patch_host(ips, monkeypatch, label):+ flags, machine, macos_major = _SIM_HOSTS[label]+ is_linux, is_windows, is_macos, is_mac_arm, is_mac_intel = flags+ monkeypatch.setattr(ips, "IS_LINUX", is_linux)+ monkeypatch.setattr(ips, "IS_WINDOWS", is_windows)+ monkeypatch.setattr(ips, "IS_MACOS", is_macos)+ monkeypatch.setattr(ips, "IS_MAC_ARM", is_mac_arm)+ monkeypatch.setattr(ips, "IS_MAC_INTEL", is_mac_intel)+ monkeypatch.setattr(ips.platform, "machine", lambda: machine)monkeypatch.setattr(- importlib.metadata,- "version",- lambda _name: "0.11.0",+ ips.platform,+ "mac_ver",+ lambda: (f"{macos_major}.0" if macos_major else "", ("", "", ""), ""),)- hint = fixes._torchcodec_version_mismatch_hint()- assert hint is not None- assert "torchcodec 0.11.0" in hint- assert "audio-torch210" in hint- assert "<0.11.0" in hint- assert "<11.0" not in hint+def test_the_installer_never_selects_a_spec_with_no_wheel_here(monkeypatch):+ """The gate must not green-light a window this platform never published into.-def test_torch210_accepts_torchcodec_010(monkeypatch):+ pip_install_try keeps a miss from ending the install, but attempting one is still a+ wasted round trip and, before that call was changed, was fatal. Two cells were real:+ Windows on the cu118 index sits at torch 2.7 and selects `>=0.3.0,<0.6.0`, where no+ release ships win_amd64; and a Mac below 14 selects `>=0.12.0`, which is macosx_14_0+ only.+ """+ ips = _load_install_python_stack()+ for label in _SIM_HOSTS:+ for python in ((3, 9), (3, 10), (3, 12), (3, 13), (3, 14)):+ for minor in range(4, 15):+ _patch_host(ips, monkeypatch, label)+ monkeypatch.setattr(ips.sys, "version_info", python + (0, "final", 0))+ spec = ips._select_torchcodec_spec(f"2.{minor}.0")+ floor, ceiling = ips._torchcodec_spec_bounds(spec)+ gate_says_yes = ips._torchcodec_spec_is_installable(spec)+ really_has = _wheel_exists_in_window(label, floor, ceiling, python)+ assert gate_says_yes == really_has, (+ f"{label} py{python[0]}.{python[1]} torch 2.{minor}: gate says "+ f"{'install' if gate_says_yes else 'skip'} for {spec}, but a wheel "+ f"{'exists' if really_has else 'does not exist'}"+ )+++# The cells of the sweep above that were real bugs or are the documented transitions, with+# the answer written by hand rather than read off _TORCHCODEC_WHEEL_HISTORY. The sweep+# checks the gate against that oracle and so passes just as happily when both are wrong;+# these say what the answer has to be.+# (host, python, torch minor, must the gate install?)+_WHEEL_GATE_ANCHORS = [+ # aarch64 got its first wheel at 0.11.0, the line torch 2.11 selects; 2.10 takes 0.10.+ ("linux-aarch64", (3, 12), 11, True),+ ("linux-aarch64", (3, 12), 10, False),+ # torchcodec 0.12+ is macosx_14_0 only, so an older Mac must not be sent to it.+ ("macos-arm64-13", (3, 12), 12, False),+ ("macos-arm64-13", (3, 12), 11, True),+ ("macos-arm64-14", (3, 12), 12, True),+ # Architecture is not the only wheel axis. torch 2.5 selects the 0.1 line, which stops at+ # Python 3.12, so 3.13 has nothing to install even on plain linux-x86_64. This was masked+ # while the 2.5 window ran to <0.3.0: it reached 0.2, which does ship cp313, so the gate+ # said yes for a release built against torch 2.6.+ ("linux-x86_64", (3, 12), 5, True),+ ("linux-x86_64", (3, 13), 5, False),+ # The floor moves too: 0.8+ dropped 3.9, so torch 2.9 has nothing for a 3.9 interpreter.+ ("linux-x86_64", (3, 9), 9, False),+ ("linux-x86_64", (3, 9), 8, True),+]+# win_amd64 starts at 0.7.0 and torch 2.5-2.7 select lines below it. Reachable rather than+# theoretical: the cu118 index tops out at torch 2.7.+_WHEEL_GATE_ANCHORS += [+ ("windows-amd64", (3, 12), minor, minor >= 8) for minor in (5, 6, 7, 8, 10, 11, 12)+]+++ "label, python, torch_minor, installable",+ _WHEEL_GATE_ANCHORS,+ ids = [f"{h}-py{p[0]}.{p[1]}-torch2.{m}" for h, p, m, _ in _WHEEL_GATE_ANCHORS],+)+def test_the_wheel_gate_answers_the_transitions_it_was_written_for(+ monkeypatch, label, python, torch_minor, installable+):+ ips = _load_install_python_stack()+ _patch_host(ips, monkeypatch, label)+ monkeypatch.setattr(ips.sys, "version_info", python + (0, "final", 0))+ spec = ips._select_torchcodec_spec(f"2.{torch_minor}.0")+ assert ips._torchcodec_spec_is_installable(spec) == installable, spec+++def test_python_windows_match_the_published_upstream_table():+ """Same reason as the compat-matrix pin: transcribed from upstream, not from ourselves."""+ ips = _load_install_python_stack()+ assert ips._TORCHCODEC_PYTHON_WINDOWS == (+ ((0, 1, 0), (3, 9), (3, 12)),+ ((0, 2, 0), (3, 9), (3, 13)),+ ((0, 8, 0), (3, 10), (3, 13)),+ ((0, 9, 0), (3, 10), (3, 14)),+ )+++def test_the_torchcodec_step_cannot_end_the_install():+ """Audio is optional; pip_install exits on failure and pip_install_try does not.++ Asserted on the source because the alternative is driving a whole install. The rule+ it encodes is the one the extras-no-deps filter above it already states: the audio+ extras step must not take down the install.+ """+ source = (REPO_ROOT / "studio" / "install_python_stack.py").read_text(encoding = "utf-8")+ step = source.split("# 13b. torchcodec", 1)[1].split("# 14.", 1)[0]+ assert "pip_install_try(" in step, "the torchcodec step must use the non-fatal install"+ assert "\n pip_install(" not in step, "pip_install() exits on failure"+++def test_the_runtime_hint_pins_the_index_it_tells_you_to_install_from(monkeypatch):+ """The installer pins the torch index for torchcodec, so a remedy that omits it hands+ back the wrong accelerator build and audio stays broken."""import importlib.metadatafixes = _load_import_fixes_module()- _stub_torch(monkeypatch, "2.10.0+cu128")- monkeypatch.setattr(- importlib.metadata,- "version",- lambda _name: "0.10.0+cu128",++ _stub_torch(monkeypatch, "2.11.0+cu128")+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.10.0")+ hint = fixes._torchcodec_version_mismatch_hint()+ assert "--index-url https://download.pytorch.org/whl/cu128 'torchcodec>=0.11" in hint++ # cpu is an index too, and the ABI-stable branch takes the same treatment.+ _stub_torch(monkeypatch, "2.12.0+cu130")+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.11.1")+ assert (+ "--index-url https://download.pytorch.org/whl/cu130 'torchcodec>=0.12.0'"+ in fixes._torchcodec_version_mismatch_hint())- assert fixes._torchcodec_version_mismatch_hint() is None+ # Untagged torch is PyPI's own build, and rocm publishes no torchcodec: no pin either way.+ for version in ("2.11.0", "2.9.0+rocm6.4"):+ _stub_torch(monkeypatch, version)+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.7.0")+ assert "--index-url" not in (fixes._torchcodec_version_mismatch_hint() or "")+ # torchcodec 0.1 is PyPI-only, so the 2.5 row must not send anyone to a torch index.+ _stub_torch(monkeypatch, "2.5.0+cu118")+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.5.0")+ assert "--index-url" not in fixes._torchcodec_version_mismatch_hint()+++def test_the_remedy_drops_the_extra_when_an_index_pin_is_needed(monkeypatch):+ """An extra cannot carry an index: the marker picks the version, and putting+ --index-url on the whole command would resolve unsloth itself from the torch index. On a+ tagged venv the extra would hand back the same unloadable wheel the warning is about."""+ import importlib.metadata-def test_import_fixes_loads_on_python39_syntax():- """Regression: module must import on 3.9 (postponed annotations for str | None)."""fixes = _load_import_fixes_module()- assert callable(fixes._torchcodec_version_mismatch_hint)+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.10.0")+ _stub_torch(monkeypatch, "2.11.0+cu128")+ pinned = fixes._torchcodec_version_mismatch_hint()+ assert "--index-url" in pinned+ assert "unsloth[audio-torch211]" not in pinned-def test_audio_extras_are_gated_to_platforms_with_a_torchcodec_wheel():- """torchcodec publishes no sdist and no wheel for Linux aarch64, Windows ARM64 or- Intel Mac, so an ungated pin makes pip fail the whole install on those hosts instead- of just skipping audio -- and the cu*/rocm*/intel torch 2.10 extras pull it in.- The marker must match PLATFORM_LACKS_TORCHCODEC_WHEEL in install_python_stack.py.- """- markers = pytest.importorskip("packaging.markers")- tomllib = _tomllib()- extras = tomllib.loads(PYPROJECT.read_text(encoding = "utf-8"))["project"][- "optional-dependencies"- ]- audio = {n: d for n, d in extras.items() if n.startswith("audio-torch")}- assert audio, "expected audio-torch* extras"+ # Untagged torch needs no pin, so the convenient alternative stays on offer.+ _stub_torch(monkeypatch, "2.11.0")+ unpinned = fixes._torchcodec_version_mismatch_hint()+ assert "--index-url" not in unpinned+ assert "unsloth[audio-torch211]" in unpinned- supported = [- {"sys_platform": "linux", "platform_machine": "x86_64"},- {"sys_platform": "win32", "platform_machine": "AMD64"},- {"sys_platform": "darwin", "platform_machine": "arm64"},- ]- unsupported = [- {"sys_platform": "linux", "platform_machine": "aarch64"},- {"sys_platform": "win32", "platform_machine": "ARM64"},- {"sys_platform": "darwin", "platform_machine": "x86_64"},- ]- for name, deps in audio.items():- for dep in deps:- _, _, marker_text = dep.partition(";")- assert marker_text.strip(), f"{name}: {dep!r} has no marker"- marker = markers.Marker(marker_text.strip())- env = {"python_version": "3.12"}- for case in supported:- assert marker.evaluate({**env, **case}), f"{name} must install on {case}"- for case in unsupported:- assert not marker.evaluate(- {**env, **case}- ), f"{name} has no wheel for {case} and must not be resolved there"---def test_torch211_rejects_torchcodec_010(monkeypatch):- """The guard must not be silent on the torch minor where the mismatch happens."""++def test_the_codec_index_honours_an_explicitly_pinned_torch_mirror(monkeypatch):+ """UNSLOTH_TORCH_INDEX_URL names the index torch itself came from. Rebuilding a public+ download.pytorch.org URL from the local tag sent an authenticated or air-gapped mirror to+ the internet, and the `--index-url` that follows also drops the inherited index+ configuration, so the codec install fails outright where public PyTorch is unreachable."""+ from studio import install_python_stack as ips++ assert ips._torchcodec_index_url("2.11.0+cu128") == "https://download.pytorch.org/whl/cu128"++ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_URL", "https://mirror.corp.example/pytorch/cu128/")+ assert ips._torchcodec_index_url("2.11.0+cu128") == "https://mirror.corp.example/pytorch/cu128"++ monkeypatch.delenv("UNSLOTH_TORCH_INDEX_URL")+ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_FAMILY", "cu126")+ assert ips._torchcodec_index_url("2.11.0+cu128") == "https://download.pytorch.org/whl/cu126"++ # The override does not make an untagged or rocm torch start pinning.+ assert ips._torchcodec_index_url("2.11.0") is None+ assert ips._torchcodec_index_url("2.11.0+rocm7.0") is None+++def test_the_runtime_remedy_honours_a_configured_torch_index(monkeypatch):+ """A warning that tells an air-gapped or authenticated host to install from+ download.pytorch.org either fails or bypasses the artifact source the install was+ configured with. The mirror is where the matching build is."""import importlib.metadatafixes = _load_import_fixes_module()- monkeypatch.setattr(- importlib.metadata,- "version",- lambda _name: "0.10.0+cu128",+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.11.0")+ _stub_torch(monkeypatch, "2.10.0+cu128")++ assert "--index-url https://download.pytorch.org/whl/cu128" in (+ fixes._torchcodec_version_mismatch_hint() or "")- _stub_torch(monkeypatch, "2.11.0")+ # The variable, not its value: a mirror URL can carry credentials and this string is+ # warned into terminals and CI logs. The shell expands it, so the command still runs.+ monkeypatch.setenv(+ "UNSLOTH_TORCH_INDEX_URL", "https://user:[email protected]/pytorch/cu128/"+ )hint = fixes._torchcodec_version_mismatch_hint()- assert hint is not None, "torch 2.11 + torchcodec 0.10 must not go unreported"- assert "torchcodec 0.10.0+cu128" in hint- assert ">=0.11" in hint- assert "<0.12.0" in hint+ assert '--index-url "$UNSLOTH_TORCH_INDEX_URL" ' in hint+ assert "secret" not in hint+ assert "mirror.corp.example" not in hint+ assert "download.pytorch.org" not in hint+ monkeypatch.delenv("UNSLOTH_TORCH_INDEX_URL")+ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_FAMILY", "cu126")+ assert "--index-url https://download.pytorch.org/whl/cu126" in (+ fixes._torchcodec_version_mismatch_hint() or ""+ )-def test_torch211_accepts_torchcodec_011(monkeypatch):- import importlib.metadata++def test_a_mismatched_accelerator_build_is_named_when_the_codec_cannot_load(monkeypatch):+ """A cu128 venv holding PyPI's default torchcodec has the right VERSION and still cannot+ dlopen, so the version hint says nothing and audio used to be disabled in silence. The+ provenance hint only speaks once the load has actually failed, so a working pairing this+ cannot explain never warns."""+ import sys+ import typesfixes = _load_import_fixes_module()_stub_torch(monkeypatch, "2.11.0+cu128")- monkeypatch.setattr(- importlib.metadata,- "version",- lambda _name: "0.11.1+cu128",++ codec = types.ModuleType("torchcodec")+ codec.__version__ = "0.11.0" # untagged: PyPI's default build+ monkeypatch.setitem(sys.modules, "torchcodec", codec)+ hint = fixes._torchcodec_provenance_hint()+ assert hint is not None+ assert "https://download.pytorch.org/whl/cu128" in hint+ assert "audio is disabled" in hint++ # Matching provenance says nothing, and neither does a rocm torch.+ codec.__version__ = "0.11.0+cu128"+ assert fixes._torchcodec_provenance_hint() is None+ codec.__version__ = "0.11.0"+ _stub_torch(monkeypatch, "2.11.0+rocm7.0")+ assert fixes._torchcodec_provenance_hint() is None+++def test_the_printed_codec_index_is_redacted(monkeypatch):+ """The install status line goes straight to the terminal and the CI log, not through+ _redact_install_output, which only covers captured pip output. An authenticated mirror+ carries its credentials in the userinfo or a query token, so printing the configured+ index verbatim persists them."""+ from studio import install_python_stack as ips++ monkeypatch.setenv(+ "UNSLOTH_TORCH_INDEX_URL", "https://user:[email protected]/pytorch/cu128/")- assert fixes._torchcodec_version_mismatch_hint() is None+ # The installer still receives the exact URL, credentials and all.+ resolved = ips._torchcodec_index_url("2.11.0+cu128")+ assert resolved == "https://user:[email protected]/pytorch/cu128"++ # What gets printed does not.+ shown = ips._strip_index_url_credentials(resolved)+ assert shown == "https://mirror.corp.example/pytorch/cu128"+ assert "secret" not in shown++ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_URL", "https://mirror.corp.example/simple?token=abc")+ assert "abc" not in ips._strip_index_url_credentials(ips._torchcodec_index_url("2.11.0+cu128"))++ # The status line itself uses the redacting call, not the raw variable.+ source = (REPO_ROOT / "studio" / "install_python_stack.py").read_text(encoding = "utf-8")+ assert 'f" from {_strip_index_url_credentials(_codec_index)}"' in source+ assert 'f" from {_codec_index}"' not in source+++def test_the_codec_index_follows_a_configured_pytorch_mirror(monkeypatch):+ """UNSLOTH_PYTORCH_MIRROR replaces the base every other index in install_python_stack is+ built from, so a codec pinned to the public site cannot be fetched on an air-gapped host+ and bypasses the artifact source on a corporate one."""+ import importlib++ monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", "https://mirror.corp.example/whl")+ from studio import install_python_stack as ips+ ips = importlib.reload(ips) # _PYTORCH_WHL_BASE is read at import time+ try:+ assert ips._torchcodec_index_url("2.11.0+cu128") == "https://mirror.corp.example/whl/cu128"+ # A full URL override still wins over the mirror base.+ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_URL", "https://other.example/pytorch/cu128")+ assert ips._torchcodec_index_url("2.11.0+cu128") == "https://other.example/pytorch/cu128"+ finally:+ monkeypatch.delenv("UNSLOTH_PYTORCH_MIRROR", raising = False)+ importlib.reload(ips)-def test_torch211_accepts_abi_stable_torchcodec(monkeypatch):- """torchcodec 0.12+ targets torch >=2.11, so it is not locked to one minor."""++def test_the_runtime_remedy_follows_a_configured_pytorch_mirror(monkeypatch):+ """Same for the runtime warning, and by naming the variable rather than its value the+ command still works without disclosing a mirror that may carry credentials."""import importlib.metadatafixes = _load_import_fixes_module()- for torch_version in ("2.11.0+cu128", "2.12.0", "2.13.0+cu130"):- for codec_version in ("0.12.0", "0.15.0+cu130"):- _stub_torch(monkeypatch, torch_version)- monkeypatch.setattr(importlib.metadata, "version", lambda _name, _v = codec_version: _v)- assert (- fixes._torchcodec_version_mismatch_hint() is None- ), f"{torch_version} + torchcodec {codec_version} is supported upstream"+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.11.0")+ _stub_torch(monkeypatch, "2.10.0+cu128")++ monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", "https://user:[email protected]/whl")+ hint = fixes._torchcodec_version_mismatch_hint()+ assert '--index-url "$UNSLOTH_PYTORCH_MIRROR"/cu128' in hint+ assert "secret" not in hint+ assert "download.pytorch.org" not in hint++ # The family names the leaf under the same mirror.+ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_FAMILY", "cu126")+ assert '--index-url "$UNSLOTH_PYTORCH_MIRROR"/cu126' in (+ fixes._torchcodec_version_mismatch_hint() or ""+ )++ # With no mirror configured the public URL comes back, family-aware as before.+ monkeypatch.delenv("UNSLOTH_PYTORCH_MIRROR")+ assert "--index-url https://download.pytorch.org/whl/cu126" in (+ fixes._torchcodec_version_mismatch_hint() or ""+ )+++def test_the_provenance_hint_does_not_assert_a_cause_it_has_not_established(monkeypatch):+ """Differing local tags show the two wheels came from different indexes, nothing more.+ torchcodec is published per accelerator on every line, 0.12+ included, so the mismatch+ stays possible there, but the load can equally have failed on a missing libavutil that no+ reinstall repairs. The hint has to name both."""+ import sys+ import types++ fixes = _load_import_fixes_module()+ _stub_torch(monkeypatch, "2.12.0+cu128")++ codec = types.ModuleType("torchcodec")+ codec.__version__ = "0.12.0"+ monkeypatch.setitem(sys.modules, "torchcodec", codec)+ hint = fixes._torchcodec_provenance_hint()+ assert hint is not None # 0.12+ is ABI-stable against torch, not accelerator-agnostic+ assert "may be built for a different accelerator" in hint+ assert "cannot load" not in hint+ assert "FFmpeg" in hint-def test_torch210_still_rejects_abi_stable_torchcodec(monkeypatch):- """The ABI-stable floor starts at torch 2.11: 2.10 keeps the exact pairing."""+def test_the_remedy_uses_the_shell_of_the_host_it_prints_on(monkeypatch):+ """PowerShell is Studio's supported Windows shell and does not expand `$NAME`, so the+ POSIX spelling pasted there produced an empty `--index-url`."""import importlib.metadatafixes = _load_import_fixes_module()- _stub_torch(monkeypatch, "2.10.0")- monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.15.0")+ monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.11.0")+ _stub_torch(monkeypatch, "2.10.0+cu128")+ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_URL", "https://user:[email protected]/cu128")- hint = fixes._torchcodec_version_mismatch_hint()+ monkeypatch.setattr(fixes.sys, "platform", "linux")+ assert '--index-url "$UNSLOTH_TORCH_INDEX_URL"' in (+ fixes._torchcodec_version_mismatch_hint() or ""+ )++ monkeypatch.setattr(fixes.sys, "platform", "win32")+ windows = fixes._torchcodec_version_mismatch_hint() or ""+ assert "--index-url $env:UNSLOTH_TORCH_INDEX_URL" in windows+ assert "secret" not in windows++ # The mirror branch follows the same rule.+ monkeypatch.delenv("UNSLOTH_TORCH_INDEX_URL")+ monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", "https://mirror.corp.example/whl")+ assert "--index-url $env:UNSLOTH_PYTORCH_MIRROR/cu128" in (+ fixes._torchcodec_version_mismatch_hint() or ""+ )+++def test_the_provenance_remedy_pins_the_compatible_window(monkeypatch):+ """The accelerator indexes carry the whole codec line, so a bare `torchcodec` on a torch+ 2.9 host installs the newest release there and trades a wrong-accelerator build for a+ wrong-version one, leaving audio just as disabled."""+ import sys+ import types++ fixes = _load_import_fixes_module()++ codec = types.ModuleType("torchcodec")+ codec.__version__ = "0.8.0"+ monkeypatch.setitem(sys.modules, "torchcodec", codec)++ _stub_torch(monkeypatch, "2.9.0+cu128")+ hint = fixes._torchcodec_provenance_hint()+ assert "'torchcodec>=0.9,<0.10.0'" in hint, hint+ assert "--index-url https://download.pytorch.org/whl/cu128 torchcodec`" not in hint++ # Past the table, the ABI-stable floor is the pin instead of a bare name.+ _stub_torch(monkeypatch, "2.12.0+cu128")+ codec.__version__ = "0.11.0"+ assert "'torchcodec>=0.12.0'" in (fixes._torchcodec_provenance_hint() or "")+++def test_a_cuda_index_codec_also_installs_npp():+ """torchcodec's CUDA build dlopens libnppicc and libnppc, and NPP is not in torch's own+ dependency set, so a --no-deps install from a cuNNN index reports success and then fails+ to import. docker/Dockerfile installs nvidia-npp-cu12 beside the same wheel."""+ source = (REPO_ROOT / "studio" / "install_python_stack.py").read_text(encoding = "utf-8")+ assert 'f"nvidia-npp-cu{_npp_major}"' in source+ assert "Installing torchcodec CUDA runtime (NPP)" in source++ # The major follows the index leaf, and a cpu or rocm index asks for nothing.+ import re++ for url, want in (+ ("https://download.pytorch.org/whl/cu128", "12"),+ ("https://download.pytorch.org/whl/cu130", "13"),+ ("https://mirror.corp.example/whl/cu128/", "12"),+ ("https://download.pytorch.org/whl/cpu", None),+ ("https://download.pytorch.org/whl/rocm6.3", None),+ ):+ match = re.search(r"/cu(\d+)/?$", url)+ assert (match.group(1)[:2] if match else None) == want, url++ # The Dockerfile this mirrors still pairs the two, so the rationale stays checkable.+ dockerfile = (REPO_ROOT / "docker" / "Dockerfile").read_text(encoding = "utf-8")+ assert "nvidia-npp-cu12" in dockerfile+++def test_the_npp_major_comes_from_the_resident_torch_not_the_index_url():+ """Matching `/cuNNN$` against an authenticated mirror ending `/simple?token=...` skipped+ NPP on a `+cu128` host, so the codec then failed to import without a CUDA toolkit."""+ import re as _re++ source = (REPO_ROOT / "studio" / "install_python_stack.py").read_text(encoding = "utf-8")+ namespace: dict = {"re": _re}+ exec(+ _re.search(r"def _cuda_major_for_npp.*?\n(?=\n\ndef )", source, _re.S).group(0),+ namespace,+ )+ npp_major = namespace["_cuda_major_for_npp"]++ # The local tag answers whatever the index URL looks like.+ opaque = "https://mirror.example/simple?token=abc"+ assert npp_major("2.11.0+cu128", opaque) == "12"+ assert npp_major("2.11.0+cu130", opaque) == "13"+ # cpu and rocm ask for nothing, on any URL.+ assert npp_major("2.11.0+cpu", "https://download.pytorch.org/whl/cpu") == ""+ assert npp_major("2.11.0+rocm6.4", "https://download.pytorch.org/whl/rocm6.4") == ""+ # An untagged torch still falls back to the public leaf.+ assert npp_major("2.11.0", "https://download.pytorch.org/whl/cu126") == "12"+ assert npp_major("2.11.0", opaque) == ""++ # And the call site reads the tag rather than re-matching the URL.+ assert "_cuda_major_for_npp(_codec_torch_ver, _codec_index)" in source+++def test_the_provenance_hint_reads_a_codec_it_cannot_import(monkeypatch):+ """An unloadable wheel usually raises while `torchcodec/__init__` imports its decoders, and+ Python drops a module whose initialisation raised, so importing it again just repeats the+ exception. Reading the version back that way left the accelerator mismatch undiagnosed in+ exactly the case the hint exists to name; the installer's metadata needs no native library."""+ import importlib.metadata+ import sys++ fixes = _load_import_fixes_module()+ _stub_torch(monkeypatch, "2.11.0+cu128")+ # No importable torchcodec at all, which is what a failed initialisation leaves behind.+ monkeypatch.delitem(sys.modules, "torchcodec", raising = False)++ def _version(name):+ if name == "torchcodec":+ return "0.11.0" # untagged: PyPI's default build+ raise importlib.metadata.PackageNotFoundError(name)++ monkeypatch.setattr(importlib.metadata, "version", _version)+ hint = fixes._torchcodec_provenance_hint()assert hint is not None- assert "audio-torch210" in hint+ assert "torchcodec 0.11.0 came from the default index" in hint+ assert "https://download.pytorch.org/whl/cu128" in hint++ # Nothing installed at all still says nothing.+ def _absent(name):+ raise importlib.metadata.PackageNotFoundError(name)++ monkeypatch.setattr(importlib.metadata, "version", _absent)+ assert fixes._torchcodec_provenance_hint() is Nonediff --git a/tests/studio/install/test_diffusers_pin.py b/tests/studio/install/test_diffusers_pin.pyindex 85e4d7ea28f..fe8bb56893e 100644--- a/tests/studio/install/test_diffusers_pin.py+++ b/tests/studio/install/test_diffusers_pin.py@@ -16,8 +16,10 @@ that installs it sits outside every skip.from __future__ import annotationsimport ast+import ioimport pathlibimport re+import tokenizeREPO_ROOT = pathlib.Path(__file__).resolve().parents[3]REQ_ROOT = REPO_ROOT / "studio" / "backend" / "requirements"@@ -41,6 +43,30 @@ def _requirements(path: pathlib.Path) -> list[str]:return out+def _code_only(source: str) -> str:+ """`source` with comment text blanked out, offsets preserved.++ The ordering check scans for requirements filenames and has to read them as installs,+ not prose. Blanking keeps every index truthful; tokenize spares a `#` inside a string."""+ lines = source.splitlines(keepends = True)+ starts, offset = [], 0+ for line in lines:+ starts.append(offset)+ offset += len(line)+ out = list(source)+ try:+ tokens = tokenize.generate_tokens(io.StringIO(source).readline)+ comments = [tok for tok in tokens if tok.type == tokenize.COMMENT]+ except (tokenize.TokenError, IndentationError, SyntaxError): # pragma: no cover+ return source+ for tok in comments:+ begin = starts[tok.start[0] - 1] + tok.start[1]+ for index in range(begin, begin + len(tok.string)):+ if out[index] != "\n":+ out[index] = " "+ return "".join(out)++def test_the_pin_file_exists_and_names_the_first_supported_release():assert PIN_FILE.is_file(), f"{PIN_FILE} is missing"lines = _requirements(PIN_FILE)@@ -108,7 +134,7 @@ def test_the_pin_step_is_not_gated_by_skip_base_or_no_torch():def test_the_pin_step_runs_after_every_other_requirements_install():"""Ordering matters: a later `uv pip install -r ...` can re-resolve diffusers back to arelease. Keeping the pin last means nothing is left that could walk it forward."""- source = STACK.read_text(encoding = "utf-8")+ source = _code_only(STACK.read_text(encoding = "utf-8"))pin_at = source.index("diffusers-pin.txt")later = [name@@ -126,6 +152,31 @@ def test_the_pin_step_runs_after_every_other_requirements_install():assert not later, f"these requirements files are installed after the diffusers pin: {later}"+def test_the_ordering_check_reads_installs_not_prose():+ """The torchcodec comment names extras-no-deps.txt after the pin, so the check must read+ that as prose while a real later install still trips it."""+ pin = 'pip_install("diffusers pin", "-r", "diffusers-pin.txt")\n'++ prose = _code_only(pin + "# cannot live in extras-no-deps.txt because markers\n")+ assert prose.rfind("extras-no-deps.txt") < prose.index(+ "diffusers-pin.txt"+ ), "a commented mention of a requirements file must not count as an install"++ real = _code_only(pin + 'pip_install("extras", "-r", "extras-no-deps.txt")\n')+ assert real.rfind("extras-no-deps.txt") > real.index(+ "diffusers-pin.txt"+ ), "a genuine later install must still be caught"++ # A `#` inside a string literal is not a comment and must survive intact.+ kept = _code_only('marker = "extras-no-deps.txt#egg"\n')+ assert "extras-no-deps.txt#egg" in kept++ source = STACK.read_text(encoding = "utf-8")+ blanked = _code_only(source)+ assert len(blanked) == len(source)+ assert blanked.index("diffusers-pin.txt") == source.index("diffusers-pin.txt")++def test_install_sh_still_delegates_the_core_package_skip():"""The handoff flag skips core packages while allowing other base entries through."""assert 'SKIP_STUDIO_BASE="$_SKIP_BASE"' in INSTALL_SH.read_text(encoding = "utf-8")diff --git a/tests/studio/install/test_windows_torch_flavor_invariant.py b/tests/studio/install/test_windows_torch_flavor_invariant.pyindex 900fefbb6a3..3f0b27a8a3a 100644--- a/tests/studio/install/test_windows_torch_flavor_invariant.py+++ b/tests/studio/install/test_windows_torch_flavor_invariant.py@@ -300,7 +300,7 @@ def _base_total(**flags) -> int:total fails here instead of drawing a progress bar past 100%."""lines = _STACK_SRC.splitlines()- start = next(i for i, line in enumerate(lines) if line.strip().startswith("base_total = 12"))+ start = next(i for i, line in enumerate(lines) if line.strip().startswith("base_total = "))end = next(i for i, line in enumerate(lines) if line.strip().startswith("base_requirements ="))block = textwrap.dedent("\n".join(lines[start:end]))namespace = {@@ -316,20 +316,20 @@ def _base_total(**flags) -> int:class TestStepTotals:- def test_windows_gained_one_step(self):- assert _base_total(IS_WINDOWS = True) == 14- assert _base_total(IS_WINDOWS = True, NO_TORCH = True) == 12+ def test_windows_totals_include_torchcodec(self):+ assert _base_total(IS_WINDOWS = True) == 15+ assert _base_total(IS_WINDOWS = True, NO_TORCH = True) == 13@pytest.mark.parametrize("flags,total",[- ({}, 16), # Linux, torch- ({"NO_TORCH": True}, 13), # Linux, GGUF-only- ({"IS_MACOS": True, "IS_MAC_ARM": True}, 13), # Apple Silicon- ({"IS_MACOS": True}, 12), # Intel Mac+ ({}, 17), # Linux, torch+ ({"NO_TORCH": True}, 14), # Linux, GGUF-only+ ({"IS_MACOS": True, "IS_MAC_ARM": True}, 14), # Apple Silicon+ ({"IS_MACOS": True}, 13), # Intel Mac],)- def test_the_other_platforms_are_unchanged(self, flags, total):+ def test_the_other_platform_totals_include_torchcodec(self, flags, total):assert _base_total(**flags) == totaldiff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex eb75c69d270..2ac2362e274 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -2444,6 +2444,8 @@ def patch_torchcodec_audio_decoder():# torch.minor -> compatible torchcodec.minor strings (see notebook_validator.py).+# torchcodec ships no `Requires-Dist: torch`, so pip cannot catch a mismatch and this table+# is the only check. Lockstep releases only; 0.12+ is the ABI-stable rule below._TORCH_TORCHCODEC_MINORS: dict[str, set[str]] = {"2.11": {"0.11"},"2.10": {"0.10"},@@ -2455,6 +2457,12 @@ _TORCH_TORCHCODEC_MINORS: dict[str, set[str]] = {}+# torch.minor -> the pyproject extra that pins the matching torchcodec line.+_TORCH_TORCHCODEC_EXTRAS: dict[str, str] = {+ "2.11": "audio-torch211",+ "2.10": "audio-torch210",+}+# torchcodec 0.12+ is ABI-stable against torch >=2.11 (its build sets TORCH_TARGET_VERSION# to 2.11), so that half of the matrix is open-ended rather than a finite set of minors.# Mirrors notebook_validator.TORCHCODEC_ABI_STABLE_{TORCH,CODEC}.@@ -2468,6 +2476,40 @@ def _torchcodec_exclusive_upper(pin: str) -> str:return f"<{major}.{int(minor) + 1}.0"+def _shell_env_ref(name: str) -> str:+ """How to reference an environment variable in the shell this host pastes into.++ PowerShell is Studio's supported Windows shell and does not expand `$NAME`; it needs+ `$env:NAME`, so the POSIX spelling silently produced an empty `--index-url`.+ """+ if sys.platform.startswith("win"):+ return f"$env:{name}"+ return f'"${name}"'+++def _torch_index_url_for_remedy(local_tag: str) -> str:+ """The index a torchcodec remedy should name for a `+local_tag` torch.++ An explicitly configured index wins, exactly as it does in+ install_python_stack._torchcodec_index_url: on an authenticated, corporate or+ air-gapped host, telling the user to install from download.pytorch.org either fails+ outright or bypasses the artifact source the install was configured with, and the+ mirror is where the matching build actually is.+ """+ if os.environ.get("UNSLOTH_TORCH_INDEX_URL", "").strip():+ # The variable, not its value: an authenticated mirror carries credentials in its+ # userinfo or query token, and this warning lands in terminals and CI logs. The+ # shell expands it, so the command still works and nothing is written down.+ return _shell_env_ref("UNSLOTH_TORCH_INDEX_URL")+ leaf = os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY", "").strip().strip("/") or local_tag+ if os.environ.get("UNSLOTH_PYTORCH_MIRROR", "").strip():+ # UNSLOTH_PYTORCH_MIRROR replaces the base every install_python_stack index is built+ # from, so naming the public site fails on an air-gapped host. Expanded, not disclosed,+ # as above.+ return f"{_shell_env_ref('UNSLOTH_PYTORCH_MIRROR')}/{leaf}"+ return f"https://download.pytorch.org/whl/{leaf}"++def _torchcodec_version_mismatch_hint() -> str | None:"""Return a user-facing hint when installed torchcodec mismatches torch."""try:@@ -2502,6 +2544,21 @@ def _torchcodec_version_mismatch_hint() -> str | None:torch_minor = ".".join(str(p) for p in torch_release)codec_minor = ".".join(str(p) for p in codec_release)+ def _index_flag(recommended: "tuple[int, ...]") -> str:+ """`--index-url ...` when torch carries an accelerator tag, else "".++ torchcodec ships one wheel per accelerator, so a remedy that installs the right+ version from the default index still lands a codec that cannot dlopen on a cu126 or+ cu128 venv. Mirrors install_python_stack._torchcodec_index_url, including the lines+ it will not pin: torchcodec 0.1 and 0.2 exist on PyPI only.+ """+ if recommended < (0, 3):+ return ""+ local = str(getattr(torch, "__version__", "")).partition("+")[2].strip().lower()+ if local == "cpu" or re.fullmatch(r"cu\d+", local or ""):+ return f"--index-url {_torch_index_url_for_remedy(local)} "+ return ""+allowed = _TORCH_TORCHCODEC_MINORS.get(torch_minor)if allowed is None:# No lockstep row: below the table stays silent; at or past the ABI floor this is a@@ -2509,24 +2566,105 @@ def _torchcodec_version_mismatch_hint() -> str | None:if not torch_at_abi:return Noneabi_pin = ".".join(str(p) for p in _TORCHCODEC_ABI_STABLE_CODEC)- return (- f"torchcodec {torchcodec_version} is incompatible with torch {torch.__version__}; "- f"install a matching build with `pip install 'torchcodec>={abi_pin}.0'`."+ install_hint = (+ f"`pip install {_index_flag(_TORCHCODEC_ABI_STABLE_CODEC)}'torchcodec>={abi_pin}.0'`")- if codec_minor in allowed:+ elif codec_minor in allowed:return None-- pin = sorted(allowed)[-1]- upper = _torchcodec_exclusive_upper(pin)- install_hint = f"`pip install 'torchcodec>={pin},{upper}'`"- if torch_minor == "2.10":- install_hint += " or `pip install 'unsloth[audio-torch210]'`"+ else:+ pin = sorted(allowed)[-1]+ upper = _torchcodec_exclusive_upper(pin)+ install_hint = f"`pip install {_index_flag(tuple(int(x) for x in pin.split('.')))}'torchcodec>={pin},{upper}'`"+ extra = _TORCH_TORCHCODEC_EXTRAS.get(torch_minor)+ # Only when no index pin is needed. An extra cannot carry one -- the marker picks the+ # version, not the index -- and --index-url on the whole command would resolve unsloth+ # from the torch index too, handing back the same unloadable wheel.+ if extra is not None and not _index_flag(tuple(int(x) for x in pin.split("."))):+ install_hint += f" or `pip install 'unsloth[{extra}]'`"return (f"torchcodec {torchcodec_version} is incompatible with torch {torch.__version__}; "f"install a matching build with {install_hint}.")+def _installed_torchcodec_version() -> "str | None":+ """The installed codec's version WITHOUT importing it, or None when nothing is installed.++ This is only ever asked once the codec has FAILED to load, and an unloadable wheel usually+ raises while `torchcodec/__init__` imports its decoders. Python drops a module whose+ initialisation raised, so importing it again just repeats the exception and the accelerator+ mismatch went undiagnosed in exactly the case this exists to name. The metadata is written+ by the installer and needs no native library.+ """+ try:+ from importlib.metadata import version+ return str(version("torchcodec"))+ except Exception:+ pass+ try:+ import torchcodec # a layout the metadata cannot describe, e.g. a source checkout+ return str(getattr(torchcodec, "__version__", "") or "")+ except Exception:+ return None+++def _torchcodec_provenance_hint() -> "str | None":+ """A remedy for a codec whose ACCELERATOR build does not match torch's, or None.++ torchcodec ships one wheel per accelerator, so a cu128 venv holding PyPI's default 0.11+ has the right VERSION and still cannot dlopen -- docker/Dockerfile pins cu128 by hand+ for exactly this. The version hint above returns None there, since the minors agree, so+ without this the codec is disabled with nothing said about how to repair it.++ Only called once the codec has actually failed to load, so a working pairing this cannot+ explain never produces a warning.+ """+ try:+ import torch+ except Exception:+ return None+ codec_version = _installed_torchcodec_version()+ if codec_version is None:+ return None+ torch_local = str(getattr(torch, "__version__", "")).partition("+")[2].strip().lower()+ codec_local = codec_version.partition("+")[2].strip().lower()+ if torch_local == codec_local:+ return None # same provenance, so the failure is something this cannot name+ if not (torch_local == "cpu" or re.fullmatch(r"cu\d+", torch_local or "")):+ return None # rocm and xpu publish no torchcodec under this name+ index = _torch_index_url_for_remedy(torch_local)+ codec_from = codec_local or "the default index"+ # The window the table allows, not a bare name: the accelerator indexes carry the whole+ # codec line, so `pip install torchcodec` on torch 2.9 trades a wrong-accelerator build+ # for a wrong-VERSION one and audio stays disabled. Past the table, the ABI floor pins.+ try:+ from packaging.version import Version+ parts = Version(str(torch.__version__).split("+", 1)[0]).release+ torch_release = tuple(parts[:2]) + (0,) * (2 - len(parts[:2]))+ except Exception:+ torch_release = ()+ allowed = _TORCH_TORCHCODEC_MINORS.get(".".join(str(p) for p in torch_release))+ if allowed:+ pin = sorted(allowed)[-1]+ want = f"'torchcodec>={pin},{_torchcodec_exclusive_upper(pin)}'"+ elif torch_release and torch_release >= _TORCHCODEC_ABI_STABLE_TORCH:+ abi = ".".join(str(p) for p in _TORCHCODEC_ABI_STABLE_CODEC)+ want = f"'torchcodec>={abi}.0'"+ else:+ want = "torchcodec"+ # "may be", not "is": this only establishes different indexes. torchcodec is published+ # per accelerator on every line, 0.12+ included, so a mismatch stays possible -- but the+ # load can equally have failed on a missing libavutil, which no reinstall fixes. Name both.+ return (+ f"torchcodec {codec_version or '?'} came from {codec_from} while "+ f"torch {getattr(torch, '__version__', '?')} is a {torch_local} build, so the codec "+ f"may be built for a different accelerator; audio is disabled. Try "+ f"`pip install --force-reinstall --no-deps --index-url {index} {want}`. "+ f"If that does not help, the failure is likely FFmpeg rather than the wheel: "+ f"torchcodec needs libavutil / libavcodec from FFmpeg 4 through 8."+ )++def disable_torchcodec_if_broken():"""Make broken torchcodec behave as if uninstalled (#5446).@@ -2552,6 +2690,16 @@ def disable_torchcodec_if_broken():# RuntimeError on dlopen failure; OSError covers chained libavutil.so misses.from torchcodec.decoders import AudioDecoderexcept (ImportError, RuntimeError, OSError):+ if mismatch_hint is None:+ # Versions agree, so the load failed for another reason. A mismatched accelerator+ # build is the one this can still name, and the one pinning the index repairs.+ try:+ provenance_hint = _torchcodec_provenance_hint()+ if provenance_hint is not None:+ import warnings+ warnings.warn(provenance_hint, stacklevel = 2)+ except Exception:+ pass # a diagnostic must never abort the disable fallback below# transformers: flip the flag (<5) and/or rebind the lru_cache'd func (>=5).try:import transformers.utils.import_utils as tf_import_utils