Prompt48 commited on
Commit
16d0ac2
·
verified ·
1 Parent(s): 62d3a2e

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//hubert//modeling_hubert.py ADDED
@@ -0,0 +1,1285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/hubert/modular_hubert.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_hubert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ import warnings
23
+ from typing import Callable, Optional, Union
24
+
25
+ import numpy as np
26
+ import torch
27
+ import torch.nn as nn
28
+ from torch.nn import CrossEntropyLoss
29
+
30
+ from ...activations import ACT2FN
31
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
32
+ from ...integrations.fsdp import is_fsdp_managed_module
33
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
34
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
35
+ from ...modeling_layers import GradientCheckpointingLayer
36
+ from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
37
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from ...processing_utils import Unpack
39
+ from ...utils import auto_docstring, is_torch_flex_attn_available, logging
40
+ from .configuration_hubert import HubertConfig
41
+
42
+
43
+ if is_torch_flex_attn_available():
44
+ from ...integrations.flex_attention import make_flex_block_causal_mask
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ class HubertPositionalConvEmbedding(nn.Module):
51
+ def __init__(self, config):
52
+ super().__init__()
53
+ self.conv = nn.Conv1d(
54
+ config.hidden_size,
55
+ config.hidden_size,
56
+ kernel_size=config.num_conv_pos_embeddings,
57
+ padding=config.num_conv_pos_embeddings // 2,
58
+ groups=config.num_conv_pos_embedding_groups,
59
+ )
60
+
61
+ self.batch_norm = None
62
+ if config.conv_pos_batch_norm:
63
+ self.batch_norm = nn.BatchNorm1d(config.hidden_size)
64
+ else:
65
+ weight_norm = nn.utils.weight_norm
66
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
67
+ weight_norm = nn.utils.parametrizations.weight_norm
68
+
69
+ if is_deepspeed_zero3_enabled():
70
+ import deepspeed
71
+
72
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
73
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
74
+ if hasattr(self.conv, "parametrizations"):
75
+ weight_g = self.conv.parametrizations.weight.original0
76
+ weight_v = self.conv.parametrizations.weight.original1
77
+ else:
78
+ weight_g = self.conv.weight_g
79
+ weight_v = self.conv.weight_v
80
+ deepspeed.zero.register_external_parameter(self, weight_v)
81
+ deepspeed.zero.register_external_parameter(self, weight_g)
82
+ else:
83
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
84
+
85
+ self.padding = HubertSamePadLayer(config.num_conv_pos_embeddings)
86
+ self.activation = ACT2FN[config.feat_extract_activation]
87
+
88
+ def forward(self, hidden_states):
89
+ hidden_states = hidden_states.transpose(1, 2)
90
+ if self.batch_norm is not None:
91
+ hidden_states = self.batch_norm(hidden_states)
92
+ hidden_states = self.conv(hidden_states)
93
+ hidden_states = self.padding(hidden_states)
94
+ hidden_states = self.activation(hidden_states)
95
+
96
+ hidden_states = hidden_states.transpose(1, 2)
97
+ return hidden_states
98
+
99
+
100
+ class HubertSamePadLayer(nn.Module):
101
+ def __init__(self, num_conv_pos_embeddings):
102
+ super().__init__()
103
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
104
+
105
+ def forward(self, hidden_states):
106
+ if self.num_pad_remove > 0:
107
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
108
+ return hidden_states
109
+
110
+
111
+ class HubertNoLayerNormConvLayer(GradientCheckpointingLayer):
112
+ def __init__(self, config, layer_id=0):
113
+ super().__init__()
114
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
115
+ self.out_conv_dim = config.conv_dim[layer_id]
116
+
117
+ self.conv = nn.Conv1d(
118
+ self.in_conv_dim,
119
+ self.out_conv_dim,
120
+ kernel_size=config.conv_kernel[layer_id],
121
+ stride=config.conv_stride[layer_id],
122
+ bias=config.conv_bias,
123
+ )
124
+ self.activation = ACT2FN[config.feat_extract_activation]
125
+
126
+ def forward(self, hidden_states):
127
+ hidden_states = self.conv(hidden_states)
128
+ hidden_states = self.activation(hidden_states)
129
+ return hidden_states
130
+
131
+
132
+ class HubertLayerNormConvLayer(GradientCheckpointingLayer):
133
+ def __init__(self, config, layer_id=0):
134
+ super().__init__()
135
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
136
+ self.out_conv_dim = config.conv_dim[layer_id]
137
+
138
+ self.conv = nn.Conv1d(
139
+ self.in_conv_dim,
140
+ self.out_conv_dim,
141
+ kernel_size=config.conv_kernel[layer_id],
142
+ stride=config.conv_stride[layer_id],
143
+ bias=config.conv_bias,
144
+ )
145
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
146
+ self.activation = ACT2FN[config.feat_extract_activation]
147
+
148
+ def forward(self, hidden_states):
149
+ hidden_states = self.conv(hidden_states)
150
+
151
+ hidden_states = hidden_states.transpose(-2, -1)
152
+ hidden_states = self.layer_norm(hidden_states)
153
+ hidden_states = hidden_states.transpose(-2, -1)
154
+
155
+ hidden_states = self.activation(hidden_states)
156
+ return hidden_states
157
+
158
+
159
+ class HubertGroupNormConvLayer(GradientCheckpointingLayer):
160
+ def __init__(self, config, layer_id=0):
161
+ super().__init__()
162
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
163
+ self.out_conv_dim = config.conv_dim[layer_id]
164
+
165
+ self.conv = nn.Conv1d(
166
+ self.in_conv_dim,
167
+ self.out_conv_dim,
168
+ kernel_size=config.conv_kernel[layer_id],
169
+ stride=config.conv_stride[layer_id],
170
+ bias=config.conv_bias,
171
+ )
172
+ self.activation = ACT2FN[config.feat_extract_activation]
173
+
174
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
175
+
176
+ def forward(self, hidden_states):
177
+ hidden_states = self.conv(hidden_states)
178
+ hidden_states = self.layer_norm(hidden_states)
179
+ hidden_states = self.activation(hidden_states)
180
+ return hidden_states
181
+
182
+
183
+ class HubertFeatureEncoder(nn.Module):
184
+ """Construct the features from raw audio waveform"""
185
+
186
+ def __init__(self, config):
187
+ super().__init__()
188
+
189
+ if config.feat_extract_norm == "group":
190
+ conv_layers = [HubertGroupNormConvLayer(config, layer_id=0)] + [
191
+ HubertNoLayerNormConvLayer(config, layer_id=i + 1) for i in range(config.num_feat_extract_layers - 1)
192
+ ]
193
+ elif config.feat_extract_norm == "layer":
194
+ conv_layers = [HubertLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)]
195
+ else:
196
+ raise ValueError(
197
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
198
+ )
199
+ self.conv_layers = nn.ModuleList(conv_layers)
200
+ self.gradient_checkpointing = False
201
+ self._requires_grad = True
202
+
203
+ def _freeze_parameters(self):
204
+ for param in self.parameters():
205
+ param.requires_grad = False
206
+ self._requires_grad = False
207
+
208
+ def forward(self, input_values):
209
+ hidden_states = input_values[:, None]
210
+
211
+ # make sure hidden_states require grad for gradient_checkpointing
212
+ if self._requires_grad and self.training:
213
+ hidden_states.requires_grad = True
214
+
215
+ for conv_layer in self.conv_layers:
216
+ hidden_states = conv_layer(hidden_states)
217
+
218
+ return hidden_states
219
+
220
+
221
+ class HubertFeatureProjection(nn.Module):
222
+ def __init__(self, config):
223
+ super().__init__()
224
+ self.feat_proj_layer_norm = config.feat_proj_layer_norm
225
+ if self.feat_proj_layer_norm:
226
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
227
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
228
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
229
+
230
+ def forward(self, hidden_states):
231
+ # non-projected hidden states are needed for quantization
232
+ if self.feat_proj_layer_norm:
233
+ hidden_states = self.layer_norm(hidden_states)
234
+ hidden_states = self.projection(hidden_states)
235
+ hidden_states = self.dropout(hidden_states)
236
+ return hidden_states
237
+
238
+
239
+ def eager_attention_forward(
240
+ module: nn.Module,
241
+ query: torch.Tensor,
242
+ key: torch.Tensor,
243
+ value: torch.Tensor,
244
+ attention_mask: Optional[torch.Tensor],
245
+ scaling: Optional[float] = None,
246
+ dropout: float = 0.0,
247
+ head_mask: Optional[torch.Tensor] = None,
248
+ **kwargs,
249
+ ):
250
+ if scaling is None:
251
+ scaling = query.size(-1) ** -0.5
252
+
253
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
254
+ if attention_mask is not None:
255
+ attn_weights = attn_weights + attention_mask
256
+
257
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
258
+
259
+ if head_mask is not None:
260
+ attn_weights = attn_weights * head_mask.view(1, -1, 1, 1)
261
+
262
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
263
+ attn_output = torch.matmul(attn_weights, value)
264
+ attn_output = attn_output.transpose(1, 2).contiguous()
265
+
266
+ return attn_output, attn_weights
267
+
268
+
269
+ class HubertAttention(nn.Module):
270
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
271
+
272
+ def __init__(
273
+ self,
274
+ embed_dim: int,
275
+ num_heads: int,
276
+ dropout: float = 0.0,
277
+ is_decoder: bool = False,
278
+ bias: bool = True,
279
+ is_causal: bool = False,
280
+ config: Optional[HubertConfig] = None,
281
+ ):
282
+ super().__init__()
283
+ self.embed_dim = embed_dim
284
+ self.num_heads = num_heads
285
+ self.dropout = dropout
286
+ self.head_dim = embed_dim // num_heads
287
+ self.config = config
288
+
289
+ if (self.head_dim * num_heads) != self.embed_dim:
290
+ raise ValueError(
291
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
292
+ f" and `num_heads`: {num_heads})."
293
+ )
294
+ self.scaling = self.head_dim**-0.5
295
+ self.is_decoder = is_decoder
296
+ self.is_causal = is_causal
297
+
298
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
299
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
300
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
301
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
302
+
303
+ def forward(
304
+ self,
305
+ hidden_states: torch.Tensor,
306
+ key_value_states: Optional[torch.Tensor] = None,
307
+ attention_mask: Optional[torch.Tensor] = None,
308
+ layer_head_mask: Optional[torch.Tensor] = None,
309
+ output_attentions: Optional[bool] = False,
310
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
311
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
312
+ **kwargs: Unpack[FlashAttentionKwargs],
313
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
314
+ """Input shape: Batch x Time x Channel"""
315
+
316
+ # if key_value_states are provided this layer is used as a cross-attention layer
317
+ # for the decoder
318
+ is_cross_attention = key_value_states is not None
319
+
320
+ # determine input shapes
321
+ bsz, tgt_len = hidden_states.shape[:-1]
322
+ src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
323
+
324
+ q_input_shape = (bsz, tgt_len, -1, self.head_dim)
325
+ kv_input_shape = (bsz, src_len, -1, self.head_dim)
326
+
327
+ # get query proj
328
+ query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
329
+
330
+ current_states = key_value_states if is_cross_attention else hidden_states
331
+ key_states = self.k_proj(current_states).view(*kv_input_shape).transpose(1, 2)
332
+ value_states = self.v_proj(current_states).view(*kv_input_shape).transpose(1, 2)
333
+
334
+ attention_interface: Callable = eager_attention_forward
335
+ if self.config._attn_implementation != "eager":
336
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
337
+
338
+ attn_output, attn_weights = attention_interface(
339
+ self,
340
+ query_states,
341
+ key_states,
342
+ value_states,
343
+ attention_mask,
344
+ dropout=0.0 if not self.training else self.dropout,
345
+ scaling=self.scaling,
346
+ output_attentions=output_attentions,
347
+ head_mask=layer_head_mask,
348
+ **kwargs,
349
+ )
350
+
351
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
352
+ attn_output = self.out_proj(attn_output)
353
+
354
+ return attn_output, attn_weights, None
355
+
356
+
357
+ class HubertFeedForward(nn.Module):
358
+ def __init__(self, config):
359
+ super().__init__()
360
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
361
+
362
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
363
+ if isinstance(config.hidden_act, str):
364
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
365
+ else:
366
+ self.intermediate_act_fn = config.hidden_act
367
+
368
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
369
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
370
+
371
+ def forward(self, hidden_states):
372
+ hidden_states = self.intermediate_dense(hidden_states)
373
+ hidden_states = self.intermediate_act_fn(hidden_states)
374
+ hidden_states = self.intermediate_dropout(hidden_states)
375
+
376
+ hidden_states = self.output_dense(hidden_states)
377
+ hidden_states = self.output_dropout(hidden_states)
378
+ return hidden_states
379
+
380
+
381
+ class HubertEncoderLayer(GradientCheckpointingLayer):
382
+ def __init__(self, config):
383
+ super().__init__()
384
+ self.attention = HubertAttention(
385
+ embed_dim=config.hidden_size,
386
+ num_heads=config.num_attention_heads,
387
+ dropout=config.attention_dropout,
388
+ is_decoder=False,
389
+ config=config,
390
+ )
391
+
392
+ self.dropout = nn.Dropout(config.hidden_dropout)
393
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
394
+ self.feed_forward = HubertFeedForward(config)
395
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
396
+
397
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
398
+ attn_residual = hidden_states
399
+ hidden_states, attn_weights, _ = self.attention(
400
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
401
+ )
402
+ hidden_states = self.dropout(hidden_states)
403
+ hidden_states = attn_residual + hidden_states
404
+
405
+ hidden_states = self.layer_norm(hidden_states)
406
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
407
+ hidden_states = self.final_layer_norm(hidden_states)
408
+
409
+ outputs = (hidden_states,)
410
+
411
+ if output_attentions:
412
+ outputs += (attn_weights,)
413
+
414
+ return outputs
415
+
416
+
417
+ class HubertEncoder(nn.Module):
418
+ def __init__(self, config):
419
+ super().__init__()
420
+ self.config = config
421
+ self.pos_conv_embed = HubertPositionalConvEmbedding(config)
422
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
423
+ self.dropout = nn.Dropout(config.hidden_dropout)
424
+ self.layers = nn.ModuleList([HubertEncoderLayer(config) for _ in range(config.num_hidden_layers)])
425
+ self.gradient_checkpointing = False
426
+
427
+ def forward(
428
+ self,
429
+ hidden_states: torch.tensor,
430
+ attention_mask: Optional[torch.Tensor] = None,
431
+ output_attentions: bool = False,
432
+ output_hidden_states: bool = False,
433
+ return_dict: bool = True,
434
+ ):
435
+ all_hidden_states = () if output_hidden_states else None
436
+ all_self_attentions = () if output_attentions else None
437
+
438
+ if attention_mask is not None:
439
+ # make sure padded tokens output 0
440
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
441
+ hidden_states[~expand_attention_mask] = 0
442
+
443
+ attention_mask = self._update_full_mask(
444
+ attention_mask,
445
+ hidden_states,
446
+ )
447
+
448
+ position_embeddings = self.pos_conv_embed(hidden_states)
449
+ hidden_states = hidden_states + position_embeddings
450
+ hidden_states = self.layer_norm(hidden_states)
451
+ hidden_states = self.dropout(hidden_states)
452
+
453
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
454
+
455
+ for layer in self.layers:
456
+ if output_hidden_states:
457
+ all_hidden_states = all_hidden_states + (hidden_states,)
458
+
459
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
460
+ dropout_probability = torch.rand([])
461
+
462
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
463
+ if not skip_the_layer or synced_gpus:
464
+ # under fsdp or deepspeed zero3 all gpus must run in sync
465
+ layer_outputs = layer(
466
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
467
+ )
468
+ hidden_states = layer_outputs[0]
469
+
470
+ if skip_the_layer:
471
+ layer_outputs = (None, None)
472
+
473
+ if output_attentions:
474
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
475
+
476
+ if output_hidden_states:
477
+ all_hidden_states = all_hidden_states + (hidden_states,)
478
+
479
+ if not return_dict:
480
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
481
+ return BaseModelOutput(
482
+ last_hidden_state=hidden_states,
483
+ hidden_states=all_hidden_states,
484
+ attentions=all_self_attentions,
485
+ )
486
+
487
+ def _update_full_mask(
488
+ self,
489
+ attention_mask: Union[torch.Tensor, None],
490
+ inputs_embeds: torch.Tensor,
491
+ ):
492
+ if attention_mask is not None:
493
+ if self.config._attn_implementation == "flash_attention_2":
494
+ attention_mask = attention_mask if 0 in attention_mask else None
495
+ elif self.config._attn_implementation == "sdpa":
496
+ # output_attentions=True & head_mask can not be supported when using SDPA, fall back to
497
+ # the manual implementation that requires a 4D causal mask in all cases.
498
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
499
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
500
+ elif self.config._attn_implementation == "flex_attention":
501
+ if isinstance(attention_mask, torch.Tensor):
502
+ attention_mask = make_flex_block_causal_mask(attention_mask, is_causal=False)
503
+ else:
504
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
505
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
506
+
507
+ return attention_mask
508
+
509
+
510
+ class HubertAttnAdapterLayer(nn.Module):
511
+ def __init__(self, config):
512
+ """
513
+ Implements adapter modules directly with 3D tensor weight as parameters and without using ModuleList to speed
514
+ up training throughput.
515
+ """
516
+ super().__init__()
517
+ self.input_dim = config.adapter_attn_dim
518
+ self.hidden_dim = config.hidden_size
519
+
520
+ self.norm = nn.LayerNorm(self.hidden_dim)
521
+ self.linear_1 = nn.Linear(self.hidden_dim, self.input_dim)
522
+ self.act_fn = nn.ReLU()
523
+ self.linear_2 = nn.Linear(self.input_dim, self.hidden_dim)
524
+
525
+ def forward(self, hidden_states: torch.FloatTensor):
526
+ hidden_states = self.norm(hidden_states)
527
+
528
+ hidden_states = self.linear_1(hidden_states)
529
+ hidden_states = self.act_fn(hidden_states)
530
+ hidden_states = self.linear_2(hidden_states)
531
+
532
+ return hidden_states
533
+
534
+
535
+ class HubertEncoderLayerStableLayerNorm(GradientCheckpointingLayer):
536
+ def __init__(self, config):
537
+ super().__init__()
538
+ self.attention = HubertAttention(
539
+ embed_dim=config.hidden_size,
540
+ num_heads=config.num_attention_heads,
541
+ dropout=config.attention_dropout,
542
+ is_decoder=False,
543
+ config=config,
544
+ )
545
+ self.dropout = nn.Dropout(config.hidden_dropout)
546
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
547
+ self.feed_forward = HubertFeedForward(config)
548
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
549
+
550
+ if getattr(config, "adapter_attn_dim", None) is not None:
551
+ self.adapter_layer = HubertAttnAdapterLayer(config)
552
+ else:
553
+ self.adapter_layer = None
554
+
555
+ def forward(
556
+ self,
557
+ hidden_states: torch.Tensor,
558
+ attention_mask: Optional[torch.Tensor] = None,
559
+ output_attentions: bool = False,
560
+ ):
561
+ attn_residual = hidden_states
562
+ hidden_states = self.layer_norm(hidden_states)
563
+ hidden_states, attn_weights, _ = self.attention(
564
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
565
+ )
566
+ hidden_states = self.dropout(hidden_states)
567
+ hidden_states = attn_residual + hidden_states
568
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
569
+
570
+ if self.adapter_layer is not None:
571
+ hidden_states = hidden_states + self.adapter_layer(hidden_states)
572
+
573
+ outputs = (hidden_states,)
574
+
575
+ if output_attentions:
576
+ outputs += (attn_weights,)
577
+
578
+ return outputs
579
+
580
+
581
+ class HubertEncoderStableLayerNorm(nn.Module):
582
+ def __init__(self, config):
583
+ super().__init__()
584
+ self.config = config
585
+ self.pos_conv_embed = HubertPositionalConvEmbedding(config)
586
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
587
+ self.dropout = nn.Dropout(config.hidden_dropout)
588
+ self.layers = nn.ModuleList(
589
+ [HubertEncoderLayerStableLayerNorm(config) for _ in range(config.num_hidden_layers)]
590
+ )
591
+ self.gradient_checkpointing = False
592
+
593
+ def forward(
594
+ self,
595
+ hidden_states,
596
+ attention_mask=None,
597
+ output_attentions=False,
598
+ output_hidden_states=False,
599
+ return_dict=True,
600
+ ):
601
+ all_hidden_states = () if output_hidden_states else None
602
+ all_self_attentions = () if output_attentions else None
603
+
604
+ if attention_mask is not None:
605
+ # make sure padded tokens output 0
606
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
607
+ hidden_states[~expand_attention_mask] = 0
608
+
609
+ attention_mask = self._update_full_mask(
610
+ attention_mask,
611
+ hidden_states,
612
+ )
613
+
614
+ position_embeddings = self.pos_conv_embed(hidden_states)
615
+ hidden_states = hidden_states + position_embeddings
616
+ hidden_states = self.dropout(hidden_states)
617
+
618
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
619
+
620
+ for layer in self.layers:
621
+ if output_hidden_states:
622
+ all_hidden_states = all_hidden_states + (hidden_states,)
623
+
624
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
625
+ dropout_probability = torch.rand([])
626
+
627
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
628
+ if not skip_the_layer or synced_gpus:
629
+ # under fsdp or deepspeed zero3 all gpus must run in sync
630
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
631
+ layer_outputs = layer(
632
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
633
+ )
634
+ hidden_states = layer_outputs[0]
635
+
636
+ if skip_the_layer:
637
+ layer_outputs = (None, None)
638
+
639
+ if output_attentions:
640
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
641
+
642
+ hidden_states = self.layer_norm(hidden_states)
643
+
644
+ if output_hidden_states:
645
+ all_hidden_states = all_hidden_states + (hidden_states,)
646
+
647
+ if not return_dict:
648
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
649
+ return BaseModelOutput(
650
+ last_hidden_state=hidden_states,
651
+ hidden_states=all_hidden_states,
652
+ attentions=all_self_attentions,
653
+ )
654
+
655
+ def _update_full_mask(
656
+ self,
657
+ attention_mask: Union[torch.Tensor, None],
658
+ inputs_embeds: torch.Tensor,
659
+ ):
660
+ if attention_mask is not None:
661
+ if self.config._attn_implementation == "flash_attention_2":
662
+ attention_mask = attention_mask if 0 in attention_mask else None
663
+ elif self.config._attn_implementation == "sdpa":
664
+ # output_attentions=True & head_mask can not be supported when using SDPA, fall back to
665
+ # the manual implementation that requires a 4D causal mask in all cases.
666
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
667
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
668
+ elif self.config._attn_implementation == "flex_attention":
669
+ if isinstance(attention_mask, torch.Tensor):
670
+ attention_mask = make_flex_block_causal_mask(attention_mask, is_causal=False)
671
+ else:
672
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
673
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
674
+
675
+ return attention_mask
676
+
677
+
678
+ @auto_docstring
679
+ class HubertPreTrainedModel(PreTrainedModel):
680
+ config: HubertConfig
681
+ base_model_prefix = "hubert"
682
+ main_input_name = "input_values"
683
+ supports_gradient_checkpointing = True
684
+ _supports_flash_attn = True
685
+ _supports_sdpa = True
686
+ _supports_flex_attn = True
687
+
688
+ def _init_weights(self, module):
689
+ """Initialize the weights"""
690
+ if isinstance(module, nn.Linear):
691
+ # Slightly different from the TF version which uses truncated_normal for initialization
692
+ # cf https://github.com/pytorch/pytorch/pull/5617
693
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
694
+ if module.bias is not None:
695
+ module.bias.data.zero_()
696
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm1d)):
697
+ module.bias.data.zero_()
698
+ module.weight.data.fill_(1.0)
699
+ elif isinstance(module, nn.Conv1d):
700
+ if is_deepspeed_zero3_enabled():
701
+ import deepspeed
702
+
703
+ if hasattr(module, "weight_v") and hasattr(module, "weight_g"):
704
+ with deepspeed.zero.GatheredParameters([module.weight_v, module.weight_g], modifier_rank=0):
705
+ nn.init.kaiming_normal_(module.weight.data)
706
+ else:
707
+ with deepspeed.zero.GatheredParameters(module.weight, modifier_rank=0):
708
+ nn.init.kaiming_normal_(module.weight.data)
709
+ else:
710
+ nn.init.kaiming_normal_(module.weight.data)
711
+
712
+ if module.bias is not None:
713
+ module.bias.data.zero_()
714
+ elif isinstance(module, HubertModel):
715
+ if hasattr(module, "masked_spec_embed"):
716
+ module.masked_spec_embed.data.uniform_()
717
+ elif isinstance(module, HubertForSequenceClassification):
718
+ if hasattr(module, "layer_weights"):
719
+ module.layer_weights.data.fill_(1.0 / (self.config.num_hidden_layers + 1))
720
+
721
+ def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
722
+ """
723
+ Computes the output length of the convolutional layers
724
+ """
725
+
726
+ def _conv_out_length(input_length, kernel_size, stride):
727
+ # 1D convolutional layer output length formula taken
728
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
729
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
730
+
731
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
732
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
733
+
734
+ return input_lengths
735
+
736
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
737
+ output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
738
+ batch_size = attention_mask.shape[0]
739
+
740
+ attention_mask = torch.zeros(
741
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
742
+ )
743
+ # these two operations makes sure that all values before the output lengths idxs are attended to
744
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
745
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
746
+ return attention_mask
747
+
748
+
749
+ def _compute_mask_indices(
750
+ shape: tuple[int, int],
751
+ mask_prob: float,
752
+ mask_length: int,
753
+ attention_mask: Optional[torch.LongTensor] = None,
754
+ min_masks: int = 0,
755
+ ) -> np.ndarray:
756
+ """
757
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
758
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
759
+ CPU as part of the preprocessing during training.
760
+
761
+ Args:
762
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
763
+ the first element is the batch size and the second element is the length of the axis to span.
764
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
765
+ independently generated mask spans of length `mask_length` is computed by
766
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
767
+ actual percentage will be smaller.
768
+ mask_length: size of the mask
769
+ min_masks: minimum number of masked spans
770
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
771
+ each batch dimension.
772
+ """
773
+ batch_size, sequence_length = shape
774
+
775
+ if mask_length < 1:
776
+ raise ValueError("`mask_length` has to be bigger than 0.")
777
+
778
+ if mask_length > sequence_length:
779
+ raise ValueError(
780
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
781
+ f" and `sequence_length`: {sequence_length}`"
782
+ )
783
+
784
+ # epsilon is used for probabilistic rounding
785
+ epsilon = np.random.rand(1).item()
786
+
787
+ def compute_num_masked_span(input_length):
788
+ """Given input length, compute how many spans should be masked"""
789
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
790
+ num_masked_span = max(num_masked_span, min_masks)
791
+
792
+ # make sure num masked span <= sequence_length
793
+ if num_masked_span * mask_length > sequence_length:
794
+ num_masked_span = sequence_length // mask_length
795
+
796
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
797
+ if input_length - (mask_length - 1) < num_masked_span:
798
+ num_masked_span = max(input_length - (mask_length - 1), 0)
799
+
800
+ return num_masked_span
801
+
802
+ # compute number of masked spans in batch
803
+ input_lengths = (
804
+ attention_mask.detach().sum(-1).tolist()
805
+ if attention_mask is not None
806
+ else [sequence_length for _ in range(batch_size)]
807
+ )
808
+
809
+ # SpecAugment mask to fill
810
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
811
+ spec_aug_mask_idxs = []
812
+
813
+ max_num_masked_span = compute_num_masked_span(sequence_length)
814
+
815
+ if max_num_masked_span == 0:
816
+ return spec_aug_mask
817
+
818
+ for input_length in input_lengths:
819
+ # compute num of masked spans for this input
820
+ num_masked_span = compute_num_masked_span(input_length)
821
+
822
+ # get random indices to mask
823
+ spec_aug_mask_idx = np.random.choice(
824
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
825
+ )
826
+
827
+ # pick first sampled index that will serve as a dummy index to pad vector
828
+ # to ensure same dimension for all batches due to probabilistic rounding
829
+ # Picking first sample just pads those vectors twice.
830
+ if len(spec_aug_mask_idx) == 0:
831
+ # this case can only happen if `input_length` is strictly smaller then
832
+ # `sequence_length` in which case the last token has to be a padding
833
+ # token which we can use as a dummy mask id
834
+ dummy_mask_idx = sequence_length - 1
835
+ else:
836
+ dummy_mask_idx = spec_aug_mask_idx[0]
837
+
838
+ spec_aug_mask_idx = np.concatenate(
839
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
840
+ )
841
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
842
+
843
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
844
+
845
+ # expand masked indices to masked spans
846
+ spec_aug_mask_idxs = np.broadcast_to(
847
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
848
+ )
849
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
850
+
851
+ # add offset to the starting indexes so that indexes now create a span
852
+ offsets = np.arange(mask_length)[None, None, :]
853
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
854
+ batch_size, max_num_masked_span * mask_length
855
+ )
856
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
857
+
858
+ # ensure that we cannot have indices larger than sequence_length
859
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
860
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
861
+
862
+ # scatter indices to mask
863
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
864
+
865
+ return spec_aug_mask
866
+
867
+
868
+ @auto_docstring
869
+ class HubertModel(HubertPreTrainedModel):
870
+ def __init__(self, config: HubertConfig):
871
+ super().__init__(config)
872
+ self.config = config
873
+ self.feature_extractor = HubertFeatureEncoder(config)
874
+ self.feature_projection = HubertFeatureProjection(config)
875
+
876
+ # model only needs masking vector if mask prob is > 0.0
877
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
878
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
879
+
880
+ if config.do_stable_layer_norm:
881
+ self.encoder = HubertEncoderStableLayerNorm(config)
882
+ else:
883
+ self.encoder = HubertEncoder(config)
884
+
885
+ # Initialize weights and apply final processing
886
+ self.post_init()
887
+
888
+ def _mask_hidden_states(
889
+ self,
890
+ hidden_states: torch.FloatTensor,
891
+ mask_time_indices: Optional[torch.FloatTensor] = None,
892
+ attention_mask: Optional[torch.LongTensor] = None,
893
+ ):
894
+ """
895
+ Masks extracted features along time axis and/or along feature axis according to
896
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
897
+ """
898
+
899
+ # `config.apply_spec_augment` can set masking to False
900
+ if not getattr(self.config, "apply_spec_augment", True):
901
+ return hidden_states
902
+
903
+ # generate indices & apply SpecAugment along time axis
904
+ batch_size, sequence_length, hidden_size = hidden_states.size()
905
+
906
+ if mask_time_indices is not None:
907
+ # apply SpecAugment along time axis with given mask_time_indices
908
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
909
+ elif self.config.mask_time_prob > 0 and self.training:
910
+ mask_time_indices = _compute_mask_indices(
911
+ (batch_size, sequence_length),
912
+ mask_prob=self.config.mask_time_prob,
913
+ mask_length=self.config.mask_time_length,
914
+ attention_mask=attention_mask,
915
+ min_masks=self.config.mask_time_min_masks,
916
+ )
917
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
918
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
919
+
920
+ if self.config.mask_feature_prob > 0 and self.training:
921
+ # generate indices & apply SpecAugment along feature axis
922
+ mask_feature_indices = _compute_mask_indices(
923
+ (batch_size, hidden_size),
924
+ mask_prob=self.config.mask_feature_prob,
925
+ mask_length=self.config.mask_feature_length,
926
+ min_masks=self.config.mask_feature_min_masks,
927
+ )
928
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
929
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
930
+ hidden_states[mask_feature_indices] = 0
931
+
932
+ return hidden_states
933
+
934
+ @auto_docstring
935
+ def forward(
936
+ self,
937
+ input_values: Optional[torch.Tensor],
938
+ attention_mask: Optional[torch.Tensor] = None,
939
+ mask_time_indices: Optional[torch.FloatTensor] = None,
940
+ output_attentions: Optional[bool] = None,
941
+ output_hidden_states: Optional[bool] = None,
942
+ return_dict: Optional[bool] = None,
943
+ ) -> Union[tuple, BaseModelOutput]:
944
+ r"""
945
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
946
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
947
+ masked extracted features in *config.proj_codevector_dim* space.
948
+
949
+ Example:
950
+
951
+ ```python
952
+ >>> from transformers import AutoProcessor, HubertModel
953
+ >>> from datasets import load_dataset
954
+
955
+ >>> processor = AutoProcessor.from_pretrained("facebook/hubert-large-ls960-ft")
956
+ >>> model = HubertModel.from_pretrained("facebook/hubert-large-ls960-ft")
957
+
958
+
959
+ >>> def map_to_array(example):
960
+ ... example["speech"] = example["audio"]["array"]
961
+ ... return example
962
+
963
+
964
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
965
+ >>> ds = ds.map(map_to_array)
966
+
967
+ >>> input_values = processor(ds["speech"][0], return_tensors="pt").input_values # Batch size 1
968
+ >>> hidden_states = model(input_values).last_hidden_state
969
+ ```"""
970
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
971
+ output_hidden_states = (
972
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
973
+ )
974
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
975
+
976
+ extract_features = self.feature_extractor(input_values)
977
+ extract_features = extract_features.transpose(1, 2)
978
+
979
+ if attention_mask is not None:
980
+ # compute reduced attention_mask corresponding to feature vectors
981
+ attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
982
+
983
+ hidden_states = self.feature_projection(extract_features)
984
+ hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices)
985
+
986
+ encoder_outputs = self.encoder(
987
+ hidden_states,
988
+ attention_mask=attention_mask,
989
+ output_attentions=output_attentions,
990
+ output_hidden_states=output_hidden_states,
991
+ return_dict=return_dict,
992
+ )
993
+
994
+ hidden_states = encoder_outputs[0]
995
+
996
+ if not return_dict:
997
+ return (hidden_states,) + encoder_outputs[1:]
998
+
999
+ return BaseModelOutput(
1000
+ last_hidden_state=hidden_states,
1001
+ hidden_states=encoder_outputs.hidden_states,
1002
+ attentions=encoder_outputs.attentions,
1003
+ )
1004
+
1005
+
1006
+ _HIDDEN_STATES_START_POSITION = 1
1007
+
1008
+
1009
+ @auto_docstring(
1010
+ custom_intro="""
1011
+ Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
1012
+ """
1013
+ )
1014
+ class HubertForCTC(HubertPreTrainedModel):
1015
+ def __init__(self, config, target_lang: Optional[str] = None):
1016
+ r"""
1017
+ target_lang (`str`, *optional*):
1018
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
1019
+ adapter.<lang>.bin. Only relevant when using an instance of [`HubertForCTC`] with adapters. Uses 'eng' by
1020
+ default.
1021
+ """
1022
+ super().__init__(config)
1023
+
1024
+ self.hubert = HubertModel(config)
1025
+ self.dropout = nn.Dropout(config.final_dropout)
1026
+
1027
+ self.target_lang = target_lang
1028
+
1029
+ if config.vocab_size is None:
1030
+ raise ValueError(
1031
+ f"You are trying to instantiate {self.__class__} with a configuration that "
1032
+ "does not define the vocabulary size of the language model head. Please "
1033
+ "instantiate the model as follows: `HubertForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
1034
+ "or define `vocab_size` of your model's configuration."
1035
+ )
1036
+ output_hidden_size = (
1037
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1038
+ )
1039
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
1040
+
1041
+ # Initialize weights and apply final processing
1042
+ self.post_init()
1043
+
1044
+ def tie_weights(self):
1045
+ """
1046
+ This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
1047
+ passing `target_lang=...` to `from_pretrained(...)`.
1048
+
1049
+ This method is **not** supposed to be called by the user and is prone to be changed in the future.
1050
+ """
1051
+
1052
+ # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
1053
+ # correctly load adapter layers for Hubert so that we do not have to introduce a new API to
1054
+ # [`PreTrainedModel`]. While slightly hacky, Hubert never has to tie input and output embeddings, so that it is
1055
+ # ok to repurpose this function here.
1056
+ target_lang = self.target_lang
1057
+
1058
+ if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
1059
+ raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
1060
+ elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
1061
+ logger.info("By default `target_lang` is set to 'eng'.")
1062
+ elif target_lang is not None:
1063
+ self.load_adapter(target_lang, force_load=True)
1064
+
1065
+ def freeze_feature_extractor(self):
1066
+ """
1067
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1068
+ not be updated during training.
1069
+ """
1070
+ warnings.warn(
1071
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1072
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1073
+ FutureWarning,
1074
+ )
1075
+ self.freeze_feature_encoder()
1076
+
1077
+ def freeze_feature_encoder(self):
1078
+ """
1079
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1080
+ not be updated during training.
1081
+ """
1082
+ self.hubert.feature_extractor._freeze_parameters()
1083
+
1084
+ def freeze_base_model(self):
1085
+ """
1086
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1087
+ be updated during training. Only the classification head will be updated.
1088
+ """
1089
+ for param in self.hubert.parameters():
1090
+ param.requires_grad = False
1091
+
1092
+ @auto_docstring
1093
+ def forward(
1094
+ self,
1095
+ input_values: Optional[torch.Tensor],
1096
+ attention_mask: Optional[torch.Tensor] = None,
1097
+ output_attentions: Optional[bool] = None,
1098
+ output_hidden_states: Optional[bool] = None,
1099
+ return_dict: Optional[bool] = None,
1100
+ labels: Optional[torch.Tensor] = None,
1101
+ ) -> Union[tuple, CausalLMOutput]:
1102
+ r"""
1103
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
1104
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
1105
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
1106
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
1107
+ config.vocab_size - 1]`.
1108
+ """
1109
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1110
+
1111
+ if labels is not None and labels.max() >= self.config.vocab_size:
1112
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1113
+
1114
+ outputs = self.hubert(
1115
+ input_values,
1116
+ attention_mask=attention_mask,
1117
+ output_attentions=output_attentions,
1118
+ output_hidden_states=output_hidden_states,
1119
+ return_dict=return_dict,
1120
+ )
1121
+
1122
+ hidden_states = outputs[0]
1123
+ hidden_states = self.dropout(hidden_states)
1124
+
1125
+ logits = self.lm_head(hidden_states)
1126
+
1127
+ loss = None
1128
+ if labels is not None:
1129
+ # retrieve loss input_lengths from attention_mask
1130
+ attention_mask = (
1131
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
1132
+ )
1133
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
1134
+
1135
+ # assuming that padded tokens are filled with -100
1136
+ # when not being attended to
1137
+ labels_mask = labels >= 0
1138
+ target_lengths = labels_mask.sum(-1)
1139
+ flattened_targets = labels.masked_select(labels_mask)
1140
+
1141
+ # ctc_loss doesn't support fp16
1142
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1143
+
1144
+ with torch.backends.cudnn.flags(enabled=False):
1145
+ loss = nn.functional.ctc_loss(
1146
+ log_probs,
1147
+ flattened_targets,
1148
+ input_lengths,
1149
+ target_lengths,
1150
+ blank=self.config.pad_token_id,
1151
+ reduction=self.config.ctc_loss_reduction,
1152
+ zero_infinity=self.config.ctc_zero_infinity,
1153
+ )
1154
+
1155
+ if not return_dict:
1156
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1157
+ return ((loss,) + output) if loss is not None else output
1158
+
1159
+ return CausalLMOutput(
1160
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1161
+ )
1162
+
1163
+
1164
+ @auto_docstring(
1165
+ custom_intro="""
1166
+ Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
1167
+ SUPERB Keyword Spotting.
1168
+ """
1169
+ )
1170
+ class HubertForSequenceClassification(HubertPreTrainedModel):
1171
+ def __init__(self, config):
1172
+ super().__init__(config)
1173
+
1174
+ if hasattr(config, "add_adapter") and config.add_adapter:
1175
+ raise ValueError(
1176
+ "Sequence classification does not support the use of Hubert adapters (config.add_adapter=True)"
1177
+ )
1178
+ self.hubert = HubertModel(config)
1179
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1180
+ if config.use_weighted_layer_sum:
1181
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1182
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
1183
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
1184
+
1185
+ # Initialize weights and apply final processing
1186
+ self.post_init()
1187
+
1188
+ def freeze_feature_extractor(self):
1189
+ """
1190
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1191
+ not be updated during training.
1192
+ """
1193
+ warnings.warn(
1194
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1195
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1196
+ FutureWarning,
1197
+ )
1198
+ self.freeze_feature_encoder()
1199
+
1200
+ def freeze_feature_encoder(self):
1201
+ """
1202
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1203
+ not be updated during training.
1204
+ """
1205
+ self.hubert.feature_extractor._freeze_parameters()
1206
+
1207
+ def freeze_base_model(self):
1208
+ """
1209
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1210
+ be updated during training. Only the classification head will be updated.
1211
+ """
1212
+ for param in self.hubert.parameters():
1213
+ param.requires_grad = False
1214
+
1215
+ @auto_docstring
1216
+ def forward(
1217
+ self,
1218
+ input_values: Optional[torch.Tensor],
1219
+ attention_mask: Optional[torch.Tensor] = None,
1220
+ output_attentions: Optional[bool] = None,
1221
+ output_hidden_states: Optional[bool] = None,
1222
+ return_dict: Optional[bool] = None,
1223
+ labels: Optional[torch.Tensor] = None,
1224
+ ) -> Union[tuple, SequenceClassifierOutput]:
1225
+ r"""
1226
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1227
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1228
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1229
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1230
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1231
+ into a tensor of type `torch.FloatTensor`. See [`HubertProcessor.__call__`] for details.
1232
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1233
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1234
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1235
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1236
+ """
1237
+
1238
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1239
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1240
+
1241
+ outputs = self.hubert(
1242
+ input_values,
1243
+ attention_mask=attention_mask,
1244
+ output_attentions=output_attentions,
1245
+ output_hidden_states=output_hidden_states,
1246
+ return_dict=return_dict,
1247
+ )
1248
+
1249
+ if self.config.use_weighted_layer_sum:
1250
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1251
+ hidden_states = torch.stack(hidden_states, dim=1)
1252
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1253
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1254
+ else:
1255
+ hidden_states = outputs[0]
1256
+
1257
+ hidden_states = self.projector(hidden_states)
1258
+ if attention_mask is None:
1259
+ pooled_output = hidden_states.mean(dim=1)
1260
+ else:
1261
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
1262
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
1263
+ hidden_states[~expand_padding_mask] = 0.0
1264
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
1265
+
1266
+ logits = self.classifier(pooled_output)
1267
+
1268
+ loss = None
1269
+ if labels is not None:
1270
+ loss_fct = CrossEntropyLoss()
1271
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1272
+
1273
+ if not return_dict:
1274
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1275
+ return ((loss,) + output) if loss is not None else output
1276
+
1277
+ return SequenceClassifierOutput(
1278
+ loss=loss,
1279
+ logits=logits,
1280
+ hidden_states=outputs.hidden_states,
1281
+ attentions=outputs.attentions,
1282
+ )
1283
+
1284
+
1285
+ __all__ = ["HubertForCTC", "HubertForSequenceClassification", "HubertModel", "HubertPreTrainedModel"]