Skip to content

Name a torchvision whose compiled ops do not match torch - #8128

Merged
danielhanchen merged 17 commits into
unslothai:mainfrom
danielhanchen:fix/broken-torchvision-import
Aug 9, 2026
Merged

danielhanchen merged 17 commits into
unslothai:mainfrom
danielhanchen:fix/broken-torchvision-import

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What broke

Running Gemma4_(E2B)_GRPO on a Colab T4, import unsloth stops here:

transformers/image_utils.py in <module>
     59     if is_torchvision_available():
---> 60         from torchvision.transforms import InterpolationMode

torchvision/_meta_registrations.py in <module>
--> 163 @torch.library.register_fake("torchvision::nms")

RuntimeError: operator torchvision::nms does not exist

That notebook's T4 branch installs vllm==0.9.2 beside Colab's torch, and torchvision comes out of it reporting a version the compatibility table accepts while its compiled ops were built against a torch that is no longer there. The message names neither torchvision nor anything the user can act on, and it arrives from inside transformers, six frames below anything they wrote.

The vLLM half of the very same breakage is already handled. The same run logged:

WARNING:unsloth.import_fixes:Unsloth: Detected broken vLLM binary extension;
disabling vLLM imports and continuing import.

Only the torchvision half fell through.

Why the existing check missed it

torchvision_compatibility_check compares importlib.metadata versions against a torch/torchvision table. Metadata cannot see an ABI break: here the versions agreed and the binary still did not load. A mismatch the table can see already raises a clear ImportError, so the compatible branch is the only blind spot.

The change

On that branch only, import torchvision (and torchvision.ops, where the compiled nms lives) and, if it fails with the ABI signature, raise an ImportError that says which package is broken and how to reinstall it:

Unsloth: torchvision==0.26.0 claims to match torch==2.11.0, but its compiled
operators do not load (RuntimeError: operator torchvision::nms does not exist).
Reinstall it with `pip install --upgrade --force-reinstall --no-cache-dir torchvision`.
Set UNSLOTH_SKIP_TORCHVISION_CHECK=1 to skip this check.
  • An import failure that does not match the signature is left alone, so the probe never claims someone else's error.
  • UNSLOTH_SKIP_TORCHVISION_CHECK=1 still short-circuits the whole function, ahead of the probe.
  • No net import cost: transformers imports torchvision from image_utils the moment anything touches processing_utils, which is exactly how the failure was reaching users.
  • Recognised shapes: torchvision::..., undefined symbol, cannot open shared object file, and the half-overwritten torchvision.io.video / io._video case, chained causes included.

Tests

tests/test_broken_torchvision_probe.py, 12 tests. All 12 fail on main (the helpers do not exist), all 12 pass with the change. tests/test_import_fixes_drift.py and tests/test_missing_torchvision_vlm.py still pass: 42 passed together. import unsloth on a healthy environment is unchanged.

Compatibility

Pure Python around an import, no torch, transformers, TRL or vLLM API touched, so it is unaffected by transformers 4.57.x through 5.x, TRL 0.22.2 through 1.x, and torch 2.6 onwards. Linux, macOS, Windows and WSL alike.

Related: unslothai/unsloth-zoo#1012 makes unsloth_zoo's own handler report the same breakage instead of re-raising the bare operator error.

@danielhanchen

Copy link
Copy Markdown
Member Author

CI status, so nobody has to re-derive it.

Eight of the reds are repo-wide on main, not from this change. Same eight on #8121, #8123, #8124 and on main itself:

The ninth, npm scan-packages, is not one of those and is also not this PR: the change is Python-only and touches no JS. It is a registry integrity mismatch on a transitive dependency,

ERROR @rolldown/[email protected]: integrity mismatch:
  expected sha512='9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg=='
  got      sha512='3Bk1dMen8xTyk/G6EOWLgh3oR2lzueGKSt3hN0mtHXyGxTyp7qgk+tizouuHFfJN0XPsK05Wb/jhQzqJWoeV0g=='

with 0 finding(s), 1 hard error(s) -- the scanner found nothing wrong with the tree, it could not verify one tarball. Rerunning it to see whether it reproduces; if it does it is worth chasing upstream on its own, not here.

@danielhanchen

Copy link
Copy Markdown
Member Author

The npm rerun came back SUCCESS, so that integrity mismatch was transient on the registry's side and not a finding. The remaining eight reds are the repo-wide set listed above.

@danielhanchen

Copy link
Copy Markdown
Member Author

Two CI notes, one of which turned into a real fix.

Chat UI Tests is not from this PR. It fails identically on #8127, which only moves save_lora outside a guard and cannot touch a Playwright font-scale test. Same assertion, same numbers on both:

