Cannot load torchcodec

Hello, I have some problem making some program and here is the code I made below

%pip install --upgrade pip 
%pip install --upgrade transformers datasets[audio] accelerate

import os
os.environ["PATH"] += os.pathsep + r"C:\GPT_AGENT_2025_BOOK\chap05\ffmpeg-2025-10-16-git\bin"

import transformers
print(transformers.__version__)


import torch
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
# from datasets import load_dataset




device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32

model_id = "openai/whisper-large-v3-turbo"

model = AutoModelForSpeechSeq2Seq.from_pretrained(
    model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
)
model.to(device)

processor = AutoProcessor.from_pretrained(model_id)

pipe = pipeline(
    "automatic-speech-recognition",
    model=model,
    tokenizer=processor.tokenizer,
    feature_extractor=processor.feature_extractor,
    torch_dtype=torch_dtype,
    device=device,
    return_timestamps=True,   
    chunk_length_s=10,  
    stride_length_s=2,  
) 

# dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
# sample = dataset[0]["audio"]
sample = "./lsy_audio_2023_58s.mp3"

result = pipe(sample)
# print(result["text"])

print(result)

and this code gives me error below

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[8], line 36
     32 # dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
     33 # sample = dataset[0]["audio"]
     34 sample = "./lsy_audio_2023_58s.mp3"
---> 36 result = pipe(sample)
     37 # print(result["text"])
     39 print(result)

File c:\Users\majh0\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\pipelines\automatic_speech_recognition.py:275, in AutomaticSpeechRecognitionPipeline.__call__(self, inputs, **kwargs)
    218 def __call__(self, inputs: Union[np.ndarray, bytes, str, dict], **kwargs: Any) -> list[dict[str, Any]]:
    219     """
    220     Transcribe the audio sequence(s) given as inputs to text. See the [`AutomaticSpeechRecognitionPipeline`]
    221     documentation for more information.
   (...)    273                 `"".join(chunk["text"] for chunk in output["chunks"])`.
    274     """
--> 275     return super().__call__(inputs, **kwargs)

File c:\Users\majh0\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\pipelines\base.py:1459, in Pipeline.__call__(self, inputs, num_workers, batch_size, *args, **kwargs)
   1457     return self.iterate(inputs, preprocess_params, forward_params, postprocess_params)
   1458 elif self.framework == "pt" and isinstance(self, ChunkPipeline):
-> 1459     return next(
   1460         iter(
   1461             self.get_iterator(
...
FFmpeg version 7: Could not load this library: C:\Users\majh0\AppData\Local\Programs\Python\Python312\Lib\site-packages\torchcodec\libtorchcodec_core7.dll
FFmpeg version 6: Could not load this library: C:\Users\majh0\AppData\Local\Programs\Python\Python312\Lib\site-packages\torchcodec\libtorchcodec_core6.dll
FFmpeg version 5: Could not load this library: C:\Users\majh0\AppData\Local\Programs\Python\Python312\Lib\site-packages\torchcodec\libtorchcodec_core5.dll
FFmpeg version 4: Could not load this library: C:\Users\majh0\AppData\Local\Programs\Python\Python312\Lib\site-packages\torchcodec\libtorchcodec_core4.dll
[end of libtorchcodec loading traceback].
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...

It says it cannot load some .dll files… there are dll files it needs like picture below….

It is really hard to find out that why this thing cannot load the .dll files even if the files are in the proper directory…

Thank you so much for the help in advance…

1 Like

May be a version issue with ffmpeg in the Windows environment.


Diagnosis: Windows cannot find compatible FFmpeg DLLs for TorchCodec, or your Torch↔TorchCodec versions don’t match. The probe core7 → core6 → core5 → core4 failing is TorchCodec’s normal fallback when the FFmpeg runtime it needs isn’t available. (GitHub)

Causes

  • FFmpeg runtime DLLs missing or not discoverable. Having ffmpeg.exe on PATH is not enough; the loader must see avcodec-*.dll, avformat-*.dll, avutil-*.dll. (docs.pytorch.org)

  • Unsupported FFmpeg major on Windows. TorchCodec supports FFmpeg 4–7 on all platforms and FFmpeg 8 on macOS/Linux. Using 8 on Windows fails with current wheels. (GitHub)

  • Torch↔TorchCodec mismatch or RC/nightly torch. Follow the version matrix: 0.8 ↔ torch 2.9, 0.7 ↔ torch 2.8, Python 3.10–3.13. Mismatches trigger the exact error you pasted. (GitHub)

  • Homebrew or custom FFmpeg builds with incompatible layouts (mac users). Known incompatibility reported; conda-forge FFmpeg works. (GitHub)

Fixes (pick one path, do it end-to-end)

A) Windows, CPU-only, stable


# fresh venv

python -m venv .venv

.\.venv\Scripts\Activate.ps1

pip install -U pip

# choose a matched pair (pick one)

pip install "torch==2.9.*" "torchcodec==0.8.*"

# or

# pip install "torch==2.8.*" "torchcodec==0.7.*"

# install shared FFmpeg DLLs via conda-forge (<8 on Windows)

# run this in an Anaconda/Miniconda prompt

conda install -y -c conda-forge "ffmpeg<8"

# make DLLs visible to Python (adjust path to your conda root)

set PATH=C:\Miniconda3\Library\bin;%PATH%

# sanity checks

python - <<'PY'

import torch, torchcodec, platform, subprocess

print("torch", torch.__version__, "torchcodec", torchcodec.__version__, "py", platform.python_version())

subprocess.run(["ffmpeg","-version"], check=True)

PY

Why this works: TorchCodec requires FFmpeg 4–7 on Windows and matched Torch↔TorchCodec versions; conda-forge provides the needed DLLs in Library\bin. (GitHub)

B) Windows, CUDA

Use conda for both Torch and TorchCodec and conda-forge FFmpeg.


conda create -n tcuda python=3.10 -y

conda activate tcuda

# install torch for your CUDA per pytorch.org

conda install -c conda-forge "ffmpeg<8"

conda install -c conda-forge "torchcodec=*=*cuda*"

Windows CUDA support is experimental and conda-first in the docs. (GitHub)

C) macOS/Linux notes

