Skip to content

fix(audio): install the audio decode shim before the training worker loads a dataset - #8436

Merged
danielhanchen merged 9 commits into
unslothai:mainfrom
LeoBorcherding:fix/audio-decode-before-dataset-load
Aug 13, 2026
Merged

danielhanchen merged 9 commits into
unslothai:mainfrom
LeoBorcherding:fix/audio-decode-before-dataset-load

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

The bug

Training an audio dataset fails on a host without an FFmpeg full-shared build:

Error loading dataset: To support decoding audio data, please install 'torchcodec'.
Training error: To support decoding audio data, please install 'torchcodec'.

torchcodec is installed, and the soundfile fallback built for this case is importable. The run dies at step 0 with an upstream message naming a package that is already present.

Root cause

ensure_audio_decoding() clears TORCHCODEC_AVAILABLE when torchcodec cannot dlopen its libraries and installs the soundfile decoder in its place. The dataset format-check endpoint calls it early, in the API process. The training worker is a separate process and starts without the shim.

The worker's only call sits behind a model-type guess:

if self._audio_type or self.is_audio_vlm:
    if not ensure_audio_decoding():
        raise RuntimeError(...)

That is enough on the common path: a correctly detected audio model reaches the guard before its preprocessing branch decodes anything, because plain load_dataset() is lazy. It is not enough in two cases, and both leave the shim uninstalled while something reads a row:

1. Audio detection returns None on a dataset that does have audio. detect_audio_type reads tokenizer_config.json, and returns None when the file is unreadable for any reason: gated repo, offline, or a cache that holds the weights but not the tokenizer files. The guard tests _audio_type, so it never fires, and the run falls through to the text format path, which reads rows and raises datasets' own torchcodec ImportError. The broad handler reports that as "Error loading dataset".

2. A manual dataset slice. The slice branch materialises rows with Dataset.from_list(list(stream.take(rows_to_stream))), which decodes the Audio column before the guard is reached, independent of what detection returned.

Case 1 is what produced the log above. Both halves are visible in one run:

12:30:23  torchcodec is unusable; decoding dataset audio with soundfile   <- API process
12:47:27  Error loading dataset: To support decoding audio data, ...      <- training worker
12:47:27  Training error: To support decoding audio data, ...

The worker never logs the first line.

The fix

Call ensure_audio_decoding() in load_and_format_dataset at the same point it already quiets third-party progress bars, documented there as the first point before any load. A decoder should be in place before anything reads a row, rather than depending on a model-type guess made earlier from a file that may not be readable.

The audio branches keep their own call and their own error, which names FFmpeg and the soundfile pair, and is what a caller should see when neither backend works. This only has to precede them. The return value is deliberately ignored at the early call: the loader does not yet know whether the dataset has an audio column, and a non-audio run on an FFmpeg-less host must stay unaffected.

Verified in a real run

Same host, same dataset, on this branch:

21:43:13  torchcodec is unusable; decoding dataset audio with soundfile   <- training worker
21:43:14  (run proceeds past dataset load)

The worker now logs the line it never logged before, the dataset loads, and no torchcodec error appears anywhere. The run then fails further along for an unrelated reason, which is case 1's other consequence: with _audio_type empty the model is treated as text, so the snac branch is skipped and the text path cannot map an audio + text dataset. That is a separate bug in detect_audio_type silently conflating "not an audio model" with "could not tell", and is not addressed here.

Tests

Three ordering assertions in a new dependency-free module. The existing test_audio_dataset_decode.py importorskips soundfile and librosa, so it skips on hosts with neither, which is precisely where this ordering is load-bearing. I put the test there first and it silently skipped, which is how I noticed.

Verified as a real regression test: with the trainer change stashed, two of the three fail; with it applied, all pass.

92 passed  (audio decode, load order, progress bars, training preflight)

One pre-existing failure, test_the_soundfile_decoder_resamples_to_the_cast_rate, reproduces on a clean main checkout at c9d92df12 and is untouched by this change.

Not yet covered by a test: the slice path in case 2. Worth adding if reviewers want it pinned rather than argued from the source.

