huseinzol05 commited on
Commit
788e48e
·
verified ·
1 Parent(s): ab802f4

Upload model

Browse files
Files changed (4) hide show
  1. README.md +199 -0
  2. config.json +16 -0
  3. model.safetensors +3 -0
  4. modeling_xcodec2.py +165 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "HKUSTAudio/xcodec2",
3
+ "architectures": [
4
+ "XCodec2Model"
5
+ ],
6
+ "auto_map": {
7
+ "AutoModel": "modeling_xcodec2.XCodec2Model"
8
+ },
9
+ "codec_decoder_hidden_size": 1024,
10
+ "codec_encoder_hidden_size": 1024,
11
+ "model_type": "xcodec",
12
+ "semantic_hidden_size": 1024,
13
+ "torch_dtype": "float32",
14
+ "transformers_version": "4.44.2",
15
+ "use_vocos": true
16
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b6b739f220c9e64e525c104afe77002067fe90ba94f4b4110aa6314195b7fcd
3
+ size 3301612648
modeling_xcodec2.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from transformers import PreTrainedModel
4
+ from configuration_bigcodec import BigCodecConfig
5
+
6
+ # 请确保这些模块路径是正确的
7
+ from vq.codec_encoder import CodecEncoder_Transformer
8
+ from vq.codec_decoder_vocos import CodecDecoderVocos
9
+ from vq.module import SemanticEncoder
10
+ from transformers import AutoFeatureExtractor, Wav2Vec2BertModel
11
+ import torch.nn.functional as F
12
+ class XCodec2Model(PreTrainedModel):
13
+ config_class = BigCodecConfig
14
+
15
+ def __init__(self, config: BigCodecConfig):
16
+ super().__init__(config)
17
+
18
+ # 1) 语义模型
19
+ self.semantic_model = Wav2Vec2BertModel.from_pretrained(
20
+ "facebook/w2v-bert-2.0",
21
+ output_hidden_states=True
22
+ )
23
+ self.semantic_model.eval()
24
+
25
+ self.SemanticEncoder_module = SemanticEncoder(
26
+ config.semantic_hidden_size,
27
+ config.semantic_hidden_size,
28
+ config.semantic_hidden_size
29
+ )
30
+
31
+ # 2) Codec Encoder
32
+ self.CodecEnc = CodecEncoder_Transformer()
33
+
34
+ # 3) Codec Decoder
35
+ self.generator = CodecDecoderVocos()
36
+
37
+ # 4) 两个全连接层
38
+ self.fc_prior = nn.Linear(2048, 2048)
39
+ self.fc_post_a = nn.Linear(2048, 1024)
40
+ feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/w2v-bert-2.0")
41
+ self.feature_extractor = feature_extractor
42
+ self.avg_pooler = nn.AvgPool1d(2, stride=2)
43
+
44
+ def forward(self, input_waveform, input_features=None, sample_rate=16000):
45
+ """
46
+ 这里的 forward 不一定要叫 forward,也可以拆成别的方法;
47
+ 但是如果想兼容 pipeline,需要在 forward 里给出核心逻辑。
48
+
49
+ 参数:
50
+ input_waveform: [batch_size, waveform_length]
51
+ sample_rate: 默认 16000
52
+ 返回:
53
+ 重构后的语音音频 (Tensor)
54
+ """
55
+ # 1) 特征提取
56
+ # 如果需要 padding,可以在这里做
57
+ wav = input_waveform
58
+ with torch.no_grad():
59
+ if input_features is None:
60
+ pad_for_wav = (320 - (wav.shape[1] % 320))
61
+ wav = torch.nn.functional.pad(wav, (0, pad_for_wav))
62
+ padded = F.pad(wav, (160, 160, 0, 0))
63
+ input_features = self.feature_extractor(
64
+ padded.cpu().numpy(),
65
+ sampling_rate=sample_rate,
66
+ return_tensors="pt"
67
+ ).input_features.to(self.device)
68
+
69
+ # 2) 语义层
70
+ semantic_output = self.semantic_model(input_features)
71
+ semantic_hidden_16 = semantic_output.hidden_states[16] # 取第16层
72
+ semantic_hidden_16 = semantic_hidden_16.transpose(1, 2) # [batch, hidden_dim, frames]
73
+ semantic_encoded = self.SemanticEncoder_module(semantic_hidden_16)
74
+
75
+ # 3) codec encoder
76
+ wav = wav.to(self.device) # shape: [batch, 1, time]
77
+ vq_emb = self.CodecEnc(wav.unsqueeze(1)) # [batch, time//down, 1024] 只是示例
78
+ vq_emb = vq_emb.transpose(1, 2) # -> [batch, 1024, frames]
79
+
80
+ concat_emb = torch.cat([semantic_encoded, vq_emb], dim=1) # [batch, 1024 + 1024, frames]
81
+
82
+ # 5) fc_prior
83
+ concat_emb = self.fc_prior(concat_emb.transpose(1, 2)).transpose(1, 2)
84
+ concat_emb = self.avg_pooler(concat_emb)
85
+
86
+ # 6) decoder 的量化部分
87
+ _, vq_code, _ = self.generator(concat_emb, vq=True)
88
+ vq_post_emb = self.generator.quantizer.get_output_from_indices(vq_code.transpose(1, 2))
89
+ vq_post_emb = vq_post_emb.transpose(1, 2)
90
+
91
+ # 7) fc_post_a
92
+ vq_post_emb = self.fc_post_a(vq_post_emb.transpose(1, 2)).transpose(1, 2)
93
+
94
+ # 8) 最后解码成波形
95
+ recon_audio = self.generator(vq_post_emb.transpose(1, 2), vq=False)[0]
96
+ # recon_audio: [batch, time]
97
+ return recon_audio
98
+
99
+ def encode_code(self, input_waveform, sample_rate=16000):
100
+ """
101
+ 将输入的音频编码为代码表示。
102
+
103
+ 参数:
104
+ input_waveform: [batch_size, waveform_length]
105
+ sample_rate: 默认 16000
106
+ 返回:
107
+ 编码后的代码 (Tensor)
108
+ """
109
+ with torch.no_grad():
110
+
111
+
112
+ wav = input_waveform
113
+ pad_for_wav = (320 - (wav.shape[1] % 320))
114
+
115
+ wav = torch.nn.functional.pad(wav, (0, pad_for_wav))
116
+
117
+ input_features = self.feature_extractor(
118
+ F.pad(wav[0,:].cpu(), (160, 160)),
119
+ sampling_rate=sample_rate,
120
+ return_tensors="pt"
121
+ ).input_features.to(self.device) # [batch, frames, feat_dim]
122
+
123
+ # 2) 语义层
124
+ semantic_output = self.semantic_model(input_features)
125
+ semantic_hidden_16 = semantic_output.hidden_states[16] # 取第16层
126
+ semantic_hidden_16 = semantic_hidden_16.transpose(1, 2) # [batch, hidden_dim, frames]
127
+ semantic_encoded = self.SemanticEncoder_module(semantic_hidden_16)
128
+
129
+ # 3) codec encoder
130
+ wav = wav.to(self.device) # shape: [batch, 1, time]
131
+ vq_emb = self.CodecEnc(wav.unsqueeze(1)) # [batch, time//down, 1024] 只是示例
132
+ vq_emb = vq_emb.transpose(1, 2) # -> [batch, 1024, frames]
133
+
134
+ # 4) 拼接
135
+ concat_emb = torch.cat([semantic_encoded, vq_emb], dim=1) # [batch, 2048, frames]
136
+
137
+ # 5) fc_prior
138
+ concat_emb = self.fc_prior(concat_emb.transpose(1, 2)).transpose(1, 2)
139
+
140
+ # 6) decoder 的量化部分,获取code
141
+ concat_emb = self.avg_pooler(concat_emb)
142
+ _, vq_code, _ = self.generator(concat_emb, vq=True)
143
+ # vq_code: [batch, frames]
144
+ return vq_code
145
+
146
+ def decode_code(self, vq_code):
147
+ """
148
+ 将编码后的代码解码回音频。
149
+
150
+ 参数:
151
+ vq_code: 编码后的代码 (Tensor) [batch, frames]
152
+ 返回:
153
+ 解码后的音频 (Tensor) [batch, waveform_length]
154
+ """
155
+ with torch.no_grad():
156
+ # 获取量化后的嵌入
157
+ vq_post_emb = self.generator.quantizer.get_output_from_indices(vq_code.transpose(1, 2))
158
+ vq_post_emb = vq_post_emb.transpose(1, 2) # [batch, 1024, frames]
159
+
160
+ # 7) fc_post_a
161
+ vq_post_emb = self.fc_post_a(vq_post_emb.transpose(1, 2)).transpose(1, 2) # [batch, 1024, frames]
162
+
163
+ # 8) 最后解码成波形
164
+ recon_audio = self.generator(vq_post_emb.transpose(1, 2), vq=False)[0] # [batch, time]
165
+ return recon_audio