andromeda01111 commited on
Commit
7abc6f2
·
verified ·
1 Parent(s): e387b5a

Upload 10 files

Browse files
src/__init__.py ADDED
File without changes
src/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (149 Bytes). View file
 
src/__pycache__/collator.cpython-39.pyc ADDED
Binary file (3.29 kB). View file
 
src/__pycache__/modeling_outputs.cpython-39.pyc ADDED
Binary file (700 Bytes). View file
 
src/__pycache__/models.cpython-39.pyc ADDED
Binary file (5.6 kB). View file
 
src/__pycache__/trainer.cpython-39.pyc ADDED
Binary file (2.04 kB). View file
 
src/collator.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict, List, Optional, Union
3
+ import torch
4
+
5
+ import transformers
6
+ from transformers import Wav2Vec2Processor, Wav2Vec2FeatureExtractor
7
+
8
+
9
+ @dataclass
10
+ class DataCollatorCTCWithPadding:
11
+ """
12
+ Data collator that will dynamically pad the inputs received.
13
+ Args:
14
+ feature_extractor (:class:`~transformers.Wav2Vec2FeatureExtractor`)
15
+ The feature_extractor used for proccessing the data.
16
+ padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
17
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
18
+ among:
19
+ * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
20
+ sequence if provided).
21
+ * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
22
+ maximum acceptable input length for the model if that argument is not provided.
23
+ * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
24
+ different lengths).
25
+ max_length (:obj:`int`, `optional`):
26
+ Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).
27
+ max_length_labels (:obj:`int`, `optional`):
28
+ Maximum length of the ``labels`` returned list and optionally padding length (see above).
29
+ pad_to_multiple_of (:obj:`int`, `optional`):
30
+ If set will pad the sequence to a multiple of the provided value.
31
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
32
+ 7.5 (Volta).
33
+ """
34
+
35
+ feature_extractor: Wav2Vec2FeatureExtractor
36
+ padding: Union[bool, str] = True
37
+ max_length: Optional[int] = None
38
+ max_length_labels: Optional[int] = None
39
+ pad_to_multiple_of: Optional[int] = None
40
+ pad_to_multiple_of_labels: Optional[int] = None
41
+
42
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
43
+ input_features = [{"input_values": feature["input_values"]} for feature in features]
44
+ label_features = [feature["labels"] for feature in features]
45
+
46
+ d_type = torch.long if isinstance(label_features[0], int) else torch.float
47
+
48
+ batch = self.feature_extractor.pad(
49
+ input_features,
50
+ padding=self.padding,
51
+ max_length=self.max_length,
52
+ pad_to_multiple_of=self.pad_to_multiple_of,
53
+ return_tensors="pt",
54
+ )
55
+
56
+ batch["labels"] = torch.tensor(label_features, dtype=d_type)
57
+
58
+ return batch
src/modeling_outputs.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional, Tuple
3
+ import torch
4
+ from transformers.file_utils import ModelOutput
5
+
6
+
7
+ @dataclass
8
+ class SpeechClassifierOutput(ModelOutput):
9
+ loss: Optional[torch.FloatTensor] = None
10
+ logits: torch.FloatTensor = None
11
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
12
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
src/models.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
4
+
5
+ from transformers.models.wav2vec2.modeling_wav2vec2 import (
6
+ Wav2Vec2PreTrainedModel,
7
+ Wav2Vec2Model
8
+ )
9
+ from transformers.models.hubert.modeling_hubert import (
10
+ HubertPreTrainedModel,
11
+ HubertModel
12
+ )
13
+
14
+ from src.modeling_outputs import SpeechClassifierOutput
15
+
16
+
17
+ class Wav2Vec2ClassificationHead(nn.Module):
18
+ """Head for wav2vec classification task."""
19
+
20
+ def __init__(self, config):
21
+ super().__init__()
22
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
23
+ self.dropout = nn.Dropout(config.final_dropout)
24
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
25
+
26
+ def forward(self, features, **kwargs):
27
+ x = features
28
+ x = self.dropout(x)
29
+ x = self.dense(x)
30
+ x = torch.tanh(x)
31
+ x = self.dropout(x)
32
+ x = self.out_proj(x)
33
+ return x
34
+
35
+
36
+ class Wav2Vec2ForSpeechClassification(Wav2Vec2PreTrainedModel):
37
+ def __init__(self, config):
38
+ super().__init__(config)
39
+ self.num_labels = config.num_labels
40
+ self.pooling_mode = config.pooling_mode
41
+ self.config = config
42
+
43
+ self.wav2vec2 = Wav2Vec2Model(config)
44
+ self.classifier = Wav2Vec2ClassificationHead(config)
45
+
46
+ self.init_weights()
47
+
48
+ def freeze_feature_extractor(self):
49
+ self.wav2vec2.feature_extractor._freeze_parameters()
50
+
51
+ def merged_strategy(
52
+ self,
53
+ hidden_states,
54
+ mode="mean"
55
+ ):
56
+ if mode == "mean":
57
+ outputs = torch.mean(hidden_states, dim=1)
58
+ elif mode == "sum":
59
+ outputs = torch.sum(hidden_states, dim=1)
60
+ elif mode == "max":
61
+ outputs = torch.max(hidden_states, dim=1)[0]
62
+ else:
63
+ raise Exception(
64
+ "The pooling method hasn't been defined! Your pooling mode must be one of these ['mean', 'sum', 'max']")
65
+
66
+ return outputs
67
+
68
+ def forward(
69
+ self,
70
+ input_values,
71
+ attention_mask=None,
72
+ output_attentions=None,
73
+ output_hidden_states=None,
74
+ return_dict=None,
75
+ labels=None,
76
+ ):
77
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
78
+ outputs = self.wav2vec2(
79
+ input_values,
80
+ attention_mask=attention_mask,
81
+ output_attentions=output_attentions,
82
+ output_hidden_states=output_hidden_states,
83
+ return_dict=return_dict,
84
+ )
85
+ hidden_states = outputs[0]
86
+ hidden_states = self.merged_strategy(hidden_states, mode=self.pooling_mode)
87
+ logits = self.classifier(hidden_states)
88
+
89
+ loss = None
90
+ if labels is not None:
91
+ if self.config.problem_type is None:
92
+ if self.num_labels == 1:
93
+ self.config.problem_type = "regression"
94
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
95
+ self.config.problem_type = "single_label_classification"
96
+ else:
97
+ self.config.problem_type = "multi_label_classification"
98
+
99
+ if self.config.problem_type == "regression":
100
+ loss_fct = MSELoss()
101
+ loss = loss_fct(logits.view(-1, self.num_labels), labels)
102
+ elif self.config.problem_type == "single_label_classification":
103
+ loss_fct = CrossEntropyLoss()
104
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
105
+ elif self.config.problem_type == "multi_label_classification":
106
+ loss_fct = BCEWithLogitsLoss()
107
+ loss = loss_fct(logits, labels)
108
+
109
+ if not return_dict:
110
+ output = (logits,) + outputs[2:]
111
+ return ((loss,) + output) if loss is not None else output
112
+
113
+ return SpeechClassifierOutput(
114
+ loss=loss,
115
+ logits=logits,
116
+ hidden_states=outputs.hidden_states,
117
+ attentions=outputs.attentions,
118
+ )
119
+
120
+
121
+ class HubertClassificationHead(nn.Module):
122
+ """Head for hubert classification task."""
123
+
124
+ def __init__(self, config):
125
+ super().__init__()
126
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
127
+ self.dropout = nn.Dropout(config.final_dropout)
128
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
129
+
130
+ def forward(self, features, **kwargs):
131
+ x = features
132
+ x = self.dropout(x)
133
+ x = self.dense(x)
134
+ x = torch.tanh(x)
135
+ x = self.dropout(x)
136
+ x = self.out_proj(x)
137
+ return x
138
+
139
+
140
+ class HubertForSpeechClassification(HubertPreTrainedModel):
141
+ def __init__(self, config):
142
+ super().__init__(config)
143
+ self.num_labels = config.num_labels
144
+ self.pooling_mode = config.pooling_mode
145
+ self.config = config
146
+
147
+ self.hubert = HubertModel(config)
148
+ self.classifier = HubertClassificationHead(config)
149
+
150
+ self.init_weights()
151
+
152
+ def freeze_feature_extractor(self): self.hubert.feature_extractor._freeze_parameters()
153
+
154
+ def merged_strategy(
155
+ self,
156
+ hidden_states,
157
+ mode="mean"):
158
+ if mode == "mean":
159
+ outputs = torch.mean(hidden_states, dim=1)
160
+ elif mode == "sum":
161
+ outputs = torch.sum(hidden_states, dim=1)
162
+ elif mode == "max":
163
+ outputs = torch.max(hidden_states, dim=1)[0]
164
+ else:
165
+ raise Exception(
166
+ "The pooling method hasn't been defined! Your pooling mode must be one of these ['mean', 'sum', 'max']")
167
+
168
+ return outputs
169
+
170
+ def forward(
171
+ self,
172
+ input_values,
173
+ attention_mask=None,
174
+ output_attentions=None,
175
+ output_hidden_states=None,
176
+ return_dict=None,
177
+ labels=None,
178
+ ):
179
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
180
+ outputs = self.hubert(
181
+ input_values,
182
+ attention_mask=attention_mask,
183
+ output_attentions=output_attentions,
184
+ output_hidden_states=output_hidden_states,
185
+ return_dict=return_dict,
186
+ )
187
+ hidden_states = outputs[0]
188
+ hidden_states = self.merged_strategy(hidden_states, mode=self.pooling_mode)
189
+ logits = self.classifier(hidden_states)
190
+
191
+ loss = None
192
+ if labels is not None:
193
+ if self.config.problem_type is None:
194
+ if self.num_labels == 1:
195
+ self.config.problem_type = "regression"
196
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
197
+ self.config.problem_type = "single_label_classification"
198
+ else:
199
+ self.config.problem_type = "multi_label_classification"
200
+
201
+ if self.config.problem_type == "regression":
202
+ loss_fct = MSELoss()
203
+ loss = loss_fct(logits.view(-1, self.num_labels), labels)
204
+ elif self.config.problem_type == "single_label_classification":
205
+ loss_fct = CrossEntropyLoss()
206
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
207
+ elif self.config.problem_type == "multi_label_classification":
208
+ loss_fct = BCEWithLogitsLoss()
209
+ loss = loss_fct(logits, labels)
210
+
211
+ if not return_dict:
212
+ output = (logits,) + outputs[2:]
213
+ return ((loss,) + output) if loss is not None else output
214
+
215
+ return SpeechClassifierOutput(
216
+ loss=loss,
217
+ logits=logits,
218
+ hidden_states=outputs.hidden_states,
219
+ attentions=outputs.attentions,
220
+ )
src/trainer.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Union
2
+
3
+ import torch
4
+ from packaging import version
5
+ from torch import nn
6
+
7
+ from transformers import (
8
+ Trainer,
9
+ is_apex_available,
10
+ )
11
+
12
+ if is_apex_available():
13
+ from apex import amp
14
+
15
+ if version.parse(torch.__version__) >= version.parse("1.6"):
16
+ _is_native_amp_available = True
17
+ from torch.cuda.amp import autocast
18
+
19
+
20
+ class CTCTrainer(Trainer):
21
+ def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor:
22
+ """
23
+ Perform a training step on a batch of inputs.
24
+
25
+ Subclass and override to inject custom behavior.
26
+
27
+ Args:
28
+ model (:obj:`nn.Module`):
29
+ The model to train.
30
+ inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
31
+ The inputs and targets of the model.
32
+
33
+ The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
34
+ argument :obj:`labels`. Check your model's documentation for all accepted arguments.
35
+
36
+ Return:
37
+ :obj:`torch.Tensor`: The tensor with training loss on this batch.
38
+ """
39
+
40
+ model.train()
41
+ inputs = self._prepare_inputs(inputs)
42
+
43
+ if self.use_amp:
44
+ with autocast():
45
+ loss = self.compute_loss(model, inputs)
46
+ else:
47
+ loss = self.compute_loss(model, inputs)
48
+
49
+ if self.args.gradient_accumulation_steps > 1:
50
+ loss = loss / self.args.gradient_accumulation_steps
51
+
52
+ if self.use_amp:
53
+ self.scaler.scale(loss).backward()
54
+ elif self.use_apex:
55
+ with amp.scale_loss(loss, self.optimizer) as scaled_loss:
56
+ scaled_loss.backward()
57
+ elif self.deepspeed:
58
+ self.deepspeed.backward(loss)
59
+ else:
60
+ loss.backward()
61
+
62
+ return loss.detach()