Skip to content

Do not let a CUDA-mismatched torchaudio take the whole import with it - #8496

Merged
danielhanchen merged 6 commits into
mainfrom
fix/torchaudio-cuda-mismatch
Aug 13, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
fix/torchaudio-cuda-mismatch

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

A text model should not die on an audio library it never asked for.

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. PyTorch has CUDA version 12.8 whereas TorchAudio has
CUDA version 12.6.

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 never
reached anything audio-shaped.

The repair

The same one disable_torchcodec_if_broken already makes, for the same
structural reason: the package resolves, find_spec reports it present, and
the failure is at native init rather than at resolution -- so every downstream
except ImportError handler is bypassed. Seating the absence sentinel gives
them 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_out parses the function and asserts
the 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 RuntimeError is re-raised rather than swallowed, so a real error
does 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, through
temporary_patches -> gemma.py -> utils.py ->
transformers.processing_utils -> transformers.audio_utils. So the guard ran
too 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 compares
source 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=error does not abort the repair, the check is not
patched out, the guard runs before the torchcodec repair, and it runs before
import unsloth_zoo.

import unsloth is clean, and the 60 tests in this file plus
test_broken_tf_does_not_break_import.py and the heterogeneous-config file
pass together.

@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: 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".

Comment thread unsloth/import_fixes.py
except ImportError:
return
except (RuntimeError, OSError) as exc:
if "different CUDA versions" not in str(exc) and "torchaudio" not in str(exc).lower():

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/import_fixes.py
"""
try:
import importlib.util
if importlib.util.find_spec("torchaudio") is None:

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/import_fixes.py Outdated
Comment on lines +2160 to +2164
try:
is_avail.cache_clear()
except AttributeError:
pass
tf_import_utils.is_torchaudio_available = lambda: False

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 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 👍 / 👎.

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.

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.

Comment on lines +40 to +44
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)

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 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 👍 / 👎.

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.

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.

@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: 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".

Comment thread README.md Outdated
* 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**.

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 the 70% VRAM claims

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 👍 / 👎.

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.

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.

danielhanchen and others added 2 commits August 12, 2026 11:51
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.
@danielhanchen
danielhanchen force-pushed the fix/torchaudio-cuda-mismatch branch from 55d3183 to 446e83d Compare August 12, 2026 11:51
pre-commit-ci Bot and others added 4 commits August 12, 2026 11:52
…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.
@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: 812698d976

ℹ️ 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 b86944e into main Aug 13, 2026
60 of 67 checks passed
@danielhanchen
danielhanchen deleted the fix/torchaudio-cuda-mismatch branch August 13, 2026 12:12
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