AssertionError: [font-scale] FAIL: wheel did not scroll the select viewport: 47 -> 88

It is SUCCESS on #8120, #8121 and #8124, whose runs predate mine, so this started between those runs and these -- a runner browser bump would do exactly this. Not something either PR can fix.

Chasing that did surface a real regression risk here, now fixed in 36be74f. This probe imports torchvision where nothing used to, so it can turn a latent failure into a hard error on import unsloth. undefined symbol and cannot open shared object file on their own were too broad: a CPU-only or driverless box whose torchvision cannot load for an unrelated reason -- a missing libcuda.so.1, a mismatched libjpeg -- imported unsloth fine before and would now have been told to reinstall torchvision.

Those two markers now also have to name torchvision or the torch libraries it links. torchvision::, torchvision.io.video and io._video stay unambiguous on their own. Everything else is left exactly as it was, which is the point: the probe should add a diagnosis, not a failure.

Three new cases cover it and all three fail without the change. 45 passed across this suite and the two neighbouring torchvision suites; import unsloth still clean.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026

@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: 47dc7edad5

ℹ️ 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".

Comment thread unsloth/import_fixes.py
Comment on lines +1033 to +1034
if not _is_broken_torchvision_error(error):
return

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 Restore modules after ignoring a failed probe

When torchvision raises an unrecognized exception after some of its submodules have loaded, returning here does not actually leave the failure alone: Python removes the failed top-level module but can retain torchvision.* entries in sys.modules. A later Transformers or VLM import may then encounter a half-initialized package and fail with circular-import or missing-attribute errors, whereas without this eager probe it would receive a clean first import. Snapshot and restore the relevant module entries when suppressing the probe error.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Simulated this one directly rather than reasoning about it, with a shim torchvision that imports extension, ops and transforms successfully and only then raises an error the probe does not recognise, which is exactly the shape described.

main: torchvision's body runs once, fails, and sys.modules is left holding ['torchvision.extension', 'torchvision.ops', 'torchvision.transforms']. This branch: the body runs twice, once for the probe and once for transformers, and sys.modules is left holding the identical three entries, with the identical final exception at the identical file, line and stack depth. So the residue is not something the probe introduces, it is already there on main, and snapshotting it would not change the end state. The retry is clean because Python removes torchvision itself on failure and re-executes its body from scratch; the retained submodules are reused exactly as they are today. No circular import or missing attribute materialised in any of the eight shapes I ran.

Comment thread unsloth/import_fixes.py
Comment on lines +1005 to +1006
if any(marker in message for marker in _TORCHVISION_ABI_MARKERS):
return True

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 Distinguish swallowed loader failures from ABI skew

When torchvision's _C extension fails to load for any reason, its extension loader catches ImportError/OSError and continues without registering the operators; _meta_registrations can then raise the same RuntimeError: operator torchvision::nms does not exist. Treating that message as unconditionally diagnostic therefore bypasses the loader filtering below and turns unrelated failures such as a missing system CUDA or image library into a hard import unsloth failure with incorrect reinstall advice. Check the extension load status or preserved loader exception rather than assuming every missing NMS schema is version skew.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The extension-loader half is right: torchvision/extension.py really does except (ImportError, OSError): pass, leaving _HAS_OPS = False, and the unguarded @torch.library.register_fake("torchvision::nms") then raises the same message whatever the underlying cause was. So an unrelated _C failure can indeed arrive wearing the nms message.

The consequence does not follow, though: it does not turn anything into a hard import unsloth failure, because import unsloth already imports torchvision. Measured with the check itself disabled (UNSLOTH_SKIP_TORCHVISION_CHECK=1), torchvision and transformers.image_utils are both in sys.modules when import unsloth returns. I then ran import unsloth against a shim torchvision on main and on this branch across seven failure shapes. On main the nms case dies with RuntimeError: operator torchvision::nms does not exist ten frames deep; on this branch it dies with the named ImportError five frames deep. Same fatality, better message. And the two shapes whose text does not name torchvision (libcudart.so.12: cannot open shared object file, a plain unrelated RuntimeError) come out byte-identical on both: same exception type, same message, same file, same line, same depth. The loader filter is doing its job.

That leaves misattribution of the message, not a new failure, and 8cb28c2 takes the teeth out of that too: the repair command is now pinned with --no-deps, so acting on it when the real cause was a missing system library reinstalls the same torchvision in place instead of rebuilding the environment. The underlying cause is discarded by torchvision's own pass, so there is nothing left for us to read.

