bezzam HF Staff commited on
Commit
64bd034
·
verified ·
1 Parent(s): e2092dd

Initial commit

Browse files
Files changed (4) hide show
  1. README.md +138 -0
  2. config.json +128 -0
  3. model.safetensors +3 -0
  4. preprocessor_config.json +13 -0
README.md ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: cc-by-nc-4.0
4
+ pipeline_tag: feature-extraction
5
+ tags:
6
+ - audio
7
+ - codec
8
+ ---
9
+
10
+ # X-Codec2 (Transformers-native)
11
+
12
+ The X-Codec2 model was proposed in [Llasa: Scaling Train-Time and Inference-Time Compute for Llama-based Speech Synthesis](https://huggingface.co/papers/2502.04128).
13
+
14
+ X-Codec2 is a neural audio codec designed to improve speech synthesis and general audio generation for large language model (LLM) pipelines. It extends the original X-Codec by refining how semantic and acoustic information is integrated and tokenized, enabling efficient and high-fidelity audio representation.
15
+
16
+ About its architecture:
17
+ - **Unified Semantic-Acoustic Tokenization**: X-Codec2 fuses outputs from a semantic encoder (e.g., Wav2Vec2-BERT) and an acoustic encoder into a single embedding, capturing both high-level meaning (e.g., text content, emotion) and low-level audio details (e.g., timbre).
18
+ - **Single-Stage Feature Scalar Quantization (FSQ)**: Unlike the multi-layer residual VQ in most approaches (e.g., DAC, EnCodec, X-Codec, Mimi), X-Codec2 uses a single-layer of Feature Scalar Quantization (FSQ) for stability and compatibility with causal, autoregressive LLMs.
19
+ - **Transformer-Friendly Design**: The 1D token structure of X-Codec2 naturally aligns with the autoregressive modeling in LLMs like LLaMA, improving training efficiency and downstream compatibility.
20
+
21
+ This model was contributed by [Eric Bezzam](https://huggingface.co/bezzam) and [Steven Zheng](https://huggingface.co/Steveeeeeeen).
22
+ The original modeling code can be found [here](https://huggingface.co/HKUSTAudio/xcodec2/blob/main/modeling_xcodec2.py), while their training code is [here](https://github.com/zhenye234/X-Codec-2.0).
23
+
24
+
25
+ ## Setup
26
+
27
+ X-Codec2 is supported natively in 🤗 Transformers. Until it is part of an official Transformers release, install from source:
28
+
29
+ ```bash
30
+ pip install git+https://github.com/huggingface/transformers
31
+ ```
32
+
33
+ ## Usage example
34
+
35
+ Here is a quick example of how to encode and decode an audio using this model:
36
+
37
+ ```python
38
+ from datasets import Audio, load_dataset
39
+ from transformers import AutoFeatureExtractor, AutoModel
40
+
41
+ model_id = "HKUSTAudio/xcodec2-hf"
42
+ model = AutoModel.from_pretrained(model_id, device_map="auto")
43
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
44
+
45
+ dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
46
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
47
+ audio = dataset[0]["audio"]["array"]
48
+ inputs = feature_extractor(audio=audio, sampling_rate=feature_extractor.sampling_rate, return_tensors="pt").to(
49
+ model.device, model.dtype
50
+ )
51
+ print("Input waveform shape:", inputs["input_values"].shape)
52
+ # Input waveform shape: torch.Size([1, 1, 93760])
53
+
54
+ # encoder and decoder
55
+ audio_codes = model.encode(**inputs).audio_codes
56
+ print("Audio codes shape:", audio_codes.shape)
57
+ # Audio codes shape: torch.Size([1, 1, 293])
58
+ audio_values = model.decode(audio_codes).audio_values
59
+ print("Audio values shape:", audio_values.shape)
60
+ # Audio values shape: torch.Size([1, 1, 93760])
61
+
62
+ # Equivalently, you can do encoding and decoding in one step
63
+ model_output = model(**inputs)
64
+ audio_codes = model_output.audio_codes
65
+ audio_values = model_output.audio_values
66
+ ```
67
+
68
+ ### Batch processing
69
+
70
+ Unlike the original [release](https://huggingface.co/HKUSTAudio/xcodec2), this implementation also supports batched inputs.
71
+
72
+ ```python
73
+ from datasets import Audio, load_dataset
74
+ from transformers import AutoFeatureExtractor, AutoModel
75
+
76
+ batch_size = 2
77
+ model_id = "HKUSTAudio/xcodec2-hf"
78
+ model = AutoModel.from_pretrained(model_id, device_map="auto")
79
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
80
+
81
+ dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
82
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
83
+ audios = [dataset[i]["audio"]["array"] for i in range(batch_size)]
84
+ inputs = feature_extractor(audio=audios, sampling_rate=feature_extractor.sampling_rate, return_tensors="pt").to(
85
+ model.device, model.dtype
86
+ )
87
+ print("Input waveform shape:", inputs["input_values"].shape)
88
+ # Input waveform shape: torch.Size([2, 1, 93760])
89
+
90
+ # encoder and decoder
91
+ encoder_output = model.encode(**inputs)
92
+ audio_codes = encoder_output.audio_codes
93
+ print("Audio codes shape:", audio_codes.shape)
94
+ # Audio codes shape: torch.Size([2, 1, 293])
95
+ audio_values = model.decode(audio_codes).audio_values
96
+ print("Audio values shape:", audio_values.shape)
97
+ # Audio values shape: torch.Size([2, 1, 93760])
98
+
99
+ # Equivalently, you can do encoding and decoding in one step
100
+ model_output = model(**inputs)
101
+ audio_codes = model_output.audio_codes
102
+ audio_values = model_output.audio_values
103
+ ```
104
+
105
+ ### Speed-up with `torch.compile`
106
+
107
+ You can speed up inference with [`torch.compile`](https://pytorch.org/docs/stable/generated/torch.compile.html). The first few calls will be slower due to compilation overhead, but subsequent calls will be faster.
108
+
109
+ On an A100, we observed a speed-up of ~1.35 for a batch size of 4 ([script](https://gist.github.com/ebezzam/3b79481b5d48d8e35c4ecc582aee0cb3#file-benchmark_torch_compile-py)).
110
+
111
+ ```python
112
+ import torch
113
+ from datasets import Audio, load_dataset
114
+ from transformers import AutoFeatureExtractor, AutoModel
115
+
116
+ batch_size = 4
117
+ model_id = "HKUSTAudio/xcodec2-hf"
118
+ model = AutoModel.from_pretrained(model_id, device_map="auto")
119
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
120
+
121
+ dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
122
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
123
+ audios = [dataset[i]["audio"]["array"] for i in range(batch_size)]
124
+ inputs = feature_extractor(
125
+ audio=audios, sampling_rate=feature_extractor.sampling_rate, padding=True, return_tensors="pt"
126
+ ).to(model.device, model.dtype)
127
+
128
+ compiled_model = torch.compile(model, fullgraph=True)
129
+
130
+ # Warmup (includes compilation on first call)
131
+ for _ in range(10):
132
+ with torch.inference_mode():
133
+ _ = compiled_model(**inputs)
134
+
135
+ with torch.inference_mode():
136
+ output = compiled_model(**inputs)
137
+ print("Audio values shape:", output.audio_values.shape)
138
+ ```
config.json ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_dropout": 0.1,
3
+ "architectures": [
4
+ "Xcodec2Model"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "downsampling_ratios": [
9
+ 2,
10
+ 2,
11
+ 4,
12
+ 4,
13
+ 5
14
+ ],
15
+ "dtype": "float32",
16
+ "encoder_hidden_size": 48,
17
+ "head_dim": 64,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 1024,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 4096,
22
+ "max_position_embeddings": 4096,
23
+ "model_type": "xcodec2",
24
+ "num_attention_heads": 16,
25
+ "num_hidden_layers": 12,
26
+ "num_key_value_heads": 16,
27
+ "pad_token_id": null,
28
+ "quantization_dim": 2048,
29
+ "quantization_levels": [
30
+ 4,
31
+ 4,
32
+ 4,
33
+ 4,
34
+ 4,
35
+ 4,
36
+ 4,
37
+ 4
38
+ ],
39
+ "rms_norm_eps": 1e-06,
40
+ "rope_parameters": {
41
+ "rope_theta": 10000.0,
42
+ "rope_type": "default"
43
+ },
44
+ "sampling_rate": 16000,
45
+ "semantic_model_config": {
46
+ "_name_or_path": "facebook/w2v-bert-2.0",
47
+ "activation_dropout": 0.0,
48
+ "adapter_act": "relu",
49
+ "adapter_kernel_size": 3,
50
+ "adapter_stride": 2,
51
+ "add_adapter": false,
52
+ "apply_spec_augment": false,
53
+ "architectures": [
54
+ "Wav2Vec2BertModel"
55
+ ],
56
+ "attention_dropout": 0.0,
57
+ "bos_token_id": 1,
58
+ "classifier_proj_size": 768,
59
+ "codevector_dim": 768,
60
+ "conformer_conv_dropout": 0.1,
61
+ "contrastive_logits_temperature": 0.1,
62
+ "conv_depthwise_kernel_size": 31,
63
+ "ctc_loss_reduction": "sum",
64
+ "ctc_zero_infinity": false,
65
+ "diversity_loss_weight": 0.1,
66
+ "dtype": "float32",
67
+ "eos_token_id": 2,
68
+ "feat_proj_dropout": 0.0,
69
+ "feat_quantizer_dropout": 0.0,
70
+ "feature_projection_input_dim": 160,
71
+ "final_dropout": 0.1,
72
+ "hidden_act": "swish",
73
+ "hidden_dropout": 0.0,
74
+ "hidden_size": 1024,
75
+ "initializer_range": 0.02,
76
+ "intermediate_size": 4096,
77
+ "layer_norm_eps": 1e-05,
78
+ "layerdrop": 0.1,
79
+ "left_max_position_embeddings": 64,
80
+ "mask_feature_length": 10,
81
+ "mask_feature_min_masks": 0,
82
+ "mask_feature_prob": 0.0,
83
+ "mask_time_length": 10,
84
+ "mask_time_min_masks": 2,
85
+ "mask_time_prob": 0.05,
86
+ "max_source_positions": 5000,
87
+ "model_type": "wav2vec2-bert",
88
+ "num_adapter_layers": 1,
89
+ "num_attention_heads": 16,
90
+ "num_codevector_groups": 2,
91
+ "num_codevectors_per_group": 320,
92
+ "num_hidden_layers": 16,
93
+ "num_negatives": 100,
94
+ "output_hidden_size": 1024,
95
+ "pad_token_id": 0,
96
+ "position_embeddings_type": "relative_key",
97
+ "proj_codevector_dim": 768,
98
+ "right_max_position_embeddings": 8,
99
+ "rotary_embedding_base": 10000,
100
+ "tdnn_dilation": [
101
+ 1,
102
+ 2,
103
+ 3,
104
+ 1,
105
+ 1
106
+ ],
107
+ "tdnn_dim": [
108
+ 512,
109
+ 512,
110
+ 512,
111
+ 512,
112
+ 1500
113
+ ],
114
+ "tdnn_kernel": [
115
+ 5,
116
+ 3,
117
+ 3,
118
+ 1,
119
+ 1
120
+ ],
121
+ "use_intermediate_ffn_before_adapter": false,
122
+ "use_weighted_layer_sum": false,
123
+ "vocab_size": null,
124
+ "xvector_output_dim": 512
125
+ },
126
+ "tie_word_embeddings": false,
127
+ "transformers_version": "5.13.0.dev0"
128
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:611a63e4dff70c19bd4718d701bb7bc522acf6293a109ab62f5db2f7ff395114
3
+ size 2517231448
preprocessor_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "feature_extractor_type": "Xcodec2FeatureExtractor",
3
+ "feature_size": 80,
4
+ "frame_length": 400,
5
+ "frame_shift": 160,
6
+ "hop_length": 320,
7
+ "num_mel_bins": 80,
8
+ "padding_side": "right",
9
+ "padding_value": 1,
10
+ "return_attention_mask": true,
11
+ "sampling_rate": 16000,
12
+ "stride": 2
13
+ }