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
Lift the transformers ceiling to 5.17.0 and align the mirrored CI caps (#11016)
Daniel Han9f85f534e1b7
diff --git a/.github/workflows/notebooks-ci.yml b/.github/workflows/notebooks-ci.ymlindex 703983799d0..e9f46bb2321 100644--- a/.github/workflows/notebooks-ci.yml+++ b/.github/workflows/notebooks-ci.yml@@ -351,18 +351,11 @@ jobs:# to let torchvision pull the right Pillow version.pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \'torch>=2.8,<2.11' 'torchvision<0.26'- # Pin to the same versions update_all_notebooks.py installs in- # generated notebooks. Keep these in lockstep with PIN_TRL /- # PIN_TRANSFORMERS in unslothai/notebooks/update_all_notebooks.py.- # `triton` because unsloth/kernels and unsloth_zoo's compiler and- # loss_utils import it at module scope, so `import unsloth` needs it- # even though _gpu_init.py treats it as optional. Same rationale as- # consolidated-tests-ci.yml line 192-205.- # Pillow is listed explicitly as a defensive belt-and-braces- # next to torchvision (vision_utils crashes ModuleNotFoundError- # if torchvision skipped its Pillow dep for any reason).- pip install 'transformers>=4.56,<5.6' 'trl>=0.22,<0.26' 'accelerate>=1.0' \- 'datasets>=3.4,<5' 'peft>=0.15,<0.20' \+ # Keep in lockstep with PIN_TRL / PIN_TRANSFORMERS in unslothai/notebooks/update_all_notebooks.py+ # and pyproject's caps. triton: `import unsloth` needs it at module scope.+ # datasets must exclude 4.4.0-4.5.0 (patch_datasets raises NotImplementedError there).+ pip install 'transformers>=4.56,<=5.17.0' 'trl>=0.22,<=1.13.0' 'accelerate>=1.0' \+ 'datasets>=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0' 'peft>=0.15,<0.20' \'bitsandbytes>=0.43' 'sentencepiece' 'protobuf' triton \Pillow safetensors tqdm packaging psutil# Converter deps (nbformat for notebook_to_python.py).diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.ymlindex a7a4cc919e5..7a03d2c763d 100644--- a/.github/workflows/studio-backend-ci.yml+++ b/.github/workflows/studio-backend-ci.yml@@ -1,31 +1,9 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-# Runs the existing studio/backend/tests/ suite (~860 tests, all CPU-friendly)-# on every PR that touches the backend or unsloth library. Until this lands,-# none of those tests run automatically. Verified locally on Python 3.13 with-# the surgical exclusions below: 861 pass, 4 skipped.+# Runs studio/backend/tests/ except the live-model / live llama.cpp tests.#-# Exclusions:-# - tests/test_studio_api.py: end-to-end against a live model + GGUF download,-# too heavy for free runners. Run separately when GPU CI is available.-# - -k 'not llama_cpp_load_progress_live': spawns a real llama.cpp process,-# not appropriate for CPU-only runners.-#-# Two jobs:-# - pytest on 3.13 over studio/backend/tests, with the floor checked statically-# - repo-cpu-tests: auto-discovered tests/ + state-isolated spoof files-#-#-# runs-on: ubuntu-24.04, not ubuntu-latest. Same image, so the jobs are unchanged; different-# queue, because nearly all of the org's ~871 queued runs ask for ubuntu-latest. Identical-# no-op jobs in one matrix: ubuntu-latest still queued past 40 min, every other label under-# 2 min (#10914). Cost: the image no longer tracks the fleet default, so bump it for 26.04.-#-# Whole-repo Python lint (syntax + ruff + debugger-leftover scan)-# moved to the dedicated `Lint CI` workflow (.github/workflows/lint-ci.yml)-# so it fires on every PR rather than only on studio/unsloth/tests-# path changes.+# ubuntu-24.04, not ubuntu-latest: far shorter org queue (#10914).name: Backend CI@@ -39,20 +17,12 @@ on:# The validate_studio_features.py step below guards docker/jupyter and the# docker notebook helpers, so a docker-only change must trigger this CI.- 'docker/**'- # The root installers: tests/sh/*.sh and tests/studio/install/* assert- # against these two files, so a change here must run the suite that- # covers it. Without them an install-only edit (the shape most AMD/ROCm- # routing fixes take) skipped Backend CI entirely.+ # tests/sh/*.sh and tests/studio/install/* assert against these two files.- 'install.sh'- 'install.ps1'- 'scripts/**'- 'pyproject.toml'- # Nine tests under tests/studio read .github/actions/*/action.yml and assert- # properties of those composite actions: cache naming, install phase timing, uv and- # pip cache discipline, and the unsloth_zoo revision notice. This is the suite that- # covers them, and without this entry an action-only change ran Core, which does not- # execute tests/studio, and skipped Backend CI, which does. The guards were then- # absent for exactly the change they guard. Same reason as install.sh above.+ # tests/studio asserts properties of .github/actions/*/action.yml.- '.github/actions/**'# Test inputs, not sources: tests/python/test_docker_publish_tag_scheme.py and# test_docker_publish_ref_freeze.py read docker-publish.yml, and@@ -134,38 +104,15 @@ concurrency:# Unique per commit on main, so a merge burst cannot cancel a pending run# before it starts. See the note below for what this is buying.group: ${{ github.workflow }}-${{ github.ref }}-${{ github.ref == 'refs/heads/main' && github.sha || '' }}- # On a PR branch: latest-only, which is what cancel-in-progress buys.- #- # On main it buys less than it looks like. GitHub cancels any PENDING run in a- # concurrency group as soon as a newer one is queued, and cancel-in-progress- # governs only runs that are already EXECUTING ("any existing pending job or- # workflow in the same concurrency group will be canceled", workflow-syntax docs).- # So a burst of merges leaves only the tip's run alive: on 2026-08-17 four merges- # in 37 minutes cancelled three consecutive main runs of this workflow and none- # completed. Detection survives on the tip, since the tree is cumulative;- # per-commit attribution does not.cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}permissions:contents: readenv:- # The oldest interpreter this code is expected to run on.- #- # Nothing executes it any more. The 3.10, 3.11 and 3.12 legs ran the same suite as 3.13- # and differed by exactly one skip marker, at 97 runner-minutes per push against a queue- # that has been observed 195 deep, so they are gone and the wall-clock they were costing- # every other workflow is gone with them.- #- # What they were really defending is that nothing reaches for a symbol newer than this,- # which is static, and scripts/lint_backend_python_floor.py now checks it here on every- # pull request in seconds across 1093 files. Raise this number only with a reason, and- # remember that raising it is a support decision, not a CI one.- #+ # Oldest supported interpreter; checked statically by scripts/lint_backend_python_floor.py.# 3.10 rather than the 3.9 pyproject.toml declares, because 3.9 is not true today:# unsloth/models/_utils.py uses dataclasses.dataclass(kw_only) and- # tempfile.TemporaryDirectory(ignore_cleanup_errors), both 3.10. Reconciling those two- # is worth doing separately; this lint is what made it visible.PYTHON_FLOOR: '3.10'@@ -173,107 +120,15 @@ jobs:pytest:name: (Python ${{ matrix.python }}, ${{ matrix.shard }})runs-on: ubuntu-24.04- # 45 guards against a hang; it is not a performance budget. The comment this replaces- # claimed 14.1 to 15.0 minutes against a limit of 30, but this step now measures 22.5 to- # 29.2 minutes across the matrix, and it has been cancelling at the limit: across the six- # open PRs on this branch's stack, five had one leg cancelled at 30m9s while its siblings- # passed at 25 to 29 minutes. Which leg loses is luck, so every PR carries a red check- # that says nothing about the PR.- # Running it on all four cores would fix the duration properly and is worth ~79- # runner-minutes a push, but this suite is not order-independent enough yet. Measured- # under `-n 4` on a 4-vCPU runner it fails tests serial does not, in more than one way and- # not the same way twice. The repo job below IS order-independent and does run parallel;- # this one waits until those dependencies are found and fixed individually. Raising the- # limit costs nothing until a job actually needs it, and a cancelled leg costs the whole- # 30 minutes anyway.- #- # This cap is the last line, not the first one. It reports the word "cancelled" and- # names nothing, which is how a single deadlocked test held main red for forty hours- # (run 32385375389 onward) while the step timings said the suite itself still finished- # its work in six minutes. The per-test --timeout below is what actually names a hang;- # this stays as the backstop for a wedge the per-test timer cannot see, such as one in- # collection or in a worker that never comes up.- #- # Unchanged by the split below, deliberately. A shard does less work than the leg it- # came from, so 45 only gets looser, and retuning it on a prediction is the failure- # this number was raised to fix: the sharded spread has not been measured on a runner- # yet. Retune it once there are runs to retune it against.+ # Hang backstop, not a performance budget; the per-test --timeout names hangs.timeout-minutes: 45strategy:- # fail-fast off: three shards of one suite, and cancelling the other two on the first- # failure would hide which of them were also red. It was already off for the- # 3.13/3.11 pair, for the same reason.fail-fast: falsematrix:- # 3.13 only, on pull requests and on main alike.- #- # Measured on one runner over the same tree: the four legs collected the same- # 26,320 tests and differed by exactly ONE of them, the >= 3.12 gate on- # test_demonstrates_the_underlying_stdlib_regression. 3.10 and 3.11 reported- # 26193 passed / 127 skipped, 3.12 and 3.13 reported 26194 / 126. Four legs cost- # 97 runner-minutes per push (1663 + 1249 + 1419 + 1506 seconds) against a queue- # that has been observed 195 deep, to re-run one identical suite four times and- # learn the value of a single skip marker.- #- # What the older legs were really defending is that nothing in the tree reaches- # for a symbol newer than the floor, and that is a static property. It is now- # checked statically, on every pull request, in seconds, by- # scripts/lint_backend_python_floor.py, which reads stdlib API availability- # rather than syntax alone and covers 1093 shipped and executed files.- #- # A static check does not run anything, though, and that part cannot be waved- # away: two interpreters that both accept a line can still behave differently on- # it, and a sys.version_info branch is only ever parsed, never taken.- #- # So the branches were counted rather than assumed. Seven backend files carry one, at- # 3.10, 3.12 and 3.14. The 3.10 ones were never straddled even by the old matrix- # (oldest leg 3.10), and 3.14 is above every leg there has ever been. What is- # genuinely lost is the PRE-3.12 side of three files.- #- # Hence the second entry: 3.11, the newest version still on that side, running those- # three files and nothing else. Roughly 40 tests in under ten seconds, beside the full- # leg rather than in front of it, so the critical path is unchanged.- #- # The 3.13 leg is three shards of one selection, balanced on measured time rather than- # file count, for the reason repo-cpu-tests was split below: it is now the longest- # thing a pull request waits for, at 763-822s parallel plus 201-234s serial.- #- # Summed test time is 1886.1s across 922 files (`--durations=0 --durations-min=0`,- # -n 16; the default 0.005s cutoff hides ~105,000 durations and is unusable here),- # split on the first letter after `test_`:- #- # a-k 542.8s 396 files 28.8%- # l-r 693.7s 318 files 36.8%- # s-z + every subdirectory 649.6s 208 files 34.4%+ # 3.13 full run, plus 3.11 for the files with a pre-3.12 sys.version_info branch.#- # so the longest shard is 1.103x an ideal third. The letters are lumpy (l is 217.2s,- # t is 280.4s, multi_account's 159.3s is stuck in the catch-all) and no contiguous- # split does better. A hand-picked letter SET reaches 1.001x and is not worth it: an- # allowlist tuned to one measurement is what the shape below exists to avoid.- #- # The shape. All three shards root at `tests/` and differ only in what they ignore:- # `--ignore=FILE` does NOT filter a file passed as an explicit argument (checked- # against pytest), so a shard rooted at an expanded glob would drag the twelve serial- # files back in past the shared --ignore list below. Shards 1 and 2 name their range- # and exclude everything else, including names outside a-z and anything below a- # subdirectory. Shard 3 is "tests/ minus the other two ranges", never an allowlist, so- # a new file lands in exactly one shard with no workflow edit: test_apple.py in 1,- # test_monkey.py in 2, and test_snake.py, tests/a_new_dir/test_x.py, foo_test.py and- # test_Zebra.py in 3. test_ci_backend_pytest_shards.py fails if that stops holding,- # and test_backend_ci_parallel_isolation.py fails if a shard collects one of the twelve.- #- # Two name shapes the split cannot absorb, forbidden by name in that guard rather than- # left to be discovered: a subdirectory called test_*, and a file matching BOTH- # discovery patterns (test_api_test.py). Each lands in no shard, because fnmatch's *- # crosses / and the suffix rule cannot say "unless it starts with test_" in one pattern.- # Diverging per prefix character was tried and reverted: it fixes test_api_test.py but- # over-consumes te_test.py into BOTH ranged shards, and completing it needs nine globs- # per shard for a filename this repo does not use.- #- # Verified at the level of the test id, not the count: the unsharded selection and the- # three shards run with --junitxml and the reports diffed gave 13,073 + 17,483 + 12,053- # = 42,609 against the baseline's 42,609, no id in two shards or in neither, and the- # same 332 skipped and 386 errored.+ # Shards root at `tests/` and differ only in ignores: `--ignore=FILE` does not filter explicit arguments.+ # Shard 3 is the remainder, so new files land in exactly one shard (test_ci_backend_pytest_shards.py).include:- python: '3.13'scope: full@@ -357,116 +212,38 @@ jobs:pyyaml jinja2 mammoth unpdf requests \'numpy<3' pytest pytest-asyncio pytest-xdist pytest-timeout httpx \soundfile librosa- # pytest-timeout: see the --timeout flags below. Without it a test that never- # returns is indistinguishable from a slow suite, and the job reports only- # "cancelled".# soundfile + librosa: test_audio_dataset_decode importorskips both, so without# them the no-torchcodec decode path is silently untested here.- # Torch CPU + transformers are required by a chunk of the backend test- # suite (gpu_selection, kv_cache_estimation, utils). CPU-only torch- # keeps the install ~250 MB / ~1 min on a clean runner.pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \'torch>=2.4,<2.11' 'torchaudio<2.11'- pip install 'transformers>=4.51,<5.5'- # peft: core/inference/inference.py imports it at module scope, and it is listed- # only in extras-no-deps.txt and no-torch-runtime.txt, neither of which this job- # installs. Without it every importorskip of that module SKIPS instead of running,- # which is invisible: test_safetensors_reasoning_stream.py reported 10 passed and- # 3 skipped here, green. Stubbing it instead does not work -- transformers probes+ # Tracks pyproject.toml's cap.+ pip install 'transformers>=4.51,<=5.17.0'+ # peft: imported at module scope by core/inference/inference.py but listed only in+ # files this job does not install, so without it every importorskip of that module+ # SKIPS and stays green. A stub does not work: transformers probes# `importlib.util.find_spec("peft")`, which raises on a stub whose __spec__ is None.- # AFTER the CPU torch line above, not before it: peft depends on torch, so pip- # would resolve that from PyPI, and the CUDA wheel it picks satisfies the range- # the next line asks for, leaving this nominally CPU-only job carrying the CUDA- # distribution and its nvidia-* dependencies.- # The version comes from the requirements file rather than being written here:- # extras-no-deps.txt pins peft==0.18.1 deliberately (0.19.0 breaks Unsloth's- # export subprocess), and an unconstrained install takes the newest release,- # so this job would test against a peft production never ships and no other- # job installs. Read out of the file so the two cannot drift apart.+ # After the CPU torch line: peft depends on torch, so earlier it would pull the CUDA wheel into+ # this CPU job. Version read from extras-no-deps.txt (pinned: peft 0.19.0 breaks the export subprocess).pip install "$(grep -m1 -E '^peft==' studio/backend/requirements/extras-no-deps.txt)"- # torchao: the pre-quant allowlist is built by importing the torchao tensor- # constructors a checkpoint names, and registration refuses unless at least one of- # them resolves. Without it every pre-quant load returns None and 21 tests across- # test_diffusion_prequant.py and test_diffusion_convrot.py fail on an install that is- # simply missing a dependency they need. CPU-only is fine: it declines to load its cpp+ # torchao: the pre-quant allowlist is built by importing the tensor constructors a+ # checkpoint names, and registration refuses unless one resolves, so without it+ # every pre-quant load returns None. CPU-only is fine: it declines its cpp# extensions under torch < 2.11 and the pure-Python constructors still import.pip install torchao- name: Backend testsif: matrix.scope == 'full'working-directory: studio/backend- # Locally validated against this dep set: 831 passed, 5 skipped, 35 deselected.- # Deselections (all environment-specific, would never pass on a GPU-less- # `ubuntu-latest` runner regardless of code correctness):- # - llama_cpp_load_progress_live: spawns a real llama.cpp process- # - TestGpuAutoSelection / TestPreSpawnGpuResolution / TestPerGpuFitGuardAllCounts:- # require live transformers config introspection on real GPUs- # - TestTransformersIntrospection: same- # - test_returns_cuda_when_cuda_available / test_calls_cuda_cache_when_cuda:- # assume CUDA-capable GPU- #- # -n 4: 1322.6s -> 343.0s locally on the same 4-worker shape as the runner, with- # an IDENTICAL result -- 51 failed / 26190 passed serial against 51 failed /- # 26188 passed parallel, and the two failure sets compared equal name for name,- # so nothing here depends on the order it runs in. (Those 51 are a local- # environment missing peft and a diffusers pin; the point is that the two modes- # agree, not the count.) Same shape as repo-cpu-tests below, which has run -n 4- # since it measured 806s -> 220s.+ # Deselections need a real GPU or a live llama.cpp process.#- # Unit tests, so this is CPU and not memory bound: the job installs --no-torch- # style CPU wheels and loads no model, unlike the inference smoke workflows- # where four workers on one runner would not fit.+ # -n 4 verified order-independent (same failure set as serial).## test_streaming_stripper is ignored here and run serially below, for the reason- # repo-cpu-tests already isolates load_freeze: it compares its own measured cost- # against a reference implementation timed in the same process, and a worker- # descheduled by the other three inflates one side of that ratio. Observed on- # staging, where the 3.10 leg reported "early markup cost 1.354s against the- # reference's 0.854s" while 3.13 passed the same commit.- #- # The other two assert ABSOLUTE elapsed time, and tightly: 50ms for a- # short-circuit that should not run at all, and 100ms for a regex backtracking- # guard. Bounds that small are inside one scheduler quantum, so under four- # workers they measure the scheduler as much as the code. Bounds of 0.5s and up- # are left in the parallel run; there are 22 files with elapsed-time bounds and- # serialising all of them would give back most of what this change buys. The- # isolation guard scans for the tight ones, so a new test below the threshold- # fails that guard instead of flaking here.- #- # test_media_auto_switch has a 0.4s budget that xdist scheduling can exceed.- # test_pr5624_regressions exceeded its 1s R1 parser bound in two contended runs.- #- # --timeout: a per-test wall-clock cap, so a test that never returns fails with its- # own name in the summary instead of taking the job's 45 minutes down with it and- # reporting "cancelled". 330s comes off the measured distribution rather than taste:- # the slowest legitimate test in this suite is- # test_conversation_archive.py::test_the_newest_revision_survives_a_tied_run_LONGER_than_the_cap- # at 82.5s (measured under -n 4 on a contended box; 75.4s serially), and the next- # ones down are 76s and 25s, so the cap is 4x the worst real test. Nothing here is- # near it, and a deadlock is caught in minutes rather than never.+ # Wall-clock-bound files run isolated; the isolation guard catches new tight bounds.#- # --timeout arms inside each xdist worker, so a stuck CONTROLLER escapes it: when a- # worker wedges holding the pipe, the session waits forever and no per-test cap is- # consulted. On the #9473 branch this step sat silent from 95% for 36.8 minutes,- # three runs running, each burning the whole 45 minute budget and reporting- # "cancelled" -- unreadable against ordinary concurrency supersession.+ # Outer `timeout` catches a wedged xdist controller that per-test --timeout cannot; SIGINT dumps the stuck frame.#- # So bound the session from outside, where a wedged worker cannot defeat it. SIGINT- # first so pytest dumps where it was stuck, SIGKILL 60s later if it will not.- # Reproduced with a test forking a child that never exits: unwrapped it hangs- # silently, wrapped it exits 124 through execnet safe_terminate -> workerpool.waitall.- # Expect a stuck FRAME, not always a test name. 1500s is ~3x the 8-10 minute norm.- #- # The thirteen --ignore flags and the -k filter stay HERE rather than moving into- # the matrix: they are the selection every shard inherits, and one copy of them is- # what makes "the twelve serial files are ignored by every parallel shard" a- # property of the step instead of three lists that have to agree. The shards differ- # only in `${{ matrix.selection }}`.- #- # The outer 1500s is not retuned on a prediction, for the reason repo-cpu-tests- # gives below: a bound that lands inside the real spread is the failure this kind of- # number exists to prevent, and the sharded spread has not been measured on a runner- # yet. It only ever gets looser as the work per shard drops.+ # Shared selection lives here so every shard inherits one list; shards differ only in matrix.selection.run: |timeout --signal=INT --kill-after=60 1500 \python -m pytest ${{ matrix.selection }} -q --tb=short -n 4 --dist loadgroup --timeout=330 \@@ -487,11 +264,7 @@ jobs:-k 'not llama_cpp_load_progress_live and not TestGpuAutoSelection and not TestPreSpawnGpuResolution and not TestPerGpuFitGuardAllCounts and not TestTransformersIntrospection and not test_returns_cuda_when_cuda_available and not test_calls_cuda_cache_when_cuda'- name: Backend tests that cannot share a worker- # One shard, one process, the same twelve files. Not split and not redistributed:- # whether any of them could go back into the parallel run was asked separately and- # the answer was no, so this step is carried unchanged and only has to be carried- # ONCE. a-k because it is the shortest shard at 28.8% of summed test time, and this- # step is 201-234s: it lands there rather than on the 36.8% shard.+ # The twelve serial files, one process.if: matrix.scope == 'full' && matrix.shard == 'a-k'working-directory: studio/backend# Relative timing against a reference measured in the same process. Serial, so the@@ -515,17 +288,6 @@ jobs:- name: Pre-3.12 branches, on the newest interpreter that takes themif: matrix.scope == 'floor-spot-check'working-directory: studio/backend- # Not a second copy of the suite. Seven backend files carry a sys.version_info- # branch, at 3.10, 3.12 and 3.14. The 3.10 ones were never straddled even by the- # old four-leg matrix, whose oldest leg WAS 3.10, so every leg took the same side- # and dropping legs loses nothing there. 3.14 is above every leg there has ever- # been. What a 3.13-only matrix genuinely stops executing is the pre-3.12 side of- # these files, and that is small enough to keep running rather than argue about.- #- # 3.11 because it is the newest version that still takes that side: closest to- # the ceiling, so anything it catches is about the boundary rather than about- # being old. Roughly 40 tests in under ten seconds, beside the full leg rather- # than in front of it, so the critical path is the full leg either way.run: |python -m pytest -q --tb=short --timeout=330 \tests/test_third_party_source.py \@@ -549,34 +311,9 @@ jobs:cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}repo-cpu-tests:- # Auto-discover everything under tests/ that is not GPU-bound by- # design. New tests added in covered directories are picked up- # without a workflow edit. Locally validated: 760 passed, 1 skipped,- # 23 deselected. tests/conftest.py (mirroring unsloth-zoo PR #624)- # pre-loads unsloth_zoo.device_type and unsloth.device_type under a- # mocked torch.cuda.is_available so the unsloth import chain- # succeeds on CPU.+ # Auto-discovers non-GPU tests; tests/conftest.py mocks torch.cuda.is_available for the import chain.name: Repo tests (CPU, ${{ matrix.shard }})runs-on: ubuntu-24.04- # Same reason as the matrix above, and now the same number. The comment this replaces- # claimed 13.4 minutes. Across the last 40 runs of this job on main the pytest step- # alone measured 852s to 1683s (14.2 to 28.1 minutes), and the install plus the four- # steps after it add a further 351s. So the worst measured run needs 33.9 minutes and- # the cap was 30: it sat inside the spread rather than above it. The clearest single- # run is 0eedeeeb, which passed -- at 1738s, 62 seconds under the limit.- #- # Which run loses is therefore a property of the runner, not of the PR. #10849 and- # #10861 were both cancelled at 30m1x against a green main, on branches that touch- # none of this.- #- # A cancelled job is also worse than a slow one, twice over. The cap fires mid-step, so- # the run blames whichever step was unlucky -- on both of those it was "Shell installer- # tests", 84s in and unrelated -- and the shell, CLI and Docker steps never run at all,- # so the PR loses that coverage silently. The suite is not the problem; the budget was.- #- # The cap stays at 45 through the split below rather than being retuned on a prediction:- # a cap that lands inside the real spread is exactly the failure this number was raised- # to fix, and the sharded spread has not been measured on a runner yet.timeout-minutes: 45strategy:# Three shards of one selection, balanced on measured time, not on file count.@@ -716,11 +453,7 @@ jobs:pyproject.tomlstudio/backend/requirements/*.txt- # node + uv unlock ~60 tests that previously skipped on CI:- # - 9 tests in test_chat_preset_builtin_invariants.py need node to- # compile a tiny TS harness against the frontend chat sources.- # - tests/python/* spawn fresh `uv venv`s to verify the no-torch- # install path; they self-skip when uv is missing.+ # node and uv are optional; dependent suites self-skip without them.- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0with:node-version: '22'@@ -742,24 +475,18 @@ jobs:# torchvision: unsloth_zoo.vision_utils imports it at module scope.pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \'torch>=2.4,<2.11' 'torchvision<0.26' 'torchaudio<2.11'- # sentence-transformers rides the transformers pin rather than a separate install, so+ # Tracks pyproject.toml's cap. sentence-transformers rides the transformers pin rather than a separate install, so# resolving it cannot bump transformers past the ceiling. It is an extra, not a core# dependency, and tests/test_st_modules_json_trust_gate.py skips without it, so# installing it here is what makes that gate run in this shard instead of skipping.# version-compat-ci's zoo-imports job runs the same file against the pinned# transformers matrix; this shard adds the core dependency set, where discovery# picks the file up and the importorskip would otherwise skip it for good.- pip install 'transformers>=4.51,<5.5' sentence-transformers+ pip install 'transformers>=4.51,<=5.17.0' sentence-transformers# bitsandbytes: hard import in unsloth/models/_utils.py. Recent# versions ship a CPU build that imports cleanly on Linux.pip install 'bitsandbytes>=0.45'- # unsloth.device_type imports unsloth_zoo.utils.Version at module- # scope, so the conftest preload needs unsloth_zoo. Pull from- # git main so this job sees the same zoo HEAD as Core / MLX /- # install.sh do (otherwise a fix on zoo main hides until release).- # No --no-deps: matches prior `pip install 'unsloth_zoo>=2026.5.1'`- # behaviour so triton etc. still come in for the Repo tests CPU- # collection imports.+ # zoo from git main (needed by the conftest preload), with deps so triton is installed.for attempt in 1 2 3; doif pip install "unsloth_zoo @ git+https://github.com/unslothai/unsloth-zoo"; thenbreak@@ -769,12 +496,7 @@ jobs:donepip install -e . --no-deps- # tests/test_formatter_fixed_point.py runs the real formatting hook, and it- # skips when the installed ruff is not the one the repo is formatted with,- # because another ruff answers a different question. Without this the guard- # would be permanently skipped here, which is the failure mode it exists to- # stop. The version is read out of .pre-commit-config.yaml rather than- # pinned a second time: a stale copy would silently disable the guard.+ # Ruff version read from .pre-commit-config.yaml so test_formatter_fixed_point.py does not skip.- name: Install the pinned ruff (formatter fixed-point guard)run: |pin="$(python -c 'import sys; sys.path.insert(0, "scripts"); import run_ruff_format as r; print(r.pinned_ruff_version(r.CONFIG.read_text(encoding = "utf-8")) or "")')"@@ -791,52 +513,12 @@ jobs:# Skip lazy compilation work the unsloth import chain wants to# do at import time on a real GPU.UNSLOTH_COMPILE_DISABLE: '1'- # --ignore: GPU-bound directories (qlora/saving need real weights;- # tests/sh is the shell suite the next step handles; tests/utils- # is a helpers folder); tests/vllm_compat + tests/version_compat- # are dedicated multi-version drift canaries with their own job- # in version-compat-ci.yml that installs the heavier dep set- # (torchcodec, full transformers/peft/bnb pins) those tests need.- # State-sensitive hardware-spoofing files run in isolation in the- # next step because they mutate hardware.py module globals, and- # tests/studio/load_freeze in the step after that because its- # assertions are wall-clock latency bounds.- # -m: honour markers from tests/python/conftest.py (`server` =- # needs studio venv, `e2e` = needs network).- # --deselect:- # - test_model_registration / test_all_model_registration:- # hit huggingface_hub for live model existence checks.- # test_autoconfig_works_with_no_torch_runtime / test_autoconfig_succeeds- # used to be deselected here too, for a tokenizers pin no-torch-runtime.txt- # was missing. #5359 added that pin and both now pass, so the lines are gone- # -- they were redundant anyway, since the -m filter above already excludes- # their `e2e` class marker, and the reason they gave outlived the bug.+ # --ignore: GPU-bound dirs, tests/sh, tests/utils, and the version-compat canaries (own workflow).+ # Spoofing and load_freeze files run isolated in later steps.#- # -n 4: 806.1s -> 219.7s locally on the same 4-worker shape as the runner, with an- # identical 2-failed / 8066-passed / 178-skipped / 40-subtest result. The three pytest- # steps below stay serial deliberately: the hardware-spoof step exists precisely- # because those files mutate hardware.py module globals, and all three already measure- # under 0.1 minutes on the runner, so there is nothing to win and isolation to lose.+ # The pytest steps below stay serial: hardware-spoof files mutate module globals.#- # --timeout / the outer `timeout`: the job cap above went from 30 to 45 minutes, and- # a backstop is only worth raising if something below it can still name a hang. Both- # mirror the backend pytest job for the reasons written out there; the numbers are- # this suite's own.- #- # 330s per test comes off this suite's measured tail, not off taste. The tail used- # to start at test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding- # at 63.6s, then 48.3s, then a run of ~31s docker-notebook durability cases. Those- # first two have since been made much cheaper and that scan now runs as 16 batches,- # so the docker-notebook cases are the tail: ~50s for the worst. This step runs- # ~2.2x slower on a 4-vCPU runner than on the box those came off, so call the worst- # legitimate test ~110s and the cap ~3x that. The headroom only grew, so 330 stands,- # and it is the same 330 the backend pytest job settled on against its own tail.- # Nothing here is near it, and a deadlock is named in minutes.- #- # --timeout arms inside each xdist worker, so a wedged CONTROLLER escapes it. 2100s- # bounds the session from outside, where it cannot: 1.25x the worst of the 40 runs- # measured above, and 2100 + the 351s of surrounding steps still lands 4 minutes- # under the job cap, so this fires first and says where it was stuck.+ # Timeouts mirror the backend pytest job; the outer one must fire before the job cap.run: |timeout --signal=INT --kill-after=60 2100 \python -m pytest ${{ matrix.selection }} -q --tb=short -n 4 --dist loadgroup --timeout=330 \@@ -848,10 +530,6 @@ jobs:env:PYTHONPATH: ${{ github.workspace }}/studioUNSLOTH_COMPILE_DISABLE: '1'- # These files mutate hardware.py module globals at runtime via the- # spoof fixtures (CUDA/ROCm/XPU/MLX/CPU), which leaks state into any- # other test that imports hardware. Run them in their own pytest- # invocation so the leak does not cross file boundaries.run: |python -m pytest -q --tb=short \tests/studio/test_hardware_dispatch_matrix.py \@@ -866,19 +544,7 @@ jobs:env:PYTHONPATH: ${{ github.workspace }}/studioUNSLOTH_COMPILE_DISABLE: '1'- # These drive a live uvicorn server and assert upper bounds on real elapsed- # time: 50 concurrent probes under 15s, a fast-shim probe under 2s, five- # sequential probes under 10s, and a not-loaded short circuit under 50 ms.- # A descheduled worker inflates them, so they run alone.- #- # The two tightest bounds this step used to carry, 250 ms for a /health burst- # and 350 ms for a 100-request burst, are gone. Both were proxies for one- # property, that the route hands its blocking call to a thread and leaves the- # event loop free, and both could be falsified by a descheduled thread with the- # code entirely correct. Those two tests now hold the blocking call open on an- # event and require /health to answer while it is held, which asserts the- # property itself and does not move with load.- # 20s serially, against the ~10 minutes -n 4 saves on this job.+ # Live uvicorn server with wall-clock bounds, so run alone.run: python -m pytest tests/studio/load_freeze -q --tb=short- name: CLI tests (unsloth_cli)@@ -918,16 +584,7 @@ jobs:cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}shell-installer-tests:- # Its own job rather than the tail of the longest one. 64 hermetic bash suites, run- # serially at 158-165s measured, sharing nothing with the Python install they used to sit- # behind: they mock uv, wsl.exe and the venv, and extract functions out of install.sh with- # sed. Two consequences of the old placement, both measured: those 165s were on the- # critical path of a job that was already the longest on the board, and when that job hit- # its cap mid-run it was this step that got named (#10849, #10861) while the steps after- # it silently never ran.- #- # No pip install here at all -- the runner's own python3 and bash are what these scripts- # use -- so the job is checkout plus the loop, and it finishes long before the shards do.+ # Hermetic bash suites in their own job, off the Python install's critical path (#10849, #10861).name: Shell installer testsruns-on: ubuntu-24.04# 165s measured, and a hung mock would otherwise sit here until the workflow's own limit.@@ -942,13 +599,7 @@ jobs:python-version: '3.12'- name: Shell installer tests- # Auto-discovered rather than allowlisted. The old hardcoded list had- # silently fallen seven files behind tests/run_all.sh, including- # test_strixhalo_wsl_reroute.sh -- the only shell coverage of the ROCm- # WSL reroute -- so that suite never ran on a PR. Skips are explicit,- # each with a reason, and tests/studio/test_ci_shell_suite_coverage.py- # fails if this step stops discovering the directory or the skip list- # grows without one.+ # Auto-discovered; tests/studio/test_ci_shell_suite_coverage.py guards discovery and skip reasons.## Skipped:# test_install_rollback_lifecycle.sh: covered by cross-platform-parity-ci.yml.diff --git a/.github/workflows/studio-export-capability-ci.yml b/.github/workflows/studio-export-capability-ci.ymlindex c7dbe310649..38be0af8fd4 100644--- a/.github/workflows/studio-export-capability-ci.yml+++ b/.github/workflows/studio-export-capability-ci.yml@@ -1,13 +1,9 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-# Runs studio/backend/tests/test_export_capability.py on Linux, Windows and macOS.-## export_capability() is per-OS (is_apple_silicon() and the PyTorch-import probe differ per-# platform) and the export backend must import without PyTorch, so this confirms the gating and-# import-safety on hosted Windows/macOS. Hosted runners have no GPU/MLX, so a real accelerator-# export is validated separately. No GPU / model / llama.cpp: the tests mock the probes and block-# torch/unsloth, so the job installs only a CPU PyTorch plus import deps.+# platform) and the export backend must import without PyTorch, so this confirms the gating+# and import-safety off Linux. A real accelerator export is validated separately.name: Unsloth export capability@@ -94,27 +90,7 @@ jobs:strategy:fail-fast: falsematrix:- # Windows only, and the reason is the same one that already removed the- # macOS leg: the only command this job runs is `pytest- # tests/test_export_capability.py`, and every test in that file goes- # through `_patch()`, which monkeypatches `_has_torch`, `get_device` and- # `is_apple_silicon`. Nothing in it touches Metal, MLX or any Apple- # binary, so a real Mac proved nothing a Linux runner did not.- #- # That argument reaches one step further than it was taken. It rests on- # studio-backend-ci.yml running the same file on ubuntu-latest as part of- # `pytest tests/` -- which it does, the file is not in that job's- # --ignore list -- and if that is true then the ubuntu leg HERE is the- # duplicate, not just the macOS one. The import-safety test does not need- # a torch-free image to be honest either: it installs its own- # `builtins.__import__` blocker and drops preloaded torch/unsloth from- # sys.modules, so it proves the same thing inside Backend CI's fully- # installed environment.- #- # Windows stays, because nothing else in CI runs this file there and- # `_has_torch`'s import probe is the per-OS behaviour the job exists for.- # Measured 67s of execution behind a 10642s queue, so the ubuntu leg was- # a runner slot spent re-proving a Linux result.+ # Windows only: tests are fully monkeypatched, and studio-backend-ci.yml already runs them on Linux.os: [windows-latest]runs-on: ${{ matrix.os }}timeout-minutes: 20@@ -146,7 +122,7 @@ jobs:- name: Install CPU PyTorch# CPU wheel index so every OS gets a CPU build; keep PyPI as an extra index so torch's# transitive deps still resolve (matching the other workflows in this repo).- run: python -m pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple "torch>=2.4,<2.13"+ run: python -m pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple "torch>=2.4,<2.15"- name: Install backend import deps# Enough to import utils.hardware and core.export.export; NOT unsloth (needs a GPU, and# the import-safety test blocks it) or triton/llama.cpp (Linux-only / native builds).diff --git a/.github/workflows/version-compat-ci.yml b/.github/workflows/version-compat-ci.ymlindex 1b3b626d099..ee9fb7026da 100644--- a/.github/workflows/version-compat-ci.yml+++ b/.github/workflows/version-compat-ci.yml@@ -1,37 +1,12 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.#-# Cross-version compat canary for the four upstream packages whose-# release cadence regularly breaks unsloth + unsloth-zoo:-#-# 1. vLLM (LoRA worker manager, BnB loader, cumem allocator)-# 2. TRL / GRPO (trainer source rewriters in unsloth.models.rl*)-# 3. PEFT (LoraConfig, get_peft_model, LoraLayer, bnb integration)-# 4. sentence-transformers (Transformer/Pooling/Normalize, Trainer)-# 5. bitsandbytes (Linear4bit, dequantize_4bit)-#-# Strategy: GitHub raw-fetch + symbol grep against every tracked-# version (no pip install, CPU-only). When upstream renames a symbol-# we depend on, the matching test fails BEFORE a user hits it. The-# `main` branch entries give us a few-day lead on PyPI releases.-#-# Cross-references:-# tests/vllm_compat/test_vllm_pinned_symbols.py (vLLM symbols)-# tests/version_compat/test_trl_grpo_pinned_symbols.py-# tests/version_compat/test_peft_pinned_symbols.py-# tests/version_compat/test_sentence_transformers_pinned_symbols.py-# tests/version_compat/test_bitsandbytes_pinned_symbols.py+# Cross-version compat canary: raw-fetch plus symbol grep against every tracked version, no pip install.name: Version Compat CIon:pull_request:- # Trigger on any unsloth source change, not just the three previously- # named files. The symbol-existence tests verify that EVERY pinned- # upstream reference in unsloth still resolves; a new- # `from peft.foo import Bar` added in unsloth/kernels/whatever.py- # is just as much a compat regression risk as one added in- # unsloth/models/rl.py.paths:- 'unsloth/**'- 'tests/vllm_compat/**'@@ -40,7 +15,10 @@ on:# repo-test shards have no sentence-transformers and skip it), so an edit to it must run here.- 'tests/test_st_modules_json_trust_gate.py'- 'pyproject.toml'- - '.github/workflows/version-compat-ci.yml'+ # Same trigger set as cap-site-consistency, so a cap moved in another workflow runs this job.+ - '.github/workflows/**'+ - 'tests/test_transformers_cap_sites.py'+ - 'tests/test_trl_cap_sites.py'# Every pytest run here loads tests/conftest.py and the tests/_shared helpers it# pulls in (installer_venv_root.py imports studio/install_manifest.py), and eight# of the collected tests import tests/_zoo_aggressive_cuda_spoof.py. Studio@@ -56,8 +34,6 @@ on:- '.github/actions/pip-cache-restore/**'- '.github/actions/pip-cache-save/**'schedule:- # Daily 06:43 UTC. Catches upstream PyPI releases roughly within- # 24 h. Off the :00 / :30 fleet-collision spots.- cron: '43 6 * * *'workflow_dispatch:@@ -73,34 +49,10 @@ permissions:contents: readjobs:- # Six jobs, one runner. Each of these suites fetches raw source from- # raw.githubusercontent.com and greps for symbols -- see tests/version_compat/_fetch.py,- # `has_def` / `first_match`. No pip install of vllm / torch / transformers is involved,- # which is the whole point of the canary and is also what makes co-locating them safe:- # there is no venv to conflict over, so "transformers 4.57.6" and "transformers main"- # can share one interpreter because neither is installed.- #- # They were six separate jobs costing six runner slots for 287s of combined work.- # Measured over a sampled main commit, each waited 23 to 31 minutes for admission to- # execute for 15 to 128 seconds. The queue is the cost, so the slots are the target.- #- # -n 4, deliberately, and not higher. The work is network-bound rather than CPU-bound,- # so more workers looks free and is not: measured locally on the full set,- #- # serial 1606 passed, 182 skipped 182.8s- # -n 4 1606 passed, 182 skipped 27.8s- # -n 8 1606 passed, 182 skipped 75.2s- #- # -n 8 is 2.7x SLOWER than -n 4, which for a fetch-bound suite is upstream throttling- # rather than core contention. 4 also matches the hosted runner's core count and the- # -n 4 every other pytest job here already uses.#- # --dist loadfile keeps each file on one worker, so a suite's tests cannot be split- # across workers and interleaved with another's.+ # -n 4: fetch-bound; -n 8 measured 2.7x slower (upstream throttling).#- # tests/studio/test_version_compat_bundle.py asserts every suite the six jobs named is- # still named here. Dropping one would not fail anything: the job would go green having- # tested less, which is the only way this change can go wrong.+ # tests/studio/test_version_compat_bundle.py asserts every suite is still named here.pinned-symbol-matrix:name: pinned-symbol matrix (vLLM, TRL, PEFT, ST, bitsandbytes, transformers)runs-on: ubuntu-latest@@ -119,6 +71,16 @@ jobs:run: |python -m pip install --upgrade pippip install 'pytest>=8' 'pytest-xdist>=3' packaging+ - name: Resolve the transformers matrix once+ # Resolve the matrix once so xdist workers collect identical parameters.+ env:+ PYTEST_TRANSFORMERS_MATRIX_FILE: ${{ runner.temp }}/transformers-matrix.json+ run: |+ PYTHONPATH=. python -c "+ import tests.version_compat.test_transformers_pinned_symbols as matrix+ print('tags:', len(matrix.TRANSFORMERS_TAGS))+ "+ echo "PYTEST_TRANSFORMERS_MATRIX_FILE=${{ runner.temp }}/transformers-matrix.json" >> "$GITHUB_ENV"- name: Run every pinned-symbol suiteenv:# Authenticated raw fetches get 5000/h; unauthenticated is 60/h and trips on the@@ -137,17 +99,74 @@ jobs:tests/version_compat/test_sentence_transformers_pinned_symbols.py \tests/version_compat/test_bitsandbytes_pinned_symbols.py \tests/version_compat/test_transformers_pinned_symbols.py \+ tests/version_compat/test_no_dtype_kwarg_at_load.py \-n 4 --dist loadfile -v --tb=short- # Optional second layer: actually `pip install` ONE representative- # version of each package and verify unsloth + unsloth-zoo modules- # import on it under the existing CUDA spoof. CPU-only, runs on- # ubuntu-latest. Catches the small set of breakages that the static- # symbol check misses (e.g. import-time side effects).+ cap-site-consistency:+ name: version-window drift (${{ matrix.os }})+ runs-on: ${{ matrix.os }}+ timeout-minutes: 10+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, windows-latest, macos-latest]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'+ - name: Install pytest only+ run: |+ python -m pip install --upgrade pip+ pip install 'pytest>=8' packaging pyyaml+ - name: Assert every site declares the same window+ # Keep on one line: PowerShell on windows-latest turns a `\` continuation into a literal path.+ run: |+ python -m pytest tests/test_transformers_cap_sites.py tests/test_trl_cap_sites.py -v --tb=short++ # Import-time lanes. floor: declared minima (py3.10 because PEFT 0.18.0 requires it). ceiling: declared maxima.+ # latest: unpinned, non-blocking canary. torchcodec rides the torch index line: a PyPI build next to a +cpu torch+ # fails `from torchcodec.decoders import ...`. hf_transfer: hub 0.x raises without it under HF_HUB_ENABLE_HF_TRANSFER=1.zoo-imports-under-spoof:- name: unsloth_zoo vllm/grpo/peft/st modules import under CUDA spoof+ name: unsloth_zoo imports under CUDA spoof (${{ matrix.slug }})runs-on: ubuntu-latest- timeout-minutes: 15+ # Only `latest` resolves outside the declared window, so only it is non-blocking.+ continue-on-error: ${{ matrix.continue_on_error == true }}+ timeout-minutes: 20+ strategy:+ fail-fast: false+ matrix:+ include:+ - slug: floor+ python: '3.10'+ torch_pins: >-+ 'torch==2.6.0' 'torchvision==0.21.0' 'torchcodec>=0.2,<0.3'+ pkg_pins: >-+ 'transformers==4.52.4' 'trl==0.18.2'+ 'peft==0.18.0' 'sentence-transformers>=5.0,<6' 'accelerate>=1.0'+ 'datasets>=3.4,<4.4' 'bitsandbytes>=0.45.5' 'triton==3.2.0'+ hf_transfer+ - slug: ceiling+ # datasets carries the declared window: the --no-deps installs below never apply pyproject's cap.+ # 3.11, not 3.12: lanes sharing an interpreter share one pip cache key.+ # Both pins must equal pyproject's ceilings (test_a_ceiling_lane_pins_the_declared_ceiling).+ python: '3.11'+ torch_pins: >-+ torch torchvision 'torchcodec>=0.12'+ pkg_pins: >-+ 'transformers==5.17.0' 'trl==1.13.0'+ peft sentence-transformers accelerate 'datasets>=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0'+ bitsandbytes triton hf_transfer+ - slug: latest+ continue_on_error: true+ python: '3.12'+ torch_pins: >-+ torch torchvision 'torchcodec>=0.12'+ pkg_pins: >-+ transformers trl peft sentence-transformers+ accelerate datasets bitsandbytes triton hf_transfersteps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:@@ -177,25 +196,26 @@ jobs:# key describe the payload. Unscoped, setup-python hashes dependency files# repo-wide, so one unrelated edit invalidates ~700MB per interpreter.with:- python-version: '3.12'+ python-version: ${{ matrix.python }}- name: Restore the pip cacheid: pip-cache# ./ resolves from GITHUB_WORKSPACE, and this job checks the repo out# under `unsloth/`, so the unprefixed path is a directory that does not# exist and the step fails with "Can't find 'action.yml'".+ # One literal name (tests/studio/test_pip_cache_naming.py), so no two lanes may share an interpreter.uses: ./unsloth/.github/actions/pip-cache-restorewith:name: version-compat-spoofkey-files: |unsloth/.github/workflows/version-compat-ci.yml- - name: Install CPU torch + supported pkg pins+ - name: Install CPU torch + this lane's pinsrun: |python -m pip install --upgrade pip# CPU torch (vllm/peft/st all depend on it).pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \- 'torch>=2.4,<2.11' 'torchvision<0.26' 'torchcodec<0.10'+ ${{ matrix.torch_pins }}# torchcodec is a hard requirement on transformers 5.x:# transformers/audio_utils.py:55 does# `importlib.metadata.version("torchcodec")` UNCONDITIONALLY,@@ -203,21 +223,26 @@ jobs:# otherwise has no audio path -- and that error trickles up# through every `import unsloth_zoo.<module>` because# unsloth-zoo's vision_utils transitively pulls- # transformers.processing_utils (-> audio_utils). The 0.10- # cap mirrors the torch 2.10 / torchvision 0.26 ABI window- # we already pin above.- # Ladder of supported floor versions per pyproject.toml.- pip install \- 'transformers>=4.56,<5.6' 'trl>=0.22,<0.26' \- 'peft>=0.18.0' 'sentence-transformers>=5.0' \- 'accelerate>=1.0' 'datasets>=3.4,<5' \- 'bitsandbytes>=0.45.5' \+ # ABI-coupled to torch, so the pair is chosen per lane. huggingface_hub unpinned: 4.x wants <1.0, 5.x >=1.5.0.+ pip install ${{ matrix.pkg_pins }} \sentencepiece protobuf safetensors numpy 'pytest>=8' \- 'huggingface_hub>=0.34' tqdm packaging psutil triton Pillow+ tqdm packaging psutil Pillow# Editable-install both repos so the test imports the# checkouts (not whatever stale PyPI version pip resolved).pip install --no-deps -e "$RUNNER_TEMP/unsloth-zoo"pip install --no-deps -e ./unsloth+ - name: Report the resolved set+ run: |+ python - <<'PY'+ from importlib.metadata import version+ for name in ("torch", "torchvision", "torchcodec", "transformers", "tokenizers",+ "huggingface_hub", "trl", "peft", "accelerate", "datasets",+ "sentence-transformers", "bitsandbytes", "triton"):+ try:+ print(f"{name}=={version(name)}")+ except Exception as error:+ print(f"{name}: {error}")+ PY- name: Run vllm_compat zoo-imports tests under spoofenv:UNSLOTH_IS_PRESENT: '1'@@ -258,10 +283,33 @@ jobs:# Catches structural TRL drift the greps miss (e.g. TRL 1.7.0's 2->3-tuple# per-token-logps return, restructured PEFT ref-adapter block) by asserting# the generated Unsloth trainer still satisfies the transform contracts.+ # models/rl.py matches TRL source text, so TRL is the deciding axis.grpo-fake-run:- name: GRPO fake-run (latest + main TRL, CPU spoof)+ name: GRPO fake-run (CPU spoof, TRL ${{ matrix.slug }})runs-on: ubuntu-latesttimeout-minutes: 18+ strategy:+ fail-fast: false+ matrix:+ include:+ - slug: floor+ python: '3.10'+ torch_pins: >-+ 'torch==2.6.0' 'torchvision==0.21.0' 'torchcodec>=0.2,<0.3'+ pkg_pins: >-+ 'transformers==4.52.4' 'peft==0.18.0'+ 'accelerate>=1.0' 'datasets>=3.4,<4.4' 'bitsandbytes>=0.45.5'+ 'triton==3.2.0' hf_transfer+ # The declared minimum, like the zoo-imports floor lane.+ trl_pin: 'trl==0.18.2'+ - slug: latest+ python: '3.12'+ torch_pins: >-+ torch torchvision 'torchcodec>=0.12'+ pkg_pins: >-+ transformers peft accelerate datasets+ bitsandbytes triton hf_transfer+ trl_pin: '--upgrade trl'steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:@@ -289,7 +337,7 @@ jobs:# key describe the payload. Unscoped, setup-python hashes dependency files# repo-wide, so one unrelated edit invalidates ~700MB per interpreter.with:- python-version: '3.12'+ python-version: ${{ matrix.python }}- name: Restore the pip cacheid: pip-cache@@ -302,21 +350,19 @@ jobs:key-files: |unsloth/.github/workflows/version-compat-ci.yml- - name: Install CPU torch + ecosystem + TRL latest+ - name: Install CPU torch + ecosystem + this lane's TRLrun: |python -m pip install --upgrade pippip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \- 'torch>=2.4,<2.11' 'torchvision<0.26' 'torchcodec<0.10'- # Ecosystem floors unsloth needs; TRL itself is installed last so it- # can pull the transformers/peft it requires.- pip install \- 'transformers>=4.57' 'peft>=0.18.0' 'accelerate>=1.0' 'datasets>=3.4,<5' \- 'bitsandbytes>=0.45.5' sentencepiece protobuf safetensors numpy 'pytest>=8' \- 'huggingface_hub>=0.34' tqdm packaging psutil triton Pillow- pip install --upgrade trl+ ${{ matrix.torch_pins }}+ # TRL last so it pulls the transformers/peft it requires.+ pip install ${{ matrix.pkg_pins }} \+ sentencepiece protobuf safetensors numpy 'pytest>=8' \+ tqdm packaging psutil Pillow+ pip install ${{ matrix.trl_pin }}pip install --no-deps -e "$RUNNER_TEMP/unsloth-zoo"pip install --no-deps -e ./unsloth- - name: Fake-run vs TRL latest+ - name: Fake-run vs this lane's TRLenv:UNSLOTH_IS_PRESENT: '1'UNSLOTH_COMPILE_DISABLE: '1'@@ -335,6 +381,8 @@ jobs:tests/version_compat/test_trl_fake_train_cpu.py \tests/version_compat/test_trl_padding_free_max_length.py \tests/version_compat/test_trl_loss_normalization_contract.py \+ tests/version_compat/test_grpo_left_pad_probe_at_the_floor.py \+ tests/version_compat/test_grpo_importance_sampling_level_at_the_floor.py \tests/version_compat/test_trl_config_defaults_contract.py \tests/version_compat/test_dense_router_aux_loss_off.py \tests/version_compat/test_pref_max_length_clamp.py \@@ -345,7 +393,7 @@ jobs:# `main` is scheduled/dispatch-only so PR jobs stay fast and a bleeding-edge# TRL break does not red every PR. github.event_name is valid in a step if.- name: Fake-run vs TRL main (scheduled / dispatch only)- if: ${{ github.event_name != 'pull_request' }}+ if: ${{ github.event_name != 'pull_request' && matrix.slug == 'latest' }}env:UNSLOTH_IS_PRESENT: '1'UNSLOTH_COMPILE_DISABLE: '1'@@ -362,6 +410,8 @@ jobs:tests/version_compat/test_trl_fake_train_cpu.py \tests/version_compat/test_trl_padding_free_max_length.py \tests/version_compat/test_trl_loss_normalization_contract.py \+ tests/version_compat/test_grpo_left_pad_probe_at_the_floor.py \+ tests/version_compat/test_grpo_importance_sampling_level_at_the_floor.py \tests/version_compat/test_trl_config_defaults_contract.py \tests/version_compat/test_dense_router_aux_loss_off.py \tests/version_compat/test_pref_max_length_clamp.py \diff --git a/docker/Dockerfile.rocm b/docker/Dockerfile.rocmindex 0b98a76055a..86f3db33fbf 100644--- a/docker/Dockerfile.rocm+++ b/docker/Dockerfile.rocm@@ -93,7 +93,7 @@ RUN set -eu; \# The whole Python stack in ONE layer, resolved once. The obvious two-step# (torch from the ROCm index, then the rest) fails twice: unsloth-zoo bounds-# torch (<2.13 now), so the second step swaps the 14 GB torch and the old one+# torch (<2.15 now), so the second step swaps the 14 GB torch and the old one# stays as a dead layer (measured: 70 GB image, 16 GB live); and under# unsafe-best-match uv takes the highest version across indexes, so a newer# pypi torch wins as a CUDA build and drags in nvidia-* wheels.diff --git a/pyproject.toml b/pyproject.tomlindex a4288d11546..b5c0d687d52 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -215,14 +215,12 @@ huggingfacenotorch = [# gate on the INSTALLED zoo rather than on this pin, so they start running by themselves# wherever 2026.9.5 or newer is the zoo actually present.#- # This branch needs that same floor for a second, independent reason: 2026.9.5 is also the- # first release to export `grpo_vision_chunks`, which both vision GRPO logprob paths in+ # The same floor is needed for a second, independent reason: 2026.9.5 is also the first+ # release to export `grpo_vision_chunks`, which both vision GRPO logprob paths in# unsloth/models/rl_replacements.py refuse to run without.#- # This does NOT lift the transformers ceiling below. 2026.9.5 still declares- # `transformers<=5.5.0` in its own metadata, so the resolver intersects our transformers- # range down to 5.5.0 whatever this file says. That one waits on- # unslothai/unsloth-zoo#1227 and a later zoo release.+ # 2026.9.9 is the first zoo carrying the ceilings below and the Gemma3 token_type_ids fix+ # (unsloth-zoo#1505) that transformers >= 5.15 needs."unsloth_zoo>=2026.9.9","wheel>=0.42.0","packaging",@@ -232,7 +230,7 @@ huggingfacenotorch = ["tyro","protobuf","sentencepiece>=0.2.0",- "datasets>=3.4.1,!=4.0.*,!=4.1.0,<4.4.0",+ "datasets>=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0","accelerate>=0.34.1","peft>=0.18.0,!=0.11.0","huggingface_hub>=0.34.0",@@ -250,8 +248,10 @@ huggingfacenotorch = [# on 3.9 and the whole extra becomes unresolvable."diffusers>=0.39.0 ; python_version >= '3.10'","diffusers ; python_version < '3.10'",- "transformers>=4.51.3,!=4.52.0,!=4.52.1,!=4.52.2,!=4.52.3,!=4.53.0,!=4.54.0,!=4.55.0,!=4.55.1,!=4.57.0,!=4.57.4,!=4.57.5,!=5.0.0,!=5.1.0,<=5.5.0",- "trl>=0.18.2,!=0.19.0,<=0.24.0",+ # Ceiling = newest release the version matrix ran. Each `!=` was tested and rejected: keep them.+ # Apple Silicon stays at 5.5.0 via unsloth_zoo's marker-split requirement.+ "transformers>=4.52.4,!=4.53.0,!=4.54.0,!=4.55.0,!=4.55.1,!=4.57.0,!=4.57.4,!=4.57.5,!=5.0.0,!=5.1.0,<=5.17.0",+ "trl>=0.18.2,!=0.19.0,<=1.13.0","sentence-transformers",]# torchcodec backend for Gemma audio / datasets>=4 (#7225).@@ -964,8 +964,8 @@ colab-new = ["unsloth_zoo>=2026.9.9","packaging","tyro",- "transformers>=4.51.3,!=4.52.0,!=4.52.1,!=4.52.2,!=4.52.3,!=4.53.0,!=4.54.0,!=4.55.0,!=4.55.1,!=4.57.0,!=4.57.4,!=4.57.5,!=5.0.0,!=5.1.0,<=5.5.0",- "datasets>=3.4.1,!=4.0.*,!=4.1.0,<4.4.0",+ "transformers>=4.52.4,!=4.53.0,!=4.54.0,!=4.55.0,!=4.55.1,!=4.57.0,!=4.57.4,!=4.57.5,!=5.0.0,!=5.1.0,<=5.17.0",+ "datasets>=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0","sentencepiece>=0.2.0","tqdm","psutil",@@ -980,7 +980,7 @@ colab-new = []colab-no-deps = ["accelerate>=0.34.1",- "trl>=0.18.2,!=0.19.0,<=0.24.0",+ "trl>=0.18.2,!=0.19.0,<=1.13.0","peft>=0.18.0","xformers ; ('linux' in sys_platform or sys_platform == 'win32') and (platform_machine == 'AMD64' or platform_machine == 'x86_64')","bitsandbytes>=0.45.5,!=0.46.0,!=0.48.0",diff --git a/scripts/scan_packages_baseline.json b/scripts/scan_packages_baseline.jsonindex 1c1c02738ec..c0496da4c5d 100644--- a/scripts/scan_packages_baseline.json+++ b/scripts/scan_packages_baseline.json@@ -866,6 +866,38 @@"evidence": "L144: return importlib.import_module(\".\" + module_name, self.__name__)","evidence_hash": "e584ecfdb097d9482bb19cd3992813bc1a119cfd4c40af14748bafe22900d91e"},+ {+ "package": "trl",+ "file": "trl/_lazy_module.py",+ "check": "Downloads and executes remote code",+ "severity": "CRITICAL",+ "evidence": "L71: return importlib.import_module(\".\" + module_name, self.__name__)",+ "evidence_hash": "e584ecfdb097d9482bb19cd3992813bc1a119cfd4c40af14748bafe22900d91e"+ },+ {+ "package": "trl",+ "file": "trl/experimental/async_distillation/vllm_client.py",+ "check": "C2 polling/beaconing loop detected",+ "severity": "CRITICAL",+ "evidence": "L48: while True: sha256:925f5318e1a94b98c1d4e73ac0f2a10cd48b9e3d7fb78e789d4b9ac9d01ceea6",+ "evidence_hash": "5de7b25a3eafdadc8b50ae22fd4f599e09f12912c05ae595797292fcb68992fa"+ },+ {+ "package": "trl",+ "file": "trl/experimental/async_grpo/vllm_client.py",+ "check": "C2 polling/beaconing loop detected",+ "severity": "CRITICAL",+ "evidence": "L48: while True: sha256:c3c21557aa82ba4593ff95c6934504bcb987ded9f67836ec1e2f371aa3166f52",+ "evidence_hash": "2d5cf3effabb28b1410203deed71a621301cce15e09dc1485b3b538b183184f8"+ },+ {+ "package": "trl",+ "file": "trl/generation/vllm_client.py",+ "check": "C2 polling/beaconing loop detected",+ "severity": "CRITICAL",+ "evidence": "L179: while True: sha256:618a8410e4ed18d0486f68db559bc9f842d00f7e6926096c3e13602d7b8329ae",+ "evidence_hash": "6990d68d4bf3b5ffdcec612b4de9de6d2383ef9b1f0e80bc6a9ffc971b11c1b0"+ },{"package": "unsloth-zoo","file": "scripts/scan_packages.py",@@ -2213,6 +2245,14 @@"evidence_hash": "ef22a4fe0d8ec7e2b0e4afc6e6a3d997cd94c981bf59790562217d4f9dd70732","file_sha256": "1d8b60e48ec8f0faf6156f6eac7368e99c2b6d34690957ef7c5e8e505cacc7db"},+ {+ "package": "datasets",+ "file": "datasets/utils/file_utils.py",+ "check": "C2 polling/beaconing loop detected",+ "severity": "CRITICAL",+ "evidence": "L443: while True: sha256:483d0708b413e70fec1791cb689364b426ea949b795d717d1ba437d08c0b9d21",+ "evidence_hash": "fdde4e280accf7805c189b49c656234f6495462314df0b1cb0d8dba3444e84a1"+ },{"package": "transformers","file": "transformers/testing_utils.py",diff --git a/studio/backend/requirements/no-torch-runtime.txt b/studio/backend/requirements/no-torch-runtime.txtindex 00ab0f81a2b..0bdd11fc7cb 100644--- a/studio/backend/requirements/no-torch-runtime.txt+++ b/studio/backend/requirements/no-torch-runtime.txt@@ -43,7 +43,7 @@ protobuf==7.35.1; python_version >= "3.10"protobuf==6.33.6; python_version < "3.10"sentencepiece>=0.2.0safetensors>=0.4.3-datasets>=3.4.1,!=4.0.*,!=4.1.0,<4.4.0+datasets>=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0accelerate>=0.34.1peft>=0.18.0,!=0.11.0huggingface_hub>=1.31.0,<2.0; python_version >= "3.10"@@ -88,7 +88,7 @@ h11==0.16.0tokenizers>=0.22.0,<=0.23.0transformers==5.5.0; python_version >= "3.10"transformers==4.57.6; python_version < "3.10"-trl>=0.18.2,!=0.19.0,<=0.24.0+trl>=0.18.2,!=0.19.0,<=1.13.0# Matches extras-no-deps.txt rather than the newest release: that file installs# --no-deps too and runs after this one, so whatever it names wins. Pinning a# higher version here would record a number no install ever ends up with. Bumpdiff --git a/studio/backend/requirements/single-env/overrides-darwin-arm64.txt b/studio/backend/requirements/single-env/overrides-darwin-arm64.txtindex 897bd1f8c42..01d2ae29bb8 100644--- a/studio/backend/requirements/single-env/overrides-darwin-arm64.txt+++ b/studio/backend/requirements/single-env/overrides-darwin-arm64.txt@@ -1,14 +1,19 @@# Keep mlx-vlm / mlx-lm on the same Transformers version as the main Unsloth# environment when uv applies their dependency metadata.#-# A window, not a floor. An override replaces EVERY requirement on the package,-# including unsloth's own transformers<=5.5.0 cap in pyproject, and install.sh's-# core install is the one uv command that does not also pass constraints.txt. A-# bare floor therefore let that resolve pick transformers 5.16.1 (the first-# release wanting tokenizers>=0.23.1) with tokenizers 0.23.2 on macOS arm64;-# extras-no-deps.txt then pinned transformers back to 5.5.0 --no-deps and left-# tokenizers stranded, so every `import transformers`, and so every-# `import mlx_lm`, raised and Apple Silicon came up chat-only.+# A window, not a floor. An override replaces EVERY requirement on the package, including+# pyproject's cap, and install.sh's core install is the one uv command that does not also+# pass constraints.txt. A bare floor let it pick transformers 5.16.1 (first to want+# tokenizers>=0.23.1) with tokenizers 0.23.2; extras-no-deps.txt then pinned transformers+# back to 5.5.0 --no-deps, stranding tokenizers, so every `import transformers` and thus+# `import mlx_lm` raised and Apple Silicon came up chat-only.+#+# This window does NOT track pyproject's published cap and must not be widened with it:+# the cap says what a `pip install unsloth` may resolve, these lines say what the pinned+# Studio single-env installs, which is constraints.txt's `transformers==5.5.0` plus the+# tokenizers window it declares. Widening only this file reproduces the failure above.+# Moving the Studio pin means changing constraints.txt, extras-no-deps.txt,+# no-torch-runtime.txt and this file together.## Unlike the huggingface_hub case below, this cannot go unsatisfiable: that one# replaced other packages' requirements ON hub while a direct requirement stilldiff --git a/studio/backend/tests/test_compressed_tensors_signature_drift.py b/studio/backend/tests/test_compressed_tensors_signature_drift.pyindex f3b40d78f2a..667ea7d9565 100644--- a/studio/backend/tests/test_compressed_tensors_signature_drift.py+++ b/studio/backend/tests/test_compressed_tensors_signature_drift.py@@ -5,9 +5,12 @@`test_compressed_tensors_load_error_message.py` runs the same check, but only where thewhole backend imports, and `studio-backend-ci.yml` pins that environment to-`transformers>=4.51,<5.5` -- outside the 5.10 rewording the matcher exists to survive.-This file reads the signatures and `_diagnosis_text` out of `routes/inference.py` with-`ast` instead, so it needs no fastapi and runs on any transformers.+`transformers>=4.51,<=5.17.0`. That window now spans the 5.10 rewording the matcher exists+to survive rather than stopping below it, but it still resolves ONE version per run, so it+proves the matcher against whatever that run happened to pick and not against both sides of+the rewording. This file reads the signatures and `_diagnosis_text` out of+`routes/inference.py` with `ast` instead, so it needs no fastapi and runs on any+transformers."""from __future__ import annotations@@ -151,8 +154,9 @@ def test_this_guard_needs_no_studio_backend_dependency():def test_a_workflow_that_installs_a_modern_transformers_actually_collects_this_file():"""The guard above is worth nothing in an environment that never runs it.- Every auto-discovering job pins `transformers>=4.51,<5.5`; the jobs that install a- modern one collect listed paths, not trees, so an unlisted file never runs.+ Every auto-discovering job pins a transformers RANGE (`>=4.51,<=5.17.0` in+ studio-backend-ci.yml) and so resolves a single version per run; the jobs that pin a+ modern one exactly collect listed paths, not trees, so an unlisted file never runs."""workflow = (Path(__file__).resolve().parents[3] / ".github" / "workflows" / "consolidated-tests-ci.yml"diff --git a/tests/test_st_modules_json_trust_gate.py b/tests/test_st_modules_json_trust_gate.pyindex 5f1be01215d..61a153d1839 100644--- a/tests/test_st_modules_json_trust_gate.py+++ b/tests/test_st_modules_json_trust_gate.py@@ -1256,8 +1256,11 @@ def test_a_404_without_a_commit_header_is_tolerated_where_upstream_gates_it(tmp_x-repo-commit, or an older hub whose error carries no response at all, leaves nothingto pin to, and on a version where nothing else checks the type that has to refuse."""+ import sentence_transformersfrom huggingface_hub.errors import EntryNotFoundError+ # The version is the condition under test; the floor lane installs sentence-transformers 5.x.+ monkeypatch.setattr(sentence_transformers, "__version__", "6.1.0", raising = False)monkeypatch.setattr(FastSentenceTransformer, "_module_path", staticmethod(lambda *a, **k: None))_patch_download(monkeypatch,diff --git a/tests/test_transformers_cap_sites.py b/tests/test_transformers_cap_sites.pynew file mode 100644index 00000000000..2c9d2398887--- /dev/null+++ b/tests/test_transformers_cap_sites.py@@ -0,0 +1,802 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""The published transformers window and every CI lane that mirrors it have to agree.++The cap is spelled in pyproject.toml, unsloth_zoo's pyproject, and several workflows. A site+left behind when the cap moves keeps CI green while testing a range users no longer get, so+the assertions are not "the number is 5.17.0" but "the window admits what was measured,+still rejects what was rejected, and no lane sits below it without saying why".++Reads files only, which is what lets it run on the Windows and macOS runners too.+"""++from __future__ import annotations++import inspect+import re+import sys+from pathlib import Path++import pytest+from packaging.requirements import InvalidRequirement, Requirement+from packaging.specifiers import SpecifierSet+from packaging.version import Version+++REPO = Path(__file__).resolve().parents[1]+PYPROJECT = REPO / "pyproject.toml"+WORKFLOWS = REPO / ".github" / "workflows"++# Newest transformers the matrix was run against; moving it means re-running the sweep first.+TESTED_CEILING = Version("5.17.0")++# Not 4.51.3: peft 0.18.0 imports GradientCheckpointingLayer (4.52.0+); 4.52.0-4.52.3 are rejected below.+TESTED_FLOOR = Version("4.52.4")++# Tested and rejected; a specifier rewrite that drops one silently re-admits a broken release.+REJECTED = (+ "4.52.0",+ "4.52.1",+ "4.52.2",+ "4.52.3",+ "4.53.0",+ "4.54.0",+ "4.55.0",+ "4.55.1",+ "4.57.0",+ "4.57.4",+ "4.57.5",+ "5.0.0",+ "5.1.0",+)++NEWLY_ADMITTED = ("5.6.0", "5.10.1", "5.14.1", "5.15.1", "5.16.1", "5.17.0")++# Keyed on (workflow, exact requirement), never the workflow alone. Empty on purpose.+PINNED_BY_DESIGN: dict[tuple[str, str], str] = {}++# pip intersects our window with the zoo's, so the zoo's ceiling decides what resolves.+ZOO_TRANSFORMERS_CEILING_BEFORE_THE_LIFT = Version("5.5.0")++ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP = Version("2026.9.7")++# CPU lanes must admit what the zoo's torch bound admits, or they test a torch nobody gets.+TESTED_TORCH = Version("2.14.0")+TORCH_MIRROR_WORKFLOW = WORKFLOWS / "studio-export-capability-ci.yml"+++def _toml() -> dict:+ """pyproject as a dict; tomllib is 3.11+ while requires-python is >=3.9, so import lazily."""+ if sys.version_info < (3, 11):+ pytest.skip("tomllib needs Python 3.11+")+ import tomllib++ return tomllib.loads(PYPROJECT.read_text(encoding = "utf-8"))+++def _pyproject_transformers() -> list[Requirement]:+ data = _toml()+ project = data.get("project") or {}+ raws: list[str] = list(project.get("dependencies") or [])+ for extra in (project.get("optional-dependencies") or {}).values():+ raws.extend(extra)+ out = []+ for raw in raws:+ try:+ req = Requirement(raw)+ except InvalidRequirement:+ continue+ if req.name.lower().replace("_", "-") == "transformers":+ out.append(req)+ return out+++def _declared_window() -> SpecifierSet:+ reqs = _pyproject_transformers()+ assert reqs, "pyproject.toml declares no transformers requirement at all"+ windows = {str(req.specifier) for req in reqs}+ assert len(windows) == 1, (+ f"pyproject.toml declares {len(windows)} different transformers windows across its "+ f"extras: {sorted(windows)}. One of them will be the one users hit and the other "+ f"will be the one CI tests."+ )+ return SpecifierSet(windows.pop())+++def _ceiling(window: SpecifierSet) -> Version:+ """The TIGHTEST upper bound: `max` reported 5.18.0 for `<=5.17.0,<=5.18.0`, which resolves at+ 5.17.0, so the assertions passed on exactly the stale cap this file exists to catch.+ """+ tops = [+ (Version(str(spec.version)), spec.operator)+ for spec in window+ if spec.operator in ("<=", "<")+ ]+ assert tops, f"the transformers window declares no upper bound at all: {window}"+ version, _operator = min(tops, key = lambda pair: (pair[0], pair[1] == "<="))+ return version+++def _pyproject_zoo() -> list[Requirement]:+ data = _toml()+ project = data.get("project") or {}+ raws: list[str] = list(project.get("dependencies") or [])+ for extra in (project.get("optional-dependencies") or {}).values():+ raws.extend(extra)+ out = []+ for raw in raws:+ try:+ req = Requirement(raw)+ except InvalidRequirement:+ continue+ if req.name.lower().replace("_", "-") == "unsloth-zoo" and req.specifier:+ out.append(req)+ return out+++def test_the_declared_zoo_floor_can_supply_the_declared_transformers_window() -> None:+ """pip intersects our requirement with the zoo's and the user gets the LOWER ceiling, and zoo+ 2026.9.5 says `transformers<=5.5.0`. Deferred while the constant is None.+ """+ if ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP is None:+ pytest.skip(+ "deferred: no unsloth_zoo release carrying the lifted transformers ceiling "+ "(unslothai/unsloth-zoo#1227) is published yet, and 2026.9.5 is the newest on "+ "PyPI, so pyproject.toml holds the zoo floor there. Until it ships, the window "+ "this file checks is wider than what pip actually resolves. Re-enable by "+ "setting ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP to the release carrying #1227."+ )+ ceiling = _ceiling(_declared_window())+ if ceiling <= ZOO_TRANSFORMERS_CEILING_BEFORE_THE_LIFT:+ pytest.skip(+ f"declared transformers ceiling {ceiling} is within what zoo "+ f"<{ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP} already admits"+ )+ reqs = _pyproject_zoo()+ assert reqs, (+ "pyproject.toml declares a transformers ceiling above what the published "+ "unsloth_zoo admits, and names no versioned unsloth_zoo requirement at all"+ )+ floors = {}+ for req in reqs:+ lower = [+ Version(str(spec.version))+ for spec in req.specifier+ if spec.operator in (">=", "==", "~=")+ ]+ assert lower, (+ f"unsloth_zoo requirement {req} has no lower bound, so it admits the release "+ f"whose own transformers cap is {ZOO_TRANSFORMERS_CEILING_BEFORE_THE_LIFT}"+ )+ floors[str(req)] = max(lower)+ stale = {+ raw: str(floor)+ for raw, floor in floors.items()+ if floor < ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP+ }+ assert not stale, (+ f"pyproject.toml admits transformers up to {ceiling} while still accepting "+ f"unsloth_zoo {stale}. pip intersects the two requirements, so users would "+ f"resolve the zoo that caps transformers at "+ f"{ZOO_TRANSFORMERS_CEILING_BEFORE_THE_LIFT} and the wider window here would "+ f"never take effect. Move the floor to "+ f"{ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP} in the same commit as the ceiling."+ )+ assert len(set(floors.values())) == 1, (+ f"pyproject.toml declares more than one unsloth_zoo floor: {floors}. One of them "+ f"is the one users hit."+ )+++def test_pyproject_declares_one_unsloth_zoo_floor() -> None:+ """Two floors across the extras means one is what users hit and the other what CI reads; an+ unbounded `unsloth_zoo` admits every old release. Both hold at 2026.9.5.+ """+ reqs = _pyproject_zoo()+ assert reqs, "pyproject.toml names no versioned unsloth_zoo requirement at all"+ floors = {}+ for req in reqs:+ lower = [+ Version(str(spec.version))+ for spec in req.specifier+ if spec.operator in (">=", "==", "~=")+ ]+ assert lower, (+ f"unsloth_zoo requirement {req} has no lower bound, so it admits every zoo "+ f"release ever published, including those whose own transformers cap is "+ f"{ZOO_TRANSFORMERS_CEILING_BEFORE_THE_LIFT}"+ )+ floors[str(req)] = max(lower)+ assert len(set(floors.values())) == 1, (+ f"pyproject.toml declares more than one unsloth_zoo floor: {floors}. One of them "+ f"is the one users hit."+ )+++def _floor(window: SpecifierSet) -> Version:+ bottoms = [Version(str(spec.version)) for spec in window if spec.operator in (">=", ">")]+ assert bottoms, f"the transformers window declares no lower bound at all: {window}"+ return max(bottoms)+++def _floor_lane_transformers_pins() -> dict[str, str]:+ """`{job: pinned transformers}` per floor lane. Parsed, not grepped: the file also pins+ transformers exactly in lanes that are NOT the floor.+ """+ if sys.version_info < (3, 11):+ pytest.skip("yaml parsing here needs the 3.11+ interpreter the job uses")+ import yaml++ doc = yaml.safe_load((WORKFLOWS / "version-compat-ci.yml").read_text(encoding = "utf-8"))+ found = {}+ for job_name, job in (doc.get("jobs") or {}).items():+ for entry in ((job.get("strategy") or {}).get("matrix") or {}).get("include") or []:+ if entry.get("slug") != "floor":+ continue+ pins = " ".join(+ str(v) for k, v in entry.items() if k.endswith("pins") or k.endswith("pin")+ )+ match = re.search(r"transformers==([\d.]+)", pins)+ assert match, (+ f"the floor lane of {job_name} no longer pins transformers exactly, so "+ f"nothing makes it run the declared floor. Retarget this test or restore the pin."+ )+ found[job_name] = match.group(1)+ return found+++def test_pyproject_declares_one_transformers_window() -> None:+ window = _declared_window()+ assert len(_pyproject_transformers()) >= 2, (+ "this test assumed pyproject names transformers in more than one place; if that "+ "stopped being true, the drift it guards against is gone and so is the point"+ )+ assert _ceiling(window) == TESTED_CEILING, (+ f"pyproject.toml caps transformers at {_ceiling(window)}, and the version matrix "+ f"was run against {TESTED_CEILING}. Raising the cap means running the sweep on the "+ f"new release and moving TESTED_CEILING here in the same commit."+ )+++def test_pyproject_declares_the_floor_the_lanes_run() -> None:+ """A floor rots downward as silently as a ceiling rots up: `transformers>=4.51.3` was declared+ beside `peft>=0.18.0`, a pair that cannot import, so the floor named an unrunnable combination.+ """+ window = _declared_window()+ assert _floor(window) == TESTED_FLOOR, (+ f"pyproject.toml floors transformers at {_floor(window)} and the floor lanes run "+ f"{TESTED_FLOOR}. Lowering the floor means proving the lower release imports with "+ f"the peft floor declared beside it, in the same commit."+ )+++def test_the_floor_lanes_run_the_declared_floor() -> None:+ lanes = _floor_lane_transformers_pins()+ assert len(lanes) >= 2, (+ f"expected both version-compat floor lanes to pin transformers; found {lanes}. A "+ f"floor nothing runs is the state this test exists to end."+ )+ drifted = {job: pin for job, pin in lanes.items() if Version(pin) != TESTED_FLOOR}+ assert not drifted, (+ f"these floor lanes pin a transformers other than the declared floor {TESTED_FLOOR}: "+ f"{drifted}. A lane above the floor leaves the floor untested; below it, the lane "+ f"tests a release users cannot install."+ )+++def test_the_floor_excludes_the_release_that_could_not_import() -> None:+ """Negative control: both checks above are equality checks, which a constant edited in the+ wrong direction satisfies too. 4.51.3 is the release that actually failed.+ """+ window = _declared_window()+ assert "4.51.3" not in window, (+ "the transformers window admits 4.51.3 again. peft 0.18.0 imports "+ "transformers.modeling_layers, which that release does not have."+ )+ assert str(TESTED_FLOOR) in window, "the window must admit the floor it declares"+++def test_the_window_admits_every_release_the_sweep_passed() -> None:+ window = _declared_window()+ missing = [v for v in NEWLY_ADMITTED if v not in window]+ assert not missing, (+ f"the transformers window {window} excludes {missing}, which the sweep passed. An "+ f"exclusion has to name the test that failed on that release."+ )+++def test_every_rejected_release_is_still_rejected() -> None:+ window = _declared_window()+ readmitted = [v for v in REJECTED if v in window]+ assert not readmitted, (+ f"the transformers window {window} now admits {readmitted}, which were tested and "+ f"rejected. Rewriting the specifier must not drop an exclusion."+ )+++def _workflow_transformers_specs(path: Path) -> list[tuple[str, Requirement]]:+ """Every `transformers<spec>` requirement spelled inside a workflow's shell steps."""+ text = path.read_text(encoding = "utf-8")+ out = []+ for match in re.finditer(r"['\"](transformers[<>=!,.\d\s]*)['\"]", text):+ try:+ req = Requirement(match.group(1))+ except InvalidRequirement:+ continue+ if req.name.lower() == "transformers" and str(req.specifier):+ out.append((match.group(1), req))+ return out+++def test_no_workflow_lane_sits_below_the_declared_ceiling() -> None:+ ceiling = _ceiling(_declared_window())+ offenders = {}+ for path in sorted(WORKFLOWS.glob("*.yml")):+ for raw, req in _workflow_transformers_specs(path):+ if any(spec.operator == "==" for spec in req.specifier):+ continue+ if ceiling in req.specifier:+ continue+ if (path.name, raw.strip()) in PINNED_BY_DESIGN:+ continue+ offenders.setdefault(path.name, []).append(raw)+ unexplained = offenders+ assert not unexplained, (+ f"these workflow lanes cap transformers below the {ceiling} the package publishes, "+ f"so they test a range users do not get: {unexplained}. Either widen the lane or "+ f"add it to PINNED_BY_DESIGN with the reason."+ )+++def test_every_exemption_names_a_lane_that_exists_today() -> None:+ """A dormant exemption is a pre-authorisation: the day its string returns, the scan finds it and+ skips it, which is the failure this file exists to prevent.+ """+ spelled = {+ (path.name, raw.strip())+ for path in sorted(WORKFLOWS.glob("*.yml"))+ for raw, _req in _workflow_transformers_specs(path)+ }+ dormant = sorted(key for key in PINNED_BY_DESIGN if key not in spelled)+ assert not dormant, (+ f"PINNED_BY_DESIGN exempts requirements no workflow spells today: {dormant}. "+ f"Each of those silently pre-authorises that exact string if it is reintroduced. "+ f"Delete the entry; add it back when a lane genuinely needs it."+ )+++def test_the_torch_mirror_admits_what_unsloth_zoo_admits() -> None:+ text = TORCH_MIRROR_WORKFLOW.read_text(encoding = "utf-8")+ found = re.findall(r"['\"](torch[<>=!,.\d\s]*)['\"]", text)+ specs = []+ for raw in found:+ try:+ req = Requirement(raw)+ except InvalidRequirement:+ continue+ if req.name.lower() == "torch" and str(req.specifier):+ specs.append((raw, req.specifier))+ assert specs, f"{TORCH_MIRROR_WORKFLOW.name} no longer pins torch; retarget this test"+ too_low = [raw for raw, spec in specs if TESTED_TORCH not in spec]+ assert not too_low, (+ f"{TORCH_MIRROR_WORKFLOW.name} caps torch below {TESTED_TORCH}, which unsloth_zoo "+ f"now admits: {too_low}. The two repos would disagree about the supported torch."+ )+++def test_the_checker_rejects_the_window_that_shipped_the_defect() -> None:+ """Negative control: every assertion above is a "nothing found" shape, which is also what a+ checker that has stopped checking reports.+ """+ shipped = SpecifierSet("".join(f"!={v}," for v in REJECTED) + ">=4.51.3,<=5.5.0")+ assert "5.5.0" in shipped+ assert "5.17.0" not in shipped, "the old window must not admit the release that fixes it"+ for rejected in REJECTED:+ assert rejected not in shipped+++def test_this_file_is_triggered_by_everything_it_scans() -> None:+ """A gate its own workflow's `paths:` filter cannot start is not a gate: the sweeps read every+ `.github/workflows/*.yml`, so moving a cap in one of them has to trigger this workflow.+ """+ if sys.version_info < (3, 11):+ pytest.skip("yaml parsing here needs the 3.11+ interpreter the job uses")+ import yaml++ workflow = yaml.safe_load((WORKFLOWS / "version-compat-ci.yml").read_text(encoding = "utf-8"))+ # PyYAML resolves a bare `on:` key to the boolean True (YAML 1.1), so read both.+ triggers = workflow.get("on", workflow.get(True)) or {}+ paths = (triggers.get("pull_request") or {}).get("paths") or []++ required = (".github/workflows/**", "tests/test_transformers_cap_sites.py")+ missing = [name for name in required if name not in paths]+ assert not missing, (+ f"version-compat-ci.yml's pull_request.paths does not cover {missing}, so a PR "+ f"touching only those files never starts the cap-site-consistency job that reads "+ f"them. Current filter: {paths}"+ )+++def test_a_stale_range_cap_is_caught_even_in_an_allowlisted_workflow(tmp_path, monkeypatch) -> None:+ """NEGATIVE CONTROL: keyed on the filename, one intentional pin exempted every other+ transformers requirement in that file, so a range cap could go stale in the scanned workflow.+ """+ workflows = tmp_path / "workflows"+ workflows.mkdir()+ (workflows / "version-compat-ci.yml").write_text(+ "run: |\n"+ " pip install 'transformers==4.51.3'\n" # exact pin: a point, not a cap+ " pip install 'transformers>=4.51.3,<=5.5.0'\n", # stale range cap: must be caught+ encoding = "utf-8",+ )+ monkeypatch.setattr(sys.modules[__name__], "WORKFLOWS", workflows)++ with pytest.raises(AssertionError) as raised:+ test_no_workflow_lane_sits_below_the_declared_ceiling()++ assert "version-compat-ci.yml" in str(raised.value)+ assert "<=5.5.0" in str(raised.value)+ assert "==4.51.3" not in str(raised.value), "an exact pin is a point in the range, not a cap"+++def _matrix_module(urlopen):+ """The pinned-symbols module, imported fresh with `urlopen` replaced, under its own name: the+ matrix is built at import, so the substitution must precede the module body.+ """+ import importlib.util+ import urllib.request++ path = (+ Path(__file__).resolve().parent / "version_compat" / "test_transformers_pinned_symbols.py"+ )+ spec = importlib.util.spec_from_file_location("_matrix_under_test", path)+ module = importlib.util.module_from_spec(spec)+ original = urllib.request.urlopen+ urllib.request.urlopen = urlopen+ try:+ spec.loader.exec_module(module)+ finally:+ urllib.request.urlopen = original+ return module+++def test_a_pypi_outage_keeps_every_load_bearing_tag() -> None:+ """`_ALWAYS` names the patches a check exists for (v5.5.0 Apple Silicon ceiling, v5.16.0+ tokenizers breakpoint); returning `_TAGS_FALLBACK` unmerged dropped both and reported green.+ """+ import urllib.error++ def refuses(*args, **kwargs):+ raise urllib.error.URLError("pypi is unreachable")++ module = _matrix_module(refuses)++ assert set(module._ALWAYS).issubset(+ module.TRANSFORMERS_TAGS+ ), "a PyPI outage dropped a load-bearing tag from the matrix"+ assert set(module._TAGS_FALLBACK).issubset(module.TRANSFORMERS_TAGS)+ assert module.TRANSFORMERS_TAGS[-1] == "main"+++def test_the_outage_fallback_reaches_the_declared_floor() -> None:+ """An outage must not quietly move the floor up: the frozen fallback began at 4.57.6, so any PyPI+ failure dropped every 4.52-4.56 check. `_ALWAYS` cannot restore them, both its anchors are 5.x.+ """+ import urllib.error++ def refuses(*args, **kwargs):+ raise urllib.error.URLError("pypi is unreachable")++ module = _matrix_module(refuses)+ declared = module._declared_floor()+ concrete = [tag for tag in module.TRANSFORMERS_TAGS if tag != "main"]+ assert concrete, "the outage fallback resolved no tags at all"+ lowest = min(module._sort_key(tag) for tag in concrete)+ assert lowest <= declared, (+ f"under a PyPI outage the oldest tag checked is {lowest}, above the declared "+ f"floor {declared}, so every release between them goes unchecked while CI is green"+ )+ minors = {module._sort_key(tag)[:2] for tag in concrete}+ missing = [m for m in ((4, 52), (4, 53), (4, 54), (4, 55), (4, 56)) if m not in minors]+ assert not missing, f"the outage fallback covers no tag for supported minors {missing}"+++def test_an_empty_release_index_keeps_every_load_bearing_tag() -> None:+ """NEGATIVE CONTROL: a reachable PyPI yielding no usable release takes a different return+ path, which has to merge the anchors too.+ """+ import io+ import json as _json++ class _Response(io.BytesIO):+ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.close()+ return False++ def empty(*args, **kwargs):+ return _Response(_json.dumps({"releases": {}}).encode("utf-8"))++ module = _matrix_module(empty)++ assert set(module._ALWAYS).issubset(module.TRANSFORMERS_TAGS)+++def test_the_declared_ceiling_stays_in_the_matrix_after_a_patch_release() -> None:+ """One tag per minor means a 5.17.1 would evict 5.17.0, the exact maximum the window admits, and+ check a version no user can resolve instead. The anchor derives from pyproject's cap.+ """+ import io+ import json as _json++ class _Response(io.BytesIO):+ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.close()+ return False++ published = {+ "5.17.0": [{"yanked": False}],+ "5.17.1": [{"yanked": False}],+ }++ def releases(*args, **kwargs):+ return _Response(_json.dumps({"releases": published}).encode("utf-8"))++ module = _matrix_module(releases)++ assert module._declared_ceiling_tag() == (+ "v5.17.0",+ ), "the anchor is no longer read from pyproject's transformers cap"+ assert "v5.17.1" in module.TRANSFORMERS_TAGS, "the newest patch is still measured"+ assert (+ "v5.17.0" in module.TRANSFORMERS_TAGS+ ), "a patch release evicted the declared ceiling from the matrix"+++def test_the_matrix_is_shared_between_xdist_workers(tmp_path, monkeypatch) -> None:+ """Each worker resolves the matrix during collection, so one timing out takes the fallback list,+ the parameter sets diverge and xdist aborts. With the cache set, the first to resolve publishes.+ """+ import io+ import json as _json+ import urllib.error++ cache = tmp_path / "matrix.json"+ monkeypatch.setenv("PYTEST_TRANSFORMERS_MATRIX_FILE", str(cache))++ class _Response(io.BytesIO):+ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.close()+ return False++ def succeeds(*args, **kwargs):+ return _Response(_json.dumps({"releases": {"5.17.0": [{"yanked": False}]}}).encode("utf-8"))++ def refuses(*args, **kwargs):+ raise urllib.error.URLError("this worker's read timed out")++ first = _matrix_module(succeeds)+ assert cache.is_file(), "the resolved matrix was not published for the other workers"++ second = _matrix_module(refuses)+ assert (+ second.TRANSFORMERS_TAGS == first.TRANSFORMERS_TAGS+ ), "a failed read gave one worker a different matrix, which aborts an xdist run"+ assert "v5.17.0" in second.TRANSFORMERS_TAGS+++def test_without_the_cache_a_failed_read_still_falls_back(tmp_path, monkeypatch) -> None:+ """NEGATIVE CONTROL: the cache is a sharing mechanism, not a new dependency."""+ import urllib.error++ monkeypatch.delenv("PYTEST_TRANSFORMERS_MATRIX_FILE", raising = False)++ def refuses(*args, **kwargs):+ raise urllib.error.URLError("pypi is unreachable")++ module = _matrix_module(refuses)+ assert set(module._TAGS_FALLBACK).issubset(module.TRANSFORMERS_TAGS)+++def test_a_pinned_patch_release_is_not_evicted_by_a_later_one() -> None:+ """Notebooks pin 5.10.1; with 5.10.4 published the (5, 10) slot becomes 5.10.4, so a symbol+ arriving in a later 5.10 patch would break them while this matrix stayed green.+ """+ import io+ import json as _json++ class _Response(io.BytesIO):+ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.close()+ return False++ def releases(*args, **kwargs):+ published = {version: [{"yanked": False}] for version in ("5.10.1", "5.10.4", "5.15.1")}+ return _Response(_json.dumps({"releases": published}).encode("utf-8"))++ module = _matrix_module(releases)++ assert (+ "v5.10.3" in module.TRANSFORMERS_TAGS+ ), "the newest 5.10 patch is still measured (PyPI 5.10.4 is tagged v5.10.3 upstream)"+ assert "v5.10.1" in module.TRANSFORMERS_TAGS, "a later patch evicted the pinned 5.10.1"+ assert "v5.15.1" in module.TRANSFORMERS_TAGS++ for version in ("5.10.1", "5.15.1"):+ assert (+ "v" + version in module._ALWAYS+ ), f"{version} is in NEWLY_ADMITTED but is not anchored in the matrix"+++def test_an_import_lane_pins_the_declared_ceiling() -> None:+ """The `latest` lane is unpinned, so once upstream publishes above the cap it resolves a+ combination no user can install. The static symbol suite cannot see import-time breakage.+ """+ import yaml++ workflow = yaml.safe_load((WORKFLOWS / "version-compat-ci.yml").read_text(encoding = "utf-8"))+ job = workflow["jobs"]["zoo-imports-under-spoof"]+ lanes = {lane["slug"]: lane for lane in job["strategy"]["matrix"]["include"]}++ assert (+ "ceiling" in lanes+ ), "no import lane pins the declared ceiling, so only the floor is exercised"+ pins = " ".join(lanes["ceiling"]["pkg_pins"].split())+ assert (+ f"'transformers=={TESTED_CEILING}'" in pins+ ), f"the ceiling lane does not pin transformers=={TESTED_CEILING}; it reads {pins}"++ assert lanes["latest"].get("continue_on_error") is True+ for slug in ("floor", "ceiling"):+ assert (+ lanes[slug].get("continue_on_error") is None+ ), f"the {slug} lane is inside the declared window, so it must stay blocking"+++def test_the_ceiling_lane_moves_with_the_declared_window() -> None:+ """NEGATIVE CONTROL: the pin is a YAML literal, so it goes stale exactly the way a cap does."""+ import yaml++ workflow = yaml.safe_load((WORKFLOWS / "version-compat-ci.yml").read_text(encoding = "utf-8"))+ lanes = {+ lane["slug"]: lane+ for lane in workflow["jobs"]["zoo-imports-under-spoof"]["strategy"]["matrix"]["include"]+ }+ pinned = re.search(r"'transformers==([0-9][^']*)'", lanes["ceiling"]["pkg_pins"])+ assert pinned is not None+ assert Version(pinned.group(1)) == TESTED_CEILING, (+ f"the ceiling lane pins {pinned.group(1)} while the declared window tops out at "+ f"{TESTED_CEILING}"+ )+++def test_no_two_import_lanes_mint_the_same_pip_cache_key() -> None:+ """Two lanes on one interpreter share a key, so whichever saves first wins and the other+ re-downloads. The restore step cannot take `matrix.slug`: the name must be a literal lowercase.+ """+ import yaml++ workflow = yaml.safe_load((WORKFLOWS / "version-compat-ci.yml").read_text(encoding = "utf-8"))+ lanes = workflow["jobs"]["zoo-imports-under-spoof"]["strategy"]["matrix"]["include"]+ interpreters = [lane["python"] for lane in lanes]+ assert len(interpreters) == len(set(interpreters)), (+ f"two import lanes share an interpreter and so share one pip cache key: "+ f"{[(lane['slug'], lane['python']) for lane in lanes]}"+ )+++def test_a_published_matrix_still_carries_the_anchors(tmp_path, monkeypatch) -> None:+ """The published file can come from another revision or an earlier run, and returning it verbatim+ dropped the floor, the old ceiling and the notebook pins while the suite reported green.+ """+ import json as _json+ import urllib.error++ cache = tmp_path / "published.json"+ cache.write_text(_json.dumps(["v5.17.0"]), encoding = "utf-8")+ monkeypatch.setenv("PYTEST_TRANSFORMERS_MATRIX_FILE", str(cache))++ def refuses(*args, **kwargs):+ raise urllib.error.URLError("this worker reads the published file, not PyPI")++ module = _matrix_module(refuses)++ assert set(module._ALWAYS).issubset(+ module.TRANSFORMERS_TAGS+ ), "the published matrix was returned without its anchors"+ assert module._declared_ceiling_tag()[0] in module.TRANSFORMERS_TAGS+ assert "v5.17.0" in module.TRANSFORMERS_TAGS+++def test_the_declared_ceiling_anchor_uses_the_tag_upstream_pushed() -> None:+ """NEGATIVE CONTROL: upstream does not always tag a release under its own name, so a ceiling+ landing on one must resolve to the tag pushed or every check fails on the fetch.+ """+ import importlib.util++ path = (+ Path(__file__).resolve().parent / "version_compat" / "test_transformers_pinned_symbols.py"+ )+ spec = importlib.util.spec_from_file_location("_ceiling_under_test", path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)++ for release, tag in module._TAG_OVERRIDES.items():+ assert module._TAG_OVERRIDES.get(release) == tag+ assert "_TAG_OVERRIDES" in inspect.getsource(+ module._declared_ceiling_tag+ ), "the ceiling anchor is built as 'v' + version and ignores the override table"+++def _newest_published_zoo_transformers_ceiling(timeout: float = 10.0):+ """(zoo version, transformers ceiling) for the newest unsloth_zoo on PyPI, else None. Never+ raises: the caller treats "could not ask" as "keep deferring".+ """+ import json+ import urllib.error+ import urllib.request++ try:+ with urllib.request.urlopen(+ "https://pypi.org/pypi/unsloth_zoo/json", timeout = timeout+ ) as handle:+ payload = json.load(handle)+ except (urllib.error.URLError, TimeoutError, ValueError, OSError):+ return None++ info = payload.get("info") or {}+ released = info.get("version")+ if not released:+ return None++ # Whole SpecifierSets: `<5.17.0` and `<=5.17.0` name the same number but differ.+ windows = []+ for raw in info.get("requires_dist") or []:+ try:+ req = Requirement(raw)+ except InvalidRequirement:+ continue+ if req.name.lower() != "transformers" or not req.specifier:+ continue+ windows.append(req.specifier)+ if not windows:+ return None+ return Version(released), windows+++def test_the_zoo_deferral_expires_when_the_zoo_release_ships() -> None:+ """The gate above skips on a hand-written constant, so this asks PyPI what the newest zoo allows+ and fails only on POSITIVE evidence it is obsolete; an offline runner stays skipped.+ """+ if ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP is not None:+ pytest.skip(+ "the floor already names a zoo release carrying the lift, so the deferral is "+ "over and the gate above is live"+ )++ published = _newest_published_zoo_transformers_ceiling()+ if published is None:+ pytest.skip("PyPI could not be asked for unsloth_zoo, so the deferral stands")++ zoo_version, zoo_windows = published+ declared = _ceiling(_declared_window())+ covering = [str(window) for window in zoo_windows if window.contains(declared)]+ assert not covering, (+ f"unsloth_zoo {zoo_version} is published and admits transformers {declared} "+ f"({', '.join(covering)}), the exact ceiling declared here, so the deferral is "+ f"over. Set ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP to {zoo_version} and raise the "+ f"unsloth_zoo floor in pyproject.toml to it in the same commit; that re-enables "+ f"test_the_declared_zoo_floor_can_supply_the_declared_transformers_window, which "+ f"is what actually checks the two windows agree."+ )diff --git a/tests/test_trl_cap_sites.py b/tests/test_trl_cap_sites.pynew file mode 100644index 00000000000..58edf7932e8--- /dev/null+++ b/tests/test_trl_cap_sites.py@@ -0,0 +1,910 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""Every TRL cap site and TRL-keyed runtime guard must agree with pyproject's window."""++from __future__ import annotations++import re+import sys+from pathlib import Path++import pytest+from packaging.requirements import InvalidRequirement, Requirement+from packaging.specifiers import SpecifierSet+from packaging.version import Version+++REPO = Path(__file__).resolve().parents[1]+PYPROJECT = REPO / "pyproject.toml"+WORKFLOWS = REPO / ".github" / "workflows"+RUNTIME_MIRROR = REPO / "studio" / "backend" / "requirements" / "no-torch-runtime.txt"+RL_REPLACEMENTS = REPO / "unsloth" / "models" / "rl_replacements.py"++# Newest TRL the matrix was run against; moving it means re-running the sweep first.+TESTED_CEILING = Version("1.13.0")++REJECTED = ("0.19.0",)++NEWLY_ADMITTED = ("0.29.1", "1.0.0", "1.6.0", "1.7.0", "1.13.0")++ZOO_TRL_CEILING_BEFORE_THE_LIFT = Version("0.24.0")++ZOO_FLOOR_WITH_LIFTED_TRL_CAP = Version("2026.9.5")++# Every unsloth_zoo up to 2026.9.7 caps datasets here; pip intersects, so users stay under it.+ZOO_DATASETS_CEILING_BEFORE_THE_LIFT = SpecifierSet("<4.4.0")++ZOO_FLOOR_WITH_LIFTED_DATASETS_CAP = Version("2026.9.8")++PINNED_BY_DESIGN = {+ ("consolidated-tests-ci.yml", "trl>=0.18.2,<1.0.0"): (+ "the TRL<1 half of a deliberate two-lane split; the sibling lane is "+ "'trl>=1,<2', so between them the pair covers both majors and neither is a cap "+ "that drifted"+ ),+}+++def _toml() -> dict:+ """tomllib is 3.11+; skip rather than fail collection on older interpreters."""+ if sys.version_info < (3, 11):+ pytest.skip("tomllib needs Python 3.11+")+ import tomllib++ return tomllib.loads(PYPROJECT.read_text(encoding = "utf-8"))+++def _pyproject_trl() -> list[Requirement]:+ data = _toml()+ project = data.get("project") or {}+ raws: list[str] = list(project.get("dependencies") or [])+ for extra in (project.get("optional-dependencies") or {}).values():+ raws.extend(extra)+ out = []+ for raw in raws:+ try:+ req = Requirement(raw)+ except InvalidRequirement:+ continue+ if req.name.lower().replace("_", "-") == "trl":+ out.append(req)+ return out+++def _declared_window() -> SpecifierSet:+ reqs = _pyproject_trl()+ assert reqs, "pyproject.toml declares no trl requirement at all"+ windows = {str(req.specifier) for req in reqs}+ assert len(windows) == 1, (+ f"pyproject.toml declares {len(windows)} different trl windows across its extras: "+ f"{sorted(windows)}. One of them will be the one users hit and the other will be "+ f"the one CI tests."+ )+ return SpecifierSet(windows.pop())+++def _ceiling(window: SpecifierSet) -> Version:+ """The TIGHTEST upper bound: `max` of `<=0.24.0,<=1.13.0` wrongly reports 1.13.0."""+ tops = [+ (Version(str(spec.version)), spec.operator)+ for spec in window+ if spec.operator in ("<=", "<")+ ]+ assert tops, f"the trl window declares no upper bound at all: {window}"+ version, _operator = min(tops, key = lambda pair: (pair[0], pair[1] == "<="))+ return version+++def test_pyproject_declares_one_trl_window() -> None:+ window = _declared_window()+ assert len(_pyproject_trl()) >= 2, (+ "this test assumed pyproject names trl in more than one place; if that stopped "+ "being true, the drift it guards against is gone and so is the point"+ )+ assert _ceiling(window) == TESTED_CEILING, (+ f"pyproject.toml caps trl at {_ceiling(window)}, and the version matrix was run "+ f"against {TESTED_CEILING}. Raising the cap means running the sweep on the new "+ f"release and moving TESTED_CEILING here in the same commit."+ )+++def test_the_window_admits_every_release_the_sweep_passed() -> None:+ window = _declared_window()+ missing = [v for v in NEWLY_ADMITTED if v not in window]+ assert not missing, (+ f"the trl window {window} excludes {missing}, which the sweep passed. An "+ f"exclusion has to name the test that failed on that release."+ )+++def test_every_rejected_release_is_still_rejected() -> None:+ window = _declared_window()+ readmitted = [v for v in REJECTED if v in window]+ assert not readmitted, (+ f"the trl window {window} now admits {readmitted}, which were tested and "+ f"rejected. Rewriting the specifier must not drop an exclusion."+ )+++def test_the_runtime_requirements_mirror_restates_the_same_window() -> None:+ """`no-torch-runtime.txt` copies pyproject's spec rather than resolving it."""+ window = _declared_window()+ found = []+ for line in RUNTIME_MIRROR.read_text(encoding = "utf-8").splitlines():+ line = line.split("#", 1)[0].strip()+ if not line:+ continue+ try:+ req = Requirement(line)+ except InvalidRequirement:+ continue+ if req.name.lower() == "trl":+ found.append(req.specifier)+ assert found, f"{RUNTIME_MIRROR.name} no longer names trl; retarget this test"+ disagree = [str(spec) for spec in found if str(spec) != str(window)]+ assert not disagree, (+ f"{RUNTIME_MIRROR.name} declares {disagree} while pyproject.toml declares "+ f"{window}. The installer would ship a different TRL range than the package "+ f"advertises."+ )+++def _pyproject_zoo() -> list[Requirement]:+ data = _toml()+ project = data.get("project") or {}+ raws: list[str] = list(project.get("dependencies") or [])+ for extra in (project.get("optional-dependencies") or {}).values():+ raws.extend(extra)+ out = []+ for raw in raws:+ try:+ req = Requirement(raw)+ except InvalidRequirement:+ continue+ if req.name.lower().replace("_", "-") == "unsloth-zoo" and req.specifier:+ out.append(req)+ return out+++def test_the_declared_zoo_floor_can_supply_the_declared_trl_window() -> None:+ """pip gives the user the LOWER of our and the zoo's trl ceilings."""+ ceiling = _ceiling(_declared_window())+ if ceiling <= ZOO_TRL_CEILING_BEFORE_THE_LIFT:+ pytest.skip(+ f"declared trl ceiling {ceiling} is within what zoo "+ f"<{ZOO_FLOOR_WITH_LIFTED_TRL_CAP} already admits; nothing to coordinate"+ )+ reqs = _pyproject_zoo()+ assert reqs, (+ "pyproject.toml declares a trl ceiling above what the published unsloth_zoo "+ "admits, and names no versioned unsloth_zoo requirement at all, so nothing "+ "stops pip resolving the zoo that caps trl lower"+ )+ floors = {}+ for req in reqs:+ lower = [+ Version(str(spec.version))+ for spec in req.specifier+ if spec.operator in (">=", "==", "~=")+ ]+ assert lower, (+ f"unsloth_zoo requirement {req} has no lower bound, so it admits the "+ f"release whose own trl cap is {ZOO_TRL_CEILING_BEFORE_THE_LIFT}"+ )+ floors[str(req)] = max(lower)+ stale = {+ raw: str(floor) for raw, floor in floors.items() if floor < ZOO_FLOOR_WITH_LIFTED_TRL_CAP+ }+ assert not stale, (+ f"pyproject.toml admits trl up to {ceiling} while still accepting unsloth_zoo "+ f"{stale}. pip intersects the two requirements, so users would resolve the zoo "+ f"that caps trl at {ZOO_TRL_CEILING_BEFORE_THE_LIFT} and the wider window here "+ f"would never take effect. Move the floor to "+ f"{ZOO_FLOOR_WITH_LIFTED_TRL_CAP} in the same commit as the ceiling."+ )+ assert len(set(floors.values())) == 1, (+ f"pyproject.toml declares more than one unsloth_zoo floor: {floors}. One of them "+ f"is the one users hit."+ )+++def _trl_version_guards() -> list[tuple[int, Version]]:+ """(line, X) for every `trl < X` early-return in rl_replacements.py."""+ text = RL_REPLACEMENTS.read_text(encoding = "utf-8")+ out = []+ pattern = re.compile(+ r"""Version\(\s*importlib_version\(\s*["']trl["']\s*\)\s*\)\s*<\s*Version\(\s*["']([\d.]+)["']\s*\)"""+ )+ for match in pattern.finditer(text):+ line = text.count("\n", 0, match.start()) + 1+ out.append((line, Version(match.group(1))))+ return out+++def test_no_trl_runtime_guard_is_unreachable_through_the_declared_window() -> None:+ """A patch gated on a TRL newer than the cap admits is dead code that ships green."""+ window = _declared_window()+ guards = _trl_version_guards()+ assert guards, (+ f"{RL_REPLACEMENTS.name} no longer gates any patch on a trl version; retarget "+ f"this test rather than deleting it"+ )+ unreachable = [(line, str(floor)) for line, floor in guards if not window.contains(str(floor))]+ assert not unreachable, (+ f"these patches in unsloth/models/rl_replacements.py require a TRL the declared "+ f"window {window} cannot resolve, so they can never run: {unreachable}. Either "+ f"lift the cap to admit that floor or delete the patch."+ )+++def _workflow_trl_specs(path: Path) -> list[tuple[str, Requirement]]:+ """Every `trl<spec>` requirement spelled inside a workflow's shell steps."""+ text = path.read_text(encoding = "utf-8")+ out = []+ for match in re.finditer(r"""['"](trl[<>=!,.\d\s]*)['"]""", text):+ try:+ req = Requirement(match.group(1))+ except InvalidRequirement:+ continue+ if req.name.lower() == "trl" and str(req.specifier):+ out.append((match.group(1), req))+ return out+++def test_no_workflow_lane_sits_below_the_declared_ceiling() -> None:+ ceiling = _ceiling(_declared_window())+ offenders: dict[str, list[str]] = {}+ for path in sorted(WORKFLOWS.glob("*.yml")):+ for raw, req in _workflow_trl_specs(path):+ if any(spec.operator == "==" for spec in req.specifier):+ continue+ if ceiling in req.specifier:+ continue+ if (path.name, raw.strip()) in PINNED_BY_DESIGN:+ continue+ offenders.setdefault(path.name, []).append(raw)+ assert not offenders, (+ f"these workflow lanes cap trl below the {ceiling} the package publishes, so they "+ f"test a range users do not get: {offenders}. Either widen the lane or add it to "+ f"PINNED_BY_DESIGN with the reason."+ )+++def _blocking_trl_lanes(path: Path) -> list[tuple[str, str, str]]:+ """Every (job, lane, trl spec) that can actually fail the run."""+ if sys.version_info < (3, 11):+ pytest.skip("yaml parsing here needs the 3.11+ interpreter the job uses")+ import yaml++ workflow = yaml.safe_load(path.read_text(encoding = "utf-8")) or {}+ out: list[tuple[str, str, str]] = []+ for job_name, job in (workflow.get("jobs") or {}).items():+ if not isinstance(job, dict):+ continue+ if job.get("continue-on-error") not in (None, False):+ continue+ includes = (((job.get("strategy") or {}).get("matrix") or {}).get("include")) or []+ lanes = includes if isinstance(includes, list) and includes else [{}]+ for lane in lanes:+ if not isinstance(lane, dict):+ continue+ if lane.get("continue_on_error") not in (None, False):+ continue+ slug = str(lane.get("slug", "<no matrix>"))+ blob = " ".join(str(v) for v in lane.values())+ for token in re.finditer(r"""(?:^|['"\s])(trl(?:[<>=!,.\d]*)?)(?=['"\s]|$)""", blob):+ out.append((str(job_name), slug, token.group(1)))+ return out+++def test_a_blocking_lane_installs_a_trl_from_the_newly_admitted_major() -> None:+ """Needs a blocking (not continue-on-error) lane on an explicit 1.x or unpinned trl."""+ window = _declared_window()+ lanes = _blocking_trl_lanes(WORKFLOWS / "version-compat-ci.yml")+ assert lanes, (+ "version-compat-ci.yml has no blocking lane that installs trl at all; retarget "+ "this test rather than deleting it"+ )+ reaches_one_x = []+ for job, slug, spec in lanes:+ if spec == "trl": # unpinned: resolves PyPI's newest, which is a 1.x+ reaches_one_x.append((job, slug, "unpinned"))+ continue+ try:+ specifier = Requirement(spec).specifier+ except InvalidRequirement:+ continue+ pins = [Version(str(s.version)) for s in specifier if s.operator == "=="]+ if any(v.major >= 1 and window.contains(str(v)) for v in pins):+ reaches_one_x.append((job, slug, spec))+ assert reaches_one_x, (+ f"no blocking lane in version-compat-ci.yml installs a TRL from the 1.x major "+ f"the window {window} now admits. Blocking lanes install: "+ f"{sorted({(j, s, p) for j, s, p in lanes})}. Lifting the cap without one means "+ f"the only lane that reaches 1.x is a continue-on-error canary, so a TRL 1.x "+ f"regression cannot fail this workflow."+ )+++def test_the_checker_rejects_the_window_that_stranded_the_patches() -> None:+ """Negative control for the "nothing found" assertions above."""+ shipped = SpecifierSet(">=0.18.2,!=0.19.0,<=0.24.0")+ assert "0.24.0" in shipped+ assert "1.13.0" not in shipped, "the old window must not admit the newly tested ceiling"+ for rejected in REJECTED:+ assert rejected not in shipped+ assert not shipped.contains("0.26.0")+ assert not shipped.contains("0.28.0")+++def test_this_file_is_triggered_by_everything_it_scans() -> None:+ """The workflow's `paths:` filter must include every file the sweeps read."""+ if sys.version_info < (3, 11):+ pytest.skip("yaml parsing here needs the 3.11+ interpreter the job uses")+ import yaml++ workflow = yaml.safe_load((WORKFLOWS / "version-compat-ci.yml").read_text(encoding = "utf-8"))+ triggers = workflow.get("on", workflow.get(True)) or {}+ paths = (triggers.get("pull_request") or {}).get("paths") or []++ required = (".github/workflows/**", "unsloth/**", "tests/test_trl_cap_sites.py")+ missing = [name for name in required if name not in paths]+ assert not missing, (+ f"version-compat-ci.yml's pull_request.paths does not cover {missing}, so a PR "+ f"touching only those files never starts the cap-site-consistency job that reads "+ f"them. Current filter: {paths}"+ )+++def test_a_stale_range_cap_is_caught_even_in_an_allowlisted_workflow(tmp_path, monkeypatch) -> None:+ """NEGATIVE CONTROL: exemptions keyed on filename would exempt every trl requirement in it."""+ workflows = tmp_path / "workflows"+ workflows.mkdir()+ (workflows / "consolidated-tests-ci.yml").write_text(+ "run: |\n"+ " pip install 'trl==0.18.2'\n" # exact pin: a point, not a cap+ " pip install 'trl>=0.18.2,<1.0.0'\n" # the allowlisted half of the split+ " pip install 'trl>=0.22,<0.26'\n", # stale range cap: must be caught+ encoding = "utf-8",+ )+ monkeypatch.setattr(sys.modules[__name__], "WORKFLOWS", workflows)++ with pytest.raises(AssertionError) as raised:+ test_no_workflow_lane_sits_below_the_declared_ceiling()++ message = str(raised.value)+ assert "consolidated-tests-ci.yml" in message+ assert "<0.26" in message+ assert "==0.18.2" not in message, "an exact pin is a point in the range, not a cap"+ assert "<1.0.0" not in message, "the allowlisted lane must stay allowlisted"+++def test_an_unreachable_guard_is_caught(tmp_path, monkeypatch) -> None:+ """NEGATIVE CONTROL: the guard sweep must fail on a floor above the cap."""+ fake = tmp_path / "rl_replacements.py"+ fake.write_text(+ "def later():\n"+ ' if Version(importlib_version("trl")) < Version("99.0.0"):\n'+ " return\n",+ encoding = "utf-8",+ )+ monkeypatch.setattr(sys.modules[__name__], "RL_REPLACEMENTS", fake)++ with pytest.raises(AssertionError) as raised:+ test_no_trl_runtime_guard_is_unreachable_through_the_declared_window()++ assert "99.0.0" in str(raised.value)+++_NON_WINDOWS_TOKENS = ("ubuntu", "linux", "macos", "darwin", "mac-", "'mac'")+++def _gated_off_windows(condition: str) -> bool:+ """Whether an `if:` keeps its step off Windows; only a POSITIVE non-Windows OS match counts."""+ lowered = condition.lower()+ if not any(token in lowered for token in _NON_WINDOWS_TOKENS):+ return False+ return "!=" not in lowered and "!" not in lowered+++def _steps_exposed_to_the_powershell_default(workflows: Path) -> list[tuple[str, str, str]]:+ """Every `run:` step a Windows runner hands to PowerShell (no `shell:`, not gated off Windows)."""+ import yaml++ exposed = []+ for path in sorted(workflows.glob("*.yml")):+ try:+ document = yaml.safe_load(path.read_text(encoding = "utf-8")) or {}+ except yaml.YAMLError:+ continue+ if not isinstance(document, dict):+ continue+ workflow_shell = ((document.get("defaults") or {}).get("run") or {}).get("shell")+ for job_name, job in (document.get("jobs") or {}).items():+ if not isinstance(job, dict):+ continue+ targets = f"{job.get('runs-on', '')}{job.get('strategy', '')}"+ if "windows" not in targets.lower():+ continue+ job_shell = ((job.get("defaults") or {}).get("run") or {}).get("shell")+ for index, step in enumerate(job.get("steps") or []):+ if not isinstance(step, dict):+ continue+ body = step.get("run")+ if not isinstance(body, str):+ continue+ if step.get("shell") or job_shell or workflow_shell:+ continue+ if _gated_off_windows(str(step.get("if", ""))):+ continue+ name = step.get("name", f"step {index}")+ exposed.append((path.name, job_name, name, body))+ return exposed+++def test_no_windows_step_uses_a_bash_line_continuation() -> None:+ r"""PowerShell passes a trailing `\` through literally, so pytest collected the whole drive."""+ if sys.version_info < (3, 11):+ pytest.skip("yaml parsing here needs the 3.11+ interpreter the job uses")++ offenders = [+ f"{workflow}: job {job!r} step {name!r}"+ for workflow, job, name, body in _steps_exposed_to_the_powershell_default(WORKFLOWS)+ if re.search(r"\\\s*\n", body)+ ]+ assert not offenders, (+ "these steps run under PowerShell on a Windows runner and use a bash `\\` line "+ "continuation, so the Windows leg silently runs a different command than the "+ "Linux one: " + "; ".join(offenders) + ". Put the command on one line or set "+ "`shell: bash` on the step."+ )+++ "condition,gated",+ [+ ("", False),+ ("startsWith(matrix.artifact, 'linux-')", True),+ ("runner.os == 'Linux'", True),+ ("matrix.os == 'ubuntu-latest'", True),+ ("runner.os == 'macOS'", True),+ ("matrix.os != 'ubuntu-latest'", False),+ ("!startsWith(matrix.artifact, 'linux-')", False),+ ("github.event_name == 'pull_request'", False),+ ],+)+def test_only_a_positive_non_windows_guard_clears_a_step(condition: str, gated: bool) -> None:+ """The `!=` case is the one that matters: it is how a step lands on Windows."""+ assert _gated_off_windows(condition) is gated+++def test_the_powershell_continuation_check_can_fail(tmp_path, monkeypatch) -> None:+ """NEGATIVE CONTROL for the PowerShell continuation check."""+ workflows = tmp_path / "workflows"+ workflows.mkdir()+ (workflows / "example-ci.yml").write_text(+ "jobs:\n"+ " gate:\n"+ " runs-on: windows-latest\n"+ " steps:\n"+ " - name: Assert every site declares the same window\n"+ " run: |\n"+ " python -m pytest tests/a.py \\\n"+ " tests/b.py -v\n",+ encoding = "utf-8",+ )+ monkeypatch.setattr(sys.modules[__name__], "WORKFLOWS", workflows)++ with pytest.raises(AssertionError) as raised:+ test_no_windows_step_uses_a_bash_line_continuation()+ assert "example-ci.yml" in str(raised.value)++ (workflows / "example-ci.yml").write_text(+ "jobs:\n"+ " gate:\n"+ " runs-on: windows-latest\n"+ " steps:\n"+ " - name: Assert every site declares the same window\n"+ " shell: bash\n"+ " run: |\n"+ " python -m pytest tests/a.py \\\n"+ " tests/b.py -v\n",+ encoding = "utf-8",+ )+ test_no_windows_step_uses_a_bash_line_continuation()+++def _ceiling_lane_trl_pins(workflows: Path) -> list[tuple[str, str, str]]:+ """(workflow, job, pinned trl version) per `slug: ceiling` matrix lane."""+ import yaml++ found = []+ for path in sorted(workflows.glob("*.yml")):+ try:+ document = yaml.safe_load(path.read_text(encoding = "utf-8")) or {}+ except yaml.YAMLError:+ continue+ if not isinstance(document, dict):+ continue+ for job_name, job in (document.get("jobs") or {}).items():+ if not isinstance(job, dict):+ continue+ strategy = job.get("strategy")+ matrix = strategy.get("matrix") if isinstance(strategy, dict) else None+ includes = matrix.get("include") if isinstance(matrix, dict) else None+ for entry in includes or []:+ if not isinstance(entry, dict) or entry.get("slug") != "ceiling":+ continue+ pins = str(entry.get("pkg_pins") or "")+ for match in re.finditer(r"trl==([0-9][0-9A-Za-z.\-]*)", pins):+ found.append((path.name, job_name, match.group(1)))+ return found+++def test_a_ceiling_lane_pins_the_declared_ceiling() -> None:+ """The range sweep exempts `==` pins, so the ceiling lane needs its own check."""+ if sys.version_info < (3, 11):+ pytest.skip("yaml parsing here needs the 3.11+ interpreter the job uses")++ declared = _ceiling(_declared_window())+ lanes = _ceiling_lane_trl_pins(WORKFLOWS)+ assert lanes, (+ "no lane with `slug: ceiling` pins trl at all, so nothing measures the top of the "+ "declared window. If the ceiling lane was renamed, rename it here too."+ )+ stale = [+ f"{workflow}: job {job!r} pins trl=={pinned}"+ for workflow, job, pinned in lanes+ if Version(pinned) != declared+ ]+ assert not stale, (+ f"the declared trl ceiling is {declared}, but " + "; ".join(stale) + ". A lane "+ f"called `ceiling` that pins something else measures a range that is no longer the "+ f"edge of the window. Move the pin with the cap."+ )+++def test_the_ceiling_lane_check_can_fail(tmp_path, monkeypatch) -> None:+ """NEGATIVE CONTROL: the stale ceiling pin that shipped."""+ workflows = tmp_path / "workflows"+ workflows.mkdir()++ def write(trl_pin: str) -> None:+ (workflows / "version-compat-ci.yml").write_text(+ "jobs:\n"+ " zoo-imports-under-spoof:\n"+ " strategy:\n"+ " matrix:\n"+ " include:\n"+ " - slug: floor\n"+ " pkg_pins: \"'transformers==4.52.4' 'trl==0.18.2'\"\n"+ " - slug: ceiling\n"+ f" pkg_pins: \"'transformers==5.17.0' '{trl_pin}'\"\n",+ encoding = "utf-8",+ )++ monkeypatch.setattr(sys.modules[__name__], "WORKFLOWS", workflows)++ write("trl==0.24.0")+ with pytest.raises(AssertionError) as raised:+ test_a_ceiling_lane_pins_the_declared_ceiling()+ assert "0.24.0" in str(raised.value)++ write(f"trl=={TESTED_CEILING}")+ test_a_ceiling_lane_pins_the_declared_ceiling()+++# Must be resolvable: trl 1.x needs datasets>=4.7.0, else pip backtracks to trl 0.29.1.+TRL_DATASETS_FLOORS = (+ (Version("0.18.2"), Version("3.0.0")),+ (Version("1.0.0"), Version("4.7.0")),+)+++def _pyproject_requirement(name: str) -> SpecifierSet:+ """The single declared window for `name`; exact `==` pins (Studio single-env) are skipped."""+ data = _toml()+ project = data.get("project") or {}+ raws: list[str] = list(project.get("dependencies") or [])+ for extra in (project.get("optional-dependencies") or {}).values():+ raws.extend(extra)+ windows = set()+ for raw in raws:+ try:+ req = Requirement(raw)+ except InvalidRequirement:+ continue+ if req.name.lower().replace("_", "-") != name:+ continue+ if all(spec.operator == "==" for spec in req.specifier) and len(req.specifier):+ continue+ windows.add(str(req.specifier))+ assert windows, f"pyproject.toml declares no {name} window at all, only exact pins"+ assert len(windows) == 1, (+ f"pyproject.toml declares {len(windows)} different {name} windows across its "+ f"extras: {sorted(windows)}. One of them will be the one users hit and the other "+ f"will be the one CI tests."+ )+ return SpecifierSet(windows.pop())+++def _datasets_floor_for(trl_version: Version) -> Version:+ floor = TRL_DATASETS_FLOORS[0][1]+ for first, declared in TRL_DATASETS_FLOORS:+ if trl_version >= first:+ floor = declared+ return floor+++def _datasets_releases() -> list[Version]:+ """Every datasets release the declared window could pick."""+ return [+ Version(v)+ for v in (+ "3.4.1",+ "3.5.0",+ "3.6.0",+ "4.0.0",+ "4.1.0",+ "4.2.0",+ "4.3.0",+ "4.4.0",+ "4.4.1",+ "4.4.2",+ "4.5.0",+ "4.6.0",+ "4.6.1",+ "4.7.0",+ "4.8.0",+ "4.8.5",+ "5.0.0",+ "5.0.1",+ )+ ]+++def test_the_declared_datasets_window_can_supply_the_declared_trl_ceiling() -> None:+ """The assertion the shipped cap failed: a ceiling no sibling window lets pip reach."""+ ceiling = _ceiling(_declared_window())+ needed = _datasets_floor_for(ceiling)+ datasets_window = _pyproject_requirement("datasets")+ usable = [v for v in _datasets_releases() if str(v) in datasets_window and v >= needed]+ assert usable, (+ f"the declared trl ceiling {ceiling} requires datasets>={needed}, but the declared "+ f"datasets window {datasets_window} admits no such release. pip does not error on "+ f"this: it backtracks to the newest trl whose datasets floor fits and installs that "+ f"instead, so the advertised ceiling is one no install can reach and nothing goes "+ f"red. Move the datasets window with the trl one, or lower the trl ceiling to the "+ f"newest release this datasets window can actually supply."+ )+++def test_the_resolvability_check_can_fail() -> None:+ """NEGATIVE CONTROL: the window that shipped, and the one that fixes it."""+ stranded = SpecifierSet(">=3.4.1,!=4.0.*,!=4.1.0,<4.4.0")+ needed = _datasets_floor_for(Version("1.13.0"))+ assert not [v for v in _datasets_releases() if str(v) in stranded and v >= needed], (+ "datasets<4.4.0 must not be able to supply a trl 1.x: that pairing is exactly the "+ "silently-unreachable ceiling this check exists to catch."+ )+ opened = SpecifierSet(">=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0")+ assert [v for v in _datasets_releases() if str(v) in opened and v >= needed]+++def _runtime_forbidden_datasets_range() -> tuple[Version, Version]:+ """The (low, high) datasets range `patch_datasets` refuses at import, read off the guard."""+ guard = RL_REPLACEMENTS.parent.parent / "import_fixes.py"+ source = guard.read_text(encoding = "utf-8")+ match = re.search(+ r'datasets_version <= Version\("([\d.]+)"\).*?datasets_version >= Version\("([\d.]+)"\)',+ source,+ re.S,+ )+ assert match, "patch_datasets no longer states its forbidden range in the shape this reads"+ return Version(match.group(2)), Version(match.group(1))+++def _workflow_datasets_specs(path: Path) -> list[tuple[str, Requirement]]:+ """Every `datasets<spec>` requirement spelled inside a workflow's shell steps."""+ text = path.read_text(encoding = "utf-8")+ out = []+ for match in re.finditer(r"""['"](datasets[<>=!,.*\d\s]*)['"]""", text):+ try:+ req = Requirement(match.group(1))+ except InvalidRequirement:+ continue+ if req.name.lower() == "datasets" and str(req.specifier):+ out.append((match.group(1), req))+ return out+++def test_no_workflow_lane_installs_a_datasets_the_runtime_guard_refuses() -> None:+ """A loose datasets bound admits 4.4.x/4.5.0, which unsloth refuses at import."""+ low, high = _runtime_forbidden_datasets_range()+ refused = [v for v in _datasets_releases() if low <= v <= high]+ assert refused, "no recorded datasets release falls in the guard's forbidden range"++ offenders: dict[str, list[str]] = {}+ for path in sorted(WORKFLOWS.glob("*.yml")):+ for raw, req in _workflow_datasets_specs(path):+ # Exact pins are NOT exempt here: `datasets==4.4.0` cannot import.+ admitted = [v for v in refused if str(v) in req.specifier]+ if admitted:+ offenders.setdefault(path.name, []).append(+ f"{raw.strip()} admits {', '.join(str(v) for v in admitted)}"+ )+ assert not offenders, (+ f"these workflow lanes can resolve a datasets that patch_datasets refuses at import "+ f"[{low}, {high}], so the job dies on `import unsloth` rather than testing anything: "+ f"{offenders}. Spell the declared pyproject window instead."+ )+++def test_the_workflow_datasets_check_can_fail(tmp_path, monkeypatch) -> None:+ """NEGATIVE CONTROL: the loose bound that shipped must be caught."""+ workflows = tmp_path / "workflows"+ workflows.mkdir()+ (workflows / "example-ci.yml").write_text(+ "jobs:\n gate:\n steps:\n - run: pip install 'datasets>=3.4,<5'\n",+ encoding = "utf-8",+ )+ monkeypatch.setattr(sys.modules[__name__], "WORKFLOWS", workflows)+ with pytest.raises(AssertionError) as raised:+ test_no_workflow_lane_installs_a_datasets_the_runtime_guard_refuses()+ assert "example-ci.yml" in str(raised.value)++ (workflows / "example-ci.yml").write_text(+ "jobs:\n gate:\n steps:\n - run: pip install "+ "'datasets>=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0'\n",+ encoding = "utf-8",+ )+ test_no_workflow_lane_installs_a_datasets_the_runtime_guard_refuses()+++def test_the_datasets_window_still_excludes_exactly_what_the_runtime_guard_refuses() -> None:+ """Must equal the guard's window: wider installs refused releases, narrower strands the ceiling."""+ low, high = _runtime_forbidden_datasets_range()++ window = _pyproject_requirement("datasets")+ for release in _datasets_releases():+ refused_at_runtime = low <= release <= high+ admitted_by_metadata = str(release) in window+ if refused_at_runtime:+ assert not admitted_by_metadata, (+ f"datasets {release} is inside patch_datasets' forbidden range "+ f"[{low}, {high}] but the declared window still admits it, so pip may "+ f"install a release that raises NotImplementedError at import."+ )+++def test_the_recorded_trl_datasets_floors_still_match_pypi() -> None:+ """Re-derive TRL_DATASETS_FLOORS from PyPI. Skips offline; this is the only network here."""+ import json+ import urllib.error+ import urllib.request++ def metadata(version: Version) -> list[str]:+ url = f"https://pypi.org/pypi/trl/{version}/json"+ try:+ with urllib.request.urlopen(url, timeout = 15) as response:+ return json.load(response)["info"].get("requires_dist") or []+ except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as error:+ pytest.skip(f"PyPI unreachable ({error})")++ for first, declared in TRL_DATASETS_FLOORS:+ floors = [+ Requirement(raw).specifier+ for raw in metadata(first)+ if Requirement(raw).name.lower() == "datasets" and not Requirement(raw).marker+ ]+ assert floors, f"trl {first} declares no unconditional datasets requirement"+ assert str(declared) in str(floors[0]), (+ f"trl {first} now declares datasets{floors[0]}, not >={declared}. Update "+ f"TRL_DATASETS_FLOORS, then re-check the declared datasets window against it."+ )+++def _newest_published_zoo_datasets_windows(timeout: float = 10.0):+ """(zoo version, datasets windows) for the newest unsloth_zoo on PyPI, else None; never raises."""+ import json+ import urllib.error+ import urllib.request++ try:+ with urllib.request.urlopen(+ "https://pypi.org/pypi/unsloth_zoo/json", timeout = timeout+ ) as handle:+ payload = json.load(handle)+ except (urllib.error.URLError, TimeoutError, ValueError, OSError):+ return None++ info = payload.get("info") or {}+ released = info.get("version")+ if not released:+ return None++ windows = []+ for raw in info.get("requires_dist") or []:+ try:+ req = Requirement(raw)+ except InvalidRequirement:+ continue+ if req.name.lower() != "datasets" or not req.specifier:+ continue+ windows.append(req.specifier)+ if not windows:+ return None+ return Version(released), windows+++def test_the_declared_zoo_floor_can_supply_the_declared_datasets_window() -> None:+ """The datasets twin of the trl zoo gate; deferred while ZOO_FLOOR_WITH_LIFTED_DATASETS_CAP is None."""+ if ZOO_FLOOR_WITH_LIFTED_DATASETS_CAP is None:+ pytest.skip(+ "deferred: no published unsloth_zoo carries the widened datasets window, so pip "+ "keeps intersecting it back to the zoo's own cap. Re-enable by setting "+ "ZOO_FLOOR_WITH_LIFTED_DATASETS_CAP to the release that carries it."+ )+ reqs = _pyproject_zoo()+ assert reqs, "pyproject.toml names no versioned unsloth_zoo requirement at all"+ floors = {}+ for req in reqs:+ lower = [+ Version(str(spec.version))+ for spec in req.specifier+ if spec.operator in (">=", "==", "~=")+ ]+ assert lower, f"unsloth_zoo requirement {req} has no lower bound"+ floors[str(req)] = max(lower)+ stale = {+ raw: str(floor)+ for raw, floor in floors.items()+ if floor < ZOO_FLOOR_WITH_LIFTED_DATASETS_CAP+ }+ assert not stale, (+ f"pyproject.toml widens datasets while still accepting unsloth_zoo {stale}, whose own "+ f"cap is {ZOO_DATASETS_CEILING_BEFORE_THE_LIFT}. Raise the floor to "+ f"{ZOO_FLOOR_WITH_LIFTED_DATASETS_CAP} in the same commit as the window."+ )+++def test_the_zoo_datasets_deferral_expires_when_the_zoo_release_ships() -> None:+ """Self-expiring deferral: fails only on positive PyPI evidence the zoo now covers the window."""+ if ZOO_FLOOR_WITH_LIFTED_DATASETS_CAP is not None:+ pytest.skip("the floor already names a zoo carrying the lift, so the gate above is live")++ published = _newest_published_zoo_datasets_windows()+ if published is None:+ pytest.skip("PyPI could not be asked for unsloth_zoo, so the deferral stands")++ zoo_version, zoo_windows = published+ declared = _pyproject_requirement("datasets")+ probe = [v for v in _datasets_releases() if str(v) in declared]+ assert probe, "the declared datasets window admits no recorded release at all"+ newest = max(probe)+ covering = [str(w) for w in zoo_windows if w.contains(str(newest))]+ assert not covering, (+ f"unsloth_zoo {zoo_version} is published and admits datasets {newest} "+ f"({', '.join(covering)}), so the deferral is over. Set "+ f"ZOO_FLOOR_WITH_LIFTED_DATASETS_CAP to {zoo_version} and raise the unsloth_zoo floor "+ f"in pyproject.toml to it in the same commit; that re-enables "+ f"test_the_declared_zoo_floor_can_supply_the_declared_datasets_window."+ )+++def test_the_zoo_datasets_expiry_can_fail(monkeypatch) -> None:+ """NEGATIVE CONTROL: expiry fires on a covering zoo and stays silent when PyPI is unreachable."""+ module = sys.modules[__name__]++ monkeypatch.setattr(+ module,+ "_newest_published_zoo_datasets_windows",+ lambda timeout = 10.0: (Version("2026.9.9"), [SpecifierSet(">=3.4.1,<5.0.0")]),+ )+ with pytest.raises(AssertionError) as raised:+ test_the_zoo_datasets_deferral_expires_when_the_zoo_release_ships()+ assert "2026.9.9" in str(raised.value)++ monkeypatch.setattr(module, "_newest_published_zoo_datasets_windows", lambda timeout = 10.0: None)+ with pytest.raises(pytest.skip.Exception):+ test_the_zoo_datasets_deferral_expires_when_the_zoo_release_ships()diff --git a/tests/version_compat/test_dense_router_aux_loss_off.py b/tests/version_compat/test_dense_router_aux_loss_off.pyindex 3ee2df60467..3b151b78232 100644--- a/tests/version_compat/test_dense_router_aux_loss_off.py+++ b/tests/version_compat/test_dense_router_aux_loss_off.py@@ -16,10 +16,12 @@ transformers = pytest.importorskip("transformers")def _trainer_after_trl_init(config):+ # One namespace: rl.py injects this into __init__, and on Python < 3.12 a comprehension in exec+ # with split globals/locals cannot see `_text_config`.# What TRL 1.7+ leaves behind for any config carrying output_router_logits with the default coef.config.get_text_config().output_router_logits = Trueself = types.SimpleNamespace(aux_loss_enabled = True, model = types.SimpleNamespace(config = config))- exec(_rl_py_constant("_DENSE_ROUTER_AUX_LOSS_OFF"), {}, {"self": self})+ exec(_rl_py_constant("_DENSE_ROUTER_AUX_LOSS_OFF"), {"self": self})return self@@ -46,7 +48,7 @@ def test_real_moe_keeps_the_aux_loss(config):def test_trainer_without_aux_loss_is_untouched():self = types.SimpleNamespace(model = None)- exec(_rl_py_constant("_DENSE_ROUTER_AUX_LOSS_OFF"), {}, {"self": self})+ exec(_rl_py_constant("_DENSE_ROUTER_AUX_LOSS_OFF"), {"self": self})assert not hasattr(self, "aux_loss_enabled")diff --git a/tests/version_compat/test_grpo_importance_sampling_level_at_the_floor.py b/tests/version_compat/test_grpo_importance_sampling_level_at_the_floor.pynew file mode 100644index 00000000000..fc98b5b80b4--- /dev/null+++ b/tests/version_compat/test_grpo_importance_sampling_level_at_the_floor.py@@ -0,0 +1,165 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The GRPO loss must resolve `importance_sampling_level` on every TRL in the declared window.++GSPO added the knob in TRL 0.20.0 as a `GRPOConfig` field the trainer copies onto itself; at+0.18.2/0.19.1 neither exists and the level is token by construction. Reading+`self.importance_sampling_level` unconditionally therefore raised AttributeError at the bottom of+`trl>=0.18.2,!=0.19.0`. `test_the_window_still_binds_what_this_loss_expects` re-derives that from+upstream, so a TRL that moves the knob again fails here rather than in a user's training loop.+"""++from __future__ import annotations++import re++import pytest++# Guarded import: `import unsloth` raises its own ImportError without torch, which importorskip re-raises.+try:+ from unsloth.models.rl_replacements import RL_PRE_ITEMS, grpo_trainer_compute_loss+except ImportError as exc:+ pytest.skip(f"needs unsloth: {exc}", allow_module_level = True)+++class _Stop(Exception):+ """Raised by the loss stubs once the kwarg under test has been captured."""+++class _Args:+ loss_type = "grpo"+ max_completion_length = 16+ delta = None+ temperature = 1.0+ unsloth_num_chunks = -1+++class _Accelerator:+ num_processes = 1+++def _trainer(+ *,+ on_trainer = None,+ on_config = None,+ with_logps: bool,+):+ """A stand-in GRPOTrainer binding `importance_sampling_level` where the TRL under test does."""+ import torch++ args = _Args()+ if on_config is not None:+ args.importance_sampling_level = on_config++ class _Trainer:+ pass++ trainer = _Trainer()+ trainer.args = args+ trainer.accelerator = _Accelerator()+ trainer.beta = 0.0+ trainer.epsilon_low = 0.2+ trainer.epsilon_high = 0.2+ if on_trainer is not None:+ trainer.importance_sampling_level = on_trainer+ trainer._get_per_token_logps = lambda *a, **k: (torch.zeros((1, 2)) if with_logps else None)+ return trainer+++def _captured_level(+ *,+ on_trainer = None,+ on_config = None,+ with_logps: bool,+) -> str:+ """Compile the real rewritten compute_loss and read the level it hands the loss."""+ torch = pytest.importorskip("torch")+ source = grpo_trainer_compute_loss("compute_loss", "")+ captured = {}++ def _loss_stub(*args, **kwargs):+ captured["level"] = kwargs.get("importance_sampling_level", "<not passed>")+ raise _Stop++ # Exec the real pre-item sources in rl_replacements globals; only the two loss entry points are stubbed.+ import unsloth.models.rl_replacements as _rl_replacements++ namespace = dict(vars(_rl_replacements))+ namespace.update(+ {+ "torch": torch,+ "detect_logit_transforms": None,+ "sanitize_logprob": lambda x: x,+ }+ )+ exec(compile("\n".join(RL_PRE_ITEMS["grpo_trainer"]), "<pre_items>", "exec"), namespace)+ namespace["grpo_compute_loss_slow"] = _loss_stub+ namespace["grpo_accumulated_loss"] = _loss_stub+ exec(+ compile(re.sub(r"^ ", "", source, flags = re.MULTILINE), "<rewritten>", "exec"), namespace+ )++ inputs = {+ "prompt_ids": torch.zeros((1, 2), dtype = torch.long),+ "prompt_mask": torch.ones((1, 2), dtype = torch.long),+ "completion_ids": torch.zeros((1, 2), dtype = torch.long),+ "completion_mask": torch.ones((1, 2), dtype = torch.long),+ "advantages": torch.zeros((1,)),+ }+ trainer = _trainer(on_trainer = on_trainer, on_config = on_config, with_logps = with_logps)+ with pytest.raises(_Stop):+ namespace["compute_loss"](trainer, object(), inputs)+ return captured["level"]++[email protected]("with_logps", [True, False], ids = ["no_grad_path", "gradient_path"])+def test_the_floor_binds_neither_and_still_reaches_the_loss(with_logps: bool) -> None:+ """0.18.2 and 0.19.1: no field, no attribute, and token level is what they implement."""+ assert _captured_level(with_logps = with_logps) == "token"++[email protected]("with_logps", [True, False], ids = ["no_grad_path", "gradient_path"])+def test_the_trainer_attribute_still_wins_where_trl_sets_it(with_logps: bool) -> None:+ """0.20.0 and up: unchanged behaviour, the trainer's own value is forwarded verbatim."""+ assert (+ _captured_level(+ on_trainer = "sequence",+ on_config = "token",+ with_logps = with_logps,+ )+ == "sequence"+ )++[email protected]("with_logps", [True, False], ids = ["no_grad_path", "gradient_path"])+def test_the_config_field_is_used_when_only_it_is_bound(with_logps: bool) -> None:+ """A config carrying the knob is honoured even if __init__ never copied it across."""+ assert _captured_level(on_config = "sequence", with_logps = with_logps) == "sequence"+++def test_the_window_still_binds_what_this_loss_expects() -> None:+ """Re-derive the table in the docstring from upstream, so a moved knob fails here."""+ from tests.version_compat._fetch import fetch_text++ expected = {+ "v0.18.2": False,+ "v0.19.1": False,+ "v0.20.0": True,+ "v0.24.0": True,+ "v1.13.0": True,+ }+ for tag, bound in expected.items():+ config = fetch_text("huggingface/trl", tag, "trl/trainer/grpo_config.py")+ trainer = fetch_text("huggingface/trl", tag, "trl/trainer/grpo_trainer.py")+ assert config is not None and trainer is not None, f"{tag}: GRPO sources not found"+ has_field = bool(re.search(r"^\s{4}importance_sampling_level\s*:", config, re.M))+ has_attr = bool(+ re.search(+ r"^\s+self\.importance_sampling_level\s*=\s*args\.importance_sampling_level",+ trainer,+ re.M,+ )+ )+ assert has_field == bound, f"{tag}: GRPOConfig field bound={has_field}, expected {bound}"+ assert has_attr == bound, f"{tag}: trainer attribute bound={has_attr}, expected {bound}"diff --git a/tests/version_compat/test_grpo_left_pad_probe_at_the_floor.py b/tests/version_compat/test_grpo_left_pad_probe_at_the_floor.pynew file mode 100644index 00000000000..e242a0232a5--- /dev/null+++ b/tests/version_compat/test_grpo_left_pad_probe_at_the_floor.py@@ -0,0 +1,159 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The left-pad probe must survive every TRL in the declared window, including the floor.++The name carrying "is this batch text only" moved twice inside `trl>=0.18.2,!=0.19.0`:+`has_images` in 0.20.0-0.23.1, `images` in 0.24.0-1.13.0, NEITHER at 0.18.2/0.19.1, where the+shipped two-branch probe raised NameError out of its own except handler and took GRPO down.+`test_the_window_still_binds_what_this_probe_expects` re-derives that table from upstream, so a+fourth spelling fails here rather than in a user's training loop.+"""++from __future__ import annotations++import re++import pytest++# Guarded import, as in the sibling floor test.+try:+ from unsloth.models.rl_replacements import grpo_trainer__generate_and_score_completions+except ImportError as exc:+ pytest.skip(f"needs unsloth: {exc}", allow_module_level = True)+++ANCHOR = 'batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size'++# `_kind` is echoed so a test cannot pass on the wrong arm.+_FLOOR = f"""+ def _generate_and_score_completions(self, inputs):+ mode = "train"+ prompt_ids = inputs["prompt_ids"]+ completion_ids = inputs["completion_ids"]+ prompt_completion_ids = inputs["prompt_completion_ids"]+ logits_to_keep = 1+ {ANCHOR}+ return max_left_pad+"""++_HAS_IMAGES = f"""+ def _generate_and_score_completions(self, inputs):+ mode = "train"+ prompt_ids = inputs["prompt_ids"]+ completion_ids = inputs["completion_ids"]+ prompt_completion_ids = inputs["prompt_completion_ids"]+ logits_to_keep = 1+ has_images = inputs["has_images"]+ if has_images:+ images = inputs["images"]+ {ANCHOR}+ return max_left_pad+"""++_IMAGES = f"""+ def _generate_and_score_completions(self, inputs):+ mode = "train"+ prompt_ids = inputs["prompt_ids"]+ completion_ids = inputs["completion_ids"]+ prompt_completion_ids = inputs["prompt_completion_ids"]+ logits_to_keep = 1+ images = inputs["images"]+ {ANCHOR}+ return max_left_pad+"""+++class _Args:+ per_device_train_batch_size = 1+ per_device_eval_batch_size = 1+++class _Trainer:+ args = _Args()++ class processing_class:+ pad_token_id = 0++ class model:+ @staticmethod+ def for_training(use_gradient_checkpointing = True):+ return None+++def _run(source: str, inputs: dict):+ """Rewrite `source`, exec it, and call it. Returns whatever `max_left_pad` ended up as."""+ rewritten = grpo_trainer__generate_and_score_completions(+ "_generate_and_score_completions",+ source,+ )+ namespace = {+ "torch": pytest.importorskip("torch"),+ "calculate_pad_tokens_in_prompt": lambda ids, keep, pad: _sentinel_tensor(),+ "_unsloth_reject_grpo_image_list": lambda *a, **k: None,+ "_unsloth_grpo_image_cell": lambda cell: cell if isinstance(cell, list) else [cell],+ "_unsloth_grpo_vision_inputs": lambda inputs: {},+ "sanitize_logprob": lambda x: x,+ }+ exec(+ compile(re.sub(r"^ ", "", rewritten, flags = re.MULTILINE), "<rewritten>", "exec"),+ namespace,+ )+ return namespace["_generate_and_score_completions"](_Trainer(), inputs)+++def _sentinel_tensor():+ import torch+ return torch.tensor([7])+++_BATCH = {+ "prompt_ids": None,+ "completion_ids": None,+ "prompt_completion_ids": None,+}+++def test_the_floor_binds_neither_name_and_still_computes_the_pad() -> None:+ """0.18.2 and 0.19.1: no vision path at all, so the batch is text only and the probe runs."""+ assert _run(_FLOOR, dict(_BATCH)) == 7+++def test_has_images_false_still_computes_the_pad() -> None:+ assert _run(_HAS_IMAGES, dict(_BATCH, has_images = False)) == 7+++def test_has_images_true_skips_the_pad() -> None:+ assert _run(_HAS_IMAGES, dict(_BATCH, has_images = True, images = ["an image"])) is None+++def test_images_none_still_computes_the_pad() -> None:+ assert _run(_IMAGES, dict(_BATCH, images = None)) == 7+++def test_images_present_skips_the_pad() -> None:+ assert _run(_IMAGES, dict(_BATCH, images = ["an image"])) is None+++def test_the_window_still_binds_what_this_probe_expects() -> None:+ """Re-derive the table in the docstring from upstream, so a fourth spelling fails here."""+ from tests.version_compat._fetch import fetch_text++ expected = {+ "v0.18.2": (False, False),+ "v0.20.0": (True, True),+ "v0.23.1": (True, True),+ "v0.24.0": (False, True),+ }+ for tag, (wants_has_images, wants_images) in expected.items():+ source = fetch_text("huggingface/trl", tag, "trl/trainer/grpo_trainer.py")+ assert source is not None, f"{tag}: grpo_trainer.py not found"+ method = re.search(+ r"\n def _generate_and_score_completions\(.*?(?=\n def |\Z)",+ source,+ re.S,+ )+ assert method, f"{tag}: no _generate_and_score_completions"+ before_anchor = method.group(0).split(ANCHOR)[0]+ assert bool(re.search(r"^\s+has_images\s*=", before_anchor, re.M)) == wants_has_images, tag+ assert bool(re.search(r"^\s+images\s*=", before_anchor, re.M)) == wants_images, tagdiff --git a/tests/version_compat/test_no_dtype_kwarg_at_load.py b/tests/version_compat/test_no_dtype_kwarg_at_load.pynew file mode 100644index 00000000000..1d62d98b9fe--- /dev/null+++ b/tests/version_compat/test_no_dtype_kwarg_at_load.py@@ -0,0 +1,71 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""No test here may name a dtype kwarg on `from_pretrained`.++Both spellings are traps across the declared window in opposite directions: `dtype =` is+forwarded into the model constructor and raises TypeError at the 4.52.4 floor, `torch_dtype =`+spans the window but is deprecated from 4.57.6. Load with neither and cast the result. Checking+the call site rather than the version makes it fail on every platform and every transformers.+"""++from __future__ import annotations++import ast+from pathlib import Path++import pytest+++HERE = Path(__file__).resolve().parent+BANNED = ("dtype", "torch_dtype")+++def _offending_calls(source: str) -> list[tuple[int, str]]:+ """`(lineno, kwarg)` for every `*.from_pretrained(..., dtype = ...)` in `source`."""+ found = []+ for node in ast.walk(ast.parse(source)):+ if not isinstance(node, ast.Call):+ continue+ func = node.func+ if not (isinstance(func, ast.Attribute) and func.attr == "from_pretrained"):+ continue+ for keyword in node.keywords:+ if keyword.arg in BANNED:+ found.append((node.lineno, keyword.arg))+ return found+++def test_no_version_compat_test_names_a_dtype_kwarg_at_load() -> None:+ offenders = {}+ scanned = 0+ for path in sorted(HERE.rglob("*.py")):+ scanned += 1+ hits = _offending_calls(path.read_text(encoding = "utf-8"))+ if hits:+ offenders[path.name] = hits+ assert scanned >= 5, (+ f"this guard scanned only {scanned} files, so it is not looking where it thinks it "+ f"is. Check the directory it globs before trusting a pass."+ )+ assert not offenders, (+ f"these loaders name a dtype kwarg on from_pretrained: {offenders}. `dtype=` raises "+ f"TypeError at the transformers floor and `torch_dtype=` is deprecated above 4.57.6, "+ f"so neither spelling holds across the declared window. Load without it and cast "+ f"the result, asserting the dtype you got."+ )+++ "snippet, want",+ [+ ("M.from_pretrained(name, dtype = torch.float32)", [(1, "dtype")]),+ ("M.from_pretrained(name, torch_dtype = torch.float32)", [(1, "torch_dtype")]),+ ("M.from_pretrained(name).to(torch.float32)", []),+ ("M.from_pretrained(name)", []),+ ("torch.zeros(4, dtype = torch.float32)", []),+ ],+)+def test_the_scanner_sees_both_spellings_and_nothing_else(snippet, want) -> None:+ """Negative control: the test above is a "nothing found" shape, which is also what a+ scanner that has stopped scanning reports."""+ assert _offending_calls(snippet) == wantdiff --git a/tests/version_compat/test_transformers_pinned_symbols.py b/tests/version_compat/test_transformers_pinned_symbols.pyindex b0188ccd414..41e16637d60 100644--- a/tests/version_compat/test_transformers_pinned_symbols.py+++ b/tests/version_compat/test_transformers_pinned_symbols.py@@ -4,48 +4,211 @@Catches breakage classes from unsloth#3998/5036/5155/5259 andunsloth-zoo#572/571/549/543/541/495/491/488/472/393/388/583/584/159.-CPU-only, no install. Anchor versions: transformers 4.57.6, 5.5.0.+CPU-only, no install. Anchors: transformers 4.57.6 (floor), 5.17.0 (ceiling) and 5.5.0+(the old ceiling, still the Apple Silicon cap)."""from __future__ import annotations+import json+import osimport re+import tempfile+import urllib.error+import urllib.request+from pathlib import Pathimport pytestfrom tests.version_compat._fetch import fetch_text, first_match, has_def-# 4.57.6 floor + every 5.x minor since 5.0.0, up to the current PyPI latest, + main.-TRANSFORMERS_TAGS = [- "v4.57.6", # anchor (must work)+# Read from pyproject: a hardcoded floor went stale and silently dropped 4.52-4.56.+_FLOOR_RE = re.compile(r"^\s*\"transformers[^\"]*?>=\s*([0-9]+(?:\.[0-9]+)*)", re.M)+_FLOOR_FALLBACK = (4, 52, 4)+++def _declared_floor() -> tuple[int, ...]:+ """The oldest transformers pyproject admits; the fallback keeps a bad read from+ widening the matrix to every release ever published."""+ pyproject = Path(__file__).resolve().parents[2] / "pyproject.toml"+ try:+ found = _FLOOR_RE.findall(pyproject.read_text(encoding = "utf-8"))+ except OSError:+ return _FLOOR_FALLBACK+ if not found:+ return _FLOOR_FALLBACK+ return min(tuple(int(part) for part in v.split(".")) for v in found)+++_FLOOR = _declared_floor()++# 4.57.6 old floor, 5.5.0 the Apple Silicon cap, 5.16.0 the tokenizers>=0.23.1 break.+_ALWAYS = ("v4.57.6", "v5.5.0", "v5.16.0", "v5.10.1", "v5.15.1")++# Exact pins notebooks use; one-tag-per-minor would evict them.++# pyproject's cap, so a later patch cannot evict the declared maximum.+_CAP = re.compile(r"^\s*\"transformers[^\"]*?<=\s*([0-9]+(?:\.[0-9]+)*)", re.M)+++def _declared_ceiling_tag() -> tuple[str, ...]:+ """The tag for the newest transformers pyproject admits, or empty if unreadable."""+ pyproject = Path(__file__).resolve().parents[2] / "pyproject.toml"+ try:+ found = _CAP.findall(pyproject.read_text(encoding = "utf-8"))+ except OSError:+ return ()+ if not found:+ return ()+ ceiling = max(found, key = lambda v: tuple(int(p) for p in v.split(".")))+ # Through the override table: some PyPI versions have no matching tag.+ return (_TAG_OVERRIDES.get(ceiling, "v" + ceiling),)+++# PyPI version -> tag where upstream disagrees (5.10.4 is tagged v5.10.3; 4.54.1 is v4.54-release).+_TAG_OVERRIDES = {"5.10.4": "v5.10.3", "4.54.1": "v4.54-release"}++# Outage fallback; must start at the declared floor (test_the_outage_fallback_reaches_the_declared_floor).+_TAGS_FALLBACK = (+ "v4.52.4",+ "v4.53.3",+ "v4.54-release",+ "v4.55.4",+ "v4.56.2",+ "v4.57.6","v5.0.0","v5.1.0","v5.2.0","v5.3.0","v5.4.0",- "v5.5.0", # anchor (must work)"v5.5.4","v5.6.2","v5.7.0",- "v5.8.0","v5.8.1","v5.9.0",- "v5.10.0",- "v5.10.1","v5.10.2",- # Upstream tagged PyPI 5.10.4 as v5.10.3 (the tag's __init__ says 5.10.4); there is no v5.10.4 tag and no 5.10.3 on- # PyPI, so fetch by the tag name."v5.10.3","v5.11.0",- "v5.12.0","v5.12.1",- "v5.13.0","v5.13.1",- "v5.14.0",- "v5.14.1", # current PyPI latest- "main",-]+ "v5.14.1",+ "v5.15.1",+ "v5.16.1",+ "v5.17.0",+)+++# Shared across xdist workers so all collect identical parameters+# (https://pytest-xdist.readthedocs.io/en/stable/known-limitations.html).+_MATRIX_CACHE_ENV = "PYTEST_TRANSFORMERS_MATRIX_FILE"+++def _cached_matrix() -> list[str] | None:+ """The shared matrix, or None when there is no cache or it is unreadable."""+ path = os.environ.get(_MATRIX_CACHE_ENV)+ if not path:+ return None+ try:+ tags = json.loads(Path(path).read_text(encoding = "utf-8"))+ except (OSError, ValueError):+ return None+ return [str(tag) for tag in tags] if isinstance(tags, list) and tags else None+++def _write_cached_matrix(tags: list[str]) -> None:+ """Publish `tags` for the other workers. Atomic, so no worker reads a partial file."""+ path = os.environ.get(_MATRIX_CACHE_ENV)+ if not path:+ return+ target = Path(path)+ try:+ target.parent.mkdir(parents = True, exist_ok = True)+ handle, temporary = tempfile.mkstemp(dir = str(target.parent), suffix = ".json")+ with os.fdopen(handle, "w", encoding = "utf-8") as stream:+ json.dump(tags, stream)+ os.replace(temporary, target)+ except OSError:+ pass+++def _resolved_tags() -> list[str]:+ """`_release_tags()`, resolved once per run and shared across xdist workers.++ Every return goes through `_with_always`, the published one included: the cache agrees on the+ PyPI half of the answer, it is not a second source of truth for the anchors. A file written by+ another revision and returned verbatim dropped the floor, the old ceiling and the notebook pins+ while reporting green.+ """+ cached = _cached_matrix()+ if cached is not None:+ return _with_always(cached)+ tags = _release_tags()+ cached = _cached_matrix()+ if cached is not None:+ return _with_always(cached)+ _write_cached_matrix(tags)+ return tags+++def _release_tags() -> list[str]:+ """Every transformers minor at or above the floor, latest patch of each, oldest first.++ Read from PyPI, not pinned: this suite says which versions the cap may be lifted to, and a+ hand-maintained list answers for the day it was edited. One tag per minor bounds the matrix; a+ patch that broke something earns a place in `_ALWAYS`. Yanked and rc/dev/post builds are+ skipped, since pip will not install them.+ """+ try:+ with urllib.request.urlopen(+ "https://pypi.org/pypi/transformers/json",+ timeout = 20,+ ) as response:+ releases = json.loads(response.read().decode("utf-8"))["releases"]+ except (urllib.error.URLError, TimeoutError, ValueError, KeyError):+ return _with_always(_TAGS_FALLBACK)++ latest_by_minor: dict[tuple[int, int], tuple[int, ...]] = {}+ for version, files in releases.items():+ if not files or all(f.get("yanked") for f in files):+ continue+ if re.fullmatch(r"\d+(?:\.\d+){2,}", version) is None:+ continue+ parts = tuple(int(g) for g in version.split("."))+ if parts < _FLOOR:+ continue+ minor = parts[:2]+ if parts > latest_by_minor.get(minor, ()):+ latest_by_minor[minor] = parts+ if not latest_by_minor:+ return _with_always(_TAGS_FALLBACK)++ tags = []+ for parts in sorted(latest_by_minor.values()):+ name = ".".join(str(p) for p in parts)+ tags.append(_TAG_OVERRIDES.get(name, "v" + name))+ return _with_always(tags)+++def _with_always(tags) -> list[str]:+ """`tags` with every `_ALWAYS` anchor present, sorted, deduplicated.++ Every return path goes through here, the fallback ones included: `_TAGS_FALLBACK` carries one+ tag per minor so it holds neither v5.5.0 nor v5.16.0, and returning it unmerged let an outage+ drop the Apple Silicon ceiling and the tokenizers breakpoint and still report green.+ """+ return sorted(set(tuple(tags) + _ALWAYS + _declared_ceiling_tag()), key = _sort_key)+++_TAG_TO_RELEASE = {tag: release for release, tag in _TAG_OVERRIDES.items()}+++def _sort_key(tag: str) -> tuple[int, ...]:+ name = _TAG_TO_RELEASE.get(tag, tag).lstrip("v")+ return tuple(int(g) for g in name.split("."))+++TRANSFORMERS_TAGS = _resolved_tags() + ["main"]# Every check runs once per tag; one that cannot skips from inside so the tag stays in the report.pytestmark = pytest.mark.parametrize("tag", TRANSFORMERS_TAGS)@@ -334,11 +497,31 @@ def test_training_args_parallel_mode_importable(tag: str):)+def test_the_matrix_starts_at_the_declared_floor(tag: str) -> None:+ """The matrix is only a compatibility claim if it begins where the claim does.++ `_FLOOR` was a literal 4.57.6 while pyproject declared 4.52.4, so every 4.52-4.56 release was+ discarded and a change landing after the floor could break supported users, matrix still green.+ """+ declared = _declared_floor()+ assert _FLOOR == declared, (+ f"_FLOOR is {_FLOOR} but pyproject declares {declared}; the matrix would skip "+ f"every release between them"+ )+ if tag == "main":+ return+ assert _sort_key(tag) >= declared, (+ f"{tag} sits below the declared floor {declared}, so the matrix is checking a "+ f"release no supported install can resolve"+ )++def test_trainer_training_step_model_train_call_is_standalone(tag: str):- """unsloth#11238 rewrites the FIRST `model.train()` inside Trainer.training_step into- `_unsloth_train_if_needed(model)`. A release that wrote `self.model.train()` earlier in that- method would turn the same replace into `self._unsloth_train_if_needed(model)`, and every- training step would die with AttributeError. Nothing else in the rewrite guards that."""+ """unsloth#11238 rewrites the FIRST `model.train()` in Trainer.training_step.++ A release writing `self.model.train()` earlier in that method turns the same replace into+ `self._unsloth_train_if_needed(model)` and every training step dies with AttributeError.+ """candidates = ["src/transformers/trainer.py", "src/transformers/trainer/__init__.py"]hit = first_match("huggingface/transformers", tag, candidates)assert hit is not Nonediff --git a/tests/version_compat/test_trl_config_defaults_contract.py b/tests/version_compat/test_trl_config_defaults_contract.pyindex 4c6310588d9..9d657b14ce7 100644--- a/tests/version_compat/test_trl_config_defaults_contract.py+++ b/tests/version_compat/test_trl_config_defaults_contract.py@@ -69,10 +69,31 @@ def _pristine(cls):return cls+# Unsloth refuses GRPO below this TRL (unsloth/models/rl.py): it crashes on the first step there.+GRPO_TRL_FLOOR = "0.20.0"+++def _skip_if_trl_is_the_mlx_shim(trl):+ # On Apple Silicon unsloth swaps trl.SFTConfig for an MLX alias (and stubs trl itself when it is+ # absent), so there are no TRL config defaults to compare against.+ if getattr(getattr(trl, "SFTConfig", None), "__name__", "") == "_MLXSFTConfig":+ pytest.skip("trl is unsloth's MLX shim on this platform")+++def _grpo_refused():+ import trl+ from packaging.version import Version+ return Version(trl.__version__) < Version(GRPO_TRL_FLOOR)++def _config_cls(name):import unsloth # noqa: F401import trl+ _skip_if_trl_is_the_mlx_shim(trl)+ if name == "GRPOConfig" and _grpo_refused():+ pytest.skip(f"unsloth refuses GRPO on trl {trl.__version__} (< {GRPO_TRL_FLOOR})")+cls = getattr(trl, name, None)if cls is None:try:@@ -224,3 +245,14 @@ def test_other_loss_types_keep_trl_epsilon_high(loss_type):output_dir = "unused", loss_type = loss_type).epsilon_high)+++def test_grpo_below_its_trl_floor_is_refused_with_an_upgrade_hint():+ import unsloth # noqa: F401+ import trl++ _skip_if_trl_is_the_mlx_shim(trl)+ if not _grpo_refused():+ pytest.skip(f"trl {trl.__version__} supports GRPO")+ with pytest.raises(ImportError, match = "GRPO needs trl >= 0.20.0"):+ trl.GRPOConfig(output_dir = "unused")diff --git a/tests/version_compat/test_trl_fake_train_cpu.py b/tests/version_compat/test_trl_fake_train_cpu.pyindex 897210c3bce..244b8d57b04 100644--- a/tests/version_compat/test_trl_fake_train_cpu.py+++ b/tests/version_compat/test_trl_fake_train_cpu.py@@ -212,10 +212,16 @@ def _load_plain():from transformers import AutoModelForCausalLM, AutoTokenizertry:+ # No dtype kwarg: `dtype=` fails at the 4.52.4 floor, `torch_dtype=` is deprecated from 4.57.6. Cast after.tok = AutoTokenizer.from_pretrained(_MODEL)- model = AutoModelForCausalLM.from_pretrained(_MODEL, dtype = torch.float32)+ model = AutoModelForCausalLM.from_pretrained(_MODEL).to(torch.float32)except OSError as e: # hub unreachable / model missingpytest.skip(f"could not fetch {_MODEL} (network/hub): {str(e)[:150]}")+ got = next(model.parameters()).dtype+ assert got == torch.float32, (+ f"the cast after load left the model in {got}, not float32. These tests compare "+ f"losses, so a silent dtype change is a silent change of what they measure."+ )if tok.pad_token is None:tok.pad_token = tok.eos_token# Unsloth's GRPO path calls model.for_training()/for_inference() (added by FastLanguageModel). A plain HF model@@ -273,7 +279,16 @@ def test_sft_trains_on_cpu(tmp_path):SFTTrainer(model = model, processing_class = tok, args = cfg, train_dataset = ds).train()+def _skip_if_unsloth_refuses_grpo():+ # Unsloth refuses GRPO below trl 0.20.0 (unsloth/models/rl.py); the floor lane runs below it.+ import trl+ from packaging.version import Version+ if Version(trl.__version__) < Version("0.20.0"):+ pytest.skip(f"unsloth refuses GRPO on trl {trl.__version__} (< 0.20.0)")++def test_grpo_trains_on_cpu(tmp_path):+ _skip_if_unsloth_refuses_grpo()from datasets import Datasetfrom trl import GRPOConfig, GRPOTrainer@@ -337,6 +352,7 @@ def test_dpo_trains_on_cpu(tmp_path):def test_grpo_evaluates_with_an_explicit_eval_batch_size(tmp_path):"""Shrinking an explicit eval batch of 8 to the train batch of 2 split num_generations = 4 groups."""+ _skip_if_unsloth_refuses_grpo()from datasets import Datasetfrom trl import GRPOConfig, GRPOTrainer@@ -374,6 +390,7 @@ def test_grpo_evaluates_with_an_explicit_eval_batch_size(tmp_path):def test_grpo_trains_on_cpu_through_the_patched_batch_sampler(tmp_path):+ _skip_if_unsloth_refuses_grpo()"""The canary above proves the GRPO trainer runs. It does NOT prove Unsloth's own``get_batch_samples`` runs, because ``_load_plain`` never goes through the loader thatinstalls it, so ``Trainer.get_batch_samples`` stays stock transformers.diff --git a/tests/version_compat/test_trl_loss_normalization_contract.py b/tests/version_compat/test_trl_loss_normalization_contract.pyindex acd544dfb49..47adfc04ba8 100644--- a/tests/version_compat/test_trl_loss_normalization_contract.py+++ b/tests/version_compat/test_trl_loss_normalization_contract.py@@ -73,25 +73,80 @@ def test_sft_loss_type_default_is_nll_after_unsloth_patch():)+def _loss_type_field(cfg_cls):+ """TRL's `loss_type` dataclass field, or None if this TRL has no such field.++ `hasattr(cfg_cls, "loss_type")` is NOT equivalent and was the bug here: from trl 0.21+ DPOConfig declares the field with a `default_factory`, which leaves no class attribute,+ so the hasattr form skipped DPO entirely on every recent TRL while still claiming to+ check it.+ """+ import dataclasses+ return next((f for f in dataclasses.fields(cfg_cls) if f.name == "loss_type"), None)+++def _pristine_config_cls(cfg_cls):+ """TRL's own config class, walking past the subclass patching rebinds over it."""+ while "_unsloth_patched_rl_config" in cfg_cls.__dict__ or cfg_cls.__name__.startswith(+ "Unsloth"+ ):+ cfg_cls = cfg_cls.__mro__[1]+ return cfg_cls++def test_loss_type_replacement_did_not_leak_to_other_trainers():- """loss_type is an unrelated field in DPO/KTO/GRPO; the global dict hits all."""+ """loss_type is an unrelated field in DPO/KTO/GRPO; the global dict hits all.++ The expectation is split rather than one literal dict, because the two halves are+ different claims and only one of them is version-independent:++ * GRPO is unsloth's own default (rl.py): TRL's `dapo` from 0.22, `bnpo` before it.+ * DPO and KTO are RELATIVE to pristine TRL, because the claim is that unsloth does+ not touch them at all. Their values are TRL's own and change between releases:+ trl 0.18.2 declares `DPOConfig.loss_type = "sigmoid"` as a plain default, while+ trl 0.24.0 declares it with `default_factory=["sigmoid"]` that `__post_init__`+ resolves back to the string. A hardcoded `["sigmoid"]` matched neither instance;+ it matched the 0.24 field default only, and the hasattr skip above hid that.+ """import unsloth # noqa: F401import trlfrom packaging.version import Version- # Unsloth follows TRL's GRPO default from 0.22, the first TRL with "dapo".- grpo = "dapo" if Version(trl.__version__) >= Version("0.22.0") else "bnpo"- expected = {"DPOConfig": ["sigmoid"], "KTOConfig": "kto", "GRPOConfig": grpo}- for name, want in expected.items():+ checked = []+ for name in ("DPOConfig", "KTOConfig"):cfg_cls = getattr(trl, name, None)- if cfg_cls is None or not hasattr(cfg_cls, "loss_type"):+ if cfg_cls is None or _loss_type_field(cfg_cls) is None:continue+ pristine = _pristine_config_cls(cfg_cls)+ assert "_unsloth_patched_rl_config" not in pristine.__dict__, (+ f"the pristine walk for {name} landed on a patched class, so comparing against "+ f"it would compare the patch with itself"+ )+ want = pristine(output_dir = "unused").loss_typegot = cfg_cls(output_dir = "unused").loss_typeassert got == want, (- f"{name}.loss_type is {got!r}, expected {want!r}. A loss_type "- "replacement leaked out of the sft_trainer branch in rl.py."+ f"{name}.loss_type is {got!r} and pristine TRL {trl.__version__} says {want!r}. "+ "A loss_type replacement leaked out of the sft_trainer branch in rl.py.")+ checked.append(name)++ grpo = getattr(trl, "GRPOConfig", None)+ grpo_refused = Version(trl.__version__) < Version("0.20.0") # unsloth/models/rl.py raises there+ if grpo is not None and not grpo_refused and _loss_type_field(grpo) is not None:+ got = grpo(output_dir = "unused").loss_type+ # Unsloth follows TRL's GRPO default from 0.22, the first TRL with "dapo" (rl.py).+ want = "dapo" if Version(trl.__version__) >= Version("0.22.0") else "bnpo"+ assert got == want, (+ f"GRPOConfig.loss_type is {got!r}, expected {want!r}. That default is unsloth's own "+ "(rl.py), so this is either a lost override or a leak."+ )+ checked.append("GRPOConfig")++ assert len(checked) >= 2, (+ f"only {checked} carried a loss_type field on trl {trl.__version__}, so this test "+ f"checked almost nothing. Retarget it rather than letting it pass empty."+ )def test_explicit_loss_type_still_wins():@@ -105,11 +160,21 @@ def test_explicit_loss_type_still_wins():assert cfg.loss_type == "chunked_nll", "explicit loss_type was clobbered"+def _skip_if_unsloth_refuses_grpo():+ # Unsloth refuses GRPO below trl 0.20.0 (unsloth/models/rl.py); the floor lane runs below it.+ import trl+ from packaging.version import Version+ if Version(trl.__version__) < Version("0.20.0"):+ pytest.skip(f"unsloth refuses GRPO on trl {trl.__version__} (< 0.20.0)")++def test_dr_grpo_turns_off_reward_scaling_by_default():"""TRL >= 0.22 defaults scale_rewards to "group" (= True), so dr_grpo must override both."""import unsloth # noqa: F401import trl+ _skip_if_unsloth_refuses_grpo()+def scale(**kwargs):return trl.GRPOConfig(output_dir = "unused", loss_type = "dr_grpo", **kwargs).scale_rewardsdiff --git a/tests/version_compat/test_trl_padding_free_max_length.py b/tests/version_compat/test_trl_padding_free_max_length.pyindex 21804618aef..ccfe9735558 100644--- a/tests/version_compat/test_trl_padding_free_max_length.py+++ b/tests/version_compat/test_trl_padding_free_max_length.py@@ -115,10 +115,16 @@ def _load_plain(model_max_seq_length = _MODEL_MAX_SEQ_LENGTH):from transformers import AutoModelForCausalLM, AutoTokenizertry:+ # No dtype kwarg: `dtype=` fails at the 4.52.4 floor, `torch_dtype=` is deprecated from 4.57.6. Cast after.tok = AutoTokenizer.from_pretrained(_MODEL)- model = AutoModelForCausalLM.from_pretrained(_MODEL, dtype = torch.float32)+ model = AutoModelForCausalLM.from_pretrained(_MODEL).to(torch.float32)except OSError as e:pytest.skip(f"could not fetch {_MODEL} (network/hub): {str(e)[:150]}")+ got = next(model.parameters()).dtype+ assert got == torch.float32, (+ f"the cast after load left the model in {got}, not float32. These tests compare "+ f"losses, so a silent dtype change is a silent change of what they measure."+ )if tok.pad_token is None:tok.pad_token = tok.eos_tokenmodel.max_seq_length = model_max_seq_length@@ -699,9 +705,12 @@ def test_pristine_trl_config_without_max_seq_length_still_truncates(tmp_path, trfrom datasets import Datasetconfig_cls = _pristine_sft_config_cls()- assert not hasattr(- config_cls(output_dir = str(tmp_path)), "max_seq_length"- ), "this TRL declares max_seq_length, so the regression cannot be reproduced here"+ # Precondition: only a TRL that dropped max_seq_length has the regression.+ if hasattr(config_cls(output_dir = str(tmp_path)), "max_seq_length"):+ pytest.skip(+ "this TRL still declares max_seq_length, so the regression it guards cannot "+ "exist here; the cap-copy path is covered by the max_length tests above"+ )model, tok = _load_plain()text = "The quick brown fox. " * 200diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 75753881a9d..061e6ef3c7a 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -1413,18 +1413,22 @@ def grpo_trainer__generate_and_score_completions(function_name, function):replacement_lines_head = """max_left_pad = Nonebatch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size+ # Which name carries "this batch has images" moved twice, and at the bottom of the+ # declared window neither name exists: 0.20.0 through 0.23.1 bind has_images, 0.24.0+ # and up bind images, and 0.18.2 / 0.19.1 have no vision path at all, so every batch+ # there is text only. Probing has_images and falling back to images without a third+ # branch made the floor raise NameError out of the except handler and killed training.try:- # TRL 0.23.1 and below path- if not has_images:- # Left pad prompt before calculation old and ref hidden states- left_pad_tokens_per_prompt = calculate_pad_tokens_in_prompt(prompt_completion_ids, logits_to_keep, self.processing_class.pad_token_id)- max_left_pad = torch.max(left_pad_tokens_per_prompt).item()- except:- # TRL 0.24.0 and below path- if images is None:- # Left pad prompt before calculation old and ref hidden states- left_pad_tokens_per_prompt = calculate_pad_tokens_in_prompt(prompt_completion_ids, logits_to_keep, self.processing_class.pad_token_id)- max_left_pad = torch.max(left_pad_tokens_per_prompt).item()+ _unsloth_text_only = not has_images+ except NameError:+ try:+ _unsloth_text_only = images is None+ except NameError:+ _unsloth_text_only = True+ if _unsloth_text_only:+ # Left pad prompt before calculation old and ref hidden states+ left_pad_tokens_per_prompt = calculate_pad_tokens_in_prompt(prompt_completion_ids, logits_to_keep, self.processing_class.pad_token_id)+ max_left_pad = torch.max(left_pad_tokens_per_prompt).item()_use_gc = self.model._unsloth_gradient_checkpointing if hasattr(self.model, '_unsloth_gradient_checkpointing') else getattr(self.args, 'gradient_checkpointing', True)self.model.for_training(use_gradient_checkpointing=_use_gc)"""@@ -3067,6 +3071,12 @@ def grpo_trainer_compute_loss(function_name, function):logit_scale_multiply, logit_scale_divide = _unsloth_resolve_logit_scales(model_config)max_left_pad = inputs.get("max_left_pad", 0)+ # importance_sampling_level is absent before TRL 0.20.0 (token level).+ importance_sampling_level = getattr(+ self,+ "importance_sampling_level",+ getattr(self.args, "importance_sampling_level", "token"),+ )if per_token_logps is not None:loss_mask = completion_maskif tool_mask is not None:@@ -3098,7 +3108,7 @@ def grpo_trainer_compute_loss(function_name, function):pixel_values = pixel_values,image_grid_thw = image_grid_thw,loss_type = self.args.loss_type,- importance_sampling_level = self.importance_sampling_level,+ importance_sampling_level = importance_sampling_level,epsilon_low = self.epsilon_low,epsilon_high = self.epsilon_high,max_completion_length = self.args.max_completion_length,@@ -3218,7 +3228,7 @@ def grpo_trainer_compute_loss(function_name, function):ref_logps = ref_logps,n_chunks = self.args.unsloth_num_chunks,loss_type = self.args.loss_type,- importance_sampling_level = self.importance_sampling_level,+ importance_sampling_level = importance_sampling_level,epsilon_low = self.epsilon_low,epsilon_high = self.epsilon_high,max_completion_length = self.args.max_completion_length,