Not addressed

Why an FFmpeg-less Windows host has torchcodec at all. pyproject.toml declares it for win32/AMD64 and scripts/notebook_validator.py enforces a torch/torchcodec compatibility matrix, but nothing installs FFmpeg or checks that the wheel can load. That is a packaging question and a bigger change; this PR just makes the fallback reach the process that needs it.

…s a dataset

An audio dataset failed training on any host without an FFmpeg full-shared build,
reporting `datasets`' own "To support decoding audio data, please install
'torchcodec'" while torchcodec was installed and the soundfile fallback that
exists for this case was importable.

ensure_audio_decoding() clears TORCHCODEC_AVAILABLE and installs the soundfile
decoder, and the dataset format-check endpoint already calls it. That runs in the
API process. The training worker is a separate process and starts without the
shim, and its only call sits in the audio preprocessing branches, which run after
load_dataset() and format_and_template_dataset() have already read rows. An Audio
column decodes during that read, so the load raised before anything installed a
decoder, and the broad handler reported it as "Error loading dataset".

Call it at the same point load_and_format_dataset already quiets third-party
progress bars, documented there as the first point before any load. The audio
branches keep their own call and their own message, which names FFmpeg and is
what a caller should see when neither backend works.

Ordering is asserted in a dependency-free module: the existing audio decode suite
importorskips soundfile and librosa, so it skips on precisely the hosts this
ordering protects.
@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@LeoBorcherding LeoBorcherding changed the title Studio: install the audio decode shim before the training worker loads a dataset [Bug] Audio: install the audio decode shim before the training worker loads a dataset Aug 12, 2026
@LeoBorcherding LeoBorcherding changed the title [Bug] Audio: install the audio decode shim before the training worker loads a dataset fix(audio): install the audio decode shim before the training worker loads a dataset Aug 12, 2026
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Review pass on head a2419af11 (now current with main)

Re-checked the diagnosis and the placement rather than just re-reading the diff. One change I want to make before this merges, two nits, and two corrections to my own description above.

Verified

  • Placement covers every row-reading path in the method. The new call at trainer.py:2456 precedes the first load_dataset() (2535), the streaming-slice materialisation Dataset.from_list(list(stream.take(...))) (2677-2679), and the audio branch (2874).
  • No missed entry point in the worker. worker.py loads datasets independently at 468/654 (_load_hf_train_and_eval_datasets), 2802 (MLX), and 5060 (embeddings). The MLX path rejects audio outright at worker.py:3368 ("Audio dataset training is not yet supported on Apple Silicon") and the embeddings path is text-only, so load_and_format_dataset (worker.py:4088) is the only audio-capable entry. Scope is complete.
  • Idempotent under the double call. The second call at 2877 hits the _installed early-out, and _install_lock re-checks under the lock, so the recursion hazard documented in audio_decode.py is not reintroduced.
  • The tests are a real regression test. Reverting the hunk flips tests 1 and 2 to failing; test 3 stays passing, since the module-level import predates this PR.
  • The dependency-free choice is empirically right. On an interpreter without soundfile, test_audio_dataset_decode.py skips at module level (could not import 'soundfile') while the new module runs and passes. That is exactly the host class this ordering protects.
  • test_audio_decode_load_order + test_audio_dataset_decode + test_training_preflight: 52 passed, 1 skipped, 0 failed.

One change before merge: the new call is the only unguarded statement in that preamble

Structurally, at trainer.py:2443-2459:

  • quiet_third_party_progress_bars(): inside try 2443-2447, except Exception, commented "never let log tidying stop a run"
  • ensure_audio_decoding(): inside nothing
  • the pre-existing audio guard at 2877: inside the method's try 2459-3029, except Exception at 3023

ensure_audio_decoding() catches ImportError on the datasets import, (ImportError, OSError, RuntimeError) on the torchcodec probe, and (ImportError, OSError) on import librosa / import soundfile. Anything else escapes, and import librosa pulls numba/llvmlite/numpy, whose ABI mismatches surface as AttributeError, TypeError, or SystemError at least as often as ImportError.

