Skip to content

fix: unblock 4 tests deselected/skipped in #5312 (real bugs) - #5359

Merged
danielhanchen merged 3 commits into
mainfrom
fix/no-torch-tokenizers-and-trl1-patch-defensive
May 11, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fix/no-torch-tokenizers-and-trl1-patch-defensive

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up to #5312. That PR surfaced two real regressions by turning previously-silent skips into explicit --deselect / pytest.skip(...) blocks, and explicitly left both as follow-ups. This PR fixes the underlying bugs so the suppressions can be dropped.

1. tokenizers unpinned in no-torch-runtime.txt breaks transformers import

Installing with --no-deps -r studio/backend/requirements/no-torch-runtime.txt (the path install.sh takes for the no-torch / GGUF-only mode) resolves transformers to 5.3.0 and tokenizers to the latest available (0.23.1). transformers 5.3.0 requires tokenizers>=0.22.0,<=0.23.0, so from transformers import AutoConfig then fails at import time:

ImportError: tokenizers>=0.22.0,<=0.23.0 is required for a normal
functioning of this module, but found tokenizers==0.23.1.

Pin tokenizers>=0.22.0,<=0.23.0 to match the constraint embedded inside every transformers version in the allowed window (4.56.0..5.3.0).

Verified locally with the exact install path: fresh uv venv -> uv pip install --no-deps -r no-torch-runtime.txt -> from transformers import AutoConfig now succeeds.

Unblocks 3 deselected cases in studio-backend-ci.yml:

  • TestE2ETokenizersFix::test_autoconfig_works_with_no_torch_runtime (parametrized py 3.12 + 3.13 -> 2 cases)
  • TestE2EFullNoTorchSandbox::test_autoconfig_succeeds

2. _patch_trl_rl_trainers raises on TRL 1.x

_patch_trl_rl_trainers has many internal try: ... except: ... return branches, but several paths (notably inspect.getsource on the thin wrappers TRL 1.x leaves in trl.trainer for trainers that moved to trl.experimental) can still propagate exceptions. The umbrella patch_trl_rl_trainers() already ring-fences each call with try/except + warning_once, but direct callers (the CI shim in consolidated-tests-ci.yml, downstream tools, end-user scripts) used to see the raw exception, which forced #5312's heredoc to ring-fence with:

except Exception as e:
    # TRL 1.x renames break the patch helper internally; we
    # accept that here and skip rather than fail the cell.
    pytest.skip(f"_patch_trl_rl_trainers raised: ...")

Rename the existing implementation to _patch_trl_rl_trainers_impl and make _patch_trl_rl_trainers a thin wrapper that catches any uncaught exception and routes it through logger.info, matching the umbrella wrapper's behaviour. Power users who want the raw raising behaviour for their own diagnostics can still call _patch_trl_rl_trainers_impl directly.

Adds tests/python/test_patch_trl_rl_trainers_defensive.py to lock the contract: the wrapper must never raise, and it must delegate to the impl on the happy path. 5 cases, all pass locally on TRL 1.4.0.

Unblocks 1 skip in consolidated-tests-ci.yml's test_compile_sft_trainer_patch.

Follow-up for #5312

Once this lands, #5312 should rebase and drop:

  • the two --deselect lines in studio-backend-ci.yml's repo-cpu-tests step
  • the except Exception ... pytest.skip(f"_patch_trl_rl_trainers raised: ") block in consolidated-tests-ci.yml's test_compile_sft_trainer_patch

Test plan

  • from transformers import AutoConfig succeeds in a fresh --no-deps -r no-torch-runtime.txt venv (Python 3.12).
  • tests/python/test_patch_trl_rl_trainers_defensive.py passes (5/5) on TRL 1.4.0.
  • _patch_trl_rl_trainers("sft_trainer") still patches via the impl on TRL 0.x and TRL 1.x (verified in local sandboxes).
  • CI green on this PR.

PR #5312 surfaced two real regressions by turning previously-silent
skips into explicit `--deselect` / `pytest.skip(...)` blocks. Both
were left as follow-ups rather than fixed in that PR. This PR fixes
the underlying bugs so the suppressions can be dropped.

