-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathaligner.py
More file actions
1494 lines (1278 loc) · 51.5 KB
/
aligner.py
File metadata and controls
1494 lines (1278 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Alignment code
Authors
* Elena Rastorgueva 2020
* Loren Lugosch 2020
"""
import random
import torch
from speechbrain.utils.checkpoints import (
mark_as_loader,
mark_as_saver,
register_checkpoint_hooks,
)
from speechbrain.utils.data_utils import undo_padding
@register_checkpoint_hooks
class HMMAligner(torch.nn.Module):
"""This class calculates Viterbi alignments in the forward method.
It also records alignments and creates batches of them for use
in Viterbi training.
Arguments
---------
states_per_phoneme : int
Number of hidden states to use per phoneme.
output_folder : str
It is the folder that the alignments will be stored in when
saved to disk. Not yet implemented.
neg_inf : float
The float used to represent a negative infinite log probability.
Using `-float("Inf")` tends to give numerical instability.
A number more negative than -1e5 also sometimes gave errors when
the `genbmm` library was used (currently not in use). (default: -1e5)
batch_reduction : string
One of "none", "sum" or "mean".
What kind of batch-level reduction to apply to the loss calculated
in the forward method.
input_len_norm : bool
Whether to normalize the loss in the forward method by the length of
the inputs.
target_len_norm : bool
Whether to normalize the loss in the forward method by the length of
the targets.
lexicon_path : string
The location of the lexicon.
Example
-------
>>> log_posteriors = torch.tensor(
... [
... [
... [-1.0, -10.0, -10.0],
... [-10.0, -1.0, -10.0],
... [-10.0, -10.0, -1.0],
... ],
... [
... [-1.0, -10.0, -10.0],
... [-10.0, -1.0, -10.0],
... [-10.0, -10.0, -10.0],
... ],
... ]
... )
>>> lens = torch.tensor([1.0, 0.66])
>>> phns = torch.tensor([[0, 1, 2], [0, 1, 0]])
>>> phn_lens = torch.tensor([1.0, 0.66])
>>> aligner = HMMAligner()
>>> forward_scores = aligner(
... log_posteriors, lens, phns, phn_lens, "forward"
... )
>>> forward_scores.shape
torch.Size([2])
>>> viterbi_scores, alignments = aligner(
... log_posteriors, lens, phns, phn_lens, "viterbi"
... )
>>> alignments
[[0, 1, 2], [0, 1]]
>>> viterbi_scores.shape
torch.Size([2])
"""
def __init__(
self,
states_per_phoneme=1,
output_folder="",
neg_inf=-1e5,
batch_reduction="none",
input_len_norm=False,
target_len_norm=False,
lexicon_path=None,
):
super().__init__()
self.states_per_phoneme = states_per_phoneme
self.output_folder = output_folder
self.neg_inf = neg_inf
self.batch_reduction = batch_reduction
self.input_len_norm = input_len_norm
self.target_len_norm = target_len_norm
self.align_dict = {}
self.lexicon_path = lexicon_path
if self.lexicon_path is not None:
with open(self.lexicon_path, encoding="utf-8") as f:
lines = f.readlines()
for i, line in enumerate(lines):
if line[0] != ";":
start_index = i
break
lexicon = {} # {"read": {0: "r eh d", 1: "r iy d"}}
lexicon_phones = set()
for i in range(start_index, len(lines)):
line = lines[i]
word = line.split()[0]
phones = line.split("/")[1]
phones = "".join([p for p in phones if not p.isdigit()])
for p in phones.split(" "):
lexicon_phones.add(p)
if "~" in word:
word = word.split("~")[0]
if word in lexicon:
number_of_existing_pronunciations = len(lexicon[word])
lexicon[word][number_of_existing_pronunciations] = phones
else:
lexicon[word] = {0: phones}
self.lexicon = lexicon
lexicon_phones = list(lexicon_phones)
lexicon_phones.sort()
self.lex_lab2ind = {p: i + 1 for i, p in enumerate(lexicon_phones)}
self.lex_ind2lab = {i + 1: p for i, p in enumerate(lexicon_phones)}
# add sil, which is not in the lexicon
self.lex_lab2ind["sil"] = 0
self.lex_ind2lab[0] = "sil"
def _use_lexicon(self, words, interword_sils, sample_pron):
"""Do processing using the lexicon to return a sequence of the possible
phonemes, the transition/pi probabilities, and the possible final states.
Inputs correspond to a single utterance, not a whole batch.
Arguments
---------
words : list
List of the words in the transcript.
interword_sils : bool
If True, optional silences will be inserted between every word.
If False, optional silences will only be placed at the beginning
and end of each utterance.
sample_pron : bool
If True, it will sample a single possible sequence of phonemes.
If False, it will return statistics for all possible sequences of
phonemes.
Returns
-------
poss_phns : torch.Tensor (phoneme)
The phonemes that are thought to be in each utterance.
log_transition_matrix : torch.Tensor (batch, from, to)
Tensor containing transition (log) probabilities.
start_states : list of ints
A list of the possible starting states in each utterance.
final_states : list of ints
A list of the possible final states for each utterance.
"""
number_of_states = 0
words_prime = [] # This will contain one "word" for each optional silence and pronunciation.
# structure of each "word_prime":
# [word index, [[state sequence 1], [state sequence 2]], <is this an optional silence?>]
word_index = 0
phoneme_indices = []
for word in words:
if word_index == 0 or interword_sils is True:
# optional silence
word_prime = [
word_index,
[
[
number_of_states + i
for i in range(self.states_per_phoneme)
]
],
True,
]
words_prime.append(word_prime)
phoneme_indices += [
self.silence_index * self.states_per_phoneme + i
for i in range(self.states_per_phoneme)
]
number_of_states += self.states_per_phoneme
word_index += 1
# word
word_prime = [word_index, [], False]
if sample_pron and len(self.lexicon[word]) > 1:
random.shuffle(self.lexicon[word])
for pron_idx in range(len(self.lexicon[word])):
pronunciation = self.lexicon[word][pron_idx]
phonemes = pronunciation.split()
word_prime[1].append([])
for p in phonemes:
phoneme_indices += [
self.lex_lab2ind[p] * self.states_per_phoneme + i
for i in range(self.states_per_phoneme)
]
word_prime[1][pron_idx] += [
number_of_states + i
for i in range(self.states_per_phoneme)
]
number_of_states += self.states_per_phoneme
if sample_pron:
break
words_prime.append(word_prime)
word_index += 1
# optional final silence
word_prime = [
word_index,
[[number_of_states + i for i in range(self.states_per_phoneme)]],
True,
]
words_prime.append(word_prime)
phoneme_indices += [
self.silence_index * self.states_per_phoneme + i
for i in range(self.states_per_phoneme)
]
number_of_states += self.states_per_phoneme
word_index += 1
transition_matrix = 1.0 * torch.eye(
number_of_states
) # diagonal = all states have a self-loop
final_states = []
for word_prime in words_prime:
word_idx = word_prime[0]
is_optional_silence = word_prime[-1]
next_word_exists = word_idx < len(words_prime) - 2
this_word_last_states = [
word_prime[1][i][-1] for i in range(len(word_prime[1]))
]
# create transitions to next state from previous state within each pronunciation
for pronunciation in word_prime[1]:
for state_idx in range(len(pronunciation) - 1):
state = pronunciation[state_idx]
next_state = pronunciation[state_idx + 1]
transition_matrix[state, next_state] = 1.0
# create transitions to next word's starting states
if next_word_exists:
if is_optional_silence or not interword_sils:
next_word_idx = word_idx + 1
else:
next_word_idx = word_idx + 2
next_word_starting_states = [
words_prime[next_word_idx][1][i][0]
for i in range(len(words_prime[next_word_idx][1]))
]
for this_word_last_state in this_word_last_states:
for next_word_starting_state in next_word_starting_states:
transition_matrix[
this_word_last_state, next_word_starting_state
] = 1.0
else:
final_states += this_word_last_states
if not is_optional_silence:
next_silence_idx = word_idx + 1
next_silence_starting_state = words_prime[next_silence_idx][1][
0
][0]
for this_word_last_state in this_word_last_states:
transition_matrix[
this_word_last_state, next_silence_starting_state
] = 1.0
log_transition_matrix = transition_matrix.log().log_softmax(1)
start_states = [words_prime[0][1][0][0]]
start_states += [
words_prime[1][1][i][0] for i in range(len(words_prime[1][1]))
]
poss_phns = torch.tensor(phoneme_indices)
return poss_phns, log_transition_matrix, start_states, final_states
def use_lexicon(self, words, interword_sils=True, sample_pron=False):
"""Do processing using the lexicon to return a sequence of the possible
phonemes, the transition/pi probabilities, and the possible final
states.
Does processing on an utterance-by-utterance basis. Each utterance
in the batch is processed by a helper method `_use_lexicon`.
Arguments
---------
words : list
List of the words in the transcript
interword_sils : bool
If True, optional silences will be inserted between every word.
If False, optional silences will only be placed at the beginning
and end of each utterance.
sample_pron: bool
If True, it will sample a single possible sequence of phonemes.
If False, it will return statistics for all possible sequences of
phonemes.
Returns
-------
poss_phns: torch.Tensor (batch, phoneme in possible phn sequence)
The phonemes that are thought to be in each utterance.
poss_phn_lens: torch.Tensor (batch)
The relative length of each possible phoneme sequence in the batch.
trans_prob: torch.Tensor (batch, from, to)
Tensor containing transition (log) probabilities.
pi_prob: torch.Tensor (batch, state)
Tensor containing initial (log) probabilities.
final_state: list of lists of ints
A list of lists of possible final states for each utterance.
Example
-------
>>> aligner = HMMAligner()
>>> aligner.lexicon = {"a": {0: "a"}, "b": {0: "b", 1: "c"}}
>>> words = [["a", "b"]]
>>> aligner.lex_lab2ind = {
... "sil": 0,
... "a": 1,
... "b": 2,
... "c": 3,
... }
>>> poss_phns, poss_phn_lens, trans_prob, pi_prob, final_states = (
... aligner.use_lexicon(words, interword_sils=True)
... )
>>> poss_phns
tensor([[0, 1, 0, 2, 3, 0]])
>>> poss_phn_lens
tensor([1.])
>>> trans_prob
tensor([[[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05,
-1.0000e+05],
[-1.0000e+05, -1.3863e+00, -1.3863e+00, -1.3863e+00, -1.3863e+00,
-1.0000e+05],
[-1.0000e+05, -1.0000e+05, -1.0986e+00, -1.0986e+00, -1.0986e+00,
-1.0000e+05],
[-1.0000e+05, -1.0000e+05, -1.0000e+05, -6.9315e-01, -1.0000e+05,
-6.9315e-01],
[-1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05, -6.9315e-01,
-6.9315e-01],
[-1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05,
0.0000e+00]]])
>>> pi_prob
tensor([[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05,
-1.0000e+05]])
>>> final_states
[[3, 4, 5]]
>>> # With no optional silences between words
>>> poss_phns_, _, trans_prob_, pi_prob_, final_states_ = (
... aligner.use_lexicon(words, interword_sils=False)
... )
>>> poss_phns_
tensor([[0, 1, 2, 3, 0]])
>>> trans_prob_
tensor([[[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05],
[-1.0000e+05, -1.0986e+00, -1.0986e+00, -1.0986e+00, -1.0000e+05],
[-1.0000e+05, -1.0000e+05, -6.9315e-01, -1.0000e+05, -6.9315e-01],
[-1.0000e+05, -1.0000e+05, -1.0000e+05, -6.9315e-01, -6.9315e-01],
[-1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05, 0.0000e+00]]])
>>> pi_prob_
tensor([[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05]])
>>> final_states_
[[2, 3, 4]]
>>> # With sampling of a single possible pronunciation
>>> import random
>>> random.seed(0)
>>> poss_phns_, _, trans_prob_, pi_prob_, final_states_ = (
... aligner.use_lexicon(words, sample_pron=True)
... )
>>> poss_phns_
tensor([[0, 1, 0, 2, 0]])
>>> trans_prob_
tensor([[[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05],
[-1.0000e+05, -1.0986e+00, -1.0986e+00, -1.0986e+00, -1.0000e+05],
[-1.0000e+05, -1.0000e+05, -6.9315e-01, -6.9315e-01, -1.0000e+05],
[-1.0000e+05, -1.0000e+05, -1.0000e+05, -6.9315e-01, -6.9315e-01],
[-1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05, 0.0000e+00]]])
"""
self.silence_index = self.lex_lab2ind["sil"]
poss_phns = []
trans_prob = []
start_states = []
final_states = []
for words_ in words:
(
poss_phns_,
trans_prob_,
start_states_,
final_states_,
) = self._use_lexicon(words_, interword_sils, sample_pron)
poss_phns.append(poss_phns_)
trans_prob.append(trans_prob_)
start_states.append(start_states_)
final_states.append(final_states_)
# pad poss_phns, trans_prob with 0 to have same length
poss_phn_lens = [len(poss_phns_) for poss_phns_ in poss_phns]
U_max = max(poss_phn_lens)
batch_size = len(poss_phns)
for index in range(batch_size):
phn_pad_length = U_max - len(poss_phns[index])
poss_phns[index] = torch.nn.functional.pad(
poss_phns[index], (0, phn_pad_length), value=0
)
trans_prob[index] = torch.nn.functional.pad(
trans_prob[index],
(0, phn_pad_length, 0, phn_pad_length),
value=self.neg_inf,
)
# Stack into single tensor
poss_phns = torch.stack(poss_phns)
trans_prob = torch.stack(trans_prob)
trans_prob[trans_prob == -float("Inf")] = self.neg_inf
# make pi prob
pi_prob = self.neg_inf * torch.ones([batch_size, U_max])
for start_state in start_states:
pi_prob[:, start_state] = 1
pi_prob = torch.nn.functional.log_softmax(pi_prob, dim=1)
# Convert poss_phn_lens from absolute to relative lengths
poss_phn_lens = torch.tensor(poss_phn_lens).float() / U_max
return poss_phns, poss_phn_lens, trans_prob, pi_prob, final_states
def _make_pi_prob(self, phn_lens_abs):
"""Creates tensor of initial (log) probabilities (known as 'pi').
Assigns all probability mass to the first phoneme in the sequence.
Arguments
---------
phn_lens_abs : torch.Tensor (batch)
The absolute length of each phoneme sequence in the batch.
Returns
-------
pi_prob : torch.Tensor (batch, phn)
"""
batch_size = len(phn_lens_abs)
U_max = int(phn_lens_abs.max())
pi_prob = self.neg_inf * torch.ones([batch_size, U_max])
pi_prob[:, 0] = 0
return pi_prob
def _make_trans_prob(self, phn_lens_abs):
"""Creates tensor of transition (log) probabilities.
Only allows transitions to the same phoneme (self-loop) or the next
phoneme in the phn sequence
Arguments
---------
phn_lens_abs : torch.Tensor (batch)
The absolute length of each phoneme sequence in the batch.
Returns
-------
trans_prob : torch.Tensor (batch, from, to)
"""
# Extract useful values for later
batch_size = len(phn_lens_abs)
U_max = int(phn_lens_abs.max())
device = phn_lens_abs.device
## trans_prob matrix consists of 2 diagonals:
## (1) offset diagonal (next state) &
## (2) main diagonal (self-loop)
# make offset diagonal
trans_prob_off_diag = torch.eye(U_max - 1)
zero_side = torch.zeros([U_max - 1, 1])
zero_bottom = torch.zeros([1, U_max])
trans_prob_off_diag = torch.cat((zero_side, trans_prob_off_diag), 1)
trans_prob_off_diag = torch.cat((trans_prob_off_diag, zero_bottom), 0)
# make main diagonal
trans_prob_main_diag = torch.eye(U_max)
# join the diagonals and repeat for whole batch
trans_prob = trans_prob_off_diag + trans_prob_main_diag
trans_prob = (
trans_prob.reshape(1, U_max, U_max)
.repeat(batch_size, 1, 1)
.to(device)
)
# clear probabilities for too-long sequences
mask_a = (
torch.arange(U_max, device=device)[None, :] < phn_lens_abs[:, None]
)
mask_a = mask_a.unsqueeze(2)
mask_a = mask_a.expand(-1, -1, U_max)
mask_b = mask_a.permute(0, 2, 1)
trans_prob = trans_prob * (mask_a & mask_b).float()
## put -infs in place of zeros:
trans_prob = torch.where(
trans_prob == 1,
trans_prob,
torch.tensor(-float("Inf"), device=device),
)
## normalize
trans_prob = torch.nn.functional.log_softmax(trans_prob, dim=2)
## set nans to v neg numbers
trans_prob[trans_prob != trans_prob] = self.neg_inf
## set -infs to v neg numbers
trans_prob[trans_prob == -float("Inf")] = self.neg_inf
return trans_prob
def _make_emiss_pred_useful(
self, emission_pred, lens_abs, phn_lens_abs, phns
):
"""Creates a 'useful' form of the posterior probabilities, rearranged
into the order of phoneme appearance in phns.
Arguments
---------
emission_pred : torch.Tensor (batch, time, phoneme in vocabulary)
posterior probabilities from our acoustic model
lens_abs : torch.Tensor (batch)
The absolute length of each input to the acoustic model,
i.e., the number of frames.
phn_lens_abs : torch.Tensor (batch)
The absolute length of each phoneme sequence in the batch.
phns : torch.Tensor (batch, phoneme in phn sequence)
The phonemes that are known/thought to be in each utterance.
Returns
-------
emiss_pred_useful : torch.Tensor
Tensor shape (batch, phoneme in phn sequence, time).
"""
# Extract useful values for later
U_max = int(phn_lens_abs.max().item())
fb_max_length = int(lens_abs.max().item())
device = emission_pred.device
# apply mask based on lens_abs
mask_lens = (
torch.arange(fb_max_length).to(device)[None, :] < lens_abs[:, None]
)
emiss_pred_acc_lens = torch.where(
mask_lens[:, :, None],
emission_pred,
torch.tensor([0.0], device=device),
)
# manipulate phn tensor, and then 'torch.gather'
phns = phns.to(device)
phns_copied = phns.unsqueeze(1).expand(-1, fb_max_length, -1)
emiss_pred_useful = torch.gather(emiss_pred_acc_lens, 2, phns_copied)
# apply mask based on phn_lens_abs
mask_phn_lens = (
torch.arange(U_max).to(device)[None, :] < phn_lens_abs[:, None]
)
emiss_pred_useful = torch.where(
mask_phn_lens[:, None, :],
emiss_pred_useful,
torch.tensor([self.neg_inf], device=device),
)
emiss_pred_useful = emiss_pred_useful.permute(0, 2, 1)
return emiss_pred_useful
def _dp_forward(
self,
pi_prob,
trans_prob,
emiss_pred_useful,
lens_abs,
phn_lens_abs,
phns,
):
"""Does forward dynamic programming algorithm.
Arguments
---------
pi_prob : torch.Tensor (batch, phn)
Tensor containing initial (log) probabilities.
trans_prob : torch.Tensor (batch, from, to)
Tensor containing transition (log) probabilities.
emiss_pred_useful : torch.Tensor (batch, phoneme in phn sequence, time)
A 'useful' form of the posterior probabilities, rearranged
into the order of phoneme appearance in phns.
lens_abs : torch.Tensor (batch)
The absolute length of each input to the acoustic model,
i.e., the number of frames.
phn_lens_abs : torch.Tensor (batch)
The absolute length of each phoneme sequence in the batch.
phns : torch.Tensor (batch, phoneme in phn sequence)
The phonemes that are known/thought to be in each utterance.
Returns
-------
sum_alpha_T : torch.Tensor (batch)
The (log) likelihood of each utterance in the batch.
"""
# useful values
batch_size = len(phn_lens_abs)
U_max = phn_lens_abs.max()
fb_max_length = lens_abs.max()
device = emiss_pred_useful.device
pi_prob = pi_prob.to(device)
trans_prob = trans_prob.to(device)
# initialise
alpha_matrix = self.neg_inf * torch.ones(
[batch_size, U_max, fb_max_length], device=device
)
alpha_matrix[:, :, 0] = pi_prob + emiss_pred_useful[:, :, 0]
for t in range(1, fb_max_length):
utt_lens_passed = lens_abs < t
if True in utt_lens_passed:
n_passed = utt_lens_passed.sum()
I_tensor = self.neg_inf * torch.ones(n_passed, U_max, U_max)
I_tensor[:, torch.arange(U_max), torch.arange(U_max)] = 0.0
I_tensor = I_tensor.to(device)
trans_prob[utt_lens_passed] = I_tensor
alpha_times_trans = batch_log_matvecmul(
trans_prob.permute(0, 2, 1), alpha_matrix[:, :, t - 1]
)
alpha_matrix[:, :, t] = (
alpha_times_trans + emiss_pred_useful[:, :, t]
)
sum_alpha_T = torch.logsumexp(
alpha_matrix[torch.arange(batch_size), :, -1], dim=1
)
return sum_alpha_T
def _dp_viterbi(
self,
pi_prob,
trans_prob,
emiss_pred_useful,
lens_abs,
phn_lens_abs,
phns,
final_states,
):
"""Calculates Viterbi alignment using dynamic programming.
Arguments
---------
pi_prob : torch.Tensor (batch, phn)
Tensor containing initial (log) probabilities.
trans_prob : torch.Tensor (batch, from, to)
Tensor containing transition (log) probabilities.
emiss_pred_useful : torch.Tensor (batch, phoneme in phn sequence, time)
A 'useful' form of the posterior probabilities, rearranged
into the order of phoneme appearance in phns.
lens_abs : torch.Tensor (batch)
The absolute length of each input to the acoustic model,
i.e., the number of frames.
phn_lens_abs : torch.Tensor (batch)
The absolute length of each phoneme sequence in the batch.
phns : torch.Tensor (batch, phoneme in phn sequence)
The phonemes that are known/thought to be in each utterance.
final_states : list
List of final states
Returns
-------
z_stars : list of lists of int
Viterbi alignments for the files in the batch.
z_stars_loc : list of lists of int
The locations of the Viterbi alignments for the files in the batch.
e.g., for a batch with a single utterance with 5 phonemes,
`z_stars_loc` will look like:
[[0, 0, 0, 1, 1, 2, 3, 3, 3, 4, 4]].
viterbi_scores : torch.Tensor (batch)
The (log) likelihood of the Viterbi path for each utterance.
"""
# useful values
batch_size = len(phn_lens_abs)
U_max = phn_lens_abs.max()
fb_max_length = lens_abs.max()
device = emiss_pred_useful.device
pi_prob = pi_prob.to(device)
trans_prob = trans_prob.to(device)
v_matrix = self.neg_inf * torch.ones(
[batch_size, U_max, fb_max_length], device=device
)
backpointers = -99 * torch.ones(
[batch_size, U_max, fb_max_length], device=device
)
# initialise
v_matrix[:, :, 0] = pi_prob + emiss_pred_useful[:, :, 0]
for t in range(1, fb_max_length):
x, argmax = batch_log_maxvecmul(
trans_prob.permute(0, 2, 1), v_matrix[:, :, t - 1]
)
v_matrix[:, :, t] = x + emiss_pred_useful[:, :, t]
backpointers[:, :, t] = argmax.type(dtype=torch.float32)
z_stars = []
z_stars_loc = []
for utterance_in_batch in range(batch_size):
len_abs = lens_abs[utterance_in_batch]
if final_states is not None:
final_states_utter = final_states[utterance_in_batch]
# Pick most probable of the final states
viterbi_finals = v_matrix[
utterance_in_batch, final_states_utter, len_abs - 1
]
final_state_chosen = torch.argmax(viterbi_finals).item()
U = final_states_utter[final_state_chosen]
else:
U = phn_lens_abs[utterance_in_batch].long().item() - 1
z_star_i_loc = [U]
z_star_i = [phns[utterance_in_batch, z_star_i_loc[0]].item()]
for time_step in range(len_abs, 1, -1):
current_best_loc = z_star_i_loc[0]
earlier_best_loc = (
backpointers[
utterance_in_batch, current_best_loc, time_step - 1
]
.long()
.item()
)
earlier_z_star = phns[
utterance_in_batch, earlier_best_loc
].item()
z_star_i_loc.insert(0, earlier_best_loc)
z_star_i.insert(0, earlier_z_star)
z_stars.append(z_star_i)
z_stars_loc.append(z_star_i_loc)
# picking out viterbi_scores
viterbi_scores = v_matrix[
torch.arange(batch_size), phn_lens_abs - 1, lens_abs - 1
]
return z_stars, z_stars_loc, viterbi_scores
def _loss_reduction(self, loss, input_lens, target_lens):
"""Applies reduction to loss as specified during object initialization.
Arguments
---------
loss : torch.Tensor (batch)
The loss tensor to be reduced.
input_lens : torch.Tensor (batch)
The absolute durations of the inputs.
target_lens : torch.Tensor (batch)
The absolute durations of the targets.
Returns
-------
loss : torch.Tensor (batch, or scalar)
The loss with reduction applied if it is specified.
"""
if self.input_len_norm is True:
loss = torch.div(loss, input_lens)
if self.target_len_norm is True:
loss = torch.div(loss, target_lens)
if self.batch_reduction == "none":
pass
elif self.batch_reduction == "sum":
loss = loss.sum()
elif self.batch_reduction == "mean":
loss = loss.mean()
else:
raise ValueError(
"`batch_reduction` parameter must be one of 'none', 'sum' or 'mean'"
)
return loss
def forward(
self,
emission_pred,
lens,
phns,
phn_lens,
dp_algorithm,
prob_matrices=None,
):
"""Prepares relevant (log) probability tensors and does dynamic
programming: either the forward or the Viterbi algorithm. Applies
reduction as specified during object initialization.
Arguments
---------
emission_pred : torch.Tensor (batch, time, phoneme in vocabulary)
Posterior probabilities from our acoustic model.
lens : torch.Tensor (batch)
The relative duration of each utterance sound file.
phns : torch.Tensor (batch, phoneme in phn sequence)
The phonemes that are known/thought to be in each utterance
phn_lens : torch.Tensor (batch)
The relative length of each phoneme sequence in the batch.
dp_algorithm : string
Either "forward" or "viterbi".
prob_matrices : dict
(Optional) Must contain keys 'trans_prob', 'pi_prob' and 'final_states'.
Used to override the default forward and viterbi operations which
force traversal over all of the states in the `phns` sequence.
Returns
-------
tensor
(1) if dp_algorithm == "forward".
``forward_scores`` : torch.Tensor (batch, or scalar)
The (log) likelihood of each utterance in the batch, with reduction
applied if specified. (OR)
(2) if dp_algorithm == "viterbi".
``viterbi_scores`` : torch.Tensor (batch, or scalar)
The (log) likelihood of the Viterbi path for each utterance, with
reduction applied if specified.
``alignments`` : list of lists of int
Viterbi alignments for the files in the batch.
"""
lens_abs = torch.round(emission_pred.shape[1] * lens).long()
phn_lens_abs = torch.round(phns.shape[1] * phn_lens).long()
phns = phns.long()
if prob_matrices is None:
pi_prob = self._make_pi_prob(phn_lens_abs)
trans_prob = self._make_trans_prob(phn_lens_abs)
final_states = None
else:
if (
("pi_prob" in prob_matrices)
and ("trans_prob" in prob_matrices)
and ("final_states" in prob_matrices)
):
pi_prob = prob_matrices["pi_prob"]
trans_prob = prob_matrices["trans_prob"]
final_states = prob_matrices["final_states"]
else:
raise ValueError(
"""`prob_matrices` must contain the keys
`pi_prob`, `trans_prob` and `final_states`"""
)
emiss_pred_useful = self._make_emiss_pred_useful(
emission_pred, lens_abs, phn_lens_abs, phns
)
if dp_algorithm == "forward":
# do forward training
forward_scores = self._dp_forward(
pi_prob,
trans_prob,
emiss_pred_useful,
lens_abs,
phn_lens_abs,
phns,
)
forward_scores = self._loss_reduction(
forward_scores, lens_abs, phn_lens_abs
)
return forward_scores
elif dp_algorithm == "viterbi":
alignments, _, viterbi_scores = self._dp_viterbi(
pi_prob,
trans_prob,
emiss_pred_useful,
lens_abs,
phn_lens_abs,
phns,
final_states,
)
viterbi_scores = self._loss_reduction(
viterbi_scores, lens_abs, phn_lens_abs
)
return viterbi_scores, alignments
else:
raise ValueError(
"dp_algorithm input must be either 'forward' or 'viterbi'"
)
def expand_phns_by_states_per_phoneme(self, phns, phn_lens):
"""Expands each phoneme in the phn sequence by the number of hidden
states per phoneme defined in the HMM.
Arguments
---------
phns : torch.Tensor (batch, phoneme in phn sequence)
The phonemes that are known/thought to be in each utterance.
phn_lens : torch.Tensor (batch)
The relative length of each phoneme sequence in the batch.
Returns
-------
expanded_phns : torch.Tensor (batch, phoneme in expanded phn sequence)
Example
-------
>>> phns = torch.tensor([[0.0, 3.0, 5.0, 0.0], [0.0, 2.0, 0.0, 0.0]])
>>> phn_lens = torch.tensor([1.0, 0.75])
>>> aligner = HMMAligner(states_per_phoneme=3)
>>> expanded_phns = aligner.expand_phns_by_states_per_phoneme(
... phns, phn_lens
... )
>>> expanded_phns
tensor([[ 0., 1., 2., 9., 10., 11., 15., 16., 17., 0., 1., 2.],
[ 0., 1., 2., 6., 7., 8., 0., 1., 2., 0., 0., 0.]])
"""
# Initialise expanded_phns
expanded_phns = torch.zeros(
phns.shape[0], phns.shape[1] * self.states_per_phoneme
)
expanded_phns = expanded_phns.to(phns.device)
phns = undo_padding(phns, phn_lens)
for i, phns_utt in enumerate(phns):
expanded_phns_utt = []
for phoneme_index in phns_utt:
expanded_phns_utt += [
self.states_per_phoneme * phoneme_index + i_
for i_ in range(self.states_per_phoneme)
]
expanded_phns[i, : len(expanded_phns_utt)] = torch.tensor(
expanded_phns_utt
)
return expanded_phns
def store_alignments(self, ids, alignments):
"""Records Viterbi alignments in `self.align_dict`.
Arguments
---------
ids : list of str
IDs of the files in the batch.
alignments : list of lists of int
Viterbi alignments for the files in the batch.
Without padding.