If you used Homebrew FFmpeg on mac and see the same error, switch to conda-forge FFmpeg. FFmpeg 8 is supported on macOS/Linux starting TorchCodec 0.8. (GitHub)

Quick triage checks

  • Print versions. If they don’t match the table, reinstall with a supported pair.

python -c "import torch,torchcodec,platform;print(torch.__version__, torchcodec.__version__, platform.python_version())" (GitHub)

  • Confirm FFmpeg runtime is on PATH for the same shell that launches Python.

ffmpeg -version should succeed. If it does but TorchCodec still fails, you likely pointed to a static or CLI-only FFmpeg without DLLs. (docs.pytorch.org)

  • Avoid RC/nightly Torch with stable TorchCodec; #912 documents the loader error with 2.9 RC. (GitHub)

Minimal workaround if you can’t fix FFmpeg now

Preconvert MP3 → WAV and pass the WAV to your pipeline:


ffmpeg -i lsy_audio_2023_58s.mp3 -ar 16000 -ac 1 -y lsy_audio_2023_58s.wav

This sidesteps MP3 decoding but does not fix the root cause. (GitHub)

Context and background

  • TorchCodec loads FFmpeg at runtime and tries majors 7→6→5→4. The error you saw is the expected probe sequence when the needed FFmpeg DLLs are missing or incompatible. The README and downstream reports show the same pattern. (GitHub)

  • Windows support is recent and labeled beta; the releases and Windows tracker call out rough edges. Expect stricter version discipline. (GitHub)

Short, curated references

Primary docs

  • TorchCodec README: FFmpeg 4–7 on all platforms, 8 on macOS/Linux; version matrix; Windows notes. (GitHub)

  • Torchaudio install page: how to install FFmpeg and how discovery works on Windows. (docs.pytorch.org)

Issue reports matching your symptoms

  • HF Datasets 4.0: exact Could not load libtorchcodec probe trace when FFmpeg libs are missing or versions mismatch. (GitHub)

  • TorchCodec #912: loader failure with Torch 2.9 RC. Confirms mismatch cause. (GitHub)

  • macOS Homebrew FFmpeg incompatibility: use conda-forge FFmpeg. (GitHub)

Hello, Thank you so much for the answer!

However.. I still don’t know why I got the same error…

I made a new venv, activated it and installed torch and torchcodec with the commands you gave me and here is the link of the picture

python -m venv venv

.\venv\Scripts\Activate.ps1

pip install -U pip

pip install "torch==2.9.*" "torchcodec==0.8.*"

I also installed ffmpeg<8 after installing miniconda3 with the command you gave and I could see some avcodec-*.dll files in the directory C:\Users\majh0\miniconda3\Library\bin like picture below

conda install -y -c conda-forge "ffmpeg<8"

I made a code with Jupyter notebook like picture below and it still gives me same error…

import os
os.system(r'set PATH=C:\Miniconda3\Library\bin;%PATH%')
# os.environ["PATH"] += os.pathsep + r"C:\GPT_AGENT_2025_BOOK\chap05\ffmpeg-2025-10-16-git\bin"

import torch, torchcodec, platform, subprocess

print("torch", torch.__version__, "torchcodec", torchcodec.__version__, "py", platform.python_version())

