flexthink commited on
Commit
2678216
1 Parent(s): 5422153

Initial importZ

Browse files
attention_mlp.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28c1d68f953ce692dbdbb0501e16cb005b232e45d9244ac2b2681931c3055e7b
3
+ size 4204478
classifier.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:896a20f78eb8cfde322b5ec4e5eb82413b75fd453bdc8763a197bd68b229358d
3
+ size 931371
custom_interface.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Mapping
2
+ import torch
3
+ import math
4
+ from speechbrain.inference.interfaces import Pretrained
5
+
6
+
7
+ class AttentionMLP(torch.nn.Module):
8
+ def __init__(self, input_dim, hidden_dim):
9
+ super(AttentionMLP, self).__init__()
10
+ self.layers = torch.nn.Sequential(
11
+ torch.nn.Linear(input_dim, hidden_dim),
12
+ torch.nn.ReLU(),
13
+ torch.nn.Linear(hidden_dim, 1, bias=False),
14
+ )
15
+
16
+ def forward(self, x):
17
+ x = self.layers(x)
18
+ att_w = torch.nn.functional.softmax(x, dim=2)
19
+ return att_w
20
+
21
+
22
+ class Discrete_EmbeddingLayer(torch.nn.Module):
23
+ """This class handles embedding layers for discrete tokens.
24
+
25
+ Arguments
26
+ ---------
27
+ num_codebooks: int ,
28
+ number of codebooks of the tokenizer.
29
+ vocab_size : int,
30
+ size of the dictionary of embeddings
31
+ emb_dim: int ,
32
+ the size of each embedding vector
33
+ pad_index: int (default: 0),
34
+ If specified, the entries at padding_idx do not contribute to the gradient.
35
+ init: boolean (default: False):
36
+ If set to True, init the embedding with the tokenizer embedding otherwise init randomly.
37
+ freeze: boolean (default: False)
38
+ If True, the embedding is frozen. If False, the model will be trained
39
+ alongside with the rest of the pipeline.
40
+ chunk_size: int
41
+ The size of lengthwize chunks use when evaluating via
42
+ Gumbel softmax
43
+
44
+ Example
45
+ -------
46
+ >>> from speechbrain.lobes.models.huggingface_transformers.encodec import Encodec
47
+ >>> model_hub = "facebook/encodec_24khz"
48
+ >>> save_path = "savedir"
49
+ >>> model = Encodec(model_hub, save_path)
50
+ >>> audio = torch.randn(4, 1000)
51
+ >>> length = torch.tensor([1.0, .5, .75, 1.0])
52
+ >>> tokens, emb = model.encode(audio, length)
53
+ >>> print(tokens.shape)
54
+ torch.Size([4, 4, 2])
55
+ >>> emb= Discrete_EmbeddingLayer(2, 1024, 1024)
56
+ >>> in_emb = emb(tokens)
57
+ >>> print(in_emb.shape)
58
+ torch.Size([4, 4, 2, 1024])
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ num_codebooks,
64
+ vocab_size,
65
+ emb_dim,
66
+ pad_index=0,
67
+ init=False,
68
+ freeze=False,
69
+ available_layers=None,
70
+ layers=None,
71
+ chunk_size=100,
72
+ ):
73
+ super(Discrete_EmbeddingLayer, self).__init__()
74
+ self.vocab_size = vocab_size
75
+ self.num_codebooks = num_codebooks
76
+ self.freeze = freeze
77
+ self.embedding = torch.nn.Embedding(
78
+ num_codebooks * vocab_size, emb_dim
79
+ ).requires_grad_(not self.freeze)
80
+ self.init = init
81
+ self.layers = layers
82
+ self.available_layers = available_layers
83
+ self.register_buffer("offsets", self.build_offsets())
84
+ self.register_buffer("layer_embs", self.compute_layer_embs())
85
+ self.chunk_size = chunk_size
86
+
87
+ def init_embedding(self, weights):
88
+ with torch.no_grad():
89
+ self.embedding.weight = torch.nn.Parameter(weights)
90
+
91
+ def build_offsets(self):
92
+ offsets = torch.arange(
93
+ 0,
94
+ self.num_codebooks * self.vocab_size,
95
+ self.vocab_size,
96
+ )
97
+ if self.layers:
98
+ selected_layers = set(self.layers)
99
+ indexes = [
100
+ idx for idx, layer in enumerate(self.available_layers)
101
+ if layer in selected_layers
102
+ ]
103
+ offsets = offsets[indexes]
104
+ return offsets
105
+
106
+ def forward(self, in_tokens):
107
+ """Computes the embedding for discrete tokens.
108
+ a sample.
109
+
110
+ Arguments
111
+ ---------
112
+ in_tokens : torch.Tensor
113
+ A (Batch x Time x num_codebooks)
114
+ audio sample
115
+ Returns
116
+ -------
117
+ in_embs : torch.Tensor
118
+ """
119
+ with torch.set_grad_enabled(not self.freeze):
120
+ # Add unique token IDs across diffrent codebooks by adding num_codebooks * vocab_size
121
+ in_tokens_offset = in_tokens + self.offsets.to(in_tokens.device)
122
+ # Forward Pass to embedding and
123
+ in_embs = self.embedding(in_tokens_offset.int())
124
+ return in_embs
125
+
126
+ def compute_layer_embs(self):
127
+ weight = self.embedding.weight
128
+
129
+ # Compute offsets
130
+ layer_idx_map = {
131
+ layer: idx
132
+ for idx, layer in enumerate(self.available_layers)
133
+ }
134
+ layer_idx = [
135
+ layer_idx_map[layer]
136
+ for layer in self.layers
137
+ ]
138
+
139
+ offsets = [
140
+ idx * self.vocab_size
141
+ for idx in layer_idx
142
+ ]
143
+
144
+ layer_embs = torch.stack([
145
+ weight[offset:offset + self.vocab_size]
146
+ for offset in offsets
147
+ ])
148
+
149
+ # To (Batch x Length x Emb)
150
+ layer_embs = layer_embs.unsqueeze(0).unsqueeze(0)
151
+ return layer_embs
152
+
153
+ def encode_logits(self, logits, length=None):
154
+ """Computes waveforms from a batch of discrete units
155
+ Arguments
156
+ ---------
157
+ units: torch.tensor
158
+ Batch of discrete unit logits [batch, length, head, token]
159
+ or tokens [batch, length, head]
160
+ spk: torch.tensor
161
+ Batch of speaker embeddings [batch, spk_dim]
162
+ Returns
163
+ -------
164
+ waveforms: torch.tensor
165
+ Batch of mel-waveforms [batch, 1, time]
166
+ """
167
+
168
+ # Convert logits to one-hot representations
169
+ # without losing the gradient
170
+ units_gumbel = torch.nn.functional.gumbel_softmax(
171
+ logits,
172
+ hard=False,
173
+ dim=-1
174
+ )
175
+
176
+ # Straight-through trick
177
+ _, argmax_idx = logits.max(dim=-1, keepdim=True)
178
+ units_ref = torch.zeros_like(logits).scatter_(
179
+ dim=-1, index=argmax_idx, src=torch.ones_like(logits)
180
+ )
181
+ units_hard = units_ref - units_gumbel.detach() + units_gumbel
182
+
183
+ # Sum over embeddings for each layer
184
+ units_hard_chunked = units_hard.chunk(
185
+ math.ceil(units_hard.size(1) / self.chunk_size),
186
+ dim=1
187
+ )
188
+ emb = torch.cat(
189
+ [
190
+ (self.layer_embs * units_hard_chunk.unsqueeze(-1)).sum(-2)
191
+ for units_hard_chunk in units_hard_chunked
192
+ ],
193
+ dim=1
194
+ )
195
+ return emb
196
+
197
+ def load_state_dict(self, state_dict, strict=True):
198
+ result = super().load_state_dict(state_dict, strict)
199
+ self.layer_embs = self.compute_layer_embs()
200
+ return result
201
+
202
+
203
+ class DiscreteSpkEmb(Pretrained):
204
+ """A ready-to-use class for utterance-level classification (e.g, speaker-id,
205
+ language-id, emotion recognition, keyword spotting, etc).
206
+ The class assumes that an self-supervised encoder like wav2vec2/hubert and a classifier model
207
+ are defined in the yaml file. If you want to
208
+ convert the predicted index into a corresponding text label, please
209
+ provide the path of the label_encoder in a variable called 'lab_encoder_file'
210
+ within the yaml.
211
+ The class can be used either to run only the encoder (encode_batch()) to
212
+ extract embeddings or to run a classification step (classify_batch()).
213
+ ```
214
+ Example
215
+ -------
216
+ >>> import torchaudio
217
+ >>> from speechbrain.pretrained import EncoderClassifier
218
+ >>> # Model is downloaded from the speechbrain HuggingFace repo
219
+ >>> tmpdir = getfixture("tmpdir")
220
+ >>> classifier = EncoderClassifier.from_hparams(
221
+ ... source="speechbrain/spkrec-ecapa-voxceleb",
222
+ ... savedir=tmpdir,
223
+ ... )
224
+ >>> # Compute embeddings
225
+ >>> signal, fs = torchaudio.load("samples/audio_samples/example1.wav")
226
+ >>> embeddings = classifier.encode_batch(signal)
227
+ >>> # Classification
228
+ >>> prediction = classifier .classify_batch(signal)
229
+ """
230
+
231
+ def __init__(self, *args, **kwargs):
232
+ super().__init__(*args, **kwargs)
233
+
234
+ def encode_batch(self, audio, length=None):
235
+ """Encodes the input audio into a single vector embedding.
236
+ The waveforms should already be in the model's desired format.
237
+ Arguments
238
+ ---------
239
+ audio : torch.tensor
240
+ Batch of tokenized audio [batch, time, heads]
241
+ length : torch.tensor
242
+ Lengths of the waveforms relative to the longest one in the
243
+ batch, tensor of shape [batch]. The longest one should have
244
+ relative length 1.0 and others len(waveform) / max_length.
245
+ Used for ignoring padding.
246
+
247
+ Returns
248
+ -------
249
+ torch.tensor
250
+ The encoded batch
251
+ """
252
+ # Manage single waveforms in input
253
+ embeddings = self.mods.discrete_embedding_layer(audio)
254
+ att_w = self.mods.attention_mlp(embeddings)
255
+ feats = torch.matmul(att_w.transpose(2, -1), embeddings).squeeze(-2)
256
+ embeddings = self.mods.embedding_model(feats, length)
257
+ return embeddings.squeeze(1)
258
+
259
+ def encode_logits(self, logits, length=None):
260
+ """Encodes the input audio logits into a single vector embedding.
261
+
262
+ Arguments
263
+ ---------
264
+ audio : torch.tensor
265
+ Batch of tokenized audio [batch, time, heads]
266
+ length : torch.tensor
267
+ Lengths of the waveforms relative to the longest one in the
268
+ batch, tensor of shape [batch]. The longest one should have
269
+ relative length 1.0 and others len(waveform) / max_length.
270
+ Used for ignoring padding.
271
+
272
+ Returns
273
+ -------
274
+ torch.tensor
275
+ The encoded batch
276
+ """
277
+ embeddings = self.mods.discrete_embedding_layer.encode_logits(logits)
278
+ att_w = self.mods.attention_mlp(embeddings)
279
+ feats = torch.matmul(att_w.transpose(2, -1), embeddings).squeeze(-2)
280
+ embeddings = self.mods.embedding_model(feats, length)
281
+ return embeddings.squeeze(1)
282
+
283
+ def forward(self, audio, length=None):
284
+ """Encodes the input audio into a single vector embedding.
285
+ The waveforms should already be in the model's desired format.
286
+ Arguments
287
+ ---------
288
+ audio : torch.tensor
289
+ Batch of tokenized audio [batch, time, heads]
290
+ or logits [batch, time, heads, tokens]
291
+ length : torch.tensor
292
+ Lengths of the waveforms relative to the longest one in the
293
+ batch, tensor of shape [batch]. The longest one should have
294
+ relative length 1.0 and others len(waveform) / max_length.
295
+ Used for ignoring padding.
296
+
297
+ Returns
298
+ -------
299
+ torch.tensor
300
+ The encoded batch
301
+ """
302
+ audio_dim = audio.dim()
303
+ if audio_dim == 3:
304
+ embeddings = self.encode_batch(audio, length)
305
+ elif audio_dim == 4:
306
+ embeddings = self.encode_logits(audio, length)
307
+ else:
308
+ raise ValueError("Unsupported audio shape {audio.shape}")
309
+ return embeddings
discrete_embedding_layer.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0242e3dbca8efaeaeaa3f79fd92d1828da4cd3504c57072fbbc4b2100a32647
3
+ size 24577457
embedding_model.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2564eaaa33bd952b771c9c09f9b3dc555285cd4801663afacf3200eb5ccf786c
3
+ size 102646844
hyperparams.yaml ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ############################################################################
2
+ # Model: ECAPA big for Speaker verification
3
+ # ############################################################################
4
+
5
+ # Feature parameters
6
+ n_mels: 80
7
+
8
+ # Pretrain folder (HuggingFace)
9
+ pretrained_path: flexthink/discrete_hubert_spk_rec_ecapatdn
10
+ # Output parameters
11
+ save_folder: tmp
12
+
13
+ ### Configuration for discrete SSL model
14
+ # ssl_model_type: hubert, wavlm, wav2vec2
15
+ # ssl_hub: facebook/hubert-large-ll60k, microsoft/wavlm-large, facebook/wav2vec2-large
16
+ ssl_model_type: hubert # hubert, wavml or wav2vec2
17
+ ssl_hub: facebook/hubert-large-ll60k
18
+ ssl_folder: !ref <save_folder>/ssl_checkpoint
19
+ kmeans_repo_id: speechbrain/SSL_Quantization
20
+ kmeans_cache_dir: !ref <save_folder>/kmeans_checkpoint
21
+ kmeans_dataset: LibriSpeech-100-360-500
22
+ freeze_ssl: True
23
+ freeze_feature_extractor: True
24
+ num_clusters: 1000
25
+
26
+ ### Config for Tokenizer
27
+ # Layer number should be among the supported layers for discrete SSL models(kmenas model should be available for that layer)
28
+ # ssl_layer_num: [3, 7, 12, 23]
29
+ # deduplicate: [False, False, False, False]
30
+ # bpe_tokenizer_path: [null , null, null, null]
31
+ ssl_layer_num: [1, 3, 7, 12, 18, 23]
32
+ ssl_layer_num_selected: [1, 3, 7, 12, 18, 23]
33
+ num_codebooks: 6
34
+ deduplicate: [False, False, False, False, False, False]
35
+ bpe_tokenizer_path: [null, null, null, null, null, null]
36
+ sample_rate: 16000
37
+
38
+ # Feature parameters
39
+ encoder_dim: 1024
40
+ # Modules
41
+ tokenizer_config:
42
+ SSL_layers: !ref <ssl_layer_num>
43
+ deduplicates: !ref <deduplicate>
44
+ bpe_tokenizers: !ref <bpe_tokenizer_path>
45
+
46
+ discrete_embedding_layer: !new:custom_interface.Discrete_EmbeddingLayer
47
+ num_codebooks: !ref <num_codebooks>
48
+ vocab_size: !ref <num_clusters>
49
+ emb_dim: !ref <encoder_dim>
50
+ available_layers: !ref <ssl_layer_num>
51
+ layers: !ref <ssl_layer_num_selected>
52
+
53
+ attention_mlp: !new:custom_interface.AttentionMLP
54
+ input_dim: !ref <encoder_dim>
55
+ hidden_dim: !ref <encoder_dim>
56
+
57
+ embedding_model: !new:speechbrain.lobes.models.ECAPA_TDNN.ECAPA_TDNN
58
+ input_size: !ref <encoder_dim>
59
+ channels: [1024, 1024, 1024, 1024, 3072]
60
+ kernel_sizes: [5, 3, 3, 3, 1]
61
+ dilations: [1, 2, 3, 4, 1]
62
+ groups: [1, 1, 1, 1, 1]
63
+ attention_channels: 128
64
+ lin_neurons: 192
65
+
66
+ modules:
67
+ embedding_model: !ref <embedding_model>
68
+ attention_mlp: !ref <attention_mlp>
69
+ discrete_embedding_layer: !ref <discrete_embedding_layer>
70
+
71
+
72
+ pretrainer: !new:speechbrain.utils.parameter_transfer.Pretrainer
73
+ loadables:
74
+ embedding_model: !ref <embedding_model>
75
+ attention_mlp: !ref <attention_mlp>
76
+ discrete_embedding_layer: !ref <discrete_embedding_layer>
77
+
78
+ paths:
79
+ embedding_model: !ref <pretrained_path>/embedding_model.ckpt
80
+ attention_mlp: !ref <pretrained_path>/attention_mlp.ckpt
81
+ discrete_embedding_layer: !ref <pretrained_path>/discrete_embedding_layer.ckpt
82
+
83
+