Skip to content

Conversation

@alien-0119
Copy link
Collaborator

@alien-0119 alien-0119 commented Dec 4, 2025

What does this PR do?

Adds # (feature)
Add X-Codec model and fast ut.

Usage Example:

from datasets import load_dataset, Audio
from transformers import AutoFeatureExtractor
from mindone.transformers import XcodecModel
import mindspore as ms

dummy_dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")

# load model and feature extractor
model_id = "hf-audio/xcodec-hubert-librispeech"
model = XcodecModel.from_pretrained(model_id)
feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)

# load audio sample
dummy_dataset = dummy_dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
audio_sample = dummy_dataset[-1]["audio"]["array"]
inputs = feature_extractor(raw_audio=audio_sample, sampling_rate=feature_extractor.sampling_rate, return_tensors="np")
inputs = {k: ms.tensor(v) for k, v in inputs.items()}

# encode and decode
encoder_outputs = model.encode(inputs["input_values"])
decoder_outputs = model.decode(encoder_outputs.audio_codes)
audio_values = decoder_outputs.audio_values

# or the equivalent with a forward pass
audio_values = model(inputs["input_values"]).audio_values

import soundfile as sf

original = audio_sample
reconstruction = audio_values[0].numpy()
sampling_rate = feature_extractor.sampling_rate

sf.write("original.wav", original, sampling_rate)
sf.write("reconstruction.wav", reconstruction.T, sampling_rate)

Performance:
Experiments were tested on Ascend Atlas 800T A2 machines with mindspore 2.7.0 pynative mode.

model precision weight load(s) s/step
hf-audio/xcodec-hubert-librispeech fp32 9.323 0.084
hf-audio/xcodec-hubert-librispeech fp16 12.156 0.083
hf-audio/xcodec-hubert-librispeech bf16 12.047 0.070

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline?
  • Did you make sure to update the documentation with your changes? E.g. record bug fixes or new features in What's New. Here are the
    documentation guidelines
  • Did you build and run the code without any errors?
  • Did you report the running environment (NPU type/MS version) and performance in the doc? (better record it for data loading, model inference, or training tasks)
  • Did you write any new necessary tests?

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

@xxx

@alien-0119 alien-0119 requested a review from vigo999 as a code owner December 4, 2025 07:11
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @alien-0119, 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 significantly expands the audio processing capabilities of the mindone.transformers library by integrating the X-Codec model. This addition provides a robust framework for encoding raw audio into discrete codebooks and decoding them back, leveraging semantic and acoustic components. The changes ensure that X-Codec is fully integrated and testable within the existing architecture.

Highlights

  • New Model Integration: The X-Codec model (v4.54.1) has been added to the mindone.transformers library, enabling advanced audio encoding and decoding capabilities.
  • Core X-Codec Implementation: The pull request introduces the full implementation of the X-Codec model, including its XcodecModel and XcodecPreTrainedModel classes, along with supporting components like ResidualUnit, SemanticEncoder, SemanticDecoder, and XcodecResidualVectorQuantization.
  • Audio Tokenizer Base Class: A new abstract base class, PreTrainedAudioTokenizerBase, has been introduced in modeling_utils.py to standardize the interface for audio tokenizers, defining encode and decode methods for raw audio to discrete codebook conversion.
  • Auto-Configuration Support: The X-Codec model is now discoverable and loadable via the AutoConfig, AutoModel, and AutoProcessor classes, simplifying its usage within the framework.
  • Unit Tests: Comprehensive unit tests for the XcodecModel have been added to ensure its correctness and compatibility with existing mindone.transformers functionalities.
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.

@alien-0119 alien-0119 changed the title feat(transformers): add X-Codec (v4.54.1) feat(transformers): add X-Codec (v4.57.1) Dec 4, 2025
Copy link
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 introduces the X-Codec model, a neural audio codec, to the library. The changes encompass the model's implementation, corresponding tests, and necessary updates to auto-classes and initialization files, primarily porting the model from PyTorch to MindSpore. My review identified a couple of issues within the new XcodecModel implementation: a duplicated parameter in a docstring and a bug in the construct method that affects its behavior when return_dict=False. I have provided specific suggestions to address these points.

if audio_codes is None:
audio_codes = self.encode(input_values, bandwidth, return_dict=False)

audio_values = self.decode(audio_codes, return_dict=return_dict)[0][..., :length]
Copy link
Contributor

Choose a reason for hiding this comment

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

high

There's a potential bug in this line. When return_dict=False, self.decode returns a tensor, and [0] performs slicing, which is likely not the intended behavior. When return_dict=True, it returns a ModelOutput object, and [0] correctly accesses the audio_values tensor.

To ensure correct behavior in both cases, you can call decode with return_dict=True unconditionally. This will always return a ModelOutput object, making the subsequent indexing safe.

Suggested change
audio_values = self.decode(audio_codes, return_dict=return_dict)[0][..., :length]
audio_values = self.decode(audio_codes, return_dict=True)[0][..., :length]

Comment on lines +556 to +557
bandwidth (`float`, *optional*):
Target bandwidth in kbps. Must be one of `config.target_bandwidths`. Defaults to the highest available bandwidth.
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The bandwidth parameter is documented twice in the construct method's docstring. This appears to be a copy-paste error and can be confusing. Please remove the duplicate entry.

@alien-0119 alien-0119 self-assigned this Dec 4, 2025
@alien-0119 alien-0119 added the new model add new model to mindone label Dec 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new model add new model to mindone

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant