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

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//hubert//modeling_tf_hubert.py ADDED
@@ -0,0 +1,1671 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """TensorFlow Hubert model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import warnings
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+ import tensorflow as tf
24
+
25
+ from ...activations_tf import get_tf_activation
26
+ from ...modeling_tf_outputs import TFBaseModelOutput, TFCausalLMOutput
27
+ from ...modeling_tf_utils import (
28
+ TFPreTrainedModel,
29
+ get_initializer,
30
+ keras,
31
+ keras_serializable,
32
+ unpack_inputs,
33
+ )
34
+ from ...tf_utils import shape_list, stable_softmax
35
+ from ...utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ logging,
39
+ replace_return_docstrings,
40
+ )
41
+ from .configuration_hubert import HubertConfig
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ _CONFIG_FOR_DOC = "HubertConfig"
47
+
48
+
49
+ LARGE_NEGATIVE = -1e8
50
+
51
+
52
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2._sample_without_replacement
53
+ def _sample_without_replacement(distribution, num_samples):
54
+ """
55
+ Categorical sampling without replacement is currently not implemented. The gumbel-max trick will do for now - see
56
+ https://github.com/tensorflow/tensorflow/issues/9260 for more info
57
+ """
58
+ z = -tf.math.log(tf.random.uniform(shape_list(distribution), 0, 1))
59
+ _, indices = tf.nn.top_k(distribution + z, num_samples)
60
+ return indices
61
+
62
+
63
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2._scatter_values_on_batch_indices
64
+ def _scatter_values_on_batch_indices(values, batch_indices, output_shape):
65
+ """
66
+ Scatter function as in PyTorch with indices in format (batch_dim, indices)
67
+ """
68
+ indices_shape = shape_list(batch_indices)
69
+ # broadcast batch dim to indices_shape
70
+ broad_casted_batch_dims = tf.reshape(
71
+ tf.broadcast_to(tf.expand_dims(tf.range(indices_shape[0]), axis=-1), indices_shape), [1, -1]
72
+ )
73
+ # transform batch_indices to pair_indices
74
+ pair_indices = tf.transpose(tf.concat([broad_casted_batch_dims, tf.reshape(batch_indices, [1, -1])], 0))
75
+ # scatter values to pair indices
76
+ return tf.scatter_nd(pair_indices, tf.reshape(values, [-1]), output_shape)
77
+
78
+
79
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2._compute_mask_indices
80
+ def _compute_mask_indices(
81
+ shape: tuple[int, int],
82
+ mask_prob: float,
83
+ mask_length: int,
84
+ min_masks: int = 0,
85
+ ) -> tf.Tensor:
86
+ """
87
+ Computes random mask spans for a given shape
88
+
89
+ Args:
90
+ shape: the shape for which to compute masks.
91
+ should be of size 2 where first element is batch size and 2nd is timesteps
92
+ attention_mask: optional padding mask of the same size as shape, which will prevent masking padded elements
93
+ mask_prob:
94
+ probability for each token to be chosen as start of the span to be masked. this will be multiplied by
95
+ number of timesteps divided by length of mask span to mask approximately this percentage of all elements.
96
+ however due to overlaps, the actual number will be smaller (unless no_overlap is True)
97
+ mask_length: size of the mask
98
+ min_masks: minimum number of masked spans
99
+
100
+ Adapted from [fairseq's
101
+ data_utils.py](https://github.com/pytorch/fairseq/blob/e0788f7007a8473a76db573985031f3c94201e79/fairseq/data/data_utils.py#L376).
102
+ """
103
+ batch_size, sequence_length = shape
104
+
105
+ if mask_length < 1:
106
+ raise ValueError("`mask_length` has to be bigger than 0.")
107
+
108
+ tf.debugging.assert_less(
109
+ mask_length,
110
+ sequence_length,
111
+ message=(
112
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and"
113
+ f" `sequence_length`: {sequence_length}`"
114
+ ),
115
+ )
116
+
117
+ # compute number of masked spans in batch
118
+ num_masked_spans = mask_prob * tf.cast(sequence_length, tf.float32) / mask_length + tf.random.uniform((1,))
119
+ num_masked_spans = tf.maximum(num_masked_spans, min_masks)
120
+ num_masked_spans = tf.cast(num_masked_spans, tf.int32)
121
+
122
+ # make sure num masked indices <= sequence_length
123
+ num_masked_spans = tf.math.minimum(sequence_length // mask_length, num_masked_spans)
124
+ num_masked_spans = tf.squeeze(num_masked_spans)
125
+
126
+ # SpecAugment mask to fill
127
+ spec_aug_mask = tf.zeros((batch_size, sequence_length), dtype=tf.int32)
128
+
129
+ # uniform distribution to sample from, make sure that offset samples are < sequence_length
130
+ uniform_dist = tf.ones((batch_size, sequence_length - (mask_length - 1)))
131
+
132
+ # get random indices to mask
133
+ spec_aug_mask_idxs = _sample_without_replacement(uniform_dist, num_masked_spans)
134
+
135
+ # expand masked indices to masked spans
136
+ spec_aug_mask_idxs = tf.expand_dims(spec_aug_mask_idxs, -1)
137
+ spec_aug_mask_idxs = tf.tile(spec_aug_mask_idxs, (1, 1, mask_length))
138
+ spec_aug_mask_idxs = tf.reshape(spec_aug_mask_idxs, (batch_size, num_masked_spans * mask_length))
139
+
140
+ offsets = tf.range(mask_length)[tf.newaxis, tf.newaxis, :]
141
+ offsets = tf.tile(offsets, (batch_size, num_masked_spans, 1))
142
+ offsets = tf.reshape(offsets, (batch_size, num_masked_spans * mask_length))
143
+
144
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
145
+
146
+ # scatter indices to mask
147
+ spec_aug_mask = _scatter_values_on_batch_indices(
148
+ tf.ones_like(spec_aug_mask_idxs), spec_aug_mask_idxs, tf.shape(spec_aug_mask)
149
+ )
150
+
151
+ return spec_aug_mask
152
+
153
+
154
+ # Copied from transformers.models.bart.modeling_tf_bart._expand_mask
155
+ def _expand_mask(mask: tf.Tensor, tgt_len: int | None = None):
156
+ """
157
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
158
+ """
159
+ src_len = shape_list(mask)[1]
160
+ tgt_len = tgt_len if tgt_len is not None else src_len
161
+ one_cst = tf.constant(1.0)
162
+ mask = tf.cast(mask, dtype=one_cst.dtype)
163
+ expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
164
+
165
+ return (one_cst - expanded_mask) * LARGE_NEGATIVE
166
+
167
+
168
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2GroupNorm with Wav2Vec2->Hubert
169
+ class TFHubertGroupNorm(keras.layers.Layer):
170
+ """
171
+ From tensorflow-addons https://www.tensorflow.org/addons/api_docs/python/tfa/layers/GroupNormalization
172
+ """
173
+
174
+ def __init__(
175
+ self,
176
+ groups: int = 32,
177
+ axis: int = -1,
178
+ epsilon: float = 1e-3,
179
+ center: bool = True,
180
+ scale: bool = True,
181
+ beta_initializer: keras.initializers.Initializer = "zeros",
182
+ gamma_initializer: keras.initializers.Initializer = "ones",
183
+ beta_regularizer: keras.regularizers.Regularizer = None,
184
+ gamma_regularizer: keras.regularizers.Regularizer = None,
185
+ beta_constraint: keras.constraints.Constraint = None,
186
+ gamma_constraint: keras.constraints.Constraint = None,
187
+ **kwargs,
188
+ ):
189
+ super().__init__(**kwargs)
190
+ self.supports_masking = True
191
+ self.groups = groups
192
+ self.axis = axis
193
+ self.epsilon = epsilon
194
+ self.center = center
195
+ self.scale = scale
196
+ self.beta_initializer = keras.initializers.get(beta_initializer)
197
+ self.gamma_initializer = keras.initializers.get(gamma_initializer)
198
+ self.beta_regularizer = keras.regularizers.get(beta_regularizer)
199
+ self.gamma_regularizer = keras.regularizers.get(gamma_regularizer)
200
+ self.beta_constraint = keras.constraints.get(beta_constraint)
201
+ self.gamma_constraint = keras.constraints.get(gamma_constraint)
202
+ self._check_axis()
203
+
204
+ def build(self, input_shape):
205
+ self._check_if_input_shape_is_none(input_shape)
206
+ self._set_number_of_groups_for_instance_norm(input_shape)
207
+ self._check_size_of_dimensions(input_shape)
208
+ self._create_input_spec(input_shape)
209
+
210
+ self._add_gamma_weight(input_shape)
211
+ self._add_beta_weight(input_shape)
212
+ self.built = True
213
+ super().build(input_shape)
214
+
215
+ def call(self, inputs):
216
+ input_shape = keras.backend.int_shape(inputs)
217
+ tensor_input_shape = tf.shape(inputs)
218
+
219
+ reshaped_inputs, group_shape = self._reshape_into_groups(inputs, input_shape, tensor_input_shape)
220
+
221
+ normalized_inputs = self._apply_normalization(reshaped_inputs, input_shape)
222
+
223
+ is_instance_norm = (input_shape[self.axis] // self.groups) == 1
224
+ if not is_instance_norm:
225
+ outputs = tf.reshape(normalized_inputs, tensor_input_shape)
226
+ else:
227
+ outputs = normalized_inputs
228
+
229
+ return outputs
230
+
231
+ def get_config(self):
232
+ config = {
233
+ "groups": self.groups,
234
+ "axis": self.axis,
235
+ "epsilon": self.epsilon,
236
+ "center": self.center,
237
+ "scale": self.scale,
238
+ "beta_initializer": keras.initializers.serialize(self.beta_initializer),
239
+ "gamma_initializer": keras.initializers.serialize(self.gamma_initializer),
240
+ "beta_regularizer": keras.regularizers.serialize(self.beta_regularizer),
241
+ "gamma_regularizer": keras.regularizers.serialize(self.gamma_regularizer),
242
+ "beta_constraint": keras.constraints.serialize(self.beta_constraint),
243
+ "gamma_constraint": keras.constraints.serialize(self.gamma_constraint),
244
+ }
245
+ base_config = super().get_config()
246
+ return {**base_config, **config}
247
+
248
+ def compute_output_shape(self, input_shape):
249
+ return input_shape
250
+
251
+ def _reshape_into_groups(self, inputs, input_shape, tensor_input_shape):
252
+ group_shape = [tensor_input_shape[i] for i in range(len(input_shape))]
253
+ is_instance_norm = (input_shape[self.axis] // self.groups) == 1
254
+ if not is_instance_norm:
255
+ group_shape[self.axis] = input_shape[self.axis] // self.groups
256
+ group_shape.insert(self.axis, self.groups)
257
+ group_shape = tf.stack(group_shape)
258
+ reshaped_inputs = tf.reshape(inputs, group_shape)
259
+ return reshaped_inputs, group_shape
260
+ else:
261
+ return inputs, group_shape
262
+
263
+ def _apply_normalization(self, reshaped_inputs, input_shape):
264
+ group_shape = keras.backend.int_shape(reshaped_inputs)
265
+ group_reduction_axes = list(range(1, len(group_shape)))
266
+ is_instance_norm = (input_shape[self.axis] // self.groups) == 1
267
+ if not is_instance_norm:
268
+ axis = -2 if self.axis == -1 else self.axis - 1
269
+ else:
270
+ axis = -1 if self.axis == -1 else self.axis - 1
271
+ group_reduction_axes.pop(axis)
272
+
273
+ mean, variance = tf.nn.moments(reshaped_inputs, group_reduction_axes, keepdims=True)
274
+
275
+ gamma, beta = self._get_reshaped_weights(input_shape)
276
+ normalized_inputs = tf.nn.batch_normalization(
277
+ reshaped_inputs,
278
+ mean=mean,
279
+ variance=variance,
280
+ scale=gamma,
281
+ offset=beta,
282
+ variance_epsilon=self.epsilon,
283
+ )
284
+ return normalized_inputs
285
+
286
+ def _get_reshaped_weights(self, input_shape):
287
+ broadcast_shape = self._create_broadcast_shape(input_shape)
288
+ gamma = None
289
+ beta = None
290
+ if self.scale:
291
+ gamma = tf.reshape(self.gamma, broadcast_shape)
292
+
293
+ if self.center:
294
+ beta = tf.reshape(self.beta, broadcast_shape)
295
+ return gamma, beta
296
+
297
+ def _check_if_input_shape_is_none(self, input_shape):
298
+ dim = input_shape[self.axis]
299
+ if dim is None:
300
+ raise ValueError(
301
+ "Axis "
302
+ + str(self.axis)
303
+ + " of input tensor should have a defined dimension but the layer received an input with shape "
304
+ + str(input_shape)
305
+ + "."
306
+ )
307
+
308
+ def _set_number_of_groups_for_instance_norm(self, input_shape):
309
+ dim = input_shape[self.axis]
310
+
311
+ if self.groups == -1:
312
+ self.groups = dim
313
+
314
+ def _check_size_of_dimensions(self, input_shape):
315
+ dim = input_shape[self.axis]
316
+ if dim < self.groups:
317
+ raise ValueError(
318
+ "Number of groups ("
319
+ + str(self.groups)
320
+ + ") cannot be more than the number of channels ("
321
+ + str(dim)
322
+ + ")."
323
+ )
324
+
325
+ if dim % self.groups != 0:
326
+ raise ValueError(
327
+ "Number of groups ("
328
+ + str(self.groups)
329
+ + ") must be a multiple of the number of channels ("
330
+ + str(dim)
331
+ + ")."
332
+ )
333
+
334
+ def _check_axis(self):
335
+ if self.axis == 0:
336
+ raise ValueError(
337
+ "You are trying to normalize your batch axis. Do you want to use tf.layer.batch_normalization instead"
338
+ )
339
+
340
+ def _create_input_spec(self, input_shape):
341
+ dim = input_shape[self.axis]
342
+ self.input_spec = keras.layers.InputSpec(ndim=len(input_shape), axes={self.axis: dim})
343
+
344
+ def _add_gamma_weight(self, input_shape):
345
+ dim = input_shape[self.axis]
346
+ shape = (dim,)
347
+
348
+ if self.scale:
349
+ self.gamma = self.add_weight(
350
+ shape=shape,
351
+ name="gamma",
352
+ initializer=self.gamma_initializer,
353
+ regularizer=self.gamma_regularizer,
354
+ constraint=self.gamma_constraint,
355
+ )
356
+ else:
357
+ self.gamma = None
358
+
359
+ def _add_beta_weight(self, input_shape):
360
+ dim = input_shape[self.axis]
361
+ shape = (dim,)
362
+
363
+ if self.center:
364
+ self.beta = self.add_weight(
365
+ shape=shape,
366
+ name="beta",
367
+ initializer=self.beta_initializer,
368
+ regularizer=self.beta_regularizer,
369
+ constraint=self.beta_constraint,
370
+ )
371
+ else:
372
+ self.beta = None
373
+
374
+ def _create_broadcast_shape(self, input_shape):
375
+ broadcast_shape = [1] * len(input_shape)
376
+ is_instance_norm = (input_shape[self.axis] // self.groups) == 1
377
+ if not is_instance_norm:
378
+ broadcast_shape[self.axis] = input_shape[self.axis] // self.groups
379
+ broadcast_shape.insert(self.axis, self.groups)
380
+ else:
381
+ broadcast_shape[self.axis] = self.groups
382
+ return broadcast_shape
383
+
384
+
385
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2WeightNormConv1D with Wav2Vec2->Hubert
386
+ class TFHubertWeightNormConv1D(keras.layers.Conv1D):
387
+ """Adapted from https://www.tensorflow.org/probability/api_docs/python/tfp/layers/weight_norm/WeightNorm"""
388
+
389
+ def __init__(self, filters, kernel_size, groups, explicit_padding, **kwargs):
390
+ super().__init__(
391
+ filters=filters,
392
+ kernel_size=kernel_size,
393
+ groups=groups,
394
+ padding="valid",
395
+ use_bias=True,
396
+ bias_initializer="he_normal",
397
+ **kwargs,
398
+ )
399
+ self.explicit_padding = explicit_padding
400
+ self.filter_axis = 2
401
+ self.kernel_norm_axes = tf.constant([0, 1])
402
+
403
+ def _init_norm(self):
404
+ """Set the norm of the weight vector."""
405
+ kernel_norm = tf.sqrt(tf.reduce_sum(tf.square(self.weight_v), axis=self.kernel_norm_axes))
406
+ self.weight_g.assign(kernel_norm[:, tf.newaxis, tf.newaxis])
407
+
408
+ def _normalize_kernel(self):
409
+ """Generate normalized weights."""
410
+ kernel = tf.nn.l2_normalize(self.weight_v, axis=self.kernel_norm_axes) * tf.transpose(self.weight_g)
411
+ self.kernel = tf.transpose(kernel)
412
+
413
+ def build(self, input_shape):
414
+ if not self.built:
415
+ super().build(input_shape)
416
+
417
+ self.kernel = tf.Variable(tf.transpose(self.kernel), name="weight_v", trainable=True)
418
+ self.weight_v = self.kernel
419
+
420
+ self.weight_g = self.add_weight(
421
+ name="weight_g",
422
+ shape=(int(self.weight_v.shape[self.filter_axis]), 1, 1),
423
+ initializer="ones",
424
+ dtype=self.weight_v.dtype,
425
+ trainable=True,
426
+ )
427
+ self._init_norm()
428
+ self.bias = self.add_weight(name="bias", shape=(self.filters,), initializer="zeros", trainable=True)
429
+
430
+ def call(self, inputs):
431
+ # TODO Matt: Assigning to attributes in call() is deeply sinful in TensorFlow, as it should be idempotent.
432
+ # This whole layer should be replaced by a layer that doesn't inherit from Conv1D, but instead calls
433
+ # a functional 1d convolution with normalized weights that it generates (but does not store!)
434
+ self._normalize_kernel()
435
+
436
+ padded_inputs = tf.pad(inputs, ((0, 0), (self.explicit_padding, self.explicit_padding), (0, 0)))
437
+ output = super().call(padded_inputs)
438
+
439
+ return output
440
+
441
+
442
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2NoLayerNormConvLayer with Wav2Vec2->Hubert
443
+ class TFHubertNoLayerNormConvLayer(keras.layers.Layer):
444
+ def __init__(self, config: HubertConfig, layer_id: int = 0, **kwargs: Any) -> None:
445
+ super().__init__(**kwargs)
446
+ self.in_conv_dim = config.conv_dim[layer_id] if layer_id > 0 else 1
447
+ self.out_conv_dim = config.conv_dim[layer_id]
448
+
449
+ self.conv = keras.layers.Conv1D(
450
+ filters=self.out_conv_dim,
451
+ kernel_size=config.conv_kernel[layer_id],
452
+ strides=config.conv_stride[layer_id],
453
+ use_bias=config.conv_bias,
454
+ name="conv",
455
+ )
456
+ self.activation = get_tf_activation(config.feat_extract_activation)
457
+
458
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
459
+ hidden_states = self.conv(hidden_states)
460
+ hidden_states = self.activation(hidden_states)
461
+ return hidden_states
462
+
463
+ def build(self, input_shape=None):
464
+ if self.built:
465
+ return
466
+ self.built = True
467
+ if getattr(self, "conv", None) is not None:
468
+ with tf.name_scope(self.conv.name):
469
+ self.conv.build([None, None, self.in_conv_dim])
470
+
471
+
472
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2LayerNormConvLayer with Wav2Vec2->Hubert
473
+ class TFHubertLayerNormConvLayer(keras.layers.Layer):
474
+ def __init__(self, config: HubertConfig, layer_id: int = 0, **kwargs: Any) -> None:
475
+ super().__init__(**kwargs)
476
+ self.in_conv_dim = config.conv_dim[layer_id] if layer_id > 0 else 1
477
+ self.out_conv_dim = config.conv_dim[layer_id]
478
+
479
+ self.conv = keras.layers.Conv1D(
480
+ filters=self.out_conv_dim,
481
+ kernel_size=config.conv_kernel[layer_id],
482
+ strides=config.conv_stride[layer_id],
483
+ use_bias=config.conv_bias,
484
+ name="conv",
485
+ )
486
+ self.layer_norm = keras.layers.LayerNormalization(name="layer_norm", epsilon=config.layer_norm_eps)
487
+ self.activation = get_tf_activation(config.feat_extract_activation)
488
+
489
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
490
+ hidden_states = self.conv(hidden_states)
491
+ hidden_states = self.layer_norm(hidden_states)
492
+ hidden_states = self.activation(hidden_states)
493
+ return hidden_states
494
+
495
+ def build(self, input_shape=None):
496
+ if self.built:
497
+ return
498
+ self.built = True
499
+ if getattr(self, "conv", None) is not None:
500
+ with tf.name_scope(self.conv.name):
501
+ self.conv.build([None, None, self.in_conv_dim])
502
+ if getattr(self, "layer_norm", None) is not None:
503
+ with tf.name_scope(self.layer_norm.name):
504
+ self.layer_norm.build([None, None, self.out_conv_dim])
505
+
506
+
507
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2GroupNormConvLayer with Wav2Vec2->Hubert
508
+ class TFHubertGroupNormConvLayer(keras.layers.Layer):
509
+ def __init__(self, config: HubertConfig, layer_id: int = 0, **kwargs: Any) -> None:
510
+ super().__init__(**kwargs)
511
+ self.in_conv_dim = config.conv_dim[layer_id] if layer_id > 0 else 1
512
+ self.out_conv_dim = config.conv_dim[layer_id]
513
+
514
+ self.conv = keras.layers.Conv1D(
515
+ filters=self.out_conv_dim,
516
+ kernel_size=config.conv_kernel[layer_id],
517
+ strides=config.conv_stride[layer_id],
518
+ use_bias=config.conv_bias,
519
+ name="conv",
520
+ )
521
+ self.activation = get_tf_activation(config.feat_extract_activation)
522
+ self.layer_norm = TFHubertGroupNorm(groups=self.out_conv_dim, epsilon=config.layer_norm_eps, name="layer_norm")
523
+
524
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
525
+ hidden_states = self.conv(hidden_states)
526
+ hidden_states = self.layer_norm(hidden_states)
527
+ hidden_states = self.activation(hidden_states)
528
+ return hidden_states
529
+
530
+ def build(self, input_shape=None):
531
+ if self.built:
532
+ return
533
+ self.built = True
534
+ if getattr(self, "conv", None) is not None:
535
+ with tf.name_scope(self.conv.name):
536
+ self.conv.build([None, None, self.in_conv_dim])
537
+ if getattr(self, "layer_norm", None) is not None:
538
+ with tf.name_scope(self.layer_norm.name):
539
+ self.layer_norm.build([None, None, self.out_conv_dim])
540
+
541
+
542
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2PositionalConvEmbedding with Wav2Vec2->Hubert
543
+ class TFHubertPositionalConvEmbedding(keras.layers.Layer):
544
+ def __init__(self, config: HubertConfig, **kwargs: Any) -> None:
545
+ super().__init__(**kwargs)
546
+ self.conv = TFHubertWeightNormConv1D(
547
+ filters=config.hidden_size,
548
+ kernel_size=config.num_conv_pos_embeddings,
549
+ groups=config.num_conv_pos_embedding_groups,
550
+ explicit_padding=config.num_conv_pos_embeddings // 2,
551
+ name="conv",
552
+ )
553
+ self.padding = TFHubertSamePadLayer(config.num_conv_pos_embeddings)
554
+ self.activation = get_tf_activation(config.feat_extract_activation)
555
+ self.config = config
556
+
557
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
558
+ hidden_states = self.conv(hidden_states)
559
+ hidden_states = self.padding(hidden_states)
560
+ hidden_states = self.activation(hidden_states)
561
+ return hidden_states
562
+
563
+ def build(self, input_shape=None):
564
+ if self.built:
565
+ return
566
+ self.built = True
567
+ if getattr(self, "conv", None) is not None:
568
+ with tf.name_scope(self.conv.name):
569
+ self.conv.build([None, None, self.config.hidden_size])
570
+
571
+
572
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2SamePadLayer with Wav2Vec2->Hubert
573
+ class TFHubertSamePadLayer(keras.layers.Layer):
574
+ def __init__(self, num_conv_pos_embeddings, **kwargs):
575
+ super().__init__(**kwargs)
576
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
577
+
578
+ def call(self, hidden_states):
579
+ if self.num_pad_remove > 0:
580
+ hidden_states = hidden_states[:, : -self.num_pad_remove, :]
581
+ return hidden_states
582
+
583
+
584
+ class TFHubertFeatureEncoder(keras.layers.Layer):
585
+ def __init__(self, config: HubertConfig, **kwargs: Any) -> None:
586
+ super().__init__(**kwargs)
587
+
588
+ if config.feat_extract_norm == "group":
589
+ conv_layers = [TFHubertGroupNormConvLayer(config, layer_id=0, name=f"conv_layers.{0}")] + [
590
+ TFHubertNoLayerNormConvLayer(config, layer_id=i + 1, name=f"conv_layers.{i + 1}")
591
+ for i in range(config.num_feat_extract_layers - 1)
592
+ ]
593
+ elif config.feat_extract_norm == "layer":
594
+ conv_layers = [
595
+ TFHubertLayerNormConvLayer(config, layer_id=i, name=f"conv_layers.{i}")
596
+ for i in range(config.num_feat_extract_layers)
597
+ ]
598
+ else:
599
+ raise ValueError(
600
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
601
+ )
602
+ self.conv_layers = conv_layers
603
+
604
+ def call(self, input_values):
605
+ hidden_states = tf.expand_dims(input_values, -1)
606
+ for conv_layer in self.conv_layers:
607
+ hidden_states = conv_layer(hidden_states)
608
+ return hidden_states
609
+
610
+ def build(self, input_shape=None):
611
+ if self.built:
612
+ return
613
+ self.built = True
614
+ for conv_layer in self.conv_layers:
615
+ with tf.name_scope(conv_layer.name):
616
+ conv_layer.build(None)
617
+
618
+
619
+ class TFHubertFeatureExtractor(TFHubertFeatureEncoder):
620
+ def __init__(self, config, **kwargs):
621
+ super().__init__(config, **kwargs)
622
+ warnings.warn(
623
+ f"The class `{self.__class__.__name__}` has been depreciated "
624
+ "and will be removed in Transformers v5. "
625
+ f"Use `{self.__class__.__bases__[0].__name__}` instead.",
626
+ FutureWarning,
627
+ )
628
+
629
+
630
+ class TFHubertFeatureProjection(keras.layers.Layer):
631
+ def __init__(self, config: HubertConfig, **kwargs):
632
+ super().__init__(**kwargs)
633
+
634
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
635
+ self.projection = keras.layers.Dense(
636
+ units=config.hidden_size,
637
+ kernel_initializer=get_initializer(config.initializer_range),
638
+ bias_initializer="zeros",
639
+ name="projection",
640
+ )
641
+ self.dropout = keras.layers.Dropout(rate=config.feat_proj_dropout)
642
+ self.config = config
643
+
644
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tf.Tensor:
645
+ hidden_states = self.layer_norm(hidden_states)
646
+ hidden_states = self.projection(hidden_states)
647
+ hidden_states = self.dropout(hidden_states, training=training)
648
+ return hidden_states
649
+
650
+ def build(self, input_shape=None):
651
+ if self.built:
652
+ return
653
+ self.built = True
654
+ if getattr(self, "layer_norm", None) is not None:
655
+ with tf.name_scope(self.layer_norm.name):
656
+ self.layer_norm.build([None, None, self.config.conv_dim[-1]])
657
+ if getattr(self, "projection", None) is not None:
658
+ with tf.name_scope(self.projection.name):
659
+ self.projection.build([None, None, self.config.conv_dim[-1]])
660
+
661
+
662
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with TFBart->TFHubert
663
+ class TFHubertAttention(keras.layers.Layer):
664
+ """Multi-headed attention from "Attention Is All You Need"""
665
+
666
+ def __init__(
667
+ self,
668
+ embed_dim: int,
669
+ num_heads: int,
670
+ dropout: float = 0.0,
671
+ is_decoder: bool = False,
672
+ bias: bool = True,
673
+ **kwargs,
674
+ ):
675
+ super().__init__(**kwargs)
676
+ self.embed_dim = embed_dim
677
+
678
+ self.num_heads = num_heads
679
+ self.dropout = keras.layers.Dropout(dropout)
680
+ self.head_dim = embed_dim // num_heads
681
+ if (self.head_dim * num_heads) != self.embed_dim:
682
+ raise ValueError(
683
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
684
+ f" and `num_heads`: {num_heads})."
685
+ )
686
+ self.scaling = self.head_dim**-0.5
687
+ self.is_decoder = is_decoder
688
+
689
+ self.k_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
690
+ self.q_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
691
+ self.v_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
692
+ self.out_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
693
+
694
+ def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
695
+ return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
696
+
697
+ def call(
698
+ self,
699
+ hidden_states: tf.Tensor,
700
+ key_value_states: tf.Tensor | None = None,
701
+ past_key_value: tuple[tuple[tf.Tensor]] | None = None,
702
+ attention_mask: tf.Tensor | None = None,
703
+ layer_head_mask: tf.Tensor | None = None,
704
+ training: bool | None = False,
705
+ ) -> tuple[tf.Tensor, tf.Tensor | None]:
706
+ """Input shape: Batch x Time x Channel"""
707
+
708
+ # if key_value_states are provided this layer is used as a cross-attention layer
709
+ # for the decoder
710
+ is_cross_attention = key_value_states is not None
711
+ bsz, tgt_len, embed_dim = shape_list(hidden_states)
712
+
713
+ # get query proj
714
+ query_states = self.q_proj(hidden_states) * self.scaling
715
+ # get key, value proj
716
+ if is_cross_attention and past_key_value is not None:
717
+ # reuse k,v, cross_attentions
718
+ key_states = past_key_value[0]
719
+ value_states = past_key_value[1]
720
+ elif is_cross_attention:
721
+ # cross_attentions
722
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
723
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
724
+ elif past_key_value is not None:
725
+ # reuse k, v, self_attention
726
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
727
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
728
+ key_states = tf.concat([past_key_value[0], key_states], axis=2)
729
+ value_states = tf.concat([past_key_value[1], value_states], axis=2)
730
+ else:
731
+ # self_attention
732
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
733
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
734
+
735
+ if self.is_decoder:
736
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
737
+ # Further calls to cross_attention layer can then reuse all cross-attention
738
+ # key/value_states (first "if" case)
739
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
740
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
741
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
742
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
743
+ past_key_value = (key_states, value_states)
744
+
745
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
746
+ query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
747
+ key_states = tf.reshape(key_states, proj_shape)
748
+ value_states = tf.reshape(value_states, proj_shape)
749
+
750
+ src_len = shape_list(key_states)[1]
751
+ attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
752
+
753
+ tf.debugging.assert_equal(
754
+ shape_list(attn_weights),
755
+ [bsz * self.num_heads, tgt_len, src_len],
756
+ message=(
757
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
758
+ f" {shape_list(attn_weights)}"
759
+ ),
760
+ )
761
+
762
+ if attention_mask is not None:
763
+ tf.debugging.assert_equal(
764
+ shape_list(attention_mask),
765
+ [bsz, 1, tgt_len, src_len],
766
+ message=(
767
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
768
+ f" {shape_list(attention_mask)}"
769
+ ),
770
+ )
771
+
772
+ attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
773
+ attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
774
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
775
+
776
+ attn_weights = stable_softmax(attn_weights, axis=-1)
777
+
778
+ if layer_head_mask is not None:
779
+ tf.debugging.assert_equal(
780
+ shape_list(layer_head_mask),
781
+ [self.num_heads],
782
+ message=(
783
+ f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
784
+ f" {shape_list(layer_head_mask)}"
785
+ ),
786
+ )
787
+
788
+ attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
789
+ attn_weights, (bsz, self.num_heads, tgt_len, src_len)
790
+ )
791
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
792
+
793
+ attn_probs = self.dropout(attn_weights, training=training)
794
+ attn_output = tf.matmul(attn_probs, value_states)
795
+
796
+ tf.debugging.assert_equal(
797
+ shape_list(attn_output),
798
+ [bsz * self.num_heads, tgt_len, self.head_dim],
799
+ message=(
800
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
801
+ f" {shape_list(attn_output)}"
802
+ ),
803
+ )
804
+
805
+ attn_output = tf.transpose(
806
+ tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
807
+ )
808
+ attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
809
+
810
+ attn_output = self.out_proj(attn_output)
811
+ attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
812
+
813
+ return attn_output, attn_weights, past_key_value
814
+
815
+ def build(self, input_shape=None):
816
+ if self.built:
817
+ return
818
+ self.built = True
819
+ if getattr(self, "k_proj", None) is not None:
820
+ with tf.name_scope(self.k_proj.name):
821
+ self.k_proj.build([None, None, self.embed_dim])
822
+ if getattr(self, "q_proj", None) is not None:
823
+ with tf.name_scope(self.q_proj.name):
824
+ self.q_proj.build([None, None, self.embed_dim])
825
+ if getattr(self, "v_proj", None) is not None:
826
+ with tf.name_scope(self.v_proj.name):
827
+ self.v_proj.build([None, None, self.embed_dim])
828
+ if getattr(self, "out_proj", None) is not None:
829
+ with tf.name_scope(self.out_proj.name):
830
+ self.out_proj.build([None, None, self.embed_dim])
831
+
832
+
833
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2FeedForward with Wav2Vec2->Hubert
834
+ class TFHubertFeedForward(keras.layers.Layer):
835
+ def __init__(self, config: HubertConfig, **kwargs):
836
+ super().__init__(**kwargs)
837
+
838
+ self.intermediate_dropout = keras.layers.Dropout(config.activation_dropout)
839
+
840
+ self.intermediate_dense = keras.layers.Dense(
841
+ units=config.intermediate_size,
842
+ kernel_initializer=get_initializer(config.initializer_range),
843
+ bias_initializer="zeros",
844
+ name="intermediate_dense",
845
+ )
846
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
847
+
848
+ self.output_dense = keras.layers.Dense(
849
+ units=config.hidden_size,
850
+ kernel_initializer=get_initializer(config.initializer_range),
851
+ bias_initializer="zeros",
852
+ name="output_dense",
853
+ )
854
+ self.output_dropout = keras.layers.Dropout(config.hidden_dropout)
855
+ self.config = config
856
+
857
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tf.Tensor:
858
+ hidden_states = self.intermediate_dense(hidden_states)
859
+ hidden_states = self.intermediate_act_fn(hidden_states)
860
+ hidden_states = self.intermediate_dropout(hidden_states, training=training)
861
+
862
+ hidden_states = self.output_dense(hidden_states)
863
+ hidden_states = self.output_dropout(hidden_states, training=training)
864
+ return hidden_states
865
+
866
+ def build(self, input_shape=None):
867
+ if self.built:
868
+ return
869
+ self.built = True
870
+ if getattr(self, "intermediate_dense", None) is not None:
871
+ with tf.name_scope(self.intermediate_dense.name):
872
+ self.intermediate_dense.build([None, None, self.config.hidden_size])
873
+ if getattr(self, "output_dense", None) is not None:
874
+ with tf.name_scope(self.output_dense.name):
875
+ self.output_dense.build([None, None, self.config.intermediate_size])
876
+
877
+
878
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2EncoderLayer with Wav2Vec2->Hubert
879
+ class TFHubertEncoderLayer(keras.layers.Layer):
880
+ def __init__(self, config: HubertConfig, **kwargs):
881
+ super().__init__(**kwargs)
882
+ self.attention = TFHubertAttention(
883
+ embed_dim=config.hidden_size,
884
+ num_heads=config.num_attention_heads,
885
+ dropout=config.attention_dropout,
886
+ is_decoder=False,
887
+ name="attention",
888
+ )
889
+ self.dropout = keras.layers.Dropout(config.hidden_dropout)
890
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
891
+ self.feed_forward = TFHubertFeedForward(config, name="feed_forward")
892
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="final_layer_norm")
893
+ self.config = config
894
+
895
+ def call(
896
+ self,
897
+ hidden_states: tf.Tensor,
898
+ attention_mask: tf.Tensor | None = None,
899
+ output_attentions: bool | None = False,
900
+ training: bool = False,
901
+ ) -> tuple[tf.Tensor]:
902
+ attn_residual = hidden_states
903
+ hidden_states, attn_weights, _ = self.attention(
904
+ hidden_states, attention_mask=attention_mask, training=training
905
+ )
906
+ hidden_states = self.dropout(hidden_states, training=training)
907
+ hidden_states = attn_residual + hidden_states
908
+
909
+ hidden_states = self.layer_norm(hidden_states)
910
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
911
+ hidden_states = self.final_layer_norm(hidden_states)
912
+
913
+ outputs = (hidden_states,)
914
+
915
+ if output_attentions:
916
+ outputs += (attn_weights,)
917
+
918
+ return outputs
919
+
920
+ def build(self, input_shape=None):
921
+ if self.built:
922
+ return
923
+ self.built = True
924
+ if getattr(self, "attention", None) is not None:
925
+ with tf.name_scope(self.attention.name):
926
+ self.attention.build(None)
927
+ if getattr(self, "layer_norm", None) is not None:
928
+ with tf.name_scope(self.layer_norm.name):
929
+ self.layer_norm.build([None, None, self.config.hidden_size])
930
+ if getattr(self, "feed_forward", None) is not None:
931
+ with tf.name_scope(self.feed_forward.name):
932
+ self.feed_forward.build(None)
933
+ if getattr(self, "final_layer_norm", None) is not None:
934
+ with tf.name_scope(self.final_layer_norm.name):
935
+ self.final_layer_norm.build([None, None, self.config.hidden_size])
936
+
937
+
938
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2EncoderLayerStableLayerNorm with Wav2Vec2->Hubert
939
+ class TFHubertEncoderLayerStableLayerNorm(keras.layers.Layer):
940
+ def __init__(self, config: HubertConfig, **kwargs):
941
+ super().__init__(**kwargs)
942
+ self.attention = TFHubertAttention(
943
+ embed_dim=config.hidden_size,
944
+ num_heads=config.num_attention_heads,
945
+ dropout=config.attention_dropout,
946
+ is_decoder=False,
947
+ name="attention",
948
+ )
949
+ self.dropout = keras.layers.Dropout(config.hidden_dropout)
950
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
951
+ self.feed_forward = TFHubertFeedForward(config, name="feed_forward")
952
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="final_layer_norm")
953
+ self.config = config
954
+
955
+ def call(
956
+ self,
957
+ hidden_states: tf.Tensor,
958
+ attention_mask: tf.Tensor | None = None,
959
+ output_attentions: bool | None = False,
960
+ training: bool = False,
961
+ ) -> tuple[tf.Tensor]:
962
+ attn_residual = hidden_states
963
+ hidden_states = self.layer_norm(hidden_states)
964
+ hidden_states, attn_weights, _ = self.attention(
965
+ hidden_states, attention_mask=attention_mask, training=training
966
+ )
967
+ hidden_states = self.dropout(hidden_states, training=training)
968
+ hidden_states = attn_residual + hidden_states
969
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
970
+
971
+ outputs = (hidden_states,)
972
+
973
+ if output_attentions:
974
+ outputs += (attn_weights,)
975
+
976
+ return outputs
977
+
978
+ def build(self, input_shape=None):
979
+ if self.built:
980
+ return
981
+ self.built = True
982
+ if getattr(self, "attention", None) is not None:
983
+ with tf.name_scope(self.attention.name):
984
+ self.attention.build(None)
985
+ if getattr(self, "layer_norm", None) is not None:
986
+ with tf.name_scope(self.layer_norm.name):
987
+ self.layer_norm.build([None, None, self.config.hidden_size])
988
+ if getattr(self, "feed_forward", None) is not None:
989
+ with tf.name_scope(self.feed_forward.name):
990
+ self.feed_forward.build(None)
991
+ if getattr(self, "final_layer_norm", None) is not None:
992
+ with tf.name_scope(self.final_layer_norm.name):
993
+ self.final_layer_norm.build([None, None, self.config.hidden_size])
994
+
995
+
996
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2Encoder with Wav2Vec2->Hubert
997
+ class TFHubertEncoder(keras.layers.Layer):
998
+ def __init__(self, config: HubertConfig, **kwargs):
999
+ super().__init__(**kwargs)
1000
+ self.config = config
1001
+ self.pos_conv_embed = TFHubertPositionalConvEmbedding(config, name="pos_conv_embed")
1002
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
1003
+ self.dropout = keras.layers.Dropout(config.hidden_dropout)
1004
+ self.layer = [TFHubertEncoderLayer(config, name=f"layers.{i}") for i in range(config.num_hidden_layers)]
1005
+
1006
+ def call(
1007
+ self,
1008
+ hidden_states: tf.Tensor,
1009
+ attention_mask: tf.Tensor | None = None,
1010
+ output_attentions: bool | None = False,
1011
+ output_hidden_states: bool | None = False,
1012
+ return_dict: bool | None = True,
1013
+ training: bool | None = False,
1014
+ ) -> TFBaseModelOutput | tuple[tf.Tensor]:
1015
+ all_hidden_states = () if output_hidden_states else None
1016
+ all_self_attentions = () if output_attentions else None
1017
+
1018
+ if attention_mask is not None:
1019
+ hidden_states = hidden_states * tf.expand_dims(attention_mask, -1)
1020
+ attention_mask = _expand_mask(attention_mask)
1021
+ else:
1022
+ attention_mask = None
1023
+
1024
+ position_embeddings = self.pos_conv_embed(hidden_states)
1025
+ hidden_states = hidden_states + position_embeddings
1026
+ hidden_states = self.layer_norm(hidden_states)
1027
+ hidden_states = self.dropout(hidden_states, training=training)
1028
+
1029
+ for i, layer_module in enumerate(self.layer):
1030
+ if output_hidden_states:
1031
+ all_hidden_states = all_hidden_states + (hidden_states,)
1032
+
1033
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
1034
+ dropout_probability = np.random.uniform(0, 1)
1035
+ if training and (dropout_probability < self.config.layerdrop): # skip the layer
1036
+ continue
1037
+
1038
+ layer_outputs = layer_module(
1039
+ hidden_states=hidden_states,
1040
+ attention_mask=attention_mask,
1041
+ output_attentions=output_attentions,
1042
+ training=training,
1043
+ )
1044
+ hidden_states = layer_outputs[0]
1045
+
1046
+ if output_attentions:
1047
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
1048
+
1049
+ # Add last layer
1050
+ if output_hidden_states:
1051
+ all_hidden_states = all_hidden_states + (hidden_states,)
1052
+
1053
+ if not return_dict:
1054
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
1055
+ return TFBaseModelOutput(
1056
+ last_hidden_state=hidden_states,
1057
+ hidden_states=all_hidden_states,
1058
+ attentions=all_self_attentions,
1059
+ )
1060
+
1061
+ def build(self, input_shape=None):
1062
+ if self.built:
1063
+ return
1064
+ self.built = True
1065
+ if getattr(self, "pos_conv_embed", None) is not None:
1066
+ with tf.name_scope(self.pos_conv_embed.name):
1067
+ self.pos_conv_embed.build(None)
1068
+ if getattr(self, "layer_norm", None) is not None:
1069
+ with tf.name_scope(self.layer_norm.name):
1070
+ self.layer_norm.build([None, None, self.config.hidden_size])
1071
+ if getattr(self, "layer", None) is not None:
1072
+ for layer in self.layer:
1073
+ with tf.name_scope(layer.name):
1074
+ layer.build(None)
1075
+
1076
+
1077
+ # Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2EncoderStableLayerNorm with Wav2Vec2->Hubert
1078
+ class TFHubertEncoderStableLayerNorm(keras.layers.Layer):
1079
+ def __init__(self, config: HubertConfig, **kwargs):
1080
+ super().__init__(**kwargs)
1081
+ self.config = config
1082
+ self.pos_conv_embed = TFHubertPositionalConvEmbedding(config, name="pos_conv_embed")
1083
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
1084
+ self.dropout = keras.layers.Dropout(config.hidden_dropout)
1085
+ self.layer = [
1086
+ TFHubertEncoderLayerStableLayerNorm(config, name=f"layers.{i}") for i in range(config.num_hidden_layers)
1087
+ ]
1088
+
1089
+ def call(
1090
+ self,
1091
+ hidden_states: tf.Tensor,
1092
+ attention_mask: tf.Tensor | None = None,
1093
+ output_attentions: bool | None = False,
1094
+ output_hidden_states: bool | None = False,
1095
+ return_dict: bool | None = True,
1096
+ training: bool | None = False,
1097
+ ) -> TFBaseModelOutput | tuple[tf.Tensor]:
1098
+ all_hidden_states = () if output_hidden_states else None
1099
+ all_self_attentions = () if output_attentions else None
1100
+
1101
+ if attention_mask is not None:
1102
+ hidden_states = hidden_states * tf.expand_dims(attention_mask, -1)
1103
+ attention_mask = _expand_mask(attention_mask)
1104
+ else:
1105
+ attention_mask = None
1106
+
1107
+ position_embeddings = self.pos_conv_embed(hidden_states)
1108
+ hidden_states = hidden_states + position_embeddings
1109
+ hidden_states = self.dropout(hidden_states, training=training)
1110
+
1111
+ for i, layer_module in enumerate(self.layer):
1112
+ if output_hidden_states:
1113
+ all_hidden_states = all_hidden_states + (hidden_states,)
1114
+
1115
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
1116
+ dropout_probability = np.random.uniform(0, 1)
1117
+ if training and (dropout_probability < self.config.layerdrop): # skip the layer
1118
+ continue
1119
+
1120
+ layer_outputs = layer_module(
1121
+ hidden_states=hidden_states,
1122
+ attention_mask=attention_mask,
1123
+ output_attentions=output_attentions,
1124
+ training=training,
1125
+ )
1126
+ hidden_states = layer_outputs[0]
1127
+
1128
+ if output_attentions:
1129
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
1130
+
1131
+ hidden_states = self.layer_norm(hidden_states)
1132
+
1133
+ if output_hidden_states:
1134
+ all_hidden_states = all_hidden_states + (hidden_states,)
1135
+
1136
+ if not return_dict:
1137
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
1138
+ return TFBaseModelOutput(
1139
+ last_hidden_state=hidden_states,
1140
+ hidden_states=all_hidden_states,
1141
+ attentions=all_self_attentions,
1142
+ )
1143
+
1144
+ def build(self, input_shape=None):
1145
+ if self.built:
1146
+ return
1147
+ self.built = True
1148
+ if getattr(self, "pos_conv_embed", None) is not None:
1149
+ with tf.name_scope(self.pos_conv_embed.name):
1150
+ self.pos_conv_embed.build(None)
1151
+ if getattr(self, "layer_norm", None) is not None:
1152
+ with tf.name_scope(self.layer_norm.name):
1153
+ self.layer_norm.build([None, None, self.config.hidden_size])
1154
+ if getattr(self, "layer", None) is not None:
1155
+ for layer in self.layer:
1156
+ with tf.name_scope(layer.name):
1157
+ layer.build(None)
1158
+
1159
+
1160
+ @keras_serializable
1161
+ class TFHubertMainLayer(keras.layers.Layer):
1162
+ config_class = HubertConfig
1163
+
1164
+ def __init__(self, config: HubertConfig, **kwargs):
1165
+ super().__init__(**kwargs)
1166
+ self.config = config
1167
+ self.feature_extractor = TFHubertFeatureEncoder(config, name="feature_extractor")
1168
+ self.feature_projection = TFHubertFeatureProjection(config, name="feature_projection")
1169
+
1170
+ if config.do_stable_layer_norm:
1171
+ self.encoder = TFHubertEncoderStableLayerNorm(config, name="encoder")
1172
+ else:
1173
+ self.encoder = TFHubertEncoder(config, name="encoder")
1174
+
1175
+ def build(self, input_shape=None):
1176
+ self.masked_spec_embed = self.add_weight(
1177
+ shape=(self.config.hidden_size,), initializer="uniform", trainable=True, name="masked_spec_embed"
1178
+ )
1179
+
1180
+ if self.built:
1181
+ return
1182
+ self.built = True
1183
+ if getattr(self, "feature_extractor", None) is not None:
1184
+ with tf.name_scope(self.feature_extractor.name):
1185
+ self.feature_extractor.build(None)
1186
+ if getattr(self, "feature_projection", None) is not None:
1187
+ with tf.name_scope(self.feature_projection.name):
1188
+ self.feature_projection.build(None)
1189
+ if getattr(self, "encoder", None) is not None:
1190
+ with tf.name_scope(self.encoder.name):
1191
+ self.encoder.build(None)
1192
+
1193
+ def _get_feat_extract_output_lengths(self, input_lengths: tf.Tensor):
1194
+ """
1195
+ Computes the output length of the convolutional layers
1196
+ """
1197
+
1198
+ def _conv_out_length(input_length, kernel_size, stride):
1199
+ # 1D convolutional layer output length formula taken
1200
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
1201
+ return (input_length - kernel_size) // stride + 1
1202
+
1203
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
1204
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
1205
+
1206
+ return input_lengths
1207
+
1208
+ def _mask_hidden_states(self, hidden_states: tf.Tensor, mask_time_indices: tf.Tensor | None = None):
1209
+ """
1210
+ Masks extracted features along time axis and/or along feature axis according to
1211
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
1212
+ """
1213
+ batch_size, sequence_length, hidden_size = shape_list(hidden_states)
1214
+
1215
+ # `config.apply_spec_augment` can set masking to False
1216
+ if not getattr(self.config, "apply_spec_augment", True):
1217
+ return hidden_states
1218
+
1219
+ if mask_time_indices is not None:
1220
+ # apply SpecAugment along time axis with given mask_time_indices
1221
+ hidden_states = tf.where(
1222
+ tf.cast(mask_time_indices[:, :, tf.newaxis], tf.bool),
1223
+ self.masked_spec_embed[tf.newaxis, tf.newaxis, :],
1224
+ hidden_states,
1225
+ )
1226
+
1227
+ elif self.config.mask_time_prob > 0:
1228
+ # generate indices & apply SpecAugment along time axis
1229
+ mask_time_indices = _compute_mask_indices(
1230
+ (batch_size, sequence_length),
1231
+ mask_prob=self.config.mask_time_prob,
1232
+ mask_length=self.config.mask_time_length,
1233
+ min_masks=2,
1234
+ )
1235
+ hidden_states = tf.where(
1236
+ tf.cast(mask_time_indices[:, :, tf.newaxis], tf.bool),
1237
+ self.masked_spec_embed[tf.newaxis, tf.newaxis, :],
1238
+ hidden_states,
1239
+ )
1240
+
1241
+ # apply SpecAugment along feature axis
1242
+ if self.config.mask_feature_prob > 0:
1243
+ mask_feature_indices = _compute_mask_indices(
1244
+ (batch_size, hidden_size),
1245
+ mask_prob=self.config.mask_feature_prob,
1246
+ mask_length=self.config.mask_feature_length,
1247
+ )
1248
+ hidden_states = tf.where(mask_feature_indices[:, tf.newaxis, :], hidden_states, 0)
1249
+
1250
+ return hidden_states
1251
+
1252
+ @unpack_inputs
1253
+ def call(
1254
+ self,
1255
+ input_values: tf.Tensor,
1256
+ attention_mask: tf.Tensor | None = None,
1257
+ token_type_ids: tf.Tensor | None = None,
1258
+ position_ids: tf.Tensor | None = None,
1259
+ head_mask: tf.Tensor | None = None,
1260
+ inputs_embeds: tf.Tensor | None = None,
1261
+ output_attentions: tf.Tensor | None = None,
1262
+ output_hidden_states: tf.Tensor | None = None,
1263
+ return_dict: bool | None = None,
1264
+ training: bool = False,
1265
+ **kwargs: Any,
1266
+ ):
1267
+ hidden_states = self.feature_extractor(tf.cast(input_values, tf.float32), training=training)
1268
+
1269
+ if attention_mask is not None:
1270
+ # compute real output lengths according to convolution formula
1271
+ output_lengths = self._get_feat_extract_output_lengths(tf.reduce_sum(attention_mask, -1))
1272
+
1273
+ attention_mask = tf.sequence_mask(
1274
+ output_lengths, maxlen=shape_list(hidden_states)[1], dtype=hidden_states.dtype
1275
+ )
1276
+
1277
+ hidden_states = self.feature_projection(hidden_states, training=training)
1278
+
1279
+ mask_time_indices = kwargs.get("mask_time_indices")
1280
+ if training:
1281
+ hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices)
1282
+
1283
+ encoder_outputs = self.encoder(
1284
+ hidden_states,
1285
+ attention_mask=attention_mask,
1286
+ output_attentions=output_attentions,
1287
+ output_hidden_states=output_hidden_states,
1288
+ return_dict=return_dict,
1289
+ training=training,
1290
+ )
1291
+ hidden_states = encoder_outputs[0]
1292
+
1293
+ if not return_dict:
1294
+ return (hidden_states,) + encoder_outputs[1:]
1295
+
1296
+ return TFBaseModelOutput(
1297
+ last_hidden_state=hidden_states,
1298
+ hidden_states=encoder_outputs.hidden_states,
1299
+ attentions=encoder_outputs.attentions,
1300
+ )
1301
+
1302
+
1303
+ class TFHubertPreTrainedModel(TFPreTrainedModel):
1304
+ """
1305
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1306
+ models.
1307
+ """
1308
+
1309
+ config_class = HubertConfig
1310
+ base_model_prefix = "hubert"
1311
+ main_input_name = "input_values"
1312
+
1313
+ @property
1314
+ def input_signature(self):
1315
+ return {
1316
+ "input_values": tf.TensorSpec((None, 16000), tf.float32, name="input_values"),
1317
+ "attention_mask": tf.TensorSpec((None, None), tf.int32, name="attention_mask"),
1318
+ "token_type_ids": tf.TensorSpec((None, None), tf.int32, name="token_type_ids"),
1319
+ }
1320
+
1321
+ def __init__(self, config, *inputs, **kwargs):
1322
+ super().__init__(config, *inputs, **kwargs)
1323
+ logger.warning(
1324
+ f"\n{self.__class__.__name__} has backpropagation operations that are NOT supported on CPU. If you wish "
1325
+ "to train/fine-tune this model, you need a GPU or a TPU"
1326
+ )
1327
+
1328
+
1329
+ HUBERT_START_DOCSTRING = r"""
1330
+
1331
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
1332
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1333
+ etc.)
1334
+
1335
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
1336
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
1337
+ behavior.
1338
+
1339
+ <Tip>
1340
+
1341
+ TensorFlow models and layers in `transformers` accept two formats as input:
1342
+
1343
+ - having all inputs as keyword arguments (like PyTorch models), or
1344
+ - having all inputs as a list, tuple or dict in the first positional argument.
1345
+
1346
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
1347
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
1348
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
1349
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
1350
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
1351
+ positional argument:
1352
+
1353
+ - a single Tensor with `input_values` only and nothing else: `model(input_values)`
1354
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
1355
+ `model([input_values, attention_mask])` or `model([input_values, attention_mask, token_type_ids])`
1356
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
1357
+ `model({"input_values": input_values, "token_type_ids": token_type_ids})`
1358
+
1359
+ Note that when creating models and layers with
1360
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
1361
+ about any of this, as you can just pass inputs like you would to any other Python function!
1362
+
1363
+ </Tip>
1364
+
1365
+ Args:
1366
+ config ([`HubertConfig`]): Model configuration class with all the parameters of the model.
1367
+ Initializing with a config file does not load the weights associated with the model, only the
1368
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1369
+ """
1370
+
1371
+ HUBERT_INPUTS_DOCSTRING = r"""
1372
+ Args:
1373
+ input_values (`np.ndarray`, `tf.Tensor`, `list[tf.Tensor]` `dict[str, tf.Tensor]` or `dict[str, np.ndarray]` and each example must have the shape `({0})`):
1374
+ Indices of input sequence tokens in the vocabulary.
1375
+
1376
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
1377
+ [`PreTrainedTokenizer.encode`] for details.
1378
+
1379
+ [What are input IDs?](../glossary#input-ids)
1380
+ attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
1381
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1382
+
1383
+ - 1 for tokens that are **not masked**,
1384
+ - 0 for tokens that are **masked**.
1385
+
1386
+ [What are attention masks?](../glossary#attention-mask)
1387
+ token_type_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
1388
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1389
+ 1]`:
1390
+
1391
+ - 0 corresponds to a *sentence A* token,
1392
+ - 1 corresponds to a *sentence B* token.
1393
+
1394
+ [What are token type IDs?](../glossary#token-type-ids)
1395
+ position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
1396
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1397
+ config.max_position_embeddings - 1]`.
1398
+
1399
+ [What are position IDs?](../glossary#position-ids)
1400
+ head_mask (`np.ndarray` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1401
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1402
+
1403
+ - 1 indicates the head is **not masked**,
1404
+ - 0 indicates the head is **masked**.
1405
+
1406
+ inputs_embeds (`np.ndarray` or `tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
1407
+ Optionally, instead of passing `input_values` you can choose to directly pass an embedded representation.
1408
+ This is useful if you want more control over how to convert `input_values` indices into associated vectors
1409
+ than the model's internal embedding lookup matrix.
1410
+ output_attentions (`bool`, *optional*):
1411
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1412
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
1413
+ config will be used instead.
1414
+ output_hidden_states (`bool`, *optional*):
1415
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1416
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
1417
+ used instead.
1418
+ return_dict (`bool`, *optional*):
1419
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
1420
+ eager mode, in graph mode the value will always be set to True.
1421
+ training (`bool`, *optional*, defaults to `False``):
1422
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1423
+ behaviors between training and evaluation).
1424
+ """
1425
+
1426
+
1427
+ @add_start_docstrings(
1428
+ "The bare TFHubert Model transformer outputting raw hidden-states without any specific head on top.",
1429
+ HUBERT_START_DOCSTRING,
1430
+ )
1431
+ class TFHubertModel(TFHubertPreTrainedModel):
1432
+ def __init__(self, config: HubertConfig, *inputs, **kwargs):
1433
+ super().__init__(config, *inputs, **kwargs)
1434
+ self.config = config
1435
+ self.hubert = TFHubertMainLayer(config, name="hubert")
1436
+
1437
+ @add_start_docstrings_to_model_forward(HUBERT_INPUTS_DOCSTRING)
1438
+ @replace_return_docstrings(output_type=TFBaseModelOutput, config_class=_CONFIG_FOR_DOC)
1439
+ @unpack_inputs
1440
+ def call(
1441
+ self,
1442
+ input_values: tf.Tensor,
1443
+ attention_mask: tf.Tensor | None = None,
1444
+ token_type_ids: tf.Tensor | None = None,
1445
+ position_ids: tf.Tensor | None = None,
1446
+ head_mask: tf.Tensor | None = None,
1447
+ inputs_embeds: tf.Tensor | None = None,
1448
+ output_attentions: bool | None = None,
1449
+ output_hidden_states: bool | None = None,
1450
+ return_dict: bool | None = None,
1451
+ training: bool = False,
1452
+ ) -> TFBaseModelOutput | tuple[tf.Tensor]:
1453
+ """
1454
+
1455
+ Returns:
1456
+
1457
+ Example:
1458
+
1459
+ ```python
1460
+ >>> from transformers import AutoProcessor, TFHubertModel
1461
+ >>> from datasets import load_dataset
1462
+
1463
+ >>> processor = AutoProcessor.from_pretrained("facebook/hubert-large-ls960-ft")
1464
+ >>> model = TFHubertModel.from_pretrained("facebook/hubert-large-ls960-ft")
1465
+
1466
+
1467
+ >>> def map_to_array(example):
1468
+ ... example["speech"] = example["audio"]["array"]
1469
+ ... return example
1470
+
1471
+
1472
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
1473
+ >>> ds = ds.map(map_to_array)
1474
+
1475
+ >>> input_values = processor(ds["speech"][0], return_tensors="tf").input_values # Batch size 1
1476
+ >>> hidden_states = model(input_values).last_hidden_state
1477
+ ```"""
1478
+
1479
+ output_hidden_states = output_hidden_states if output_hidden_states else self.config.output_hidden_states
1480
+ output_attentions = output_attentions if output_attentions else self.config.output_attentions
1481
+ return_dict = return_dict if return_dict else self.config.return_dict
1482
+
1483
+ outputs = self.hubert(
1484
+ input_values=input_values,
1485
+ attention_mask=attention_mask,
1486
+ token_type_ids=token_type_ids,
1487
+ position_ids=position_ids,
1488
+ head_mask=head_mask,
1489
+ inputs_embeds=inputs_embeds,
1490
+ output_attentions=output_attentions,
1491
+ output_hidden_states=output_hidden_states,
1492
+ return_dict=return_dict,
1493
+ training=training,
1494
+ )
1495
+
1496
+ return outputs
1497
+
1498
+ def build(self, input_shape=None):
1499
+ if self.built:
1500
+ return
1501
+ self.built = True
1502
+ if getattr(self, "hubert", None) is not None:
1503
+ with tf.name_scope(self.hubert.name):
1504
+ self.hubert.build(None)
1505
+
1506
+
1507
+ @add_start_docstrings(
1508
+ """TFHubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).""",
1509
+ HUBERT_START_DOCSTRING,
1510
+ )
1511
+ class TFHubertForCTC(TFHubertPreTrainedModel):
1512
+ def __init__(self, config: HubertConfig, *inputs, **kwargs):
1513
+ super().__init__(config, *inputs, **kwargs)
1514
+
1515
+ self.hubert = TFHubertMainLayer(config, name="hubert")
1516
+ self.dropout = keras.layers.Dropout(config.final_dropout)
1517
+ self.lm_head = keras.layers.Dense(config.vocab_size, name="lm_head")
1518
+ self.output_hidden_size = (
1519
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1520
+ )
1521
+
1522
+ def freeze_feature_extractor(self):
1523
+ """
1524
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1525
+ not be updated during training.
1526
+ """
1527
+ warnings.warn(
1528
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1529
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1530
+ FutureWarning,
1531
+ )
1532
+ self.freeze_feature_encoder()
1533
+
1534
+ def freeze_feature_encoder(self):
1535
+ """
1536
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1537
+ not be updated during training.
1538
+ """
1539
+ self.hubert.feature_extractor.trainable = False
1540
+
1541
+ @add_start_docstrings_to_model_forward(HUBERT_INPUTS_DOCSTRING)
1542
+ @replace_return_docstrings(output_type=TFCausalLMOutput, config_class=_CONFIG_FOR_DOC)
1543
+ @unpack_inputs
1544
+ def call(
1545
+ self,
1546
+ input_values: tf.Tensor,
1547
+ attention_mask: tf.Tensor | None = None,
1548
+ token_type_ids: tf.Tensor | None = None,
1549
+ position_ids: tf.Tensor | None = None,
1550
+ head_mask: tf.Tensor | None = None,
1551
+ inputs_embeds: tf.Tensor | None = None,
1552
+ output_attentions: bool | None = None,
1553
+ labels: tf.Tensor | None = None,
1554
+ output_hidden_states: bool | None = None,
1555
+ return_dict: bool | None = None,
1556
+ training: bool | None = False,
1557
+ ) -> TFCausalLMOutput | tuple[tf.Tensor]:
1558
+ r"""
1559
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
1560
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1561
+ config.vocab_size]` (see `input_values` docstring) Tokens with indices set to `-100` are ignored (masked),
1562
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1563
+
1564
+ Returns:
1565
+
1566
+ Example:
1567
+
1568
+ ```python
1569
+ >>> import tensorflow as tf
1570
+ >>> from transformers import AutoProcessor, TFHubertForCTC
1571
+ >>> from datasets import load_dataset
1572
+
1573
+ >>> processor = AutoProcessor.from_pretrained("facebook/hubert-large-ls960-ft")
1574
+ >>> model = TFHubertForCTC.from_pretrained("facebook/hubert-large-ls960-ft")
1575
+
1576
+
1577
+ >>> def map_to_array(example):
1578
+ ... example["speech"] = example["audio"]["array"]
1579
+ ... return example
1580
+
1581
+
1582
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
1583
+ >>> ds = ds.map(map_to_array)
1584
+
1585
+ >>> input_values = processor(ds["speech"][0], return_tensors="tf").input_values # Batch size 1
1586
+ >>> logits = model(input_values).logits
1587
+ >>> predicted_ids = tf.argmax(logits, axis=-1)
1588
+
1589
+ >>> transcription = processor.decode(predicted_ids[0])
1590
+
1591
+ >>> # compute loss
1592
+ >>> target_transcription = "A MAN SAID TO THE UNIVERSE SIR I EXIST"
1593
+
1594
+ >>> # Pass the transcription as text to encode labels
1595
+ >>> labels = processor(text=transcription, return_tensors="tf").input_values
1596
+
1597
+ >>> loss = model(input_values, labels=labels).loss
1598
+ ```"""
1599
+ if labels is not None and tf.reduce_max(labels) >= self.config.vocab_size:
1600
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1601
+
1602
+ outputs = self.hubert(
1603
+ input_values=input_values,
1604
+ attention_mask=attention_mask,
1605
+ token_type_ids=token_type_ids,
1606
+ position_ids=position_ids,
1607
+ head_mask=head_mask,
1608
+ inputs_embeds=inputs_embeds,
1609
+ output_attentions=output_attentions,
1610
+ output_hidden_states=output_hidden_states,
1611
+ return_dict=return_dict,
1612
+ training=training,
1613
+ )
1614
+ hidden_states = outputs[0]
1615
+ hidden_states = self.dropout(hidden_states, training=training)
1616
+
1617
+ logits = self.lm_head(hidden_states)
1618
+
1619
+ if labels is not None:
1620
+ attention_mask = (
1621
+ attention_mask if attention_mask is not None else tf.ones_like(input_values, dtype=tf.float32)
1622
+ )
1623
+ input_lengths = self.hubert._get_feat_extract_output_lengths(tf.reduce_sum(attention_mask, axis=-1))
1624
+
1625
+ # assuming that padded tokens are filled with -100
1626
+ # when not being attended to
1627
+ labels_mask = tf.cast(labels >= 0, tf.int32)
1628
+ target_lengths = tf.reduce_sum(labels_mask, axis=-1)
1629
+
1630
+ loss = tf.nn.ctc_loss(
1631
+ logits=logits,
1632
+ labels=labels,
1633
+ logit_length=input_lengths,
1634
+ label_length=target_lengths,
1635
+ blank_index=self.config.pad_token_id,
1636
+ logits_time_major=False,
1637
+ )
1638
+
1639
+ if self.config.ctc_loss_reduction == "sum":
1640
+ loss = tf.reduce_sum(loss)
1641
+ loss = tf.reshape(loss, (1,))
1642
+ if self.config.ctc_loss_reduction == "mean":
1643
+ loss = tf.reduce_mean(loss)
1644
+ loss = tf.reshape(loss, (1,))
1645
+ else:
1646
+ loss = None
1647
+
1648
+ if not return_dict:
1649
+ output = (logits,) + outputs[1:]
1650
+ return ((loss,) + output) if loss is not None else output
1651
+
1652
+ return TFCausalLMOutput(
1653
+ loss=loss,
1654
+ logits=logits,
1655
+ hidden_states=outputs.hidden_states,
1656
+ attentions=outputs.attentions,
1657
+ )
1658
+
1659
+ def build(self, input_shape=None):
1660
+ if self.built:
1661
+ return
1662
+ self.built = True
1663
+ if getattr(self, "hubert", None) is not None:
1664
+ with tf.name_scope(self.hubert.name):
1665
+ self.hubert.build(None)
1666
+ if getattr(self, "lm_head", None) is not None:
1667
+ with tf.name_scope(self.lm_head.name):
1668
+ self.lm_head.build([None, None, self.output_hidden_size])
1669
+
1670
+
1671
+ __all__ = ["TFHubertForCTC", "TFHubertModel", "TFHubertPreTrainedModel"]