gautamtata commited on
Commit
5d7fda2
1 Parent(s): 3db4497

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +110 -1
handler.py CHANGED
@@ -1,10 +1,119 @@
1
- from transformers import AutoConfig, Wav2Vec2Processor, Wav2Vec2ForSpeechClassification
2
  from torch import nn
3
  import torch
4
  import torchaudio
5
  import torch.nn.functional as F
6
  from typing import Dict, List, Any
 
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  # Assuming the provided predict and related functions are part of your handler
9
 
10
  class EndpointHandler():
 
1
+ from transformers import AutoConfig, Wav2Vec2Processor
2
  from torch import nn
3
  import torch
4
  import torchaudio
5
  import torch.nn.functional as F
6
  from typing import Dict, List, Any
7
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
8
 
9
+ from transformers.models.wav2vec2.modeling_wav2vec2 import (
10
+ Wav2Vec2PreTrainedModel,
11
+ Wav2Vec2Model
12
+ )
13
+
14
+
15
+ class Wav2Vec2ClassificationHead(nn.Module):
16
+ """Head for wav2vec classification task."""
17
+
18
+ def __init__(self, config):
19
+ super().__init__()
20
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
21
+ self.dropout = nn.Dropout(config.final_dropout)
22
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
23
+
24
+ def forward(self, features, **kwargs):
25
+ x = features
26
+ x = self.dropout(x)
27
+ x = self.dense(x)
28
+ x = torch.tanh(x)
29
+ x = self.dropout(x)
30
+ x = self.out_proj(x)
31
+ return x
32
+
33
+
34
+ class Wav2Vec2ForSpeechClassification(Wav2Vec2PreTrainedModel):
35
+ def __init__(self, config):
36
+ super().__init__(config)
37
+ self.num_labels = config.num_labels
38
+ self.pooling_mode = config.pooling_mode
39
+ self.config = config
40
+
41
+ self.wav2vec2 = Wav2Vec2Model(config)
42
+ self.classifier = Wav2Vec2ClassificationHead(config)
43
+
44
+ self.init_weights()
45
+
46
+ def freeze_feature_extractor(self):
47
+ self.wav2vec2.feature_extractor._freeze_parameters()
48
+
49
+ def merged_strategy(
50
+ self,
51
+ hidden_states,
52
+ mode="mean"
53
+ ):
54
+ if mode == "mean":
55
+ outputs = torch.mean(hidden_states, dim=1)
56
+ elif mode == "sum":
57
+ outputs = torch.sum(hidden_states, dim=1)
58
+ elif mode == "max":
59
+ outputs = torch.max(hidden_states, dim=1)[0]
60
+ else:
61
+ raise Exception(
62
+ "The pooling method hasn't been defined! Your pooling mode must be one of these ['mean', 'sum', 'max']")
63
+
64
+ return outputs
65
+
66
+ def forward(
67
+ self,
68
+ input_values,
69
+ attention_mask=None,
70
+ output_attentions=None,
71
+ output_hidden_states=None,
72
+ return_dict=None,
73
+ labels=None,
74
+ ):
75
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
76
+ outputs = self.wav2vec2(
77
+ input_values,
78
+ attention_mask=attention_mask,
79
+ output_attentions=output_attentions,
80
+ output_hidden_states=output_hidden_states,
81
+ return_dict=return_dict,
82
+ )
83
+ hidden_states = outputs[0]
84
+ hidden_states = self.merged_strategy(hidden_states, mode=self.pooling_mode)
85
+ logits = self.classifier(hidden_states)
86
+
87
+ loss = None
88
+ if labels is not None:
89
+ if self.config.problem_type is None:
90
+ if self.num_labels == 1:
91
+ self.config.problem_type = "regression"
92
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
93
+ self.config.problem_type = "single_label_classification"
94
+ else:
95
+ self.config.problem_type = "multi_label_classification"
96
+
97
+ if self.config.problem_type == "regression":
98
+ loss_fct = MSELoss()
99
+ loss = loss_fct(logits.view(-1, self.num_labels), labels)
100
+ elif self.config.problem_type == "single_label_classification":
101
+ loss_fct = CrossEntropyLoss()
102
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
103
+ elif self.config.problem_type == "multi_label_classification":
104
+ loss_fct = BCEWithLogitsLoss()
105
+ loss = loss_fct(logits, labels)
106
+
107
+ if not return_dict:
108
+ output = (logits,) + outputs[2:]
109
+ return ((loss,) + output) if loss is not None else output
110
+
111
+ return SpeechClassifierOutput(
112
+ loss=loss,
113
+ logits=logits,
114
+ hidden_states=outputs.hidden_states,
115
+ attentions=outputs.attentions,
116
+ )
117
  # Assuming the provided predict and related functions are part of your handler
118
 
119
  class EndpointHandler():