Comment thread unsloth/import_fixes.py Outdated
f"Unsloth: torch=={torch_version_raw} and "
f"torchvision=={torchvision_version_raw} are compatible."
)
_probe_torchvision_binary(torch_version_raw, torchvision_version_raw)

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 Reject newer incompatible torchvision minors before probing

This call is reached for every tv_v >= required_tv_str, but torchvision minors are paired one-to-one with torch minors rather than being backward-compatible minimums. For example, torch 2.4 with torchvision 0.20 reaches the probe even though 0.20 is the torch 2.5 companion; if it raises the NMS error, the new diagnostic incorrectly says the versions claim to match and recommends repairing the binary instead of installing torchvision 0.19. Require the expected torchvision minor, not merely a lower bound, before classifying the failure as hidden binary corruption.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Half right, and the half that matters is fixed elsewhere. You are correct that the gate is a lower bound, so torch 2.4 with torchvision 0.20 reads as compatible and reaches the probe; that lower bound predates this PR and is not something the PR changed.

Turning it into an exact-minor requirement is what I am rejecting. TORCH_TORCHVISION_COMPAT only has rows for torch 2.4 through 2.9, everything newer goes through _infer_required_torchvision's formula, and requiring an exact match would start raising ImportError on nightlies, +cpu/+rocm/+xpu local builds and any pair the table has not caught up with yet, which is a far larger blast radius than the one misattributed message. The consequence you actually named, a repair command that recommends the wrong wheel, is fixed in 8cb28c2: the command is now pinned to the companion release the table names, so on your torch 2.4 example it says torchvision==0.19.*, which is exactly the wheel you asked for.

danielhanchen and others added 5 commits August 8, 2026 03:21
torchvision_compatibility_check compares version metadata, and metadata
cannot see an ABI break. Running Gemma4_(E2B)_GRPO turned one up: its T4
branch installs vllm==0.9.2 beside Colab's torch, and torchvision came out
reporting a version the table accepts while its ops were built against a
torch that is gone. import unsloth then died with

    RuntimeError: operator torchvision::nms does not exist

raised from transformers/image_utils.py, naming neither torchvision nor
what to do about it. The vLLM half of the same breakage was already
handled: the run logged "Detected broken vLLM binary extension; disabling
vLLM imports and continuing".

So import torchvision on the path the table calls compatible, which is the
only blind spot, and turn the loader error into one that says which package
is broken and how to reinstall it. UNSLOTH_SKIP_TORCHVISION_CHECK=1 still
skips everything, and an import failure we cannot explain is left alone.

No extra import cost in practice: transformers imports torchvision from
image_utils as soon as anything touches processing_utils.
Comments and docstrings only. AST gate with --strip-docstrings passes on both
files; without it both report CODE CHANGED, which is expected since a docstring
is an AST node. Docstrings touched: the module docstring of
tests/test_broken_torchvision_probe.py and _probe_torchvision_binary's.
The probe imports torchvision where nothing used to, so it can turn a latent
failure into a hard error on `import unsloth`. `undefined symbol` and
`cannot open shared object file` on their own are not enough: a CPU-only or
driverless box whose torchvision cannot load for an unrelated reason -- a
missing libcuda, a mismatched libjpeg -- would have imported unsloth fine
before and would now be told to reinstall torchvision.

Those two markers now also have to name torchvision or the torch libraries it
links. `torchvision::`, `torchvision.io.video` and `io._video` stay
unambiguous on their own. Anything else is left exactly as it was, which is
the point: the probe adds a diagnosis, it must not add a failure.

Three new cases; all three fail without the change.
@danielhanchen
danielhanchen force-pushed the fix/broken-torchvision-import branch from 47dc7ed to 9c7d244 Compare August 8, 2026 03:21

@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: 9c7d24477a

ℹ️ 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".

