Skip to content

Replace soundfile+torchaudio with torchcodec AudioDecoder in load_audio#20190

Merged
JustinTong0323 merged 6 commits intosgl-project:mainfrom
JustinTong0323:feat/audio-torchcodec
Mar 10, 2026
Merged

Replace soundfile+torchaudio with torchcodec AudioDecoder in load_audio#20190
JustinTong0323 merged 6 commits intosgl-project:mainfrom
JustinTong0323:feat/audio-torchcodec

Conversation

@JustinTong0323
Copy link
Copy Markdown
Collaborator

@JustinTong0323 JustinTong0323 commented Mar 9, 2026

Motivation

Follow-up to #20055 (video decoding migration to torchcodec). This PR migrates load_audio() from soundfile + torchaudio to torchcodec's AudioDecoder, unifying all media decoding under torchcodec.

Changes

Replace soundfile.read() + torchaudio.functional.resample() with torchcodec.decoders.AudioDecoder, which handles decoding, resampling, and channel conversion in a single step. Falls back to soundfile + torchaudio on ARM / no-FFmpeg environments, reusing video_decoder._BACKEND flag for unified detection.

Before: soundfile loads raw audio → numpy mono conversion → torchaudio polyphase resample
After: AudioDecoder(source, sample_rate=sr, num_channels=1) → done

  • All input formats preserved: bytes, base64, HTTP URL, file://, local path
  • Output shape backward-compatible: mono → (time,), stereo → (time, channels)
  • ARM fallback to soundfile + torchaudio via shared _BACKEND flag from video_decoder.py

Test plan

  • Short audio (<1min, mono & stereo, various sample rates)
  • Long stereo audio (2hr, 44.1kHz→16kHz) — 3.09s
  • Base64 and bytes input
  • file:// URL input
  • Multi-channel stereo preservation (mono=False)
  • Qwen2-Audio-7B-Instruct server: speech recognition (Trump WEF) ✅
  • Qwen2-Audio-7B-Instruct server: ambient audio (bird song) ✅
  • CI: all existing audio-related tests pass

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request streamlines the audio loading process by unifying media decoding under the torchcodec library. It replaces a multi-step process involving soundfile and torchaudio with a single, more efficient AudioDecoder call, leading to improved performance and a cleaner codebase for audio handling.

Highlights

  • Audio Decoding Migration: Migrated the load_audio() function from using soundfile and torchaudio to torchcodec.decoders.AudioDecoder.
  • Simplified Audio Processing: Consolidated decoding, resampling, and channel conversion into a single step using AudioDecoder.
  • Dependency Reduction: Removed direct imports of soundfile, torch, and torchaudio from the load_audio() function.
  • Performance Improvement: Achieved approximately 3x faster audio loading for a 2-minute stereo audio file.
  • Input/Output Compatibility: Ensured all existing input formats are preserved and the output shape remains backward-compatible.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • python/sglang/srt/utils/common.py
    • Replaced soundfile and torchaudio based audio loading with torchcodec.decoders.AudioDecoder.
    • Refactored input handling to prepare sources for AudioDecoder.
    • Adjusted output format to maintain backward compatibility.
Activity
  • No human activity has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request effectively refactors the load_audio function to use torchcodec.AudioDecoder, replacing the previous implementation that relied on soundfile and torchaudio. This change simplifies the codebase by unifying media decoding under a single library and makes the audio loading process more efficient and cleaner. The implementation correctly handles various input sources and maintains backward compatibility of the output format. I have one suggestion to enhance the robustness of handling audio files from HTTP sources.

Note: Security Review did not run due to the size of the PR.

Comment thread python/sglang/srt/utils/common.py Outdated
Comment on lines 863 to 865
response = requests.get(audio_file, stream=True, timeout=timeout)
audio_file = BytesIO(response.content)
source = response.content
response.close()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For improved robustness when fetching audio from URLs, it's a good practice to use a with statement for requests.get. This ensures the network connection is properly closed, even if errors occur. Adding response.raise_for_status() will also make the function fail fast for bad HTTP responses (e.g., 404 Not Found), which is more explicit than failing later during decoding. I've also removed stream=True as it's not necessary when immediately accessing .content.

Suggested change
response = requests.get(audio_file, stream=True, timeout=timeout)
audio_file = BytesIO(response.content)
source = response.content
response.close()
with requests.get(audio_file, timeout=timeout) as response:
response.raise_for_status()
source = response.content

Use torchcodec's AudioDecoder for audio loading, which handles decoding,
resampling, and channel conversion in a single step. This aligns audio
loading with the video decoding migration to torchcodec (sgl-project#20055) and
removes the soundfile/torchaudio dependency from the audio path.
@JustinTong0323 JustinTong0323 force-pushed the feat/audio-torchcodec branch from 31c3ef8 to 9dc5c26 Compare March 9, 2026 11:47
@JustinTong0323 JustinTong0323 marked this pull request as ready for review March 9, 2026 12:47
@JustinTong0323
Copy link
Copy Markdown
Collaborator Author

/tag-run-ci-label

@JustinTong0323
Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

1 similar comment
@JustinTong0323
Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

@JustinTong0323 JustinTong0323 enabled auto-merge (squash) March 10, 2026 17:18
@JustinTong0323 JustinTong0323 merged commit 11d9c36 into sgl-project:main Mar 10, 2026
358 of 388 checks passed
liubiyongge pushed a commit to liubiyongge/sglang that referenced this pull request Mar 13, 2026
Wangzheee pushed a commit to Wangzheee/sglang that referenced this pull request Mar 21, 2026
JustinTong0323 added a commit to JustinTong0323/sglang that referenced this pull request Apr 7, 2026
yhyang201 pushed a commit to yhyang201/sglang that referenced this pull request Apr 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants