SeyedAli commited on
Commit
1be8004
1 Parent(s): 54063ad

Upload 2 files

Browse files
Files changed (2) hide show
  1. modeling_outputs.py +12 -0
  2. models.py +222 -0
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
models.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
153
+ self.hubert.feature_extractor._freeze_parameters()
154
+
155
+ def merged_strategy(
156
+ self,
157
+ hidden_states,
158
+ mode="mean"
159
+ ):
160
+ if mode == "mean":
161
+ outputs = torch.mean(hidden_states, dim=1)
162
+ elif mode == "sum":
163
+ outputs = torch.sum(hidden_states, dim=1)
164
+ elif mode == "max":
165
+ outputs = torch.max(hidden_states, dim=1)[0]
166
+ else:
167
+ raise Exception(
168
+ "The pooling method hasn't been defined! Your pooling mode must be one of these ['mean', 'sum', 'max']")
169
+
170
+ return outputs
171
+
172
+ def forward(
173
+ self,
174
+ input_values,
175
+ attention_mask=None,
176
+ output_attentions=None,
177
+ output_hidden_states=None,
178
+ return_dict=None,
179
+ labels=None,
180
+ ):
181
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
182
+ outputs = self.hubert(
183
+ input_values,
184
+ attention_mask=attention_mask,
185
+ output_attentions=output_attentions,
186
+ output_hidden_states=output_hidden_states,
187
+ return_dict=return_dict,
188
+ )
189
+ hidden_states = outputs[0]
190
+ hidden_states = self.merged_strategy(hidden_states, mode=self.pooling_mode)
191
+ logits = self.classifier(hidden_states)
192
+
193
+ loss = None
194
+ if labels is not None:
195
+ if self.config.problem_type is None:
196
+ if self.num_labels == 1:
197
+ self.config.problem_type = "regression"
198
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
199
+ self.config.problem_type = "single_label_classification"
200
+ else:
201
+ self.config.problem_type = "multi_label_classification"
202
+
203
+ if self.config.problem_type == "regression":
204
+ loss_fct = MSELoss()
205
+ loss = loss_fct(logits.view(-1, self.num_labels), labels)
206
+ elif self.config.problem_type == "single_label_classification":
207
+ loss_fct = CrossEntropyLoss()
208
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
209
+ elif self.config.problem_type == "multi_label_classification":
210
+ loss_fct = BCEWithLogitsLoss()
211
+ loss = loss_fct(logits, labels)
212
+
213
+ if not return_dict:
214
+ output = (logits,) + outputs[2:]
215
+ return ((loss,) + output) if loss is not None else output
216
+
217
+ return SpeechClassifierOutput(
218
+ loss=loss,
219
+ logits=logits,
220
+ hidden_states=outputs.hidden_states,
221
+ attentions=outputs.attentions,
222
+ )