Prompt48 commited on
Commit
928b717
·
verified ·
1 Parent(s): a2df67d

Upload edit\Qwen3-TTS-test\.venv\Lib\site-packages\transformers\models\hubert\modular_hubert.py with huggingface_hub

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//hubert//modular_hubert.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Hubert model."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from ...activations import ACT2FN
23
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
24
+ from ...modeling_outputs import BaseModelOutput
25
+ from ...modeling_utils import PreTrainedModel
26
+ from ...utils import auto_docstring
27
+ from ..wav2vec2.modeling_wav2vec2 import (
28
+ Wav2Vec2Encoder,
29
+ Wav2Vec2EncoderStableLayerNorm,
30
+ Wav2Vec2FeatureEncoder,
31
+ Wav2Vec2ForCTC,
32
+ Wav2Vec2ForSequenceClassification,
33
+ Wav2Vec2Model,
34
+ Wav2Vec2SamePadLayer,
35
+ )
36
+ from .configuration_hubert import HubertConfig
37
+
38
+
39
+ _HIDDEN_STATES_START_POSITION = 1
40
+
41
+
42
+ class HubertPositionalConvEmbedding(nn.Module):
43
+ def __init__(self, config):
44
+ super().__init__()
45
+ self.conv = nn.Conv1d(
46
+ config.hidden_size,
47
+ config.hidden_size,
48
+ kernel_size=config.num_conv_pos_embeddings,
49
+ padding=config.num_conv_pos_embeddings // 2,
50
+ groups=config.num_conv_pos_embedding_groups,
51
+ )
52
+
53
+ self.batch_norm = None
54
+ if config.conv_pos_batch_norm:
55
+ self.batch_norm = nn.BatchNorm1d(config.hidden_size)
56
+ else:
57
+ weight_norm = nn.utils.weight_norm
58
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
59
+ weight_norm = nn.utils.parametrizations.weight_norm
60
+
61
+ if is_deepspeed_zero3_enabled():
62
+ import deepspeed
63
+
64
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
65
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
66
+ if hasattr(self.conv, "parametrizations"):
67
+ weight_g = self.conv.parametrizations.weight.original0
68
+ weight_v = self.conv.parametrizations.weight.original1
69
+ else:
70
+ weight_g = self.conv.weight_g
71
+ weight_v = self.conv.weight_v
72
+ deepspeed.zero.register_external_parameter(self, weight_v)
73
+ deepspeed.zero.register_external_parameter(self, weight_g)
74
+ else:
75
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
76
+
77
+ self.padding = HubertSamePadLayer(config.num_conv_pos_embeddings)
78
+ self.activation = ACT2FN[config.feat_extract_activation]
79
+
80
+ def forward(self, hidden_states):
81
+ hidden_states = hidden_states.transpose(1, 2)
82
+ if self.batch_norm is not None:
83
+ hidden_states = self.batch_norm(hidden_states)
84
+ hidden_states = self.conv(hidden_states)
85
+ hidden_states = self.padding(hidden_states)
86
+ hidden_states = self.activation(hidden_states)
87
+
88
+ hidden_states = hidden_states.transpose(1, 2)
89
+ return hidden_states
90
+
91
+
92
+ class HubertSamePadLayer(Wav2Vec2SamePadLayer):
93
+ pass
94
+
95
+
96
+ class HubertFeatureEncoder(Wav2Vec2FeatureEncoder):
97
+ pass
98
+
99
+
100
+ class HubertFeatureProjection(nn.Module):
101
+ def __init__(self, config):
102
+ super().__init__()
103
+ self.feat_proj_layer_norm = config.feat_proj_layer_norm
104
+ if self.feat_proj_layer_norm:
105
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
106
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
107
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
108
+
109
+ def forward(self, hidden_states):
110
+ # non-projected hidden states are needed for quantization
111
+ if self.feat_proj_layer_norm:
112
+ hidden_states = self.layer_norm(hidden_states)
113
+ hidden_states = self.projection(hidden_states)
114
+ hidden_states = self.dropout(hidden_states)
115
+ return hidden_states
116
+
117
+
118
+ class HubertEncoder(Wav2Vec2Encoder):
119
+ pass
120
+
121
+
122
+ class HubertEncoderStableLayerNorm(Wav2Vec2EncoderStableLayerNorm):
123
+ pass
124
+
125
+
126
+ @auto_docstring
127
+ class HubertPreTrainedModel(PreTrainedModel):
128
+ config: HubertConfig
129
+ base_model_prefix = "hubert"
130
+ main_input_name = "input_values"
131
+ supports_gradient_checkpointing = True
132
+ _supports_flash_attn = True
133
+ _supports_sdpa = True
134
+ _supports_flex_attn = True
135
+
136
+ def _init_weights(self, module):
137
+ """Initialize the weights"""
138
+ if isinstance(module, nn.Linear):
139
+ # Slightly different from the TF version which uses truncated_normal for initialization
140
+ # cf https://github.com/pytorch/pytorch/pull/5617
141
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
142
+ if module.bias is not None:
143
+ module.bias.data.zero_()
144
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm1d)):
145
+ module.bias.data.zero_()
146
+ module.weight.data.fill_(1.0)
147
+ elif isinstance(module, nn.Conv1d):
148
+ if is_deepspeed_zero3_enabled():
149
+ import deepspeed
150
+
151
+ if hasattr(module, "weight_v") and hasattr(module, "weight_g"):
152
+ with deepspeed.zero.GatheredParameters([module.weight_v, module.weight_g], modifier_rank=0):
153
+ nn.init.kaiming_normal_(module.weight.data)
154
+ else:
155
+ with deepspeed.zero.GatheredParameters(module.weight, modifier_rank=0):
156
+ nn.init.kaiming_normal_(module.weight.data)
157
+ else:
158
+ nn.init.kaiming_normal_(module.weight.data)
159
+
160
+ if module.bias is not None:
161
+ module.bias.data.zero_()
162
+ elif isinstance(module, HubertModel):
163
+ if hasattr(module, "masked_spec_embed"):
164
+ module.masked_spec_embed.data.uniform_()
165
+ elif isinstance(module, HubertForSequenceClassification):
166
+ if hasattr(module, "layer_weights"):
167
+ module.layer_weights.data.fill_(1.0 / (self.config.num_hidden_layers + 1))
168
+
169
+ def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
170
+ """
171
+ Computes the output length of the convolutional layers
172
+ """
173
+
174
+ def _conv_out_length(input_length, kernel_size, stride):
175
+ # 1D convolutional layer output length formula taken
176
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
177
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
178
+
179
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
180
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
181
+
182
+ return input_lengths
183
+
184
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
185
+ output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
186
+ batch_size = attention_mask.shape[0]
187
+
188
+ attention_mask = torch.zeros(
189
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
190
+ )
191
+ # these two operations makes sure that all values before the output lengths idxs are attended to
192
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
193
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
194
+ return attention_mask
195
+
196
+
197
+ class HubertModel(Wav2Vec2Model, HubertPreTrainedModel):
198
+ def __init__(self, config: HubertConfig):
199
+ super().__init__(config)
200
+ self.config = config
201
+ self.feature_extractor = HubertFeatureEncoder(config)
202
+ self.feature_projection = HubertFeatureProjection(config)
203
+
204
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
205
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
206
+
207
+ if config.do_stable_layer_norm:
208
+ self.encoder = HubertEncoderStableLayerNorm(config)
209
+ else:
210
+ self.encoder = HubertEncoder(config)
211
+
212
+ # Initialize weights and apply final processing
213
+ self.post_init()
214
+
215
+ del self.adapter
216
+
217
+ def freeze_feature_extractor(self):
218
+ raise AttributeError("Not needed for Hubert")
219
+
220
+ def freeze_feature_encoder(self):
221
+ raise AttributeError("Not needed for Hubert")
222
+
223
+ def forward(
224
+ self,
225
+ input_values: Optional[torch.Tensor],
226
+ attention_mask: Optional[torch.Tensor] = None,
227
+ mask_time_indices: Optional[torch.FloatTensor] = None,
228
+ output_attentions: Optional[bool] = None,
229
+ output_hidden_states: Optional[bool] = None,
230
+ return_dict: Optional[bool] = None,
231
+ ) -> Union[tuple, BaseModelOutput]:
232
+ r"""
233
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
234
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
235
+ masked extracted features in *config.proj_codevector_dim* space.
236
+
237
+ Example:
238
+
239
+ ```python
240
+ >>> from transformers import AutoProcessor, HubertModel
241
+ >>> from datasets import load_dataset
242
+
243
+ >>> processor = AutoProcessor.from_pretrained("facebook/hubert-large-ls960-ft")
244
+ >>> model = HubertModel.from_pretrained("facebook/hubert-large-ls960-ft")
245
+
246
+
247
+ >>> def map_to_array(example):
248
+ ... example["speech"] = example["audio"]["array"]
249
+ ... return example
250
+
251
+
252
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
253
+ >>> ds = ds.map(map_to_array)
254
+
255
+ >>> input_values = processor(ds["speech"][0], return_tensors="pt").input_values # Batch size 1
256
+ >>> hidden_states = model(input_values).last_hidden_state
257
+ ```"""
258
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
259
+ output_hidden_states = (
260
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
261
+ )
262
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
263
+
264
+ extract_features = self.feature_extractor(input_values)
265
+ extract_features = extract_features.transpose(1, 2)
266
+
267
+ if attention_mask is not None:
268
+ # compute reduced attention_mask corresponding to feature vectors
269
+ attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
270
+
271
+ hidden_states = self.feature_projection(extract_features)
272
+ hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices)
273
+
274
+ encoder_outputs = self.encoder(
275
+ hidden_states,
276
+ attention_mask=attention_mask,
277
+ output_attentions=output_attentions,
278
+ output_hidden_states=output_hidden_states,
279
+ return_dict=return_dict,
280
+ )
281
+
282
+ hidden_states = encoder_outputs[0]
283
+
284
+ if not return_dict:
285
+ return (hidden_states,) + encoder_outputs[1:]
286
+
287
+ return BaseModelOutput(
288
+ last_hidden_state=hidden_states,
289
+ hidden_states=encoder_outputs.hidden_states,
290
+ attentions=encoder_outputs.attentions,
291
+ )
292
+
293
+
294
+ class HubertForCTC(Wav2Vec2ForCTC):
295
+ pass
296
+
297
+
298
+ class HubertForSequenceClassification(Wav2Vec2ForSequenceClassification):
299
+ pass
300
+
301
+
302
+ __all__ = ["HubertForCTC", "HubertForSequenceClassification", "HubertModel", "HubertPreTrainedModel"]