subprocess.run(["ffmpeg","-version"], check=True)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[21], line 5
      2 os.system(r'set PATH=C:\Miniconda3\Library\bin;%PATH%')
      3 # os.environ["PATH"] += os.pathsep + r"C:\GPT_AGENT_2025_BOOK\chap05\ffmpeg-2025-10-16-git\bin"
----> 5 import torch, torchcodec, platform, subprocess
      7 print("torch", torch.__version__, "torchcodec", torchcodec.__version__, "py", platform.python_version())
      9 subprocess.run(["ffmpeg","-version"], check=True)

File c:\GPT_AGENT_2025_BOOK\venv\Lib\site-packages\torchcodec\__init__.py:10
      1 # Copyright (c) Meta Platforms, Inc. and affiliates.
      2 # All rights reserved.
      3 #
   (...)      7 # Note: usort wants to put Frame and FrameBatch after decoders and samplers,
      8 # but that results in circular import.
      9 from ._frame import AudioSamples, Frame, FrameBatch  # usort:skip # noqa
---> 10 from . import decoders, samplers  # noqa
     12 try:
     13     # Note that version.py is generated during install.
     14     from .version import __version__  # noqa: F401

File c:\GPT_AGENT_2025_BOOK\venv\Lib\site-packages\torchcodec\decoders\__init__.py:7
      1 # Copyright (c) Meta Platforms, Inc. and affiliates.
      2 # All rights reserved.
      3 #
...
FFmpeg version 7: Could not load this library: C:\GPT_AGENT_2025_BOOK\venv\Lib\site-packages\torchcodec\libtorchcodec_core7.dll
FFmpeg version 6: Could not load this library: C:\GPT_AGENT_2025_BOOK\venv\Lib\site-packages\torchcodec\libtorchcodec_core6.dll
FFmpeg version 5: Could not load this library: C:\GPT_AGENT_2025_BOOK\venv\Lib\site-packages\torchcodec\libtorchcodec_core5.dll
FFmpeg version 4: Could not load this library: C:\GPT_AGENT_2025_BOOK\venv\Lib\site-packages\torchcodec\libtorchcodec_core4.dll
[end of libtorchcodec loading traceback].

I actually installed ffmpeg which is under version 8 with the command through miniconda…

I don’t know why this thing still gives me error like this..

Could you please help me more if you don’t mind..? ;(

Thank you so much in advance.

1 Like

When using Python in a Windows environment, particularly with venv, conda, or Jupyter, DLL errors occasionally occur because the Windows PATH environment variable isn’t used to locate DLLs…


You’re hitting a Windows DLL-loading problem for TorchCodec plus a possible version or kernel mismatch. The error text in your HF thread shows TorchCodec probing core8→7→6→5→4 and failing to bind FFmpeg. That pattern means the FFmpeg runtime DLLs are not visible to the Python process or the Torch↔TorchCodec pair is mismatched. (Hugging Face Forums)

Causes

  • Python ≥3.8 on Windows does not use PATH for dependent DLLs. You must add the FFmpeg DLL folder to the current process with os.add_dll_directory(...) before importing torchcodec. Adding PATH via os.system("set PATH=...") does not affect the running process. Order is also tricky if you add multiple directories. (Python documentation)
  • FFmpeg major not supported for your OS. TorchCodec supports FFmpeg 4–7 on all platforms. FFmpeg 8 is supported on Mac/Linux. Windows requires 4–7 today. (GitHub)
  • Torch/TorchCodec mismatch. Use the matrix: TorchCodec 0.8 ↔ torch 2.9. TorchCodec 0.7 ↔ torch 2.8. Python 3.10–3.13 for 0.8. Nightly/RC combos often fail to load. (GitHub)
  • Wrong Jupyter kernel or mixed environments. Installing in one venv and running another reproduces the same error. (Hugging Face Forums)
  • On macOS only: Homebrew FFmpeg layouts have caused incompatibility; conda-forge FFmpeg works. Not your Windows case, but relevant if you switch machines. (GitHub)

Solutions

1) Keep venv + conda FFmpeg. Add the DLL dir correctly.

Put this at the very top of your notebook, before any torch or torchcodec import.

# Use Python's Windows DLL API (3.8+). Add the folder that holds avcodec/avformat/avutil DLLs.
# TorchCodec README + version matrix: https://github.com/pytorch/torchcodec  (docs)
# Torchaudio FFmpeg install notes on Windows: https://docs.pytorch.org/audio/main/installation.html  (install tips)

from pathlib import Path
import os, sys

ffmpeg_dll_dir = Path(r"C:\Users\majh0\miniconda3\Library\bin")  # adjust if your conda root differs
assert ffmpeg_dll_dir.exists(), ffmpeg_dll_dir
os.add_dll_directory(str(ffmpeg_dll_dir))  # Python 3.8+ DLL search

import torch, torchcodec, platform, subprocess
print("exe:", sys.executable)
print("torch", torch.__version__, "torchcodec", torchcodec.__version__, "py", platform.python_version())
subprocess.run(["ffmpeg", "-version"], check=True)

Background: os.add_dll_directory was added in 3.8 for this exact scenario. It affects the current process and is the supported way to expose dependency DLLs. Adding to PATH in a child shell does not help. Avoid adding multiple DLL dirs since search order is unspecified. (Python documentation)

2) Pin a supported version set.

Pick one:

# CPU
pip install "torch==2.9.*" "torchcodec==0.8.*"
# or
# pip install "torch==2.8.*" "torchcodec==0.7.*"

Reason: TorchCodec pairs with specific torch versions. The README documents 0.8↔2.9 and 0.7↔2.8. (GitHub)

3) Ensure FFmpeg 4–7 and use a shared build.

# In an Anaconda/Miniconda prompt
conda install -y -c conda-forge "ffmpeg<8"
# DLLs land in ...\miniconda3\Library\bin  (the dir you pass to os.add_dll_directory)

Conda-forge FFmpeg provides the needed Windows runtime DLLs. (PyTorch Documentation)

4) Make sure Jupyter is using the same interpreter.

# inside your venv
pip install ipykernel
python -m ipykernel install --user --name asrvenv --display-name "Python (asrvenv)"
# then select "Python (asrvenv)" in Jupyter

This prevents importing from a different Python that lacks your fixes. (Hugging Face Forums)

5) One-env fallback to avoid mixing tools.

If mixing venv + conda is awkward, put everything in one conda env:

conda create -n asr python=3.10 -y
conda activate asr
conda install -c conda-forge "ffmpeg<8"
pip install "torch==2.9.*" "torchcodec==0.8.*"
python -c "import torch, torchcodec; print(torch.__version__, torchcodec.__version__)"

Windows support is marked experimental, and the README recommends conda for CUDA and Windows cases. (GitHub)

6) Temporary workaround if you must proceed.

Preconvert MP3 → WAV with FFmpeg and feed WAV to the pipeline. This avoids MP3 decoding, but it does not fix DLL loading.

ffmpeg -i input.mp3 -ar 16000 -ac 1 -y input.wav

Use only while you stabilize the environment. (Hugging Face Forums)

Why your specific repro keeps failing

  • You set PATH in a child shell (os.system("set PATH=...")). The current Python process did not inherit it. Python ≥3.8 also ignores PATH for dependent DLLs. Use os.add_dll_directory and the exact Miniconda path that actually contains avcodec-*.dll. (Python documentation)
  • Your HF post shows the expected TorchCodec probe sequence and a venv site-packages path. That confirms a loader failure, not a missing Python package. (Hugging Face Forums)
  • If you added more than one DLL directory, search order is unspecified. Keep only the conda Library\bin. (Discussions on Python.org)

Quick checklist

  • torch==2.9.*, torchcodec==0.8.*, Python 3.10–3.13. (GitHub)
  • conda install -c conda-forge "ffmpeg<8" on Windows. DLLs in ...\miniconda3\Library\bin. (PyTorch Documentation)
  • Top cell calls os.add_dll_directory(r"...\miniconda3\Library\bin") before importing torchcodec. (Python documentation)
  • Jupyter kernel points to the same venv. (Hugging Face Forums)

Context and background

  • TorchCodec loads FFmpeg at runtime. It supports FFmpeg 4–7 across platforms and 8 on Mac/Linux. The README also lists the torch↔torchcodec compatibility table. Windows is labeled experimental. (GitHub)
  • Many similar Windows reports reduce to DLL discovery or mismatched versions. Torchaudio docs endorse conda-forge FFmpeg to simplify discovery on Windows. (PyTorch Documentation)

Supplemental references

Core docs

  • TorchCodec README: support matrix, FFmpeg majors, Windows notes. Useful for exact pins. (GitHub)
  • Torchaudio install page: FFmpeg on Windows via conda-forge. Good for verifying FFmpeg placement. (PyTorch Documentation)

Related issues

  • Homebrew FFmpeg incompatibility on macOS. Use conda-forge FFmpeg instead. (GitHub)
  • Python 3.8+ DLL behavior and os.add_dll_directory. Explains why editing PATH is insufficient and why order is unspecified. (Python documentation)

Hello! Thank you so much!!

I solved the problem that I had!!

If you didn’t give me a hand, I wouldn’t solve this problem….

Thank you so much again!!!

By the way, do I need to press Solution button? if I need to do then I will do it!

1 Like

If it works, that’s fine.

By the way, do I need to press Solution button?

It’s optional, but pressing it makes it clear that it’s resolved.:grinning_face:

1 Like

OK! I will press that Solution button!

Thank you so much again!

1 Like

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.