Before this PR that blast radius was audio runs only, and the throw landed in the method's own handler, which reports it as a dataset error. With the call hoisted above the try, it escapes load_and_format_dataset entirely and fails every training run, text included, on a host with a half-broken librosa. That is a worse failure mode than the one being fixed.

try:
    ensure_audio_decoding()
except Exception:  # noqa: BLE001 - a broken librosa must not stop a text run
    pass

The alternative is widening the import guard in audio_decode.py to except Exception, which is arguably where the real defect is: the docstring already promises "False means neither backend is importable", and an import that raises AttributeError is precisely that case. I lean toward the call-site guard here to keep this diff local and mirror the neighbouring statement, and to treat the narrow tuple as separate.

Nits

A text-only run on an FFmpeg-less host is not quite "unaffected". True for the return value, which is deliberately ignored, but two side effects now reach every run: with soundfile present, Audio.decode_example/encode_example are patched process-wide and an INFO line about soundfile decoding lands in a pure-text run's log; with neither backend, logger.warning("No usable audio decoder: ...") fires on every text run. The second is the one that generates a bug report. A quiet = True kwarg on the speculative call would keep the warning on the branches that mean it. Related: on a healthy host the probe eagerly imports torchcodec on every run. torch is resident by then so the cost is small, but it is new work on the text path.

Test failure ergonomics. body.index(...) raises ValueError rather than failing an assertion, so renaming the # ========== AUDIO MODELS: custom preprocessing ========== banner or reformatting = load_dataset( errors with a stack trace that reads like a broken test rather than "the ordering invariant moved". A small _index(body, needle) helper asserting presence with a message fixes that. Separately, _load_and_format_dataset_body() slices from the def to EOF, so it returns the rest of the file, not the method body. Correct today, since each anchor's first occurrence is inside the method, but it should slice to the next \n def .

Two corrections to the description above

  • "Not yet covered by a test: the slice path in case 2" undersells it. Test 1 asserts against the first = load_dataset( (2535), and the slice load at 2677 is downstream of it, so any regression that moves the shim past the slice also moves it past 2535 and fails. It is pinned transitively. The real gap is a new row-reading path added above line 2456 that does not spell = load_dataset(, e.g. load_from_disk or Dataset.from_list.
  • The pre-existing test_the_soundfile_decoder_resamples_to_the_cast_rate failure is unverified on the host I re-checked on: that module skips wholesale there without soundfile.

…fail a text run

The call this branch added for the training worker sits above
load_and_format_dataset's own try, so anything it raises escapes the method
instead of landing in the handler that reports a dataset error.

ensure_audio_decoding() catches ImportError, OSError and RuntimeError around its
probes, but `import librosa` pulls numba, llvmlite and numpy, whose ABI
mismatches surface as AttributeError, TypeError or SystemError at least as
often. Before the hoist that blast radius was audio runs only; from the new
position it would fail every training run, text included, on a host with a
half-broken librosa. That is worse than the bug being fixed.

Guarded the same way as the progress-bar block directly above it. The audio
branches further down still call it and still report the failure that names
FFmpeg, so nothing a caller sees changes.

Pinned with an ast assertion rather than source text: the first statement in the
method that calls the shim must be a try that holds the call directly and whose
handler catches Exception. The method's own large try contains a later call but
not directly, so it cannot satisfy the assertion by accident.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed since the review comment above: 0e7c56192.

  • fa0f13591 wraps the early ensure_audio_decoding() call in try/except Exception, matching the progress-bar block directly above it, so an import error out of librosa cannot escape load_and_format_dataset and fail a text-only run. Adds a fourth test pinning the guard via ast.
  • Merged main to bring the branch current with base. No conflicts.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 0e7c56192c

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

datasets<4 has no config.TORCHCODEC_AVAILABLE, so reading it raised AttributeError,
which the function catches nowhere and its callers do not expect. pyproject still
allows datasets>=3.4.1, and on such an install the call in the audio branch of
load_and_format_dataset is unguarded, so an audio run failed reporting a missing
config attribute instead of training.

Those versions decode audio through soundfile already, so there is nothing to install
and nothing to patch: return True.

Verified against a real datasets 3.6.0 in an isolated venv, plus 4.2.0, 4.3.0 and
4.4.0 which are unchanged.
@danielhanchen

Copy link
Copy Markdown
Member

Reviewed this together with #8625 and validated it on a host that reproduces the bug natively: this box has torchcodec 0.10.0 installed with FFmpeg's shared libraries absent, so import datasets.features._torchcodec raises OSError: libavutil.so.60: cannot open shared object file. No simulation or shim was needed.

The bug is real, and the fix works

Driving the real load_and_format_dataset against openai/whisper-tiny + hf-internal-testing/dailytalk-dummy with a manual slice (dataset_slice_start=0, dataset_slice_end=0):

merge base 22cb12ec this PR
/api/train/status error To support decoding audio data, please install 'torchcodec'. null
phase error at step 0 loading_model
worker log: torchcodec is unusable; decoding dataset audio with soundfile 0 1
worker log: [dataset-slice] Downloaded 1 rows 0 1

The log counts are the part a screenshot cannot carry: the decoder is installed in the worker, which is the process that lacked it. The slice path is the "case 2" your description flags as untested, and it is the one that fires here.

One fix pushed

ensure_audio_decoding reads config.TORCHCODEC_AVAILABLE behind except ImportError only. That attribute landed in datasets 4.0.0, and pyproject.toml still allows datasets>=3.4.1, so on a 3.x install the call raises AttributeError — a type the function catches nowhere and its callers do not expect. It matters because the pre-existing call in the audio branch is unguarded, so an audio run there died reporting a missing config attribute rather than training. Your new call is wrapped in except Exception, so it cannot make this worse, but it sits directly next to it.

Those versions decode through soundfile already, so there is nothing to install: return True.

Verified in isolated uv venvs — datasets 3.6.0 fails without the change and passes with it; 4.2.0, 4.3.0 and 4.4.0 are unaffected. Added a regression test that fails without the fix with exactly that AttributeError.

Compatibility

  • Text runs are unchanged. The same text dataset produces byte-identical outcomes on the merge base, each PR alone, and both merged.
  • Platform/accelerator invariant. [Windows, Linux, WSL, macOS] × [NVIDIA, AMD, CPU] simulated: the added lines contain no sys.platform, os.name or torch.cuda branching, and worker.py:4073 loads the dataset before the model, so no GPU is held either way. Audio on Apple Silicon is rejected earlier at worker.py:3368, so that row is vacuous.
  • AMD is a first-class beneficiary. torchcodec wheels are built against CPU/CUDA torch, so ROCm users hit this same masked failure (huggingface/datasets#7914).
  • No frontend file, no new import, no signature change.

Two notes, neither blocking

A text run gains an audio side effect. On a broken-torchcodec host the speculative call patches datasets.Audio process-wide and logs torchcodec is unusable; decoding dataset audio with soundfile during a pure text run. Harmless — a text dataset has no Audio column — but on Linux aarch64, where pyproject.toml ships no torchcodec at all, that line will appear on every text run. You raised this yourself; a quiet=True kwarg on the speculative call would still be worth having.

A pre-existing hazard, not yours. _installed and _ORIGINAL_ENCODE are module-level while the class they patch is global, so two module instances (the backend on sys.path under two prefixes) let the second capture the first's shim as _ORIGINAL_ENCODE and recurse. I demonstrated it in a test but left it alone: it needs an import layout Studio does not have, and it is out of scope here. A if Audio.encode_example is not _encode_with_soundfile guard at the capture site would close it.

Both PRs merge cleanly with each other, and the suites pass: 85 in the audio/preflight modules on this branch, plus 282 source-level and 26 end-to-end checks across the merge base, each PR, and both combined.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 09301be0e7

ℹ️ 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 97841d8 into unslothai:main Aug 13, 2026
37 of 40 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.

2 participants