Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

ci: install the CPU-only torch wheel on the Linux jobs (#2118)

Alpamys Makazhan7d355d363434
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c16e439e..d2c39f61 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -531,6 +531,11 @@ jobs:
# One spec with both extras: `-e ".[dev]" ".[qat]"` asks pip for
# soup-cli twice, once editable and once not, and resolution fails.
# Ends with `plan`'s stack: pinned on a pull request, the newest at night; torchao floats.
+ # Deliberately NOT on the CPU torch index (2026-10-21), unlike the other Linux jobs:
+ # that index also hosts `torchao`, as `0.18.0+cpu` (pure Python), and pip prefers it to
+ # PyPI's `0.18.0` (the compiled abi3 wheel), so this job would test a build no user
+ # installs from PyPI. It runs nightly and on release/** only, so the CUDA download is a
+ # small cost. tests/test_ci_cpu_torch_on_linux.py names this exemption.
run: pip install -e ".[dev,qat]" "torch>=2.6.0" ${{ needs.plan.outputs.constraints }}
- name: Prove torchao is actually importable, so the tests do not skip
run: python -c "import torchao; print(torchao.__version__)"
@@ -594,6 +599,9 @@ jobs:
# already pulls torch" breaks the job with a message naming the CVE
# rather than the cause.
# Ends with `plan`'s stack: pinned on a pull request, the newest at night.
+ # CPU-only torch (2026-10-21), as in the `test` job: see the comment there.
+ env:
+ PIP_EXTRA_INDEX_URL: https://download.pytorch.org/whl/cpu
run: pip install -e ".[dev]" "torch>=2.6.0" ${{ needs.plan.outputs.constraints }}
- name: Warm tiny GPT-2 cache
@@ -706,6 +714,12 @@ jobs:
python-version: "3.11"
- name: Install with Transformers floor constraints
if: needs.plan.outputs.docs_only != 'true'
+ # CPU-only torch and torchaudio (2026-10-21), as in the `test` job: see the comment
+ # there. 2.6.0+cpu exists on the CPU index for cp311, cp312 and cp313 (linux x86_64)
+ # for both, and the pins in transformers-floor.txt accept it (PEP 440). The version
+ # it reports is `2.6.0+cpu`, which the next-but-one step compares by public version.
+ env:
+ PIP_EXTRA_INDEX_URL: https://download.pytorch.org/whl/cpu
run: pip install -e ".[dev,audio]" -c .github/constraints/transformers-floor.txt
- name: Verify constrained dependency graph
if: needs.plan.outputs.docs_only != 'true'
@@ -718,6 +732,8 @@ jobs:
import re
from pathlib import Path
+ from packaging.version import Version
+
constraints = Path(".github/constraints/transformers-floor.txt").read_text(
encoding="utf-8"
)
@@ -735,7 +751,8 @@ jobs:
assert name in expected, f"floor constraints missing exact {name} pin"
want = expected[name]
got = md.version(name)
- assert got == want, (
+ # The public part: a CPU wheel reports `2.6.0+cpu` for the pin `==2.6.0`.
+ assert Version(got).public == want, (
f"floor job expected {name}=={want} from "
f".github/constraints/transformers-floor.txt, got {got} — "
f"pip silently upgraded, ignored -c, or constraints drifted"
@@ -911,6 +928,21 @@ jobs:
# and not in the dev extra: a local run stays serial unless a contributor
# asks for workers.
# Ends with `plan`'s stack: pinned on a pull request and a push to main, the newest at night.
+ #
+ # 2026-10-21: the Linux cells install the CPU-only torch wheel. PyPI's Linux torch
+ # drags in the CUDA stack (19 packages, 2.43 GB beside the 555 MB torch wheel for
+ # 2.14.1) on runners that have no GPU; the CPU wheel (196 MB, no nvidia-* and no
+ # triton) comes from PyTorch's own index. `PIP_EXTRA_INDEX_URL`, not a flag on the
+ # command: the line above is pinned by tests/test_ci_full_matrix_on_approval.py, and
+ # PyPI stays the main index for every other package (the CPU index mirrors only
+ # older or equal copies of them). On this step only, so a pip a test runs is not
+ # redirected. Windows and macOS already get CPU wheels from PyPI, so it is empty
+ # there. `torch==2.14.1` and `torch>=2.6.0` both accept `2.14.1+cpu` (PEP 440) and
+ # pip prefers the local version to PyPI's plain one. If PyPI ever has a torch the CPU
+ # index does not, the CUDA wheel is resolved silently: the install log says which.
+ # tests/test_ci_cpu_torch_on_linux.py pins every job that does this.
+ env:
+ PIP_EXTRA_INDEX_URL: ${{ runner.os == 'Linux' && 'https://download.pytorch.org/whl/cpu' || '' }}
run: pip install -e ".[dev]" "pytest-xdist[psutil]" ${{ needs.plan.outputs.constraints }}
- name: Warm HF Hub cache (models the tests load)
if: env.RUN_SUITE == 'true'
diff --git a/.github/workflows/dependency-drift.yml b/.github/workflows/dependency-drift.yml
index 167a4728..4d2716af 100644
--- a/.github/workflows/dependency-drift.yml
+++ b/.github/workflows/dependency-drift.yml
@@ -42,6 +42,8 @@ jobs:
python-version: "3.12"
- name: Install the latest resolvable stack
+ # PyPI only, on purpose (2026-10-21): ci.yml's Linux jobs install the CPU torch wheel,
+ # and this weekly job is the one that resolves what a Linux user gets from PyPI.
run: pip install -e ".[dev,audio]"
- name: Report resolved versions against the declared bounds
diff --git a/.github/workflows/recipe-attach.yml b/.github/workflows/recipe-attach.yml
index 169a3021..97e479ff 100644
--- a/.github/workflows/recipe-attach.yml
+++ b/.github/workflows/recipe-attach.yml
@@ -89,6 +89,10 @@ jobs:
# `[train]`, not `[dev]`: the attach needs torch, transformers and peft
# and nothing from the test extras.
# The pinned stack of ci.yml's pull-request cells on a pull request and a push; a manual run resolves the newest.
+ # CPU-only torch, as in ci.yml's `test` job (2026-10-21): the attach runs on the meta
+ # device, and the CUDA wheels are 2.4 GB more to download.
+ env:
+ PIP_EXTRA_INDEX_URL: https://download.pytorch.org/whl/cpu
run: pip install -e ".[train]" ${{ (github.event_name == 'pull_request' || github.event_name == 'push') && '-c .github/constraints/pinned-upstream.txt' || '' }}
- name: Ratchet every shipped config's attach
# Exit 2 is a new cannot-attach, or a pinned config that now attaches;
diff --git a/.github/workflows/recipe-validation.yml b/.github/workflows/recipe-validation.yml
index 405c581b..3b7b3ebd 100644
--- a/.github/workflows/recipe-validation.yml
+++ b/.github/workflows/recipe-validation.yml
@@ -95,6 +95,10 @@ jobs:
python-version: "3.11"
- name: Install dependencies
# The pinned stack of ci.yml's pull-request cells: this workflow runs on pull requests and pushes only.
+ # CPU-only torch, as in ci.yml's `test` job (2026-10-21): the runner has no GPU, and the
+ # CUDA wheels are 2.4 GB more to download.
+ env:
+ PIP_EXTRA_INDEX_URL: https://download.pytorch.org/whl/cpu
run: pip install -e ".[dev]" -c .github/constraints/pinned-upstream.txt
- name: Validate every recipe (parameterised pytest)
run: pytest tests/test_recipes_v031.py tests/test_recipes.py -v --tb=short --no-cov
diff --git a/tests/test_ci_cpu_torch_on_linux.py b/tests/test_ci_cpu_torch_on_linux.py
new file mode 100644
index 00000000..3885dd00
--- /dev/null
+++ b/tests/test_ci_cpu_torch_on_linux.py
@@ -0,0 +1,382 @@
+"""Linux CI jobs install the CPU-only torch wheel; Windows and macOS cells are left alone.
+
+PyPI's Linux ``torch`` wheel depends on the CUDA runtime (19 packages, 2.43 GB beside the
+555 MB wheel, for torch 2.14.1), and no CI runner has a GPU. PyTorch's own index serves a
+196 MB ``2.14.1+cpu`` wheel with none of it. Windows and macOS get CPU wheels from PyPI
+already, so only Linux needs the second index.
+
+The switch is ``PIP_EXTRA_INDEX_URL`` in the ``env:`` of the install step, never a flag on
+the command: the ``pip install`` lines are parsed and pinned by
+``tests/test_ci_full_matrix_on_approval.py``, and an environment variable leaves them as
+they are. PyPI stays the main index (``PIP_INDEX_URL`` is never set), because the CPU
+index mirrors only older or equal copies of every other package. This file pins:
+
+* every step that installs torch (the name, or an extra that pulls it in) sets the CPU
+ index on a Linux runner and sets nothing on Windows and macOS, matrix cells included;
+* the jobs that stay on PyPI's wheel are named, with the reason, and the set of jobs that
+ install torch is exact, so a new one has to decide;
+* the index is set on those steps only: not for a whole job, where it would also redirect
+ a pip that a test runs, and not for a workflow;
+* the floor job's version assertion reads the public version, because the CPU wheel
+ reports ``2.6.0+cpu`` for the pin ``torch==2.6.0``.
+
+Read off the parsed workflows, never off the text. The control class mutates copies of the
+real workflows and expects each mutation to be reported.
+"""
+
+from __future__ import annotations
+
+import copy
+import importlib.metadata
+import json
+import re
+from pathlib import Path
+from typing import Any
+
+import pytest
+from packaging.specifiers import SpecifierSet
+from packaging.version import Version
+
+from tests.test_ci_full_matrix_on_approval import (
+ _PIP_INSTALL,
+ _render,
+ _requested,
+ _shell_commands,
+ _workflows,
+)
+from tests.test_ci_pinned_upstream import _declared
+
+ROOT = Path(__file__).resolve().parents[1]
+PYPROJECT = ROOT / "pyproject.toml"
+CONSTRAINTS = ROOT / ".github" / "constraints"
+
+CPU_INDEX = "https://download.pytorch.org/whl/cpu"
+INDEX_VARIABLES = ("PIP_EXTRA_INDEX_URL", "PIP_INDEX_URL")
+#: A pip install that asks for either of these brings torch with it.
+TORCH_PACKAGES = frozenset({"torch", "torchaudio"})
+RUNNER_OS = {
+ "ubuntu-latest": "Linux",
+ "windows-latest": "Windows",
+ "macos-latest": "macOS",
+ "macos-14": "macOS",
+}
+
+#: (workflow file, job) pairs whose install step sets the CPU index on Linux.
+ON_CPU_INDEX = frozenset(
+ {
+ ("ci.yml", "test"),
+ ("ci.yml", "pytorch-smoke"),
+ ("ci.yml", "transformers-floor"),
+ ("recipe-validation.yml", "validate-recipes"),
+ ("recipe-attach.yml", "verify"),
+ }
+)
+#: Jobs that install torch and stay on PyPI's wheel, each with why.
+LEFT_ON_PYPI = {
+ ("ci.yml", "torchao-contract"): (
+ "the CPU index also hosts torchao, as 0.18.0+cpu (pure Python), and pip prefers a "
+ "local version to PyPI's plain 0.18.0 (the compiled abi3 wheel): the job would test "
+ "a build no user installs from PyPI"
+ ),
+ ("dependency-drift.yml", "latest-stack"): (
+ "the weekly job that resolves what a Linux user gets from PyPI"
+ ),
+}
+
+
+def _cells(workflows: dict[str, Any], file: str, job: dict[str, Any]) -> list[str]:
+ """The runner labels *job* runs on: the matrix's operating systems for ``test``."""
+ runs_on = job["runs-on"]
+ if runs_on == "${{ matrix.os }}":
+ release = workflows[file]["jobs"]["plan"]["env"]["RELEASE_MATRIX"]
+ return list(json.loads(release)["os"])
+ return [runs_on]
+
+
+def _context(label: str) -> dict[str, Any]:
+ return {
+ "github": {"event_name": "pull_request"},
+ "needs": {
+ "plan": {"outputs": {"constraints": "-c .github/constraints/pinned-upstream.txt"}}
+ },
+ "runner": {"os": RUNNER_OS[label]},
+ "matrix": {"os": label},
+ }
+
+
+def _installs_torch(rendered: str, pyproject: str) -> bool:
+ """Whether a rendered ``pip install`` names torch or installs an extra that needs it."""
+ names, extras = _requested(rendered)
+ if names & TORCH_PACKAGES:
+ return True
+ return extras is not None and bool(set(_declared(pyproject, extras)) & TORCH_PACKAGES)
+
+
+def _torch_steps(workflows: dict[str, Any]) -> list[tuple[str, str, dict[str, Any]]]:
+ """(file, job name, step) for every step whose pip install brings torch."""
+ pyproject = PYPROJECT.read_text(encoding="utf-8")
+ found = []
+ for file, workflow in workflows.items():
+ for name, job in workflow["jobs"].items():
+ for step in job.get("steps", []):
+ if "python" in str(step.get("shell", "")):
+ continue # a script for another interpreter, not a command line
+ for command in _shell_commands(str(step.get("run", ""))):
+ if not _PIP_INSTALL.search(command):
+ continue
+ if _installs_torch(_render(command, _context("ubuntu-latest")), pyproject):
+ found.append((file, name, step))
+ break
+ return found
+
+
+def _index_of(step: dict[str, Any], label: str) -> str:
+ """The extra index *step* gives pip on a runner labelled *label*; empty if none."""
+ raw = (step.get("env") or {}).get("PIP_EXTRA_INDEX_URL")
+ return "" if raw is None else _render(str(raw), _context(label))
+
+
+def _problems(workflows: dict[str, Any]) -> list[str]:
+ """Everything wrong with how *workflows* pick torch's index; empty if they are right."""
+ problems = []
+ torch_steps = _torch_steps(workflows)
+ for file, name, step in torch_steps:
+ job = workflows[file]["jobs"][name]
+ for label in _cells(workflows, file, job):
+ linux = RUNNER_OS[label] == "Linux"
+ want = CPU_INDEX if linux and (file, name) not in LEFT_ON_PYPI else ""
+ got = _index_of(step, label)
+ if got != want:
+ problems.append(
+ f"{file} / {name} / {step.get('name')!r} on {label}: "
+ f"PIP_EXTRA_INDEX_URL is {got!r}, expected {want!r}"
+ )
+ in_scope = {id(step) for _, _, step in torch_steps}
+ for file, workflow in workflows.items():
+ for variable in INDEX_VARIABLES:
+ if variable in (workflow.get("env") or {}):
+ problems.append(f"{file}: {variable} is set for the whole workflow")
+ for name, job in workflow["jobs"].items():
+ for variable in INDEX_VARIABLES:
+ if variable in (job.get("env") or {}):
+ problems.append(f"{file} / {name}: {variable} is set for the whole job")
+ for step in job.get("steps", []):
+ environment = step.get("env") or {}
+ if "PIP_INDEX_URL" in environment:
+ problems.append(
+ f"{file} / {name} / {step.get('name')!r}: PIP_INDEX_URL drops PyPI as "
+ "the main index; use PIP_EXTRA_INDEX_URL"
+ )
+ if "PIP_EXTRA_INDEX_URL" in environment and id(step) not in in_scope:
+ problems.append(
+ f"{file} / {name} / {step.get('name')!r}: sets PIP_EXTRA_INDEX_URL but "
+ "installs no torch"
+ )
+ if "download.pytorch.org" in str(step.get("run", "")):
+ problems.append(
+ f"{file} / {name} / {step.get('name')!r}: names PyTorch's index on a "
+ "command line; set PIP_EXTRA_INDEX_URL in the step's env instead"
+ )
+ return problems
+
+
+def _install_step(workflows: dict[str, Any], file: str, job: str) -> dict[str, Any]:
+ (step,) = [s for f, j, s in _torch_steps(workflows) if (f, j) == (file, job)]
+ return step
+
+
+class TestTheReaderHasTeeth:
+ """CONTROL for the tests below: each mutation of a copy of the real workflows is reported."""
+
+ @pytest.mark.parametrize(
+ ("command", "expected"),
+ [
+ ('pip install -e ".[dev]"', True),
+ ('pip install -e ".[train]" -c pins.txt', True),
+ ('pip install -e ".[dev,audio]" -c floor.txt', True),
+ ('pip install -e ".[dev,qat]" "torch>=2.6.0"', True),
+ ('pip install -e "." "torch>=2.6.0"', True),
+ ("pip install -e .", False),
+ ("pip install -e . pytest", False),
+ ('pip install -e ".[mlx]" pytest', False),
+ ("pip install ruff", False),
+ ("pip install -e . huggingface-hub pyyaml", False),
+ ],
+ )
+ def test_it_knows_what_installs_torch(self, command, expected):
+ pyproject = PYPROJECT.read_text(encoding="utf-8")
+ assert _installs_torch(command, pyproject) is expected, command
+
+ def test_the_test_job_runs_on_all_three_systems_and_only_linux_gets_the_index(self):
+ workflows = _workflows()
+ job = workflows["ci.yml"]["jobs"]["test"]
+ assert sorted(_cells(workflows, "ci.yml", job)) == [
+ "macos-latest",
+ "ubuntu-latest",
+ "windows-latest",
+ ]
+ step = _install_step(workflows, "ci.yml", "test")
+ assert _index_of(step, "ubuntu-latest") == CPU_INDEX
+ assert _index_of(step, "windows-latest") == ""
+ assert _index_of(step, "macos-latest") == ""
+
+ def test_a_missing_index_on_a_linux_job_is_reported(self):
+ workflows = copy.deepcopy(_workflows())
+ _install_step(workflows, "ci.yml", "pytorch-smoke")["env"].pop("PIP_EXTRA_INDEX_URL")
+ (problem,) = _problems(workflows)
+ assert "ci.yml / pytorch-smoke" in problem and "expected" in problem, problem
+
+ def test_a_missing_index_on_the_linux_test_cell_is_reported(self):
+ workflows = copy.deepcopy(_workflows())
+ _install_step(workflows, "ci.yml", "test")["env"].pop("PIP_EXTRA_INDEX_URL")
+ (problem,) = _problems(workflows)
+ assert "ci.yml / test" in problem and "ubuntu-latest" in problem, problem
+
+ def test_the_index_on_every_system_is_reported_for_windows_and_macos(self):
+ workflows = copy.deepcopy(_workflows())
+ _install_step(workflows, "ci.yml", "test")["env"]["PIP_EXTRA_INDEX_URL"] = CPU_INDEX
+ problems = _problems(workflows)
+ assert len(problems) == 2, problems
+ assert any("windows-latest" in problem for problem in problems), problems
+ assert any("macos-latest" in problem for problem in problems), problems
+
+ def test_a_wrong_index_is_reported(self):
+ workflows = copy.deepcopy(_workflows())
+ step = _install_step(workflows, "recipe-attach.yml", "verify")
+ step["env"]["PIP_EXTRA_INDEX_URL"] = "https://download.pytorch.org/whl/cu130"
+ (problem,) = _problems(workflows)
+ assert "recipe-attach.yml / verify" in problem, problem
+
+ def test_an_exempt_job_that_takes_the_index_is_reported(self):
+ workflows = copy.deepcopy(_workflows())
+ step = _install_step(workflows, "ci.yml", "torchao-contract")
+ step["env"] = {"PIP_EXTRA_INDEX_URL": CPU_INDEX}
+ (problem,) = _problems(workflows)
+ assert "torchao-contract" in problem and "expected ''" in problem, problem
+
+ def test_a_new_job_that_installs_torch_is_reported_until_it_has_the_index(self):
+ workflows = copy.deepcopy(_workflows())
+ workflows["ci.yml"]["jobs"]["new-job"] = {
+ "runs-on": "ubuntu-latest",
+ "steps": [{"name": "Install", "run": 'pip install -e ".[train]"'}],
+ }
+ (problem,) = _problems(workflows)
+ assert "new-job" in problem, problem
+ workflows["ci.yml"]["jobs"]["new-job"]["steps"][0]["env"] = {
+ "PIP_EXTRA_INDEX_URL": CPU_INDEX
+ }
+ assert _problems(workflows) == []
+
+ def test_the_index_for_a_whole_job_or_workflow_is_reported(self):
+ for place in ("job", "workflow"):
+ workflows = copy.deepcopy(_workflows())
+ target = workflows["ci.yml"]["jobs"]["lint"] if place == "job" else workflows["ci.yml"]
+ target.setdefault("env", {})["PIP_EXTRA_INDEX_URL"] = CPU_INDEX
+ (problem,) = _problems(workflows)
+ assert f"whole {place}" in problem, problem
+
+ def test_pypi_as_the_main_index_dropped_is_reported(self):
+ workflows = copy.deepcopy(_workflows())
+ step = _install_step(workflows, "ci.yml", "pytorch-smoke")
+ step["env"]["PIP_INDEX_URL"] = CPU_INDEX
+ (problem,) = _problems(workflows)
+ assert "PIP_INDEX_URL drops PyPI" in problem, problem
+
+ def test_the_index_on_a_step_that_installs_no_torch_is_reported(self):
+ workflows = copy.deepcopy(_workflows())
+ (step,) = [
+ s
+ for s in workflows["ci.yml"]["jobs"]["lint"]["steps"]
+ if str(s.get("run", "")) == "pip install ruff"
+ ]
+ step["env"] = {"PIP_EXTRA_INDEX_URL": CPU_INDEX}
+ (problem,) = _problems(workflows)
+ assert "installs no torch" in problem, problem
+
+ def test_the_index_spelled_on_a_command_line_is_reported(self):
+ workflows = copy.deepcopy(_workflows())
+ step = _install_step(workflows, "ci.yml", "pytorch-smoke")
+ step["run"] += f" --extra-index-url {CPU_INDEX}"
+ problems = _problems(workflows)
+ assert any("names PyTorch's index on a command line" in line for line in problems), problems
+
+
+class TestTheCommittedWorkflows:
+ def test_every_step_that_installs_torch_picks_its_index_by_operating_system(self):
+ assert _problems(_workflows()) == []
+
+ def test_the_jobs_that_install_torch_are_exactly_the_ones_named_here(self):
+ """A new job that installs torch is on neither list until someone decides."""
+ installing = {(file, name) for file, name, _ in _torch_steps(_workflows())}
+ assert installing == ON_CPU_INDEX | LEFT_ON_PYPI.keys()
+ assert not ON_CPU_INDEX & LEFT_ON_PYPI.keys()
+
+ def test_each_job_on_the_cpu_index_installs_on_linux(self):
+ workflows = _workflows()
+ for file, name in sorted(ON_CPU_INDEX):
+ job = workflows[file]["jobs"][name]
+ assert "Linux" in {RUNNER_OS[label] for label in _cells(workflows, file, job)}, name
+
+ @pytest.mark.parametrize("file", ["pinned-upstream.txt", "transformers-floor.txt"])
+ def test_the_torch_pins_are_public_versions_a_cpu_wheel_satisfies(self, file):
+ """``torch==2.6.0+cu124`` would refuse the CPU wheel; ``torch==2.6.0`` accepts it."""
+ text = (CONSTRAINTS / file).read_text(encoding="utf-8")
+ pins = dict(re.findall(r"^([A-Za-z0-9_-]+)==(\S+)\s*$", text, re.M))
+ assert "torch" in pins, file
+ for name in sorted(TORCH_PACKAGES & pins.keys()):
+ assert Version(pins[name]).local is None, (file, name, pins[name])
+ assert SpecifierSet(f"=={pins[name]}").contains(f"{pins[name]}+cpu"), (file, name)
+
+
+def _floor_script() -> str:
+ """The Python the floor job runs to compare installed versions with its constraints."""
+ steps = _workflows()["ci.yml"]["jobs"]["transformers-floor"]["steps"]
+ (step,) = [
+ s for s in steps if s.get("name") == "Assert installed versions match floor constraints"
+ ]
+ match = re.search(r"<<'PY'\n(.*?)\nPY\s*$", str(step["run"]), re.S)
+ assert match is not None, step["run"]
+ return match.group(1)
+
+
+def _run_floor_script(monkeypatch: pytest.MonkeyPatch, versions: dict[str, str]) -> None:
+ monkeypatch.chdir(ROOT)
+ monkeypatch.setattr(importlib.metadata, "version", lambda name: versions[name])
+ exec(compile(_floor_script(), "<transformers-floor assertion>", "exec"), {"__name__": "x"})
+
+
+class TestTheFloorJobReadsThePublicVersion:
+ """``torch==2.6.0`` installs ``2.6.0+cpu`` from the CPU index, and ``md.version`` says so."""
+
+ @staticmethod
+ def _pins() -> dict[str, str]:
+ text = (CONSTRAINTS / "transformers-floor.txt").read_text(encoding="utf-8")
+ return dict(re.findall(r"^([A-Za-z0-9_-]+)==([^\s#]+)\s*$", text, re.M))
+
+ def test_the_exact_pins_pass(self, monkeypatch):
+ _run_floor_script(monkeypatch, self._pins())
+
+ def test_the_cpu_wheels_pass(self, monkeypatch):
+ pins = self._pins()
+ versions = {
+ name: f"{pin}+cpu" if name in TORCH_PACKAGES else pin for name, pin in pins.items()
+ }
+ assert versions["torch"].endswith("+cpu") and versions["torchaudio"].endswith("+cpu")
+ _run_floor_script(monkeypatch, versions)
+
+ @pytest.mark.parametrize(
+ ("name", "drifted"),
+ [
+ ("torch", "2.6.1+cpu"),
+ ("torch", "2.6.1"),
+ ("torchaudio", "2.7.0+cpu"),
+ ("transformers", "5.16.2"),
+ ("typer", "0.16.0"),
+ ],
+ )
+ def test_a_drifted_version_still_fails(self, monkeypatch, name, drifted):
+ versions = dict(self._pins())
+ assert versions[name] != drifted
+ versions[name] = drifted
+ with pytest.raises(AssertionError, match=f"floor job expected {name}=="):
+ _run_floor_script(monkeypatch, versions)
diff --git a/tests/test_issue842_checkpoint_visible_nf4.py b/tests/test_issue842_checkpoint_visible_nf4.py
index 24a58e29..d78ddd89 100644
--- a/tests/test_issue842_checkpoint_visible_nf4.py
+++ b/tests/test_issue842_checkpoint_visible_nf4.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import ast
+import importlib.util
import os
import sys
@@ -154,14 +156,316 @@ def test_production_capability_gate_keeps_cpu_on_the_old_path():
assert _can_use_checkpoint_visible_nf4_gemm(torch.randn(2, 16), state) is False
+_BNB_DISPATCH_NAMES = ("_gemm_4bit_use_custom_fn", "_gemm_4bit_custom_max_m")
+
+
+def _module_level_names(source):
+ """Names a module source binds at its top level (Assign / AnnAssign / def / class).
+
+ Walks into top-level ``if`` / ``try`` / ``with`` blocks, because bitsandbytes binds
+ the dispatch names under ``if torch.version.hip is None:`` / ``else:``. Function and
+ class bodies are not entered: a local variable is not a module attribute.
+ """
+ bound = set()
+
+ def add_target(target):
+ if isinstance(target, ast.Name):
+ bound.add(target.id)
+ elif isinstance(target, (ast.Tuple, ast.List)):
+ for element in target.elts:
+ add_target(element)
+ elif isinstance(target, ast.Starred):
+ add_target(target.value)
+
+ def visit(statements):
+ for node in statements:
+ if isinstance(node, ast.Assign):
+ for target in node.targets:
+ add_target(target)
+ elif isinstance(node, ast.AnnAssign):
+ if node.value is not None:
+ add_target(node.target)
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ bound.add(node.name)
+ elif isinstance(node, ast.If):
+ visit(node.body)
+ visit(node.orelse)
+ elif isinstance(node, (ast.Try, ast.TryStar)):
+ visit(node.body)
+ for handler in node.handlers:
+ visit(handler.body)
+ visit(node.orelse)
+ visit(node.finalbody)
+ elif isinstance(node, (ast.With, ast.AsyncWith)):
+ visit(node.body)
+
+ visit(ast.parse(source).body)
+ return bound
+
+
+def _missing_module_level_names(source, names):
+ """The entries of ``names`` that ``source`` does not bind at module level."""
+ bound = _module_level_names(source)
+ return [name for name in names if name not in bound]
+
+
+def _locate_bnb_cuda_ops_source():
+ """Path of ``bitsandbytes/backends/cuda/ops`` (module or package), without importing it.
+
+ Returns ``None`` only when bitsandbytes is not installed (the caller skips). When it
+ IS installed and the module is not where we expect it, this fails instead of
+ skipping: bitsandbytes is an unconditional ``[train]`` dependency, so a moved or
+ renamed module is exactly the upstream change this canary exists to report.
+ """
+ spec = importlib.util.find_spec("bitsandbytes")
+ if spec is None:
+ return None
+ locations = list(spec.submodule_search_locations or [])
+ candidates = [
+ os.path.join(root, "backends", "cuda", leaf)
+ for root in locations
+ for leaf in ("ops.py", os.path.join("ops", "__init__.py"))
+ ]
+ for path in candidates:
+ if os.path.isfile(path):
+ return path
+ expected = " or ".join(candidates) or "backends/cuda/ops.py under the bitsandbytes package"
+ pytest.fail(
+ f"bitsandbytes is installed (search locations {locations}) but its CUDA ops module "
+ f"is not at the expected path {expected}. "
+ "src/soup_cli/utils/layer_stream_runtime.py (_can_use_checkpoint_visible_nf4_gemm) "
+ f"reads {' / '.join(_BNB_DISPATCH_NAMES)} from that module, so find where "
+ "bitsandbytes moved them and update this canary and that reader together.",
+ pytrace=False,
+ )
+
+
+def _canary_body():
+ # Read the source instead of importing ``bitsandbytes.backends.cuda.ops``: that module
+ # reads ``torch._C._cuda_getCurrentRawStream`` at import (bitsandbytes 0.50.2,
+ # ops.py:69), which a CPU-only torch wheel does not have, so an import would skip
+ # this canary on every CPU-wheel CI cell.
+ ops_path = _locate_bnb_cuda_ops_source()
+ if ops_path is None:
+ pytest.skip("bitsandbytes is not installed")
+
+ with open(ops_path, encoding="utf-8") as handle:
+ source = handle.read()
+
+ missing = _missing_module_level_names(source, _BNB_DISPATCH_NAMES)
+ assert not missing, (
+ f"bitsandbytes {ops_path} no longer binds {missing} at module level; "
+ "layer_stream_runtime._can_use_checkpoint_visible_nf4_gemm reads them"
+ )
+
+
def test_bitsandbytes_private_dispatch_contract_is_visible_to_cpu_ci():
+ _canary_body()
+
+
+_SAMPLE_NAMES = ("_gemm_4bit_use_custom_fn", "_gemm_4bit_custom_max_m")
+
+
+def test_dispatch_name_check_accepts_names_bound_the_way_bitsandbytes_binds_them():
+ source = (
+ "import torch\n"
+ "if torch.version.hip is None:\n"
+ " _gemm_4bit_use_custom_fn = _custom_cuda\n"
+ " _gemm_4bit_custom_max_m: int = 1536\n"
+ "else:\n"
+ " _gemm_4bit_use_custom_fn = _custom_rocm\n"
+ " _gemm_4bit_custom_max_m = 256\n"
+ )
+ assert _missing_module_level_names(source, _SAMPLE_NAMES) == []
+ defined = "def _gemm_4bit_use_custom_fn():\n pass\n_gemm_4bit_custom_max_m = 1\n"
+ assert _missing_module_level_names(defined, _SAMPLE_NAMES) == []
+
+
+ ("source", "expected_missing"),
+ [
+ ("_gemm_4bit_use_custom_fn = 1\n", ["_gemm_4bit_custom_max_m"]),
+ ("_gemm_4bit_custom_max_m = 1\n", ["_gemm_4bit_use_custom_fn"]),
+ ("", ["_gemm_4bit_use_custom_fn", "_gemm_4bit_custom_max_m"]),
+ (
+ "def helper():\n _gemm_4bit_use_custom_fn = 1\n _gemm_4bit_custom_max_m = 2\n",
+ ["_gemm_4bit_use_custom_fn", "_gemm_4bit_custom_max_m"],
+ ),
+ (
+ "_gemm_4bit_use_custom_fn: int\n_gemm_4bit_custom_max_m = 1\n",
+ ["_gemm_4bit_use_custom_fn"],
+ ),
+ (
+ "# _gemm_4bit_use_custom_fn = 1\n_gemm_4bit_custom_max_m = 1\n",
+ ["_gemm_4bit_use_custom_fn"],
+ ),
+ ],
+ ids=[
+ "missing-max-m",
+ "missing-use-custom-fn",
+ "empty-module",
+ "bound-only-inside-a-function",
+ "annotation-without-value",
+ "mentioned-only-in-a-comment",
+ ],
+)
+def test_dispatch_name_check_reports_the_name_that_is_missing(source, expected_missing):
+ assert _missing_module_level_names(source, _SAMPLE_NAMES) == expected_missing
+
+
+_FIRST, _SECOND = _SAMPLE_NAMES
+
+
+ "source",
+ [
+ f"if flag:\n {_FIRST} = 1\n{_SECOND} = 1\n",
+ f"if flag:\n pass\nelse:\n {_FIRST} = 1\n{_SECOND} = 1\n",
+ f"if flag:\n pass\nelif other:\n {_FIRST} = 1\n{_SECOND} = 1\n",
+ f"try:\n {_FIRST} = 1\nexcept ImportError:\n pass\n{_SECOND} = 1\n",
+ f"try:\n pass\nexcept ImportError:\n {_FIRST} = 1\n{_SECOND} = 1\n",
+ f"try:\n pass\nexcept ImportError:\n pass\nelse:\n {_FIRST} = 1\n{_SECOND} = 1\n",
+ f"try:\n pass\nfinally:\n {_FIRST} = 1\n{_SECOND} = 1\n",
+ f"try:\n pass\nexcept* ValueError:\n {_FIRST} = 1\n{_SECOND} = 1\n",
+ f"with context():\n {_FIRST} = 1\n{_SECOND} = 1\n",
+ f"async with context():\n {_FIRST} = 1\n{_SECOND} = 1\n",
+ (
+ "with context():\n"
+ " try:\n"
+ " if flag:\n"
+ " pass\n"
+ " else:\n"
+ f" {_FIRST} = 1\n"
+ " finally:\n"
+ " pass\n"
+ f"{_SECOND} = 1\n"
+ ),
+ ],
+ ids=[
+ "only-under-if-body",
+ "only-under-else",
+ "only-under-elif",
+ "only-under-try-body",
+ "only-under-except",
+ "only-under-try-else",
+ "only-under-finally",
+ "only-under-except-star",
+ "only-under-with",
+ "only-under-async-with",
+ "only-under-else-nested-in-try-in-with",
+ ],
+)
+def test_dispatch_name_check_enters_every_block_that_can_bind_a_module_name(source):
+ # One name is bound at the top level, the other ONLY inside the block under test, so
+ # a walker that stops descending into that block reports the second name as missing.
+ assert _missing_module_level_names(source, _SAMPLE_NAMES) == []
+
+
+def _fake_bitsandbytes_find_spec(monkeypatch, spec):
+ """Make ``importlib.util.find_spec("bitsandbytes")`` return ``spec``; others are real."""
+ real_find_spec = importlib.util.find_spec
+
+ def find_spec(name, *args, **kwargs):
+ if name == "bitsandbytes":
+ return spec
+ return real_find_spec(name, *args, **kwargs)
+
+ monkeypatch.setattr(importlib.util, "find_spec", find_spec)
+
+
+def _installed_bitsandbytes(root):
+ from types import SimpleNamespace
+
+ return SimpleNamespace(submodule_search_locations=[str(root)])
+
+
+def _outcome_of(call):
+ """Run ``call``; report ``("failed" | "skipped" | "passed", message)``.
+
+ ``pytest.raises`` would let a ``skip`` escape, and a skipped test is not a red one: a
+ canary that went back to skipping would then read as "not failed" instead of failing
+ this test. Catching both outcomes lets the test assert on the outcome itself.
+ """
try:
- from bitsandbytes.backends.cuda import ops as bnb_cuda_ops
- except (ImportError, AttributeError) as exc:
- pytest.skip(f"bitsandbytes CUDA ops cannot import with this torch build: {exc}")
+ call()
+ except pytest.fail.Exception as error:
+ return "failed", str(error)
+ except pytest.skip.Exception as error:
+ return "skipped", str(error)
+ return "passed", ""
+
+
+def test_ops_locator_skips_only_when_bitsandbytes_is_not_installed(monkeypatch):
+ _fake_bitsandbytes_find_spec(monkeypatch, None)
+ assert _locate_bnb_cuda_ops_source() is None
+ outcome, message = _outcome_of(_canary_body)
+ assert (outcome, message) == ("skipped", "bitsandbytes is not installed")
+
+
+def test_ops_locator_fails_when_bitsandbytes_is_installed_but_ops_module_moved(
+ monkeypatch, tmp_path
+):
+ cuda_dir = tmp_path / "backends" / "cuda"
+ cuda_dir.mkdir(parents=True)
+ (cuda_dir / "ops_renamed.py").write_text(
+ f"{_FIRST} = 1\n{_SECOND} = 2\n", encoding="utf-8"
+ )
+ _fake_bitsandbytes_find_spec(monkeypatch, _installed_bitsandbytes(tmp_path))
+
+ outcome, message = _outcome_of(_locate_bnb_cuda_ops_source)
+
+ assert outcome == "failed", (outcome, message)
+ assert os.path.join(str(tmp_path), "backends", "cuda", "ops.py") in message
+ assert "src/soup_cli/utils/layer_stream_runtime.py" in message
+ assert _FIRST in message and _SECOND in message
+ # The canary itself must fail the same way, not skip.
+ assert _outcome_of(_canary_body)[0] == "failed"
+
+
[email protected]("locations", [None, []], ids=["no-locations", "empty-locations"])
+def test_ops_locator_fails_when_an_installed_bitsandbytes_has_no_search_locations(
+ monkeypatch, locations
+):
+ from types import SimpleNamespace
+
+ spec = SimpleNamespace(submodule_search_locations=locations)
+ _fake_bitsandbytes_find_spec(monkeypatch, spec)
+
+ outcome, message = _outcome_of(_locate_bnb_cuda_ops_source)
+
+ assert outcome == "failed", (outcome, message)
+ assert "backends/cuda/ops.py" in message
+ assert "src/soup_cli/utils/layer_stream_runtime.py" in message
+
+
+ "relative_path",
+ [("backends", "cuda", "ops.py"), ("backends", "cuda", "ops", "__init__.py")],
+ ids=["ops-module", "ops-package"],
+)
+def test_ops_locator_finds_the_module_as_a_file_or_a_package(
+ monkeypatch, tmp_path, relative_path
+):
+ ops_file = tmp_path.joinpath(*relative_path)
+ ops_file.parent.mkdir(parents=True)
+ ops_file.write_text("", encoding="utf-8")
+ _fake_bitsandbytes_find_spec(monkeypatch, _installed_bitsandbytes(tmp_path))
+
+ assert _locate_bnb_cuda_ops_source() == str(ops_file)
+
+
+def test_canary_reads_the_names_from_the_located_ops_source(monkeypatch, tmp_path):
+ ops_file = tmp_path / "backends" / "cuda" / "ops.py"
+ ops_file.parent.mkdir(parents=True)
+ _fake_bitsandbytes_find_spec(monkeypatch, _installed_bitsandbytes(tmp_path))
+
+ ops_file.write_text(f"{_FIRST} = 1\n{_SECOND} = 2\n", encoding="utf-8")
+ assert _outcome_of(_canary_body) == ("passed", "")
- assert hasattr(bnb_cuda_ops, "_gemm_4bit_use_custom_fn")
- assert hasattr(bnb_cuda_ops, "_gemm_4bit_custom_max_m")
+ ops_file.write_text(f"{_FIRST} = 1\n", encoding="utf-8")
+ with pytest.raises(AssertionError, match=_SECOND) as excinfo:
+ _canary_body()
+ assert str(ops_file) in str(excinfo.value)
@pytest.mark.parametrize(