1. studio/backend/requirements/no-torch-runtime.txt: pin tokenizers

   Installing with `--no-deps -r no-torch-runtime.txt` (the path
   install.sh takes for the no-torch / GGUF-only mode) resolves
   transformers to 5.3.0 and tokenizers to the latest available
   (0.23.1). transformers 5.3.0 requires
   `tokenizers>=0.22.0,<=0.23.0`, so `from transformers import
   AutoConfig` then fails at import time:

       ImportError: tokenizers>=0.22.0,<=0.23.0 is required for a
       normal functioning of this module, but found
       tokenizers==0.23.1.

   Pin `tokenizers>=0.22.0,<=0.23.0` to match the constraint
   embedded inside every transformers version in the allowed window
   (4.56.0..5.3.0). Verified locally: a fresh `uv venv` + `uv pip
   install --no-deps -r no-torch-runtime.txt` followed by
   `from transformers import AutoConfig` now succeeds.

   Unblocks 3 deselected cases in studio-backend-ci.yml:
     - TestE2ETokenizersFix::test_autoconfig_works_with_no_torch_runtime
       (parametrized py 3.12 + 3.13 -> 2 cases)
     - TestE2EFullNoTorchSandbox::test_autoconfig_succeeds

2. unsloth/models/rl.py: defensive wrapper for _patch_trl_rl_trainers

   _patch_trl_rl_trainers has many internal `try: ... except: ...
   return` branches, but several paths (notably inspect.getsource on
   the thin wrappers TRL 1.x leaves in trl.trainer for trainers that
   moved to trl.experimental) can still propagate exceptions. The
   umbrella patch_trl_rl_trainers() ring-fences each call with
   try/except + warning_once, but direct callers (the CI shim in
   consolidated-tests-ci.yml, downstream tools, end-user scripts)
   used to see the raw exception, which forced #5312's CI heredoc to
   ring-fence with:

       except Exception as e:
           # TRL 1.x renames break the patch helper internally; we
           # accept that here and skip rather than fail the cell.
           pytest.skip(f"_patch_trl_rl_trainers raised: ...")

   Rename the existing implementation to _patch_trl_rl_trainers_impl
   and make _patch_trl_rl_trainers a thin wrapper that catches any
   uncaught exception and routes it through logger.info, matching
   the umbrella wrapper's behaviour. Power users who want the raw
   raising behaviour for their own diagnostics can still call
   _patch_trl_rl_trainers_impl directly.

   Adds tests/python/test_patch_trl_rl_trainers_defensive.py to lock
   the contract: the wrapper must never raise, and it must delegate
   to the impl on the happy path.

   Unblocks 1 skip in consolidated-tests-ci.yml's
   test_compile_sft_trainer_patch.

Follow-up for #5312 once this lands: drop the two `--deselect` lines
in studio-backend-ci.yml's repo-cpu-tests step and drop the
`except Exception ... pytest.skip(f"_patch_trl_rl_trainers raised: ")`
block in consolidated-tests-ci.yml's test_compile_sft_trainer_patch.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e774494427

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# `from transformers import AutoConfig` then fails at import time:
# ImportError: tokenizers>=0.22.0,<=0.23.0 is required ...,
# but found tokenizers==0.23.1.
tokenizers>=0.22.0,<=0.23.0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Update shell test for versioned tokenizers pin

In the studio-backend-ci.yml Shell installer tests step I checked, tests/sh/test_torch_constraint.sh is run on every backend CI job, and it still asserts grep -c '^tokenizers$' and derives the tokenizers line number from that exact match. With this new pinned requirement, bash tests/sh/test_torch_constraint.sh now fails the “tokenizers present as standalone line” and “tokenizers before transformers” checks, so this change blocks that CI job until the structural test accepts the versioned tokenizers spec.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request pins the tokenizers dependency to ensure compatibility with transformers during dependency-free installations and introduces a defensive wrapper around _patch_trl_rl_trainers to prevent exceptions from propagating to direct callers. New regression tests are added to verify this error-handling behavior. Feedback suggests using logger.warning_once instead of logger.info when patching fails to maintain consistency with established patterns in the codebase and ensure visibility of issues.

Comment thread unsloth/models/rl.py
Comment on lines +560 to +563
logger.info(
f"Unsloth: Could not patch trl.trainer.{trainer_file}: "
f"{type(e).__name__}: {e}"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The wrapper uses logger.info to log patching failures, but the "umbrella" function patch_trl_rl_trainers (line 1973) uses logger.warning_once. To maintain consistency with the intended "umbrella behavior" mentioned in the PR description and to ensure that unexpected patching failures are sufficiently visible without flooding logs, consider using logger.warning_once here as well. This also ensures the specific error details are captured dynamically.

Suggested change
logger.info(
f"Unsloth: Could not patch trl.trainer.{trainer_file}: "
f"{type(e).__name__}: {e}"
)
logger.warning_once(
f"Unsloth: Could not patch trl.trainer.{trainer_file}: "
f"{type(e).__name__}: {e}"
)
References
  1. Prioritize consistency with established coding patterns within a module.
  2. User-facing warning messages should be dynamically generated to include the specific configuration values they refer to, rather than using hardcoded examples.

Drop verbose justifications down to one or two lines per site.
The PR description carries the full context; in-file comments
only need to point at the WHY.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8386322315

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# Must match the bound every transformers 4.56..5.3 declares.
# With --no-deps, unpinned resolves to 0.23.1+ and `from transformers
# import AutoConfig` raises ImportError at import time.
tokenizers>=0.22.0,<=0.23.0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update negative control to remove versioned tokenizers

When the e2e tokenizer suite is enabled, TestE2ETokenizersFix::test_negative_control_no_tokenizers still creates its "without tokenizers" requirements copy by dropping only lines whose stripped text equals tokenizers; this new versioned requirement survives that filter, so the copied file still installs tokenizers and AutoConfig succeeds, causing the negative-control assertion to fail. Adjust the test/filter alongside this requirement change so the no-tokenizers copy actually removes tokenizers>=....

Useful? React with 👍 / 👎.

tokenizers 0.23.0 was never published to PyPI (versions go 0.22.2 ->
0.23.1), so `tokenizers<=0.23.0` resolves to 0.22.2 in practice, the
same version the explicit >=0.22.0,<=0.23.0 pin resolved to. Verified
on Python 3.12 and 3.13.
@danielhanchen
danielhanchen merged commit 1c91f49 into main May 11, 2026
13 of 14 checks passed
@danielhanchen
danielhanchen deleted the fix/no-torch-tokenizers-and-trl1-patch-defensive branch May 11, 2026 09:39
danielhanchen added a commit that referenced this pull request May 11, 2026
Address bot review feedback on #5361:

* Codex (P2): the previous relaxed regex `^tokenizers([<>=!,~ ]|$)`
  accepted any version operator, so `tokenizers>=0.23.1` would still
  pass the test even though that line would re-introduce the import
  failure #5359 fixed.

* Gemini (medium): the boundary char class did not cover all PEP 508
  separators (`[`, `;`, `@`).

Replace the single check with two:

1. Loose: `^tokenizers([^a-zA-Z0-9._-]|$)` confirms the package is
   listed (covers extras, env markers, URLs, bare line).

2. Tight regression guard: pipe those lines through a second grep
   that requires `<=0.23.0` or the functionally equivalent
   `<0.23.1`. Rejects bare `tokenizers`, `>=0.22.0` (no upper
   bound), `>=0.23.1`, `!=0.23.0`, `<=0.24.0`, etc.

Verified locally:
- Current main (tokenizers<=0.23.0): 25 PASS, 0 FAIL.
- Spot-check with the bug reverted (bare `tokenizers`): the new
  "tokenizers pinned with upper bound excluding 0.23.1+" check
  FAILS as intended; the original "listed" check still passes.
danielhanchen added a commit that referenced this pull request May 11, 2026
* fix(tests/sh): accept pinned tokenizers line after #5359

#5359 pinned the tokenizers line in
studio/backend/requirements/no-torch-runtime.txt from bare
`tokenizers` to `tokenizers<=0.23.0` to stop pip from resolving to
0.23.1+ (which transformers rejects at import time). The shell test
in tests/sh/test_torch_constraint.sh was still asserting the literal
`^tokenizers$` regex, which fails on the pinned form. Surfaced as
a hard fail on PR #5312's Backend CI Repo tests (CPU) step:

  === Structural: tokenizers in no-torch-runtime.txt ===
    FAIL: tokenizers present as standalone line (expected '1', got '0')
    FAIL: tokenizers before transformers (expected 'yes', got 'no')

Relax the regex to `^tokenizers([<>=!,~ ]|$)` so it matches both bare
and version-constrained forms, which preserves the original intent
(verify tokenizers is present in the file, before transformers).
Verified locally: 24 PASS, 0 FAIL.

* fixup(tests/sh): tighten tokenizers check to guard the safe bound

Address bot review feedback on #5361:

* Codex (P2): the previous relaxed regex `^tokenizers([<>=!,~ ]|$)`
  accepted any version operator, so `tokenizers>=0.23.1` would still
  pass the test even though that line would re-introduce the import
  failure #5359 fixed.

* Gemini (medium): the boundary char class did not cover all PEP 508
  separators (`[`, `;`, `@`).

Replace the single check with two:

1. Loose: `^tokenizers([^a-zA-Z0-9._-]|$)` confirms the package is
   listed (covers extras, env markers, URLs, bare line).

2. Tight regression guard: pipe those lines through a second grep
   that requires `<=0.23.0` or the functionally equivalent
   `<0.23.1`. Rejects bare `tokenizers`, `>=0.22.0` (no upper
   bound), `>=0.23.1`, `!=0.23.0`, `<=0.24.0`, etc.

Verified locally:
- Current main (tokenizers<=0.23.0): 25 PASS, 0 FAIL.
- Spot-check with the bug reverted (bare `tokenizers`): the new
  "tokenizers pinned with upper bound excluding 0.23.1+" check
  FAILS as intended; the original "listed" check still passes.
danielhanchen added a commit that referenced this pull request Sep 7, 2026
…control

setup.ps1 is what Windows updates run and it already carries the anyio repair
probe this one is modelled on, so the tokenizers probe belongs beside it rather
than only in setup.sh. Exercised against real venvs through pwsh: a stranded pair
forces the dependency pass, a healthy pair and an unreadable one do not, matching
the bash sibling case for case.

tests/python/test_tokenizers_and_torch_constraint.py's negative control dropped
the tokenizers line by comparing the whole line against "tokenizers". That
matched the bare entry #4748 added and matched nothing once #5359 gave it a
version bound, so the control installed tokenizers and then asserted an import
failure that could not happen. It has been failing on every tree since, unnoticed
because the class carries the e2e marker the CI lane filters out. Match by package
name instead, which survives the next bound too. The class passes 7/7.
danielhanchen added a commit that referenced this pull request Sep 8, 2026
…ort (#10431)

* Pin tokenizers with transformers so Apple Silicon keeps Train and Export

transformers declares a tokenizers window and enforces it at import, so a venv
holding a transformers that rejects its tokenizers cannot 'import transformers'
at all. mlx_lm imports transformers, so mlx_stack_blockers() reports a blocker
and Studio settles chat-only with Train and Export disabled.

A fresh 'install.sh --local' on macOS arm64 produced exactly that pair. The core
phase resolves with UV_OVERRIDE=overrides-darwin-arm64.txt and without
constraints.txt, and a uv override replaces every requirement on a package, so
that file's unbounded 'transformers>=5.5.0' also replaced pyproject's <=5.5.0
cap. Since transformers 5.16.0 (2026-08-26), the first release wanting
tokenizers>=0.23.1, that resolve lands transformers 5.16.1 + tokenizers 0.23.2;
step 3b of install_python_stack.py then installs extras-no-deps.txt with
--no-deps, which pins transformers back to 5.5.0 and leaves tokenizers stranded.
No commit here caused it: a third-party release walked into an unbounded
override, which is why the new gate checks the resolved pair rather than a
version number a diff would show.

extras-no-deps.txt now names both halves, which is the file that decides the
final versions on every platform and on both fresh install and update.
constraints.txt carries the same window globally, for the reason the anyio cap
gives: a later with-deps step must not re-resolve it up. no-torch-runtime.txt
spells its existing cap as the same full window so one canonical pair exists.

setup.sh gets a sibling of the anyio repair probe: an already-broken venv whose
unsloth is current takes the fast update path, which never reaches the step that
repairs the pair, so 'unsloth studio update' would report 'up to date' and fix
nothing. It reads metadata rather than importing transformers, since importing
is what is broken.

tests/studio/install/test_transformers_tokenizers_pair.py locks the shape: every
installing requirements file that pins transformers must bound tokenizers to the
window that release declares, no file may admit 0.23.2, and a sequential resolve
of the real macOS arm64 install (core phase, then the --no-deps overlay) must end
with a pair transformers accepts. On the tree before this commit, four of its six
checks fail.

* Drop two stale deselects from Backend CI

Both named a tokenizers pin no-torch-runtime.txt was missing; #5359 added it and
both tests pass now. They were redundant regardless: the -m filter on the same
command already excludes their e2e class marker.

* Bound the macOS arm64 transformers override to the version it pins against

The override existed to raise mlx-vlm/mlx-lm's transformers floor, but an
override replaces every requirement on the package, so the bare floor also
replaced unsloth's own transformers<=5.5.0 cap on the one uv command that does
not pass constraints.txt: install.sh's core install. From transformers 5.16.0
that resolve started landing 5.16.1 with tokenizers 0.23.2 on Apple Silicon,
which the later --no-deps pin turned into a stranded pair.

Capping at the version constraints.txt already pins makes the core phase resolve
consistently on its own rather than being repaired a step later. Verified with
uv pip compile for aarch64-apple-darwin / py3.13: transformers 5.5.0,
tokenizers 0.22.2, and mlx 0.32.1 / mlx-lm 0.31.3 / mlx-vlm 0.6.17 unchanged
from the uncapped resolve.

This cannot go unsatisfiable the way the huggingface_hub override once did: that
one replaced other packages' requirements on hub while a direct requirement still
had to be satisfied, whereas no requirement on transformers survives this
override to contradict it. A new test keeps the override and constraints.txt in
lockstep.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Give the repair probe a Windows sibling, and restore a dead negative control

setup.ps1 is what Windows updates run and it already carries the anyio repair
probe this one is modelled on, so the tokenizers probe belongs beside it rather
than only in setup.sh. Exercised against real venvs through pwsh: a stranded pair
forces the dependency pass, a healthy pair and an unreadable one do not, matching
the bash sibling case for case.

tests/python/test_tokenizers_and_torch_constraint.py's negative control dropped
the tokenizers line by comparing the whole line against "tokenizers". That
matched the bare entry #4748 added and matched nothing once #5359 gave it a
version bound, so the control installed tokenizers and then asserted an import
failure that could not happen. It has been failing on every tree since, unnoticed
because the class carries the e2e marker the CI lane filters out. Match by package
name instead, which survives the next bound too. The class passes 7/7.

* Exclude the pinned release from the override test's excess check

* Derive the override's excess candidates from the pin

Building on the previous commit, which was right that the pinned release must not
count as excess. The remaining half is that a fixed pair of releases goes vacuous
once the pin passes them: with 5.16.1 pinned, neither 5.16.1 nor 5.15.1 is above
it and the check tests nothing. Derive the next minor and the next major from the
pin, keep the two named releases since they are the ones that shipped the
tokenizers window change, and the assertion keeps asking its question after every
future bump.

Verified both ways: passes on this branch, and against an unbounded override it
reports ['5.15.1', '5.16.1', '5.6.0', '6.0.0'].

* Make the resolver check fail only on a resolver verdict

Codex is right that this test runs in the ordinary CPU lane and reaches the index
twice plus a urlopen, so it had two ways to turn someone else's PR red for
reasons that say nothing about our pins: subprocess.TimeoutExpired was not caught
at all, and any uv failure whose stderr missed a four-word list became a hard
failure, which a 429 or an index 500 would.

Inverted instead of marked. Marking it e2e would take it out of the lane the
regression it guards actually reaches, and the e2e marker is registered in
tests/python/conftest.py, which does not cover this directory. Now the test fails
only when uv returns a resolution verdict (no solution found, unsatisfiable,
because, conflict) and skips on everything else, including a timeout, a missing
uv, an OSError, and a PyPI reply that is slow, throttled or not JSON. The compile
budget drops from 600s to 180s so a hung index cannot hold a job for ten minutes.

Verified all three ways against a live uv: an unreachable index skips, an
unsatisfiable pair still fails with 'No solution found when resolving
dependencies: Because transformers==5.5.0 depends on tokenizers>=0.22.0,<=0.23.0',
and a healthy resolve returns.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Nilay Yadav <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant