MagicLuke commited on
Commit
cb95574
·
verified ·
1 Parent(s): 8d94934

Upload HFECAPATDNN

Browse files
config.json CHANGED
@@ -3,6 +3,10 @@
3
  "architectures": [
4
  "HFECAPATDNN"
5
  ],
 
 
 
 
6
  "model_type": "ecapa_tdnn",
7
  "torch_dtype": "float32",
8
  "transformers_version": "4.49.0"
 
3
  "architectures": [
4
  "HFECAPATDNN"
5
  ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_ecapa_tdnn.ECAPAConfig",
8
+ "AutoModel": "modeling_ecapa_tdnn.HFECAPATDNN"
9
+ },
10
  "model_type": "ecapa_tdnn",
11
  "torch_dtype": "float32",
12
  "transformers_version": "4.49.0"
configuration_ecapa_tdnn.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class ECAPAConfig(PretrainedConfig):
4
+ model_type = "ecapa_tdnn"
5
+ def __init__(self, C=1024, **kwargs):
6
+ super().__init__(**kwargs)
7
+ self.C = C
modeling_ecapa_tdnn.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ This is the ECAPA-TDNN model.
3
+ This model is modified and combined based on the following three projects:
4
+ 1. https://github.com/clovaai/voxceleb_trainer/issues/86
5
+ 2. https://github.com/lawlict/ECAPA-TDNN/blob/master/ecapa_tdnn.py
6
+ 3. https://github.com/speechbrain/speechbrain/blob/96077e9a1afff89d3f5ff47cab4bca0202770e4f/speechbrain/lobes/models/ECAPA_TDNN.py
7
+
8
+ '''
9
+
10
+ import math, torch, torchaudio
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+
14
+ class SEModule(nn.Module):
15
+ def __init__(self, channels, bottleneck=128):
16
+ super(SEModule, self).__init__()
17
+ self.se = nn.Sequential(
18
+ nn.AdaptiveAvgPool1d(1),
19
+ nn.Conv1d(channels, bottleneck, kernel_size=1, padding=0),
20
+ nn.ReLU(),
21
+ # nn.BatchNorm1d(bottleneck), # I remove this layer
22
+ nn.Conv1d(bottleneck, channels, kernel_size=1, padding=0),
23
+ nn.Sigmoid(),
24
+ )
25
+
26
+ def forward(self, input):
27
+ x = self.se(input)
28
+ return input * x
29
+
30
+ class Bottle2neck(nn.Module):
31
+
32
+ def __init__(self, inplanes, planes, kernel_size=None, dilation=None, scale = 8):
33
+ super(Bottle2neck, self).__init__()
34
+ width = int(math.floor(planes / scale))
35
+ self.conv1 = nn.Conv1d(inplanes, width*scale, kernel_size=1)
36
+ self.bn1 = nn.BatchNorm1d(width*scale)
37
+ self.nums = scale -1
38
+ convs = []
39
+ bns = []
40
+ num_pad = math.floor(kernel_size/2)*dilation
41
+ for i in range(self.nums):
42
+ convs.append(nn.Conv1d(width, width, kernel_size=kernel_size, dilation=dilation, padding=num_pad))
43
+ bns.append(nn.BatchNorm1d(width))
44
+ self.convs = nn.ModuleList(convs)
45
+ self.bns = nn.ModuleList(bns)
46
+ self.conv3 = nn.Conv1d(width*scale, planes, kernel_size=1)
47
+ self.bn3 = nn.BatchNorm1d(planes)
48
+ self.relu = nn.ReLU()
49
+ self.width = width
50
+ self.se = SEModule(planes)
51
+
52
+ def forward(self, x):
53
+ residual = x
54
+ out = self.conv1(x)
55
+ out = self.relu(out)
56
+ out = self.bn1(out)
57
+
58
+ spx = torch.split(out, self.width, 1)
59
+ for i in range(self.nums):
60
+ if i==0:
61
+ sp = spx[i]
62
+ else:
63
+ sp = sp + spx[i]
64
+ sp = self.convs[i](sp)
65
+ sp = self.relu(sp)
66
+ sp = self.bns[i](sp)
67
+ if i==0:
68
+ out = sp
69
+ else:
70
+ out = torch.cat((out, sp), 1)
71
+ out = torch.cat((out, spx[self.nums]),1)
72
+
73
+ out = self.conv3(out)
74
+ out = self.relu(out)
75
+ out = self.bn3(out)
76
+
77
+ out = self.se(out)
78
+ out += residual
79
+ return out
80
+
81
+ class PreEmphasis(torch.nn.Module):
82
+
83
+ def __init__(self, coef: float = 0.97):
84
+ super().__init__()
85
+ self.coef = coef
86
+ self.register_buffer(
87
+ 'flipped_filter', torch.FloatTensor([-self.coef, 1.]).unsqueeze(0).unsqueeze(0)
88
+ )
89
+
90
+ def forward(self, input: torch.tensor) -> torch.tensor:
91
+ input = input.unsqueeze(1)
92
+ input = F.pad(input, (1, 0), 'reflect')
93
+ return F.conv1d(input, self.flipped_filter).squeeze(1)
94
+
95
+ class FbankAug(nn.Module):
96
+
97
+ def __init__(self, freq_mask_width = (0, 8), time_mask_width = (0, 10)):
98
+ self.time_mask_width = time_mask_width
99
+ self.freq_mask_width = freq_mask_width
100
+ super().__init__()
101
+
102
+ def mask_along_axis(self, x, dim):
103
+ original_size = x.shape
104
+ batch, fea, time = x.shape
105
+ if dim == 1:
106
+ D = fea
107
+ width_range = self.freq_mask_width
108
+ else:
109
+ D = time
110
+ width_range = self.time_mask_width
111
+
112
+ mask_len = torch.randint(width_range[0], width_range[1], (batch, 1), device=x.device).unsqueeze(2)
113
+ mask_pos = torch.randint(0, max(1, D - mask_len.max()), (batch, 1), device=x.device).unsqueeze(2)
114
+ arange = torch.arange(D, device=x.device).view(1, 1, -1)
115
+ mask = (mask_pos <= arange) * (arange < (mask_pos + mask_len))
116
+ mask = mask.any(dim=1)
117
+
118
+ if dim == 1:
119
+ mask = mask.unsqueeze(2)
120
+ else:
121
+ mask = mask.unsqueeze(1)
122
+
123
+ x = x.masked_fill_(mask, 0.0)
124
+ return x.view(*original_size)
125
+
126
+ def forward(self, x):
127
+ x = self.mask_along_axis(x, dim=2)
128
+ x = self.mask_along_axis(x, dim=1)
129
+ return x
130
+
131
+ class ECAPA_TDNN(nn.Module):
132
+
133
+ def __init__(self, C):
134
+
135
+ super(ECAPA_TDNN, self).__init__()
136
+
137
+ self.torchfbank = torch.nn.Sequential(
138
+ PreEmphasis(),
139
+ # torchaudio.transforms.MelSpectrogram(sample_rate=16000, n_fft=512, win_length=400, hop_length=160, \
140
+ # f_min = 20, f_max = 7600, window_fn=torch.hamming_window, n_mels=80),
141
+ torchaudio.transforms.Resample(orig_freq=16000, new_freq=22050),
142
+ torchaudio.transforms.MelSpectrogram(
143
+ sample_rate = 22050,
144
+ n_fft = 2048,
145
+ hop_length = 512,
146
+ win_length = 2048,
147
+ # window_fn = lambda *_: window,
148
+ center = False,
149
+ power = 2.0,
150
+ n_mels = 256,
151
+ norm = "slaney",
152
+ mel_scale = "htk",
153
+ ),
154
+ torchaudio.transforms.AmplitudeToDB(
155
+ stype="power", top_db=80
156
+ )
157
+ )
158
+
159
+ self.specaug = FbankAug() # Spec augmentation
160
+
161
+ # self.conv1 = nn.Conv1d(80, C, kernel_size=5, stride=1, padding=2)
162
+ # self.conv1 = nn.Conv1d(256, C, kernel_size=5, stride=1, padding=2)
163
+ self.conv1 = nn.Conv1d(232, C, kernel_size=5, stride=1, padding=2)
164
+ self.relu = nn.ReLU()
165
+ self.bn1 = nn.BatchNorm1d(C)
166
+ self.layer1 = Bottle2neck(C, C, kernel_size=3, dilation=2, scale=8)
167
+ self.layer2 = Bottle2neck(C, C, kernel_size=3, dilation=3, scale=8)
168
+ self.layer3 = Bottle2neck(C, C, kernel_size=3, dilation=4, scale=8)
169
+ # I fixed the shape of the output from MFA layer, that is close to the setting from ECAPA paper.
170
+ self.layer4 = nn.Conv1d(3*C, 1536, kernel_size=1)
171
+ self.attention = nn.Sequential(
172
+ nn.Conv1d(4608, 256, kernel_size=1),
173
+ nn.ReLU(),
174
+ nn.BatchNorm1d(256),
175
+ nn.Tanh(), # I add this layer
176
+ nn.Conv1d(256, 1536, kernel_size=1),
177
+ nn.Softmax(dim=2),
178
+ )
179
+ self.bn5 = nn.BatchNorm1d(3072)
180
+ self.fc6 = nn.Linear(3072, 192)
181
+ self.bn6 = nn.BatchNorm1d(192)
182
+
183
+
184
+ def forward(self, x, aug):
185
+ with torch.no_grad():
186
+ x = self.torchfbank(x)
187
+ # x = self.torchfbank(x)+1e-6
188
+ # x = x.log()
189
+ x = x - torch.mean(x, dim=-1, keepdim=True) # mean normalization
190
+ if aug == True:
191
+ x = self.specaug(x)
192
+ # only take the first 232 mel bins
193
+ if x.dim() == 3:
194
+ x = x[:, :232, :]
195
+ else:
196
+ x = x[:232]
197
+
198
+ x = self.conv1(x)
199
+ x = self.relu(x)
200
+ x = self.bn1(x)
201
+
202
+ x1 = self.layer1(x)
203
+ x2 = self.layer2(x+x1)
204
+ x3 = self.layer3(x+x1+x2)
205
+
206
+ x = self.layer4(torch.cat((x1,x2,x3),dim=1))
207
+ x = self.relu(x)
208
+
209
+ t = x.size()[-1]
210
+
211
+ global_x = torch.cat((x,torch.mean(x,dim=2,keepdim=True).repeat(1,1,t), torch.sqrt(torch.var(x,dim=2,keepdim=True).clamp(min=1e-4)).repeat(1,1,t)), dim=1)
212
+
213
+ w = self.attention(global_x)
214
+
215
+ mu = torch.sum(x * w, dim=2)
216
+ sg = torch.sqrt( ( torch.sum((x**2) * w, dim=2) - mu**2 ).clamp(min=1e-4) )
217
+
218
+ x = torch.cat((mu,sg),1)
219
+ x = self.bn5(x)
220
+ x = self.fc6(x)
221
+ x = self.bn6(x)
222
+
223
+ return x
224
+
225
+
226
+ import torch
227
+ from transformers import PreTrainedModel
228
+ from configuration_ecapa_tdnn import ECAPAConfig
229
+
230
+
231
+ class HFECAPATDNN(PreTrainedModel):
232
+ config_class = ECAPAConfig
233
+ base_model_prefix = "ecapa_tdnn"
234
+ def __init__(self, config):
235
+ super().__init__(config)
236
+ self.model = ECAPA_TDNN(C=config.C)
237
+ def forward(self, *args, **kwargs):
238
+ return self.model(*args, **kwargs)