Respair commited on
Commit
2584aa9
·
verified ·
1 Parent(s): a260881

Create models.py

Browse files
Files changed (1) hide show
  1. models.py +278 -0
models.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from loss import *
2
+
3
+ class AlignmentEncoder(torch.nn.Module):
4
+ """
5
+ Module for alignment text and mel spectrogram.
6
+
7
+ Args:
8
+ n_mel_channels: Dimension of mel spectrogram.
9
+ n_text_channels: Dimension of text embeddings.
10
+ n_att_channels: Dimension of model
11
+ temperature: Temperature to scale distance by.
12
+ Suggested to be 0.0005 when using dist_type "l2" and 15.0 when using "cosine".
13
+ condition_types: List of types for nemo.collections.tts.modules.submodules.ConditionalInput.
14
+ dist_type: Distance type to use for similarity measurement. Supports "l2" and "cosine" distance.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ n_mel_channels=128,
20
+ n_text_channels=512,
21
+ n_att_channels=128,
22
+ temperature=0.0005,
23
+ condition_types=[],
24
+ dist_type="l2",
25
+ ):
26
+ super().__init__()
27
+ self.temperature = temperature
28
+ # self.cond_input = ConditionalInput(n_text_channels, n_text_channels, condition_types)
29
+ self.softmax = torch.nn.Softmax(dim=3)
30
+ self.log_softmax = torch.nn.LogSoftmax(dim=3)
31
+
32
+ self.key_proj = nn.Sequential(
33
+ ConvNorm(n_text_channels, n_text_channels * 2, kernel_size=3, bias=True, w_init_gain='relu'),
34
+ torch.nn.ReLU(),
35
+ ConvNorm(n_text_channels * 2, n_att_channels, kernel_size=1, bias=True),
36
+ )
37
+
38
+ self.query_proj = nn.Sequential(
39
+ ConvNorm(n_mel_channels, n_mel_channels * 2, kernel_size=3, bias=True, w_init_gain='relu'),
40
+ torch.nn.ReLU(),
41
+ ConvNorm(n_mel_channels * 2, n_mel_channels, kernel_size=1, bias=True),
42
+ torch.nn.ReLU(),
43
+ ConvNorm(n_mel_channels, n_att_channels, kernel_size=1, bias=True),
44
+ )
45
+ if dist_type == "l2":
46
+ self.dist_fn = self.get_euclidean_dist
47
+ elif dist_type == "cosine":
48
+ self.dist_fn = self.get_cosine_dist
49
+ else:
50
+ raise ValueError(f"Unknown distance type '{dist_type}'")
51
+
52
+ @staticmethod
53
+ def _apply_mask(inputs, mask, mask_value):
54
+ if mask is None:
55
+ return
56
+
57
+ mask = rearrange(mask, "B T2 1 -> B 1 1 T2")
58
+ inputs.data.masked_fill_(mask, mask_value)
59
+
60
+ def get_dist(self, keys, queries, mask=None):
61
+ """Calculation of distance matrix.
62
+
63
+ Args:
64
+ queries (torch.tensor): B x C1 x T1 tensor (probably going to be mel data).
65
+ keys (torch.tensor): B x C2 x T2 tensor (text data).
66
+ mask (torch.tensor): B x T2 x 1 tensor, binary mask for variable length entries and also can be used
67
+ for ignoring unnecessary elements from keys in the resulting distance matrix (True = mask element, False = leave unchanged).
68
+ Output:
69
+ dist (torch.tensor): B x T1 x T2 tensor.
70
+ """
71
+ # B x C x T1
72
+ queries_enc = self.query_proj(queries)
73
+ # B x C x T2
74
+ keys_enc = self.key_proj(keys)
75
+ # B x 1 x T1 x T2
76
+ dist = self.dist_fn(queries_enc=queries_enc, keys_enc=keys_enc)
77
+
78
+ self._apply_mask(dist, mask, float("inf"))
79
+
80
+ return dist.squeeze(1)
81
+
82
+ @staticmethod
83
+ def get_euclidean_dist(queries_enc, keys_enc):
84
+ queries_enc = rearrange(queries_enc, "B C T1 -> B C T1 1")
85
+ keys_enc = rearrange(keys_enc, "B C T2 -> B C 1 T2")
86
+ # B x C x T1 x T2
87
+ distance = (queries_enc - keys_enc) ** 2
88
+ # B x 1 x T1 x T2
89
+ l2_dist = distance.sum(axis=1, keepdim=True)
90
+ return l2_dist
91
+
92
+ @staticmethod
93
+ def get_cosine_dist(queries_enc, keys_enc):
94
+ queries_enc = rearrange(queries_enc, "B C T1 -> B C T1 1")
95
+ keys_enc = rearrange(keys_enc, "B C T2 -> B C 1 T2")
96
+ cosine_dist = -torch.nn.functional.cosine_similarity(queries_enc, keys_enc, dim=1)
97
+ cosine_dist = rearrange(cosine_dist, "B T1 T2 -> B 1 T1 T2")
98
+ return cosine_dist
99
+
100
+ @staticmethod
101
+ def get_durations(attn_soft, text_len, spect_len):
102
+ """Calculation of durations.
103
+
104
+ Args:
105
+ attn_soft (torch.tensor): B x 1 x T1 x T2 tensor.
106
+ text_len (torch.tensor): B tensor, lengths of text.
107
+ spect_len (torch.tensor): B tensor, lengths of mel spectrogram.
108
+ """
109
+ attn_hard = binarize_attention_parallel(attn_soft, text_len, spect_len)
110
+ durations = attn_hard.sum(2)[:, 0, :]
111
+ assert torch.all(torch.eq(durations.sum(dim=1), spect_len))
112
+ return durations
113
+
114
+ @staticmethod
115
+ def get_mean_dist_by_durations(dist, durations, mask=None):
116
+ """Select elements from the distance matrix for the given durations and mask and return mean distance.
117
+
118
+ Args:
119
+ dist (torch.tensor): B x T1 x T2 tensor.
120
+ durations (torch.tensor): B x T2 tensor. Dim T2 should sum to T1.
121
+ mask (torch.tensor): B x T2 x 1 binary mask for variable length entries and also can be used
122
+ for ignoring unnecessary elements in dist by T2 dim (True = mask element, False = leave unchanged).
123
+ Output:
124
+ mean_dist (torch.tensor): B x 1 tensor.
125
+ """
126
+ batch_size, t1_size, t2_size = dist.size()
127
+ assert torch.all(torch.eq(durations.sum(dim=1), t1_size))
128
+
129
+ AlignmentEncoder._apply_mask(dist, mask, 0)
130
+
131
+ # TODO(oktai15): make it more efficient
132
+ mean_dist_by_durations = []
133
+ for dist_idx in range(batch_size):
134
+ mean_dist_by_durations.append(
135
+ torch.mean(
136
+ dist[
137
+ dist_idx,
138
+ torch.arange(t1_size),
139
+ torch.repeat_interleave(torch.arange(t2_size), repeats=durations[dist_idx]),
140
+ ]
141
+ )
142
+ )
143
+
144
+ return torch.tensor(mean_dist_by_durations, dtype=dist.dtype, device=dist.device)
145
+
146
+ @staticmethod
147
+ def get_mean_distance_for_word(l2_dists, durs, start_token, num_tokens):
148
+ """Calculates the mean distance between text and audio embeddings given a range of text tokens.
149
+
150
+ Args:
151
+ l2_dists (torch.tensor): L2 distance matrix from Aligner inference. T1 x T2 tensor.
152
+ durs (torch.tensor): List of durations corresponding to each text token. T2 tensor. Should sum to T1.
153
+ start_token (int): Index of the starting token for the word of interest.
154
+ num_tokens (int): Length (in tokens) of the word of interest.
155
+ Output:
156
+ mean_dist_for_word (float): Mean embedding distance between the word indicated and its predicted audio frames.
157
+ """
158
+ # Need to calculate which audio frame we start on by summing all durations up to the start token's duration
159
+ start_frame = torch.sum(durs[:start_token]).data
160
+
161
+ total_frames = 0
162
+ dist_sum = 0
163
+
164
+ # Loop through each text token
165
+ for token_ind in range(start_token, start_token + num_tokens):
166
+ # Loop through each frame for the given text token
167
+ for frame_ind in range(start_frame, start_frame + durs[token_ind]):
168
+ # Recall that the L2 distance matrix is shape [spec_len, text_len]
169
+ dist_sum += l2_dists[frame_ind, token_ind]
170
+
171
+ # Update total frames so far & the starting frame for the next token
172
+ total_frames += durs[token_ind]
173
+ start_frame += durs[token_ind]
174
+
175
+ return dist_sum / total_frames
176
+
177
+ def forward(self, queries, keys, mask=None, attn_prior=None, conditioning=None):
178
+ """Forward pass of the aligner encoder.
179
+
180
+ Args:
181
+ queries (torch.tensor): B x C1 x T1 tensor (probably going to be mel data).
182
+ keys (torch.tensor): B x C2 x T2 tensor (text data).
183
+ mask (torch.tensor): B x T2 x 1 tensor, binary mask for variable length entries (True = mask element, False = leave unchanged).
184
+ attn_prior (torch.tensor): prior for attention matrix.
185
+ conditioning (torch.tensor): B x 1 x C2 conditioning embedding
186
+ Output:
187
+ attn (torch.tensor): B x 1 x T1 x T2 attention mask. Final dim T2 should sum to 1.
188
+ attn_logprob (torch.tensor): B x 1 x T1 x T2 log-prob attention mask.
189
+ """
190
+ # keys = self.cond_input(keys.transpose(1, 2), conditioning).transpose(1, 2)
191
+ # B x C x T1
192
+ queries_enc = self.query_proj(queries)
193
+ # B x C x T2
194
+ keys_enc = self.key_proj(keys)
195
+ # B x 1 x T1 x T2
196
+ distance = self.dist_fn(queries_enc=queries_enc, keys_enc=keys_enc)
197
+ attn = -self.temperature * distance
198
+
199
+ if attn_prior is not None:
200
+ attn = self.log_softmax(attn) + torch.log(attn_prior[:, None] + 1e-8)
201
+
202
+ attn_logprob = attn.clone()
203
+
204
+ self._apply_mask(attn, mask, -float("inf"))
205
+
206
+ attn = self.softmax(attn) # softmax along T2
207
+ return attn, attn_logprob
208
+
209
+
210
+
211
+ def get_mask_from_lengths(
212
+ lengths: Optional[torch.Tensor] = None,
213
+ x: Optional[torch.Tensor] = None,
214
+ ) -> torch.Tensor:
215
+ """Constructs binary mask from a 1D torch tensor of input lengths
216
+
217
+ Args:
218
+ lengths: Optional[torch.tensor] (torch.tensor): 1D tensor with lengths
219
+ x: Optional[torch.tensor] = tensor to be used on, last dimension is for mask
220
+ Returns:
221
+ mask (torch.tensor): num_sequences x max_length binary tensor
222
+ """
223
+ if lengths is None:
224
+ assert x is not None
225
+ return torch.ones(x.shape[-1], dtype=torch.bool, device=x.device)
226
+ else:
227
+ if x is None:
228
+ max_len = torch.max(lengths)
229
+ else:
230
+ max_len = x.shape[-1]
231
+ ids = torch.arange(0, max_len, device=lengths.device, dtype=lengths.dtype)
232
+ mask = ids < lengths.unsqueeze(1)
233
+ return mask
234
+
235
+ class AlignerModel(torch.nn.Module):
236
+ """Speech-to-text alignment model (https://arxiv.org/pdf/2108.10447.pdf) that is used to learn alignments between mel spectrogram and text."""
237
+
238
+ def __init__(self):
239
+
240
+ # num_tokens = len(self.tokenizer.tokens)
241
+ # self.tokenizer_pad = self.tokenizer.pad
242
+ # self.tokenizer_unk = self.tokenizer.oov
243
+
244
+ super().__init__()
245
+
246
+ self.embed = nn.Embedding(214, 512)
247
+ self.alignment_encoder = AlignmentEncoder()
248
+
249
+
250
+ # self.bin_loss = BinLoss()
251
+ # self.add_bin_loss = False
252
+ # self.bin_loss_scale = 0.0
253
+ # self.bin_loss_start_ratio = cfg.bin_loss_start_ratio
254
+ # self.bin_loss_warmup_epochs = cfg.bin_loss_warmup_epochs
255
+
256
+ def forward(self, *, spec, spec_len, text, text_len, attn_prior=None):
257
+ # with torch.amp.autocast(self.device.type, enabled=False):
258
+ attn_soft, attn_logprob = self.alignment_encoder(
259
+ queries=spec,
260
+ keys=self.embed(text).transpose(1, 2),
261
+ mask=get_mask_from_lengths(text_len).unsqueeze(-1) == 0,
262
+ attn_prior=attn_prior,
263
+ )
264
+
265
+ return attn_soft, attn_logprob
266
+
267
+
268
+ # mod = AlignerModel()
269
+
270
+ # attn_soft, attn_logprob = mod(spec=mel_input,
271
+ # spec_len=mel_input_length,
272
+ # text=text_input,
273
+ # text_len=text_input_length,
274
+ # attn_prior = attn_prior)
275
+
276
+
277
+ # attn_soft.shape
278
+ # text_input, text_input_length, mel_input, mel_input_length, attn_prior