Skip to content

fix(amd:audio): decode audio through PyAV when torchcodec installs but cannot load - #8642

Merged
danielhanchen merged 50 commits into
unslothai:mainfrom
LeoBorcherding:fix/report-torchcodec-cannot-load
Sep 16, 2026
Merged

danielhanchen merged 50 commits into
unslothai:mainfrom
LeoBorcherding:fix/report-torchcodec-cannot-load

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

The gap

On a Windows host, audio training fails with:

To support decoding audio data, please install 'torchcodec'.

torchcodec is installed. importlib.metadata.version("torchcodec") returns 0.10.0. The message names a package that is already there.

Why

pyproject.toml declares torchcodec for linux and win32 on x86_64/AMD64, and scripts/notebook_validator.py enforces a torch/torchcodec compatibility matrix for it, citing unslothai/notebooks#261. Both are about versions. The wheel is Python-side only: at import it dlopens FFmpeg's avcodec/avutil.

Windows ships neither, and pip has no FFmpeg wheel to depend on, so the package installs cleanly, reports a version, satisfies the matrix, and fails at import:

RuntimeError: Could not load libtorchcodec. Likely causes:
  1. FFmpeg is not properly installed in your environment...
     On Windows, ensure you've installed the "full-shared" version which ships DLLs.

datasets 4.x decodes audio only through torchcodec, and its availability check reports an unloadable install the same way it reports a missing one. Nothing between setup finishing and that error says otherwise.

The change

Both installers probe the import once python deps are in, and report what they found, in the same shape as the existing whisper.cpp steps (what is wrong, what to do, what still works):

torchcodec     installed but cannot load its FFmpeg libraries; audio datasets decode
               through soundfile instead, which covers wav/flac/mp3/ogg but not
               m4a/aac/webm; install an FFmpeg full-shared build to decode those

The coverage claim is measured, not assumed. soundfile 0.14 bundles libsndfile 1.2.2, whose formats include WAV, FLAC, MP3, OGG and AIFF, and exclude m4a/aac/webm. So this is a real limitation on a narrow set of containers, not audio being broken, and the message says so.

An absent torchcodec stays silent: that says nothing about FFmpeg, and utils/datasets/audio_decode.py still provides the soundfile path. A probe that cannot run is silent for the same reason.

Reporting only, deliberately

Vendoring an FFmpeg full-shared build would mean redistributing an LGPL/GPL binary per arch, with its own update and CVE path, to reach containers most speech datasets do not use. That is a bigger decision than this gap needs, and it can be made later without undoing this. The tradeoff: m4a/webm datasets still fail, but with an error that finally names FFmpeg.

Tests

Seven, four of which fail without the change, across both installers via parametrize. They cover the three-way probe outcome (ok / absent / unloadable, exercised by forcing each import result), that the reported line names FFmpeg, soundfile and the real format coverage, that the probe sits behind the skip-python-deps guard, and that setup.sh still parses under bash -n.

The heredoc test feeds the script to bash as bytes. A text pipe on Windows re-encodes the box characters setup.sh draws its rules with, and translates every \n back to \r\n, which bash rejects as a syntax error the real file does not have. I hit both in that order.

7 passed  (this suite)

test_setup_llama_cpp_backend.py has 20 failures here and the identical 20 on a clean main checkout; they shell out to setup.sh under Windows bash and are untouched by this change.

Related

The "Not addressed" note in #8436 pointed at exactly this. That PR made the soundfile fallback reach the training worker; this one makes the installer say when the fallback is what you are running on. No file overlap with #8436 or #8625.

Update: decode through PyAV instead of only reporting

Commits 881794c through 82c1171 turn the report into a fix, and drop the installer changes entirely. When torchcodec is installed but cannot load, audio rows decode through soundfile first and PyAV second, so m4a, aac and webm work without an FFmpeg full-shared build. The fallback lives in two places: Studio's utils/datasets/audio_decode.py, and unsloth/import_fixes.py, where disable_torchcodec_if_broken installs the same decoder on datasets.features.audio.Audio so any import unsloth script gets it. It only runs on datasets 4.x with a torchcodec that fails to load, honours Audio(stream_index=...) (an absolute index, or the default track through streams.best when unset, as torchcodec does), and leaves a working torchcodec alone. The dataset preview now summarises decoded audio cells whether they arrive as lists or numpy arrays. Every audio-torch2xx extra lists soundfile and PyAV beside torchcodec, the Studio PyAV floor is 12.3 (older wheels need numpy<2), resampling falls through to PyAV when librosa is absent or cannot import, and the disabler treats any exception from the torchcodec import as a broken install, matching the installer probe. studio/setup.sh and studio/setup.ps1 are untouched: the fix needs no installer step. The one report a user gets is a warning at import unsloth that names why torchcodec did not load (FFmpeg missing from the loader path, FFmpeg present so the cause is elsewhere, or a failure that never reached libtorchcodec) and that audio datasets now decode through soundfile and PyAV. Tests: studio/backend/tests/test_audio_dataset_decode.py gained PyAV cases and tests/test_datasets_audio_fallback.py covers the library patch, including an AST check that keeps both decoders identical.