Comment thread unsloth/import_fixes.py
"""
try:
import torchvision # noqa: F401
import torchvision.ops # noqa: F401 where the compiled nms lives

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 Probe the extension rather than just importing ops

For the supported torch 2.1/torchvision 0.16 pairing, torchvision's extension loader catches ImportError/OSError, and its guarded meta registrations allow both of these imports to succeed with _HAS_OPS == False; importing torchvision.ops only defines wrappers and does not execute nms. A broken _C therefore passes this probe and fails later when an operator is actually called. Check torchvision.extension._has_ops() or otherwise force a harmless dispatcher lookup so the probe covers versions that predate the unguarded fake-NMS registration.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Checked this against upstream rather than from memory, tag by tag. @torch.library.register_fake("torchvision::nms") sits unguarded at _meta_registrations.py:163 in v0.19.0, v0.20.0, v0.21.0 and v0.24.1, and is absent from v0.16.0, v0.17.0 and v0.18.0. So on everything from 0.19 onward a broken _C makes import torchvision itself raise and the probe catches it; the blind spot you describe is real only for 0.16 through 0.18, which pair with torch 2.1 through 2.3. The compatibility table here starts at torch 2.4, and transformers>=4.51.3 does not run on that torch either.

The remedy is the part I would not take even for the versions it covers. _has_ops() is False whenever _C did not load, which includes a torchvision built without its extensions at all: that install cannot do nms or roi_align, but it can do torchvision.transforms, which is the only thing transformers imports from it. Gating on _has_ops() would hard-fail import unsloth on boxes that work today, to cover versions we do not support. The current probe reacts only to an import that actually failed, which is why it can only ever remove a path that was already broken.

Every torchvision wheel requires an exact torch==X.Y.Z (0.24.1 requires
torch==2.9.1), so the unpinned `pip install --upgrade --force-reinstall
torchvision` the new message printed resolves the newest torchvision and then
pulls a new torch in to satisfy it. On a Colab or Kaggle image that is the
pinned torch every other wheel was built against, vLLM included, so following
the advice broke more than it repaired.

Pin to the companion release the compatibility table names, and pass --no-deps
so torch is never a candidate. The pin also covers the case where the version
gate passed on its lower bound: torch 2.4 accepts torchvision >= 0.19, so an
installed 0.20 reaches the probe, and 0.19 is what actually repairs that box.

pip's own docs: --upgrade selects the newest version and, under the default
only-if-needed strategy, upgrades a dependency that the newer package no longer
accepts; --force-reinstall reinstalls the whole resolved set.
@danielhanchen

Copy link
Copy Markdown
Member Author

Where this stands

1. Before the PR. Running Gemma4_(E2B)_GRPO on a Colab T4, import unsloth stopped six frames below anything the user wrote:

transformers/image_utils.py in <module>
     59     if is_torchvision_available():
---> 60         from torchvision.transforms import InterpolationMode

torchvision/_meta_registrations.py in <module>
--> 163 @torch.library.register_fake("torchvision::nms")

RuntimeError: operator torchvision::nms does not exist

That notebook's T4 branch installs vllm==0.9.2 beside Colab's torch, and torchvision comes out of it reporting a version the compatibility table accepts while its compiled ops were built against a torch that is no longer there. torchvision_compatibility_check compares importlib.metadata versions, and metadata cannot see an ABI break, so the compatible branch was the one blind spot. The vLLM half of the same breakage was already handled in the same run (Detected broken vLLM binary extension; disabling vLLM imports); only torchvision fell through.

2. After the PR. On the compatible branch only, torchvision is imported and, if it fails with the ABI signature, the failure is named where the user can act on it:

Unsloth: torchvision==0.24.1 claims to match torch==2.9.1, but its compiled operators
do not load (RuntimeError: operator torchvision::nms does not exist). Reinstall it with
`pip install --force-reinstall --no-deps --no-cache-dir "torchvision==0.24.*"`.
Set UNSLOTH_SKIP_TORCHVISION_CHECK=1 to skip this check.

3. Real or theoretical. Real, and reproduced from a notebook run, not constructed. The important thing the review round established is that the probe is not new failure surface: import unsloth already imports torchvision. With the check itself disabled via UNSLOTH_SKIP_TORCHVISION_CHECK=1, torchvision and transformers.image_utils are both in sys.modules by the time import unsloth returns. So on main this environment already dies during import unsloth; it just dies ten frames deep with a message naming nothing the user owns. The PR changes the message and the depth, not the outcome.

One review item was a genuine defect in the new message, and 8cb28c2 fixes it. torchvision==0.24.1 declares Requires-Dist: torch (==2.9.1), an exact pin, so the original unpinned pip install --upgrade --force-reinstall --no-cache-dir torchvision resolves the newest torchvision and then has to replace torch to satisfy it. pip's own docs close it: --upgrade selects the newest version, the default only-if-needed strategy upgrades a dependency the newer package no longer accepts, and --force-reinstall reinstalls the whole resolved set. On a Colab or Kaggle image that torch is what every other wheel was built against, vLLM included, so following the advice broke more than it repaired. The command is now pinned to the companion release the table names for the installed torch, with --no-deps.

4. What merging could break.

No new hardware path. Pure Python around an import, with no torch, transformers, TRL or vLLM API touched and no device query.

The old path is untouched, measured rather than asserted. import unsloth was run against a shim torchvision on main and on this branch, seven failure shapes each:

shim raises main this branch
RuntimeError: operator torchvision::nms does not exist fails, depth 10 named ImportError, depth 5
ImportError: _C.so: undefined symbol: _ZN3c10... fails, depth 7 named ImportError, depth 5
OSError: libtorchvision_ops.so: cannot open shared object file fails, depth 10 named ImportError, depth 5
ImportError: cannot import name 'video' from 'torchvision.io.video' fails, depth 7 named ImportError, depth 5
chained wrapper whose __cause__ carries torchvision:: fails, depth 7 named ImportError, depth 5
OSError: libcudart.so.12: cannot open shared object file fails, depth 10 identical: same type, message, file, line, depth
RuntimeError: some entirely unrelated failure fails, depth 10 identical

The last two are the ones that matter for backwards compatibility: an import failure whose text does not name torchvision or the torch libraries it links comes out byte-identical to main, so a box whose torchvision cannot load for an unrelated reason keeps exactly the behaviour it had.

Old installs. Nothing is imported from unsloth_zoo or Unsloth Studio, and no public name changes. UNSLOTH_SKIP_TORCHVISION_CHECK=1 still short-circuits the whole function ahead of the probe, pinned by a test that asserts the ordering in the AST, so any environment that already opts out is unaffected.

Simulations

Theorised first: (H1) does import unsloth already import torchvision, which decides whether the probe adds failure surface at all; (H2) can a _C failure with an unrelated cause arrive wearing the nms message; (H3) is _has_ops() a better probe; (H4) is there a torchvision old enough that the probe is blind; (H5) does the printed pip command replace torch; (H6) does swallowing an unrecognised error poison sys.modules.

Executed on Linux, CUDA_VISIBLE_DEVICES=0:

  • H1, H2, H6: 9 shim scenarios x 2 checkouts of end-to-end import unsloth, table above. H1 true, so H2's stated consequence does not hold. H6 false: a shim that loads three submodules and then raises an unrecognised error leaves the identical ['torchvision.extension', 'torchvision.ops', 'torchvision.transforms'] residue and the identical final exception on both checkouts, so the residue is main's, not the probe's.
  • H4: read _meta_registrations.py at seven upstream tags. The unguarded register_fake("torchvision::nms") is present in v0.19.0 through v0.24.1 and absent in v0.16.0 through v0.18.0, so the blind spot exists only for torchvision <= 0.18, pairing with torch <= 2.3.
  • H5: torchvision's own wheel metadata plus the pip documentation for --upgrade, --upgrade-strategy and --force-reinstall.
  • Version matrix: the changed logic lifted out of import_fixes.py and exercised on 10 interpreters, torch 2.6.0 / 2.7.1 / 2.8.0 / 2.9.1 / 2.10.0 / 2.11.0 / 2.12.0 CPU plus 2.8.0+cu128 / 2.9.1+cu128 / 2.12.0+cu130, transformers 5.14.1. Identical on all ten: companion versions for torch 2.4 through 2.14, classification of all 8 error shapes, the repair command, and the skip variable.
  • Edge cases: a None error, an empty-message ImportError, a self-referential __cause__ cycle (terminates, does not hang), torchvision absent entirely, and the skip variable set.
  • 18 tests in tests/test_broken_torchvision_probe.py; tests/test_import_fixes_drift.py and tests/test_missing_torchvision_vlm.py still pass, 48 together.

Not executed, reasoned from source: macOS and Windows. The change adds no path handling, no shell out and no platform branch, and the marker set includes the Windows-shaped loader failures alongside the POSIX ones. torchvision 0.16 through 0.18 were also read rather than run.

Related: unslothai/unsloth-zoo#1012 makes unsloth_zoo's own handler report the same breakage instead of re-raising the bare operator error.

@danielhanchen

Copy link
Copy Markdown
Member Author

Review notes: what this does, and what it cannot break

Before the PR

Running Gemma4_(E2B)_GRPO on a Colab T4, import unsloth stopped six frames below anything the user wrote:

transformers/image_utils.py in <module>
     59     if is_torchvision_available():
---> 60         from torchvision.transforms import InterpolationMode

torchvision/_meta_registrations.py in <module>
--> 163 @torch.library.register_fake("torchvision::nms")

RuntimeError: operator torchvision::nms does not exist

That notebook's T4 branch installs vllm==0.9.2 beside Colab's torch, and the torchvision that comes out of it reports a version the compatibility table accepts while its compiled ops were built against a torch that is no longer present. torchvision_compatibility_check compares importlib.metadata versions, and metadata cannot see an ABI break, so the compatible branch was the blind spot. The vLLM half of the identical breakage was already handled in that same run (Detected broken vLLM binary extension; disabling vLLM imports); only torchvision fell through.

After the PR

On the compatible branch only, torchvision and torchvision.ops are imported, and if that fails with the ABI signature the error is re-raised as an ImportError that names the broken package and how to repair it:

Unsloth: torchvision==0.26.0 claims to match torch==2.11.0, but its compiled operators do not
load (RuntimeError: operator torchvision::nms does not exist). Reinstall it with
`pip install --force-reinstall --no-deps --no-cache-dir "torchvision==0.26.*"`.
Set UNSLOTH_SKIP_TORCHVISION_CHECK=1 to skip this check.

Real or theoretical

Real, and reproduced from a notebook run rather than reasoned about. The failing import is the one transformers performs itself from image_utils the moment anything touches processing_utils, which is exactly the route by which the error was already reaching users, so the probe adds no import that was not going to happen.

If merged, what could it break

The risk here is not the detection, it is the two ways a probe like this can misfire: claiming someone else's error, and printing a repair command that makes things worse. I drove the real functions over every failure shape, 14 cases plus the command checks, all as expected.

Correctly identified as a torchvision ABI break: the reported torchvision::nms, torchvision::roi_align, the half-overwritten torchvision.io.video and torchvision.io._video cases, an undefined symbol naming libc10 or libtorch_cpu, a cannot open shared object file naming torchvision/_C.so, and a chained exception whose generic outer message hides an nms cause.

Deliberately not claimed, so an unrelated failure still imports unsloth exactly as before: a missing PIL, a missing libcudart.so.12, a bare undefined symbol: mysteryfn with nothing torch-shaped in it, and a numpy ABI complaint. A chained exception whose cause is also unrelated is left alone too. This matters because the probe imports torchvision where nothing used to, so a box whose torchvision cannot load for its own reasons must not be handed a "reinstall torchvision".

The repair command is pinned and --no-deps, and both are load-bearing. Every torchvision wheel requires an exact torch==X.Y.Z, so an unpinned pip install --upgrade --force-reinstall torchvision resolves the newest torchvision and then replaces the user's torch to satisfy it, which on a Colab or Kaggle image is the pinned torch every other wheel was built against, vLLM included. My run asserts the emitted command is version-pinned, carries --no-deps, and contains no bare --upgrade. The pin also covers the case where the version gate passed on its lower bound, so the companion release is reinstalled rather than the newest one; with no table entry it falls back to an unpinned but still --no-deps command.

Otherwise nothing changes. UNSLOTH_SKIP_TORCHVISION_CHECK=1 still short-circuits the whole function ahead of the probe, the mismatch branch that already raised a clear ImportError is untouched, and no public symbol or default moves, so older unsloth_zoo and existing Unsloth Studio installs behave identically.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

The 0.<minor>.* range under-specifies the pair. torchvision 0.22.0 requires
torch 2.7.0 and 0.22.1 requires torch 2.7.1, both confirmed against PyPI, so on
a 2.7.0 host pip picks 0.22.1 and --no-deps then keeps the torch that does not
match it. Following the advertised repair rebuilt the mismatch it repairs.

torch's own patch is already in scope, and the two move together, so carry it
into the companion and name one wheel.
@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed and fixed in 57cafbd05. I checked the pairing against PyPI rather than against our own table:

torchvision 0.22.0 requires: ['torch==2.7.0']
torchvision 0.22.1 requires: ['torch==2.7.1']

So the reading is exactly right. On a torch 2.7.0 host, torchvision==0.22.* resolves 0.22.1, and --no-deps then keeps the 2.7.0 that 0.22.1 does not pair with. Following the command we print would rebuild the ABI mismatch the command exists to repair, which is the worst possible failure for a message whose whole job is to tell someone what to type.

The full torch version was already in scope as torch_release, and the patch numbers move together, so the companion now carries torch's own patch and the command names one wheel:

host before after
torch 2.7.0 torchvision==0.22.* torchvision==0.22.0
torch 2.7.1 torchvision==0.22.* torchvision==0.22.1
torch 2.9.1 torchvision==0.24.* torchvision==0.24.1

Two paths deliberately keep their old behaviour. A torch version with no patch component still yields a two-number pair, so the range stands rather than inventing a .0. An unrecognised torch still gets the bare torchvision, since there is nothing to derive from.

Three tests added. The first is discriminating: restoring the wildcard turns test_the_repair_names_the_wheel_for_this_torch_patch red and leaves the other 20 green. The third asserts the pairing against live PyPI metadata rather than against the table it is supposed to justify, and skips rather than fails when the network is unavailable, so it cannot become a flake in CI.

21 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: da7b65b13e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread unsloth/import_fixes.py
Comment on lines +1123 to +1124
if len(torch_release) >= 3:
required = (required[0], required[1], torch_release[2])

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 Use a companion patch map for torch 2.0 wheels

On torch 2.0.x environments this fallback path now derives the repair pin from the torch patch, but the pip wheel matrix is shifted for that release line: torch 2.0.0 pairs with torchvision 0.15.1 and torch 2.0.1 pairs with torchvision 0.15.2. If the new probe catches a broken torchvision there, the suggested --no-deps reinstall will install 0.15.0/0.15.1 instead, preserving the installed torch and leaving or recreating the ABI mismatch the command is meant to fix.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The torch 2.0 matrix is right, but the branch is unreachable, so this is not a bug to fix.

Confirmed from live PyPI metadata: torchvision 0.15.1 requires torch (==2.0.0) and 0.15.2 requires torch (==2.0.1), so the 2.0 line is indeed offset by one and is the only line that is. Patch-for-patch alignment holds for every release from 0.16.x/torch 2.1 through 0.28.x/torch 2.13.

It cannot be reached, though. torchvision_compatibility_check runs only from _gpu_init.py during import unsloth, and that import needs unsloth_zoo, which this repo pins at unsloth_zoo>=2026.8.5 (pyproject.toml:119,164,652) and which requires torch<2.13.0,>=2.4.0. unsloth/models/_utils.py:3419 enforces the same 2.4 floor directly. Getting to a torch 2.0 host means a --no-deps install on a torch four minor releases below the supported floor.

Adding a (2, 0): (0, 15) special case would be dead code for a version Unsloth refuses to run on, so I would rather not carry it.

Comment on lines +217 to +219
requirements = metadata["info"].get("requires_dist") or []
assert (
torch_requirement in requirements

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 Parse Requires-Dist instead of matching raw strings

When this network-backed test actually reaches PyPI, requires_dist entries are PEP 508 requirement strings such as torch (==2.7.0), not the raw torch==2.7.0 values placed in expected. That makes the assertion fail even though the metadata is correct; parse each entry with packaging.requirements.Requirement or compare against the PEP 508 form.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not correct for the versions this test asserts. Checked against live PyPI rather than from memory:

https://pypi.org/pypi/torchvision/0.22.0/json -> requires_dist: ['torch==2.7.0']
https://pypi.org/pypi/torchvision/0.22.1/json -> requires_dist: ['torch==2.7.1']

Bare, not parenthesised, so the raw string comparison matches and the test passes. It is not skipped either: the file runs 22 passed, 0 skipped with the network up, and the only skip in it is the pypi.org unreachable guard.

The parenthesised form is real, but it comes from older setuptools metadata and stops at torchvision 0.17.1 (torch (==2.2.1)); 0.17.2 onward is bare (torch==2.2.2). Every version this test touches is on the bare side, so parsing with packaging.requirements.Requirement would add a dependency and a code path without changing any outcome.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 71a21a278a

ℹ️ 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".

Comment thread unsloth/import_fixes.py Outdated
spec = f"torchvision=={required[0]}.{required[1]}.*"
local = _torch_local_tag(torch_version_raw)
index = ""
if local and not local.lower().startswith("cu") and _TORCH_BACKEND_INDEX.fullmatch(local):

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 Preserve the CUDA wheel family in repair commands

On supported CUDA installs whose family differs from PyPI's default build—such as the repository's torch==2.4.0+cu118 configurations—this condition explicitly omits the PyTorch index for every +cu... tag. As pip install --help documents, --index-url selects the package repository, so pinning only torchvision==0.19.0 does not select its +cu118 wheel; the command instead installs the PyPI CUDA build while --no-deps retains the cu118 torch, potentially leaving _C unable to load and reproducing the mismatch. Use https://download.pytorch.org/whl/cu118 (and likewise the detected CUDA family) just as for the other backend tags.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct. Fixed in d21bf6b63: the CUDA carve-out is gone and every recognised backend tag now gets its own index.

I left cu tags out on the theory that PyPI already ships a CUDA build and the sonames match across cu12x. That does not cover cu11, and this repo ships cu118only, cu118onlytorch211, cu118onlytorch212 and the rest (pyproject.toml:176 onward), so a cu118 host is a supported shape here. PyPI's wheel links libcudart.so.12, which a cu118 torch does not provide.

Checked that each index actually carries the wheel the table would name, by listing the real file indexes:

whl/cu118/torchvision   18 versions, 0.15.0 .. 0.22.1   (0.19.0 present, the torch 2.4.0 companion)
whl/cu126/torchvision   11 versions, 0.21.0 .. 0.28.0
whl/cu128/torchvision    7 versions, 0.22.0 .. 0.26.0

A bare torchvision==0.19.0 on that index resolves 0.19.0+cu118, since PEP 440 lets a specifier without a local segment match a local version. Where an index does not carry the version, pip fails loudly with no matching distribution, which is the right outcome rather than installing the wrong wheel silently.

A torch with no local tag keeps PyPI, which is the build that pairs with it. Test extended to cu118, cu126 and cu128.

Comment thread unsloth/import_fixes.py Outdated
# `torch 2.9.1+rocm7.2.0.lw.git7e1940d4` beside a `repo.radeon.com` torchvision),
# a source build, and any nightly, whose stable-looking companion version is
# synthesised from the release numbers alone.
_TORCH_PRERELEASE_TAGS = (".dev", "a0", "b0", "rc", "alpha", "beta", "nightly")

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 Recognize every prerelease before suggesting stable wheels

For valid PEP 440 prereleases other than the literal first alpha or beta, such as torch==2.11.0a1+cu128 or 2.11.0b2+cu128, none of these substrings match and the CUDA local tag is classified as public. If the new probe then detects an ABI error, it recommends installing the stable torchvision==0.26.0 beside the prerelease torch, which has no guaranteed matching stable binary and can preserve the failure. Parse the version and use Version(...).is_prerelease rather than matching only a0 and b0.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct. Fixed in d21bf6b63.

The substring list came from the existing _pre_tags further down this file, and it does miss everything past the first alpha or beta. packaging.version.Version is already imported here as TrueVersion, so the check now parses instead of matching:

2.11.0a1+cu128          is_prerelease=True    (no 'a0' substring)
2.11.0b2+cu128          is_prerelease=True    (no 'b0' substring)
2.7.0rc1                is_prerelease=True
2.12.0.dev20260801+cpu  is_prerelease=True
2.7.1 / 2.7.0+cu128     is_prerelease=False
2.9.1+rocm7.2.0.lw.git7e1940d4  is_prerelease=False   (still caught, by the local tag)

An unparseable version now also takes the no-public-wheel path rather than being handed a pin. Test cases added for a1, b2 and rc1; red against the old substring list.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: d21bf6b638

ℹ️ 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".

@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: b66a90adae

ℹ️ 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".

Comment thread unsloth/import_fixes.py
Comment on lines +1031 to +1033
if not torch_version_raw or "+" not in torch_version_raw:
return ""
return torch_version_raw.split("+", 1)[1]

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 Preserve the backend for Conda torch builds

The remaining fresh case after the CUDA-index fix is the repository's conda extra: Conda records CUDA/ROCm selection in its build string, while importlib.metadata.version("torch") commonly returns only a public version such as 2.5.1. In that environment this helper returns an empty tag, so the repair command omits the PyTorch backend index and installs PyPI's torchvision while --no-deps retains the Conda torch, potentially recreating the binary mismatch. Derive the backend from torch's runtime metadata (for example CUDA/HIP/XPU state), or avoid advertising a pip command when distribution metadata does not identify the wheel family.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and it is the same class as the CUDA-index item. Fixed in 9dc515f74.

Checked the conda side rather than assuming it: conda encodes the backend in the build string (py3.12_cuda12.4_cudnn9_0) and leaves the version plain, so importlib.metadata.version('torch') returns 2.5.1 and _torch_local_tag is empty. An empty tag is also the normal PyPI case, so it cannot simply stop meaning PyPI, and torch.version.cuda does not separate them either: a conda CUDA build and a PyPI build both report one.

What does separate them is conda's own ledger. Per the conda package spec a prefix carries one conda-meta/<name>-<version>-<build>.json per installed package, and version may not contain -, so pytorch-<version>- is an exact prefix match. When torch is recorded there the message drops the pip command and falls back to "Reinstall the torchvision built for torch==X, from wherever that torch came from". Matching on the exact version keeps pytorch-lightning-*.json from answering for torch, and a pip torch inside a conda prefix is unaffected. The check runs only while building the error message.

Regression test test_a_conda_torch_is_not_sent_to_pypis_torchvision in tests/test_broken_torchvision_probe.py: fails on the parent commit with the PyPI pip install --force-reinstall --no-deps line, passes after. Full file 24 passed.

danielhanchen and others added 4 commits August 9, 2026 08:54
conda records the backend in the build string and leaves the version
plain, so a conda torch reaches the local-tag check looking exactly like
a PyPI one and gets the unqualified pin. --no-deps then keeps a conda
CPU or ROCm torch beside PyPI's CUDA-only torchvision, rebuilding the
mismatch the command exists to clear. Read conda's own ledger,
conda-meta/<name>-<version>-<build>.json, and fall back to the advice
that names no wheel.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: fa456a7451

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 2536edd into unslothai:main Aug 9, 2026
46 of 50 checks passed
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