Repository navigation
Do not let a CUDA-mismatched torchaudio take the whole import with it - #8496
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: df9c1a72b8
ℹ️ 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".
| except ImportError: | ||
| return | ||
| except (RuntimeError, OSError) as exc: | ||
| if "different CUDA versions" not in str(exc) and "torchaudio" not in str(exc).lower(): |
There was a problem hiding this comment.
Restrict disabling to the CUDA-mismatch signature
When torchaudio raises an unrelated RuntimeError or OSError whose message merely mentions the package—such as an undefined symbol in libtorchaudio.so—this condition treats it as a CUDA-version mismatch, suppresses the exception, and globally disables torchaudio. This contradicts the function's stated behavior of re-raising unrelated failures; require the specific mismatch signature rather than accepting any error containing torchaudio.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Left as is. The condition is deliberately wider than the CUDA-mismatch string: an OSError: libtorchaudio.so: undefined symbol: ... is the same class of broken install, and narrowing the match would put that case back to killing import unsloth, which is what this PR removes. disable_torchcodec_if_broken disables on any exception for the same reason.
| """ | ||
| try: | ||
| import importlib.util | ||
| if importlib.util.find_spec("torchaudio") is None: |
There was a problem hiding this comment.
Handle preloaded torchaudio modules without a spec
When an application or test preloads a torchaudio proxy/stub in sys.modules without assigning __spec__, find_spec("torchaudio") raises ValueError: torchaudio.__spec__ is None. Because this new unconditional import-time probe does not handle that exception, import unsloth now fails even though importing the already-loaded module itself would succeed; check sys.modules first or handle this find_spec case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Left as is. find_spec does raise ValueError on a sys.modules entry whose __spec__ is None, but import_fixes.py already makes about thirty import-time find_spec calls with the same exposure, including disable_torchcodec_if_broken right above this one. It needs a hand-built types.ModuleType stub with no __spec__; a MagicMock carries one, and the None sentinel this function seats returns None from find_spec.
| try: | ||
| is_avail.cache_clear() | ||
| except AttributeError: | ||
| pass | ||
| tf_import_utils.is_torchaudio_available = lambda: False |
There was a problem hiding this comment.
Invalidate the cached speech-availability wrapper
When Transformers 5's is_speech_available() has been evaluated before this repair, its @lru_cache retains True even after the underlying torchaudio checker is cleared and replaced here. Consumers guarded by the composite speech backend then continue into torchaudio-dependent code after the package has been replaced with a None sentinel, producing a raw import failure instead of taking their unavailable-backend path; clear is_speech_available alongside is_torchaudio_available.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 889f868. Confirmed against transformers main: is_speech_available is separately @lru_cached there and BACKENDS_MAPPING binds it at import time, so clearing only is_torchaudio_available left speech answering True. Both caches are cleared now, with test_the_speech_backend_goes_down_with_torchaudio standing up the 5.x shape explicitly since the 4.x shape cannot fail.
| saved = {k: v for k, v in sys.modules.items() if k.startswith("torchaudio")} | ||
| yield module | ||
| for key in [k for k in sys.modules if k.startswith("torchaudio")]: | ||
| sys.modules.pop(key, None) | ||
| sys.modules.update(saved) |
There was a problem hiding this comment.
Restore availability flags after each test
When Transformers or Datasets is installed, either mismatch test permanently replaces its torchaudio availability checker and sets the package-level availability flags to false, but this fixture restores only sys.modules. Those mutations therefore leak into every later test in the pytest process, making audio-related results order-dependent even though the original torchaudio modules are restored; snapshot and restore the patched availability attributes during fixture teardown.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 889f868. The repair assigns onto the live transformers and datasets modules rather than through monkeypatch, so those flags outlived the fixture. It now snapshots and restores the four patch sites.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 55d3183a9f
ℹ️ 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".
| * The opt-in **MCP control endpoint** lets AI clients manage models, training, recipes and exports. | ||
| ### Training | ||
| * Train and RL **500+ models** up to **2x faster** with **70% less VRAM**; MoE up to **12x faster**. | ||
| * Train and RL **500+ models** up to **2x faster** with **701% less VRAM**; MoE up to **12x faster**. |
There was a problem hiding this comment.
The release-version replacement also changed every existing 70% less claim to 701% less, including the model table at lines 218–225. A reduction over 100% is mathematically impossible and publishes materially false performance claims; restore these percentages to 70% while retaining 0.1.701 only in the release URLs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed: the README edit was dropped from the branch entirely, so the diff is now only the guard, the _gpu_init wiring and its tests.
torchaudio._extension.utils._check_cuda_version compares the CUDA version torchaudio was BUILT against with torch's and raises on any difference: RuntimeError: Detected that PyTorch and TorchAudio were compiled with different CUDA versions. That runs at extension init, so it takes down the import for every caller, including ones that only wanted CPU-side audio I/O and ones that never asked for torchaudio at all. Measured on a Kaggle 2xT4 session running Kaggle-Muse_Glimmer_(30B)-GRPO, a text model, which died at cell 4 having never reached anything audio-shaped. Same repair as disable_torchcodec_if_broken, for the same structural reason: the package resolves, find_spec says so, and the failure is at native init, so every downstream except-ImportError handler is bypassed. Seating the absence sentinel gives them their chance back, and flips the transformers and datasets availability flags the way the torchcodec repair already does. It deliberately does NOT patch out _check_cuda_version. That check is right; torchaudio's CUDA ops really are unusable against a different runtime, and silencing it in place would leave them reachable and wrong. A test parses the function and asserts the name appears only in its docstring, where it is explaining why it is not touched. An unrelated RuntimeError is re-raised rather than swallowed, or a real error would end up hidden behind a message about CUDA versions.
The guard was correct and never ran in time. It was invoked in the late import-fix block at line 250, and `import unsloth_zoo` is at line 155; unsloth_zoo's temporary_patches reach transformers.processing_utils, which imports transformers.audio_utils, which imports torchaudio. So a torchaudio that raises at extension init took the whole unsloth import down 95 lines before the repair could neutralise it. Kaggle-Muse_Glimmer_(30B)-GRPO kept dying at cell 4 with the fix present and pinned. Move the call up beside torchvision_compatibility_check, ahead of the unsloth_zoo import. An existing test asserted the torchcodec repair ran FIRST, which is the placement that made this useless, so it was encoding the bug. torchcodec is reached lazily and torchaudio eagerly, so the order has to be the other way round. Corrected, and a second test asserts the call precedes the unsloth_zoo import outright rather than being merely present.
55d3183 to
446e83d
Compare
…ing the flags transformers exposes torchaudio twice: as `torchaudio` and as the composite `speech` backend, which is nothing but `is_torchaudio_available()`. On 4.x both read one module global, so setting that flag covered them. On 5.x each is separately lru_cached, so a `speech` answer computed before the repair survives it and `requires_backends(..., "speech")` waves callers into a torchaudio that is now a None sentinel. Clear both caches. The tests flipped those flags on the real transformers and datasets modules and the fixture restored only sys.modules, so `is_torchaudio_available = lambda: False` leaked into every later test in the process. The fixture now snapshots and restores the patch sites too.
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
A text model should not die on an audio library it never asked for.
torchaudio._extension.utils._check_cuda_versioncompares the CUDA versiontorchaudio was built against with torch's, and raises on any difference:
That runs at extension init, so it takes down the whole import -- for callers
that only wanted CPU-side audio I/O, and for callers that never asked for
torchaudio at all and merely imported something that does.
Found on a real Kaggle session with two Tesla T4s running
Kaggle-Muse_Glimmer_(30B)-GRPO, a text model. It died at cell 4 having neverreached anything audio-shaped.
The repair
The same one
disable_torchcodec_if_brokenalready makes, for the samestructural reason: the package resolves,
find_specreports it present, andthe failure is at native init rather than at resolution -- so every downstream
except ImportErrorhandler is bypassed. Seating the absence sentinel givesthem their chance back, and the transformers and datasets availability flags
get flipped the way the torchcodec repair already flips theirs.
What it deliberately does not do
It does not patch out
_check_cuda_version. That check is correct:torchaudio's CUDA ops really are unusable against a different runtime, and
silencing it in place would leave them reachable and wrong. Making the package
absent is the honest version of the same repair, and it is loud -- the warning
names the original error and says the package has been disabled for the
process.
test_the_check_itself_is_never_patched_outparses the function and assertsthe name appears only in its docstring, where it is explaining why it is not
touched. A future edit reaching for the shortcut fails there.
An unrelated
RuntimeErroris re-raised rather than swallowed, so a real errordoes not end up hidden behind a message about CUDA versions.
Where it has to run
The guard is useless if anything has already imported torchaudio by the time it
fires. It was originally seated after the torchcodec repair, which is after
import unsloth_zoo-- and unsloth_zoo reaches torchaudio on its own, throughtemporary_patches->gemma.py->utils.py->transformers.processing_utils->transformers.audio_utils. So the guard rantoo late to guard anything on the very path that found the bug.
It now runs in the early import block, ahead of
import unsloth_zoo.An existing test asserted the old order and so was encoding the bug; it is
replaced by one that asserts the guard runs before the torchcodec repair, plus
test_the_guard_runs_before_anything_can_import_torchaudio, which comparessource line numbers and fails if the call ever drifts back below
import unsloth_zoo.Tests
tests/test_torchaudio_cuda_mismatch.py, 8 tests: mismatched is made absent,healthy is left untouched, absent is not invented, unrelated failures
propagate,
PYTHONWARNINGS=errordoes not abort the repair, the check is notpatched out, the guard runs before the torchcodec repair, and it runs before
import unsloth_zoo.import unslothis clean, and the 60 tests in this file plustest_broken_tf_does_not_break_import.pyand the heterogeneous-config filepass together.