Studio evidence: same host, same broken torchcodec, before and after

Two isolated Studio installs (merge base 1e07231 and head bcfe23e) under separate UNSLOTH_STUDIO_HOMEs, each with torchcodec==0.9.0 against torch 2.11 so from torchcodec.decoders import AudioDecoder raises the "Could not load libtorchcodec" error. A three-row parquet with an m4a Audio column is uploaded through the dataset picker, then opened with View dataset.

Dataset preview before and after

Before: /api/hub/datasets/check-format answers 500 with Format not recognised from soundfile and the dialog shows its error state. After: three rows, is_audio true, every cell <audio, 46080 samples @ 22050 Hz, 2.1s>.

Recording of the before flow:

Before

Recording of the after flow:

After

pyproject declares torchcodec on linux and win32, and notebook_validator enforces
a torch/torchcodec compatibility matrix for it, but its wheel is Python-side only:
at import it dlopens FFmpeg's avcodec/avutil. Windows ships neither, and pip has
no FFmpeg wheel to depend on, so the package installs, reports a version, passes
the matrix, and then fails at import.

datasets 4.x decodes audio only through torchcodec and reports that failure as
"To support decoding audio data, please install 'torchcodec'" -- naming a package
that is already installed, on a host where the problem is FFmpeg. Nothing between
the install and that message says otherwise.

Both installers now probe the import once deps are in and say what they found. The
message names FFmpeg, says decoding falls back to soundfile, and gives that
fallback's real coverage (wav/flac/mp3/ogg via libsndfile, not m4a/aac/webm), so
it reads as a limitation rather than as audio being broken. An absent torchcodec
stays silent: that says nothing about FFmpeg, and the soundfile path still stands.

Reporting only. Vendoring an FFmpeg full-shared build would mean redistributing an
LGPL/GPL binary per arch, with its own update path, to reach formats most speech
datasets do not use. That is a bigger decision than this gap needs.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 4 commits August 13, 2026 15:02
- setup.sh read _SKIP_PYTHON_DEPS outside the base install that assigns it, so
  UNSLOTH_STUDIO_LLAMA_ONLY=1 aborted the run under `set -u`. Gate on _LLAMA_ONLY
  as well: that path installs no Python deps, so there is nothing new to report.
  The read is defaulted too, so a later edit cannot reintroduce the unbound case.

- Importing torchcodec imports torch, so bound both probes the way this repo
  already bounds torch imports: `timeout 60` in setup.sh, next to the XPU probe
  that does the same, and Invoke-BoundedPythonProbe in setup.ps1.

- Split the unloadable state into ffmpeg and broken. A damaged wheel or a
  torch/torchcodec ABI mismatch also raises at import, and answering that with
  "install an FFmpeg build" sends the reader at the wrong thing. The split is
  between torchcodec's own loader and an unrelated import error; it does not
  claim to pick between the causes that loader lists, which it prints together.

- The missing-package test accepted all three states, so it could never fail.
  It now forces ModuleNotFoundError and requires absent.

The behavioural tests read the probe out of setup.sh rather than carrying a copy
of it, so they exercise what actually ships, and a new test holds the two
installers to the same probe body.
@LeoBorcherding LeoBorcherding changed the title Studio: report a torchcodec that installed but cannot load fix(amd:audio): report a torchcodec that installed but cannot load Aug 13, 2026
@LeoBorcherding LeoBorcherding changed the title fix(amd:audio): report a torchcodec that installed but cannot load fix(amd:audio): report a torchcodec that installed but cannot load on amd Aug 13, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

LeoBorcherding and others added 5 commits August 13, 2026 19:12
install.ps1 runs setup.ps1 with SKIP_STUDIO_BASE=1, which skips the base install
the other bare-`python` probes sit in, and nothing puts the venv on PATH. So the
torchcodec probe read the system interpreter, found no torchcodec, and printed
nothing on the path every Windows install actually takes.
Invoke-BoundedPythonProbe builds -c <body> by wrapping the body in double quotes,
so the four in the comment closed that argument early. Windows split the rest into
stray argv entries and python ran the truncated head, which still parses: the
except-Exception branch lost its print, so the probe exited 0 with no output and
the report never fired on Windows.

The comment says the same thing without quoting it, and the pwsh test runs the
shipped helper against the shipped body with an unloadable torchcodec on
PYTHONPATH -- the one case a truncated body answers nothing at all.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

LeoBorcherding and others added 3 commits August 14, 2026 00:39
Three findings from the review on 17ed9e7:

The shell fallback for hosts with no coreutils timeout, stock macOS above all,
ran the import with no deadline. The body now carries signal.alarm(60) like the
XPU probe in this same script; the default action ends the process, which reads
as the silent case. alarm is POSIX-only, and Windows is bounded by the helper.

ModuleNotFoundError from a transitive module reported an installed torchcodec as
absent, so a damaged install got no warning. Only a missing torchcodec itself is
absent now, read off the exception name.

The state was compared against all of stdout, so any banner ahead of the answer
matched no arm and dropped the report. Both installers now read a TORCHCODEC=
line, sed in setup.sh and a line-anchored match in setup.ps1.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A damaged wheel that fails on one of torchcodec's own submodules raises
ModuleNotFoundError naming torchcodec.<sub>, and folding that back to the
top-level name reported an installed-but-broken package as absent, which is
silent. An absent package always names itself exactly from import torchcodec,
so the exact comparison loses nothing and treats torchcodec.* as broken.

The test asserting the submodule form was absent was wrong; it now expects
broken.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

End-to-end check on the AMD box this came from: RX 9060 XT (gfx1200), ROCm 7.1, Windows 11.

torchcodec is installed and cannot load. Importing it raises the libtorchcodec loader error, which is the exact state this PR exists to surface, and before it the installer said nothing at all. Now it does:

torchcodec     installed but cannot load its FFmpeg libraries; audio datasets decode
               through soundfile instead, which covers wav/flac/mp3/ogg but not
               m4a/aac/webm; install an FFmpeg full-shared build to decode those

The second half of that message holds up too. With torchcodec unable to load, an audio LoRA finetune of unsloth/orpheus-3b-0.1-ft still ran to completion on the soundfile path: soundfile 0.14.0, libsndfile 1.2.2, datasets 4.3.0. 30/30 steps, final loss 4.4073, avg 4.74, grad norm 0.479.

So the warning is accurate in both directions: it names the real dependency, and it does not overstate the damage, since the formats libsndfile covers keep working.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Orpheus training successfully and exporting (no image for export but exported with success on windows with RX 9060xt
image

image

chatgpt-codex-connector[bot]

This comment was marked as resolved.

The loader message names a missing FFmpeg, a torch mismatch and another native
dependency in one breath, so matching libtorchcodec in the traceback sent every
one of them to install FFmpeg. Documenting that limit in a comment was not
enough: the probe now asks the system instead, through find_library plus a PATH
walk for the versioned avutil-*.dll names Windows uses and find_library cannot
glob.

No FFmpeg on the loader path keeps the ffmpeg state and its advice. FFmpeg
present with the loader still failing is a new native state, which names the two
remaining causes without picking between them, since nothing available here can.

The tests pin the FFmpeg answer in both directions, so a runner that happens to
have it installed cannot flip the states this rests on.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 62d987d2ad

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

Copy link
Copy Markdown
Member

Final state at 62d987d, after four Codex rounds (stream_index, PyAV declared in the audio extras and the Studio floor raised to 12.3, any torchcodec import failure treated as broken, librosa import guarded):

  • Codex: no major issues on 62d987d.
  • AMD gfx1151 Linux (ROCm): 59 passed, 1 skipped, base versus head NO_REGRESSION.
  • AMD gfx1151 Windows (no Docker): 47 passed, 3 skipped, NO_REGRESSION. The library test skips there because the Studio venv has no torch; the Studio audio tests run.
  • AMD Linux shell installer suites: 67 run at base and head, 0 failed.
  • Hosted Linux, macOS 15 (Apple Silicon) and Windows: all green with av, soundfile, librosa and datasets installed so the PyAV tests execute rather than skip.
  • Studio before and after on the same broken torchcodec, recordings in the description: the dataset preview goes from a "Format not recognised" error to three decoded rows with summarised audio cells.

Two failures in tests/studio/install/test_dependency_pass_skips.py show up here on this branch and identically on a clean main checkout, so they are not from this change.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 472295dd16

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

Copy link
Copy Markdown
Member

Update for 472295d, which moves the torchcodec probe out of the two installer heredocs into torchcodec_load_state() in unsloth/import_fixes.py (loaded by file path, so no import unsloth):

  • Codex: no major issues on 472295d.
  • AMD gfx1151 Linux: 61 passed, 1 skipped, NO_REGRESSION. Windows: 48 passed, 3 skipped, NO_REGRESSION. Shell installer suites: 67 run at base and head, 0 failed.
  • Hosted Linux, macOS 15 and Windows: green.
  • Probe cost is unchanged at about 1.1 s on a broken-torchcodec venv (the torch import); loading the module by path adds about 20 ms.
  • Decode cost of the fallback, 10 s clips on CPU: wav 0.4 ms per row against 6.4 ms through torchcodec, m4a 8 to 10 ms per row against 3 ms, so compressed containers are about three times slower on the PyAV path but still around a thousand times real time. A working torchcodec is never touched, so a healthy install pays nothing.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 814b83cf18

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants