-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrnnt.py
767 lines (719 loc) · 34.7 KB
/
rnnt.py
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
from abc import ABC, abstractmethod
from typing import List, Optional, Tuple
import torch
from torchaudio.models import Emformer
__all__ = ["RNNT", "emformer_rnnt_base", "emformer_rnnt_model"]
class _TimeReduction(torch.nn.Module):
r"""Coalesces frames along time dimension into a
fewer number of frames with higher feature dimensionality.
Args:
stride (int): number of frames to merge for each output frame.
"""
def __init__(self, stride: int) -> None:
super().__init__()
self.stride = stride
def forward(self, input: torch.Tensor, lengths: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Forward pass.
B: batch size;
T: maximum input sequence length in batch;
D: feature dimension of each input sequence frame.
Args:
input (torch.Tensor): input sequences, with shape `(B, T, D)`.
lengths (torch.Tensor): with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in ``input``.
Returns:
(torch.Tensor, torch.Tensor):
torch.Tensor
output sequences, with shape
`(B, T // stride, D * stride)`
torch.Tensor
output lengths, with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in output sequences.
"""
B, T, D = input.shape
num_frames = T - (T % self.stride)
input = input[:, :num_frames, :]
lengths = lengths.div(self.stride, rounding_mode="trunc")
T_max = num_frames // self.stride
output = input.reshape(B, T_max, D * self.stride)
output = output.contiguous()
return output, lengths
class _CustomLSTM(torch.nn.Module):
r"""Custom long-short-term memory (LSTM) block that applies layer normalization
to internal nodes.
Args:
input_dim (int): input dimension.
hidden_dim (int): hidden dimension.
layer_norm (bool, optional): if ``True``, enables layer normalization. (Default: ``False``)
layer_norm_epsilon (float, optional): value of epsilon to use in
layer normalization layers (Default: 1e-5)
"""
def __init__(
self,
input_dim: int,
hidden_dim: int,
layer_norm: bool = False,
layer_norm_epsilon: float = 1e-5,
) -> None:
super().__init__()
self.x2g = torch.nn.Linear(input_dim, 4 * hidden_dim, bias=(not layer_norm))
self.p2g = torch.nn.Linear(hidden_dim, 4 * hidden_dim, bias=False)
if layer_norm:
self.c_norm = torch.nn.LayerNorm(hidden_dim, eps=layer_norm_epsilon)
self.g_norm = torch.nn.LayerNorm(4 * hidden_dim, eps=layer_norm_epsilon)
else:
self.c_norm = torch.nn.Identity()
self.g_norm = torch.nn.Identity()
self.hidden_dim = hidden_dim
def forward(
self, input: torch.Tensor, state: Optional[List[torch.Tensor]]
) -> Tuple[torch.Tensor, List[torch.Tensor]]:
r"""Forward pass.
B: batch size;
T: maximum sequence length in batch;
D: feature dimension of each input sequence element.
Args:
input (torch.Tensor): with shape `(T, B, D)`.
state (List[torch.Tensor] or None): list of tensors
representing internal state generated in preceding invocation
of ``forward``.
Returns:
(torch.Tensor, List[torch.Tensor]):
torch.Tensor
output, with shape `(T, B, hidden_dim)`.
List[torch.Tensor]
list of tensors representing internal state generated
in current invocation of ``forward``.
"""
if state is None:
B = input.size(1)
h = torch.zeros(B, self.hidden_dim, device=input.device, dtype=input.dtype)
c = torch.zeros(B, self.hidden_dim, device=input.device, dtype=input.dtype)
else:
h, c = state
gated_input = self.x2g(input)
outputs = []
for gates in gated_input.unbind(0):
gates = gates + self.p2g(h)
gates = self.g_norm(gates)
input_gate, forget_gate, cell_gate, output_gate = gates.chunk(4, 1)
input_gate = input_gate.sigmoid()
forget_gate = forget_gate.sigmoid()
cell_gate = cell_gate.tanh()
output_gate = output_gate.sigmoid()
c = forget_gate * c + input_gate * cell_gate
c = self.c_norm(c)
h = output_gate * c.tanh()
outputs.append(h)
output = torch.stack(outputs, dim=0)
state = [h, c]
return output, state
class _Transcriber(ABC):
@abstractmethod
def forward(self, input: torch.Tensor, lengths: torch.Tensor,idx) -> Tuple[torch.Tensor, torch.Tensor]:
pass
@abstractmethod
def infer(
self,
input: torch.Tensor,
lengths: torch.Tensor,
states: Optional[List[List[torch.Tensor]]],
) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
pass
class _EmformerEncoder(torch.nn.Module, _Transcriber):
r"""Emformer-based recurrent neural network transducer (RNN-T) encoder (transcription network).
Args:
input_dim (int): feature dimension of each input sequence element.
output_dim (int): feature dimension of each output sequence element.
segment_length (int): length of input segment expressed as number of frames.
right_context_length (int): length of right context expressed as number of frames.
time_reduction_input_dim (int): dimension to scale each element in input sequences to
prior to applying time reduction block.
time_reduction_stride (int): factor by which to reduce length of input sequence.
transformer_num_heads (int): number of attention heads in each Emformer layer.
transformer_ffn_dim (int): hidden layer dimension of each Emformer layer's feedforward network.
transformer_num_layers (int): number of Emformer layers to instantiate.
transformer_left_context_length (int): length of left context.
transformer_dropout (float, optional): transformer dropout probability. (Default: 0.0)
transformer_activation (str, optional): activation function to use in each Emformer layer's
feedforward network. Must be one of ("relu", "gelu", "silu"). (Default: "relu")
transformer_max_memory_size (int, optional): maximum number of memory elements to use. (Default: 0)
transformer_weight_init_scale_strategy (str, optional): per-layer weight initialization scaling
strategy. Must be one of ("depthwise", "constant", ``None``). (Default: "depthwise")
transformer_tanh_on_mem (bool, optional): if ``True``, applies tanh to memory elements. (Default: ``False``)
"""
def __init__(
self,
*,
input_dim: int,
output_dim: int,
segment_length: int,
right_context_length: int,
time_reduction_input_dim: int,
time_reduction_stride: int,
transformer_num_heads: int,
transformer_ffn_dim: int,
transformer_num_layers: int,
transformer_left_context_length: int,
transformer_dropout: float = 0.0,
transformer_activation: str = "relu",
transformer_max_memory_size: int = 0,
transformer_weight_init_scale_strategy: str = "depthwise",
transformer_tanh_on_mem: bool = False,
) -> None:
super().__init__()
self.input_linear = torch.nn.Linear(
input_dim,
time_reduction_input_dim,
bias=False,
)
self.time_reduction = _TimeReduction(time_reduction_stride)
transformer_input_dim = time_reduction_input_dim * time_reduction_stride
self.transformer = Emformer(
transformer_input_dim,
transformer_num_heads,
transformer_ffn_dim,
transformer_num_layers,
segment_length // time_reduction_stride,
dropout=transformer_dropout,
activation=transformer_activation,
left_context_length=transformer_left_context_length,
right_context_length=right_context_length // time_reduction_stride,
max_memory_size=transformer_max_memory_size,
weight_init_scale_strategy=transformer_weight_init_scale_strategy,
tanh_on_mem=transformer_tanh_on_mem,
)
self.output_linear = torch.nn.Linear(transformer_input_dim, output_dim)
self.layer_norm = torch.nn.LayerNorm(output_dim)
def forward(self, input: torch.Tensor, lengths: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Forward pass for training.
B: batch size;
T: maximum input sequence length in batch;
D: feature dimension of each input sequence frame (input_dim).
Args:
input (torch.Tensor): input frame sequences right-padded with right context, with
shape `(B, T + right context length, D)`.
lengths (torch.Tensor): with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in ``input``.
Returns:
(torch.Tensor, torch.Tensor):
torch.Tensor
output frame sequences, with
shape `(B, T // time_reduction_stride, output_dim)`.
torch.Tensor
output input lengths, with shape `(B,)` and i-th element representing
number of valid elements for i-th batch element in output frame sequences.
"""
input_linear_out = self.input_linear(input)
time_reduction_out, time_reduction_lengths = self.time_reduction(input_linear_out, lengths)
transformer_out, transformer_lengths = self.transformer(time_reduction_out, time_reduction_lengths)
output_linear_out = self.output_linear(transformer_out)
layer_norm_out = self.layer_norm(output_linear_out)
return layer_norm_out, transformer_lengths
@torch.jit.export
def infer(
self,
input: torch.Tensor,
lengths: torch.Tensor,
states: Optional[List[List[torch.Tensor]]],
) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
r"""Forward pass for inference.
B: batch size;
T: maximum input sequence segment length in batch;
D: feature dimension of each input sequence frame (input_dim).
Args:
input (torch.Tensor): input frame sequence segments right-padded with right context, with
shape `(B, T + right context length, D)`.
lengths (torch.Tensor): with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in ``input``.
state (List[List[torch.Tensor]] or None): list of lists of tensors
representing internal state generated in preceding invocation
of ``infer``.
Returns:
(torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
torch.Tensor
output frame sequences, with
shape `(B, T // time_reduction_stride, output_dim)`.
torch.Tensor
output input lengths, with shape `(B,)` and i-th element representing
number of valid elements for i-th batch element in output.
List[List[torch.Tensor]]
output states; list of lists of tensors
representing internal state generated in current invocation
of ``infer``.
"""
input_linear_out = self.input_linear(input)
time_reduction_out, time_reduction_lengths = self.time_reduction(input_linear_out, lengths)
(
transformer_out,
transformer_lengths,
transformer_states,
) = self.transformer.infer(time_reduction_out, time_reduction_lengths, states)
output_linear_out = self.output_linear(transformer_out)
layer_norm_out = self.layer_norm(output_linear_out)
return layer_norm_out, transformer_lengths, transformer_states
class _Predictor(torch.nn.Module):
r"""Recurrent neural network transducer (RNN-T) prediction network.
Args:
num_symbols (int): size of target token lexicon.
output_dim (int): feature dimension of each output sequence element.
symbol_embedding_dim (int): dimension of each target token embedding.
num_lstm_layers (int): number of LSTM layers to instantiate.
lstm_hidden_dim (int): output dimension of each LSTM layer.
lstm_layer_norm (bool, optional): if ``True``, enables layer normalization
for LSTM layers. (Default: ``False``)
lstm_layer_norm_epsilon (float, optional): value of epsilon to use in
LSTM layer normalization layers. (Default: 1e-5)
lstm_dropout (float, optional): LSTM dropout probability. (Default: 0.0)
"""
def __init__(
self,
num_symbols: int,
output_dim: int,
symbol_embedding_dim: int,
num_lstm_layers: int,
lstm_hidden_dim: int,
lstm_layer_norm: bool = False,
lstm_layer_norm_epsilon: float = 1e-5,
lstm_dropout: float = 0.0,
) -> None:
super().__init__()
self.embedding = torch.nn.Embedding(num_symbols, symbol_embedding_dim)
self.input_layer_norm = torch.nn.LayerNorm(symbol_embedding_dim)
self.lstm_layers = torch.nn.ModuleList(
[
_CustomLSTM(
symbol_embedding_dim if idx == 0 else lstm_hidden_dim,
lstm_hidden_dim,
layer_norm=lstm_layer_norm,
layer_norm_epsilon=lstm_layer_norm_epsilon,
)
for idx in range(num_lstm_layers)
]
)
self.dropout = torch.nn.Dropout(p=lstm_dropout)
self.linear = torch.nn.Linear(lstm_hidden_dim, output_dim)
self.output_layer_norm = torch.nn.LayerNorm(output_dim)
self.lstm_dropout = lstm_dropout
def forward(
self,
input: torch.Tensor,
lengths: torch.Tensor,
state: Optional[List[List[torch.Tensor]]] = None,
) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
r"""Forward pass.
B: batch size;
U: maximum sequence length in batch;
D: feature dimension of each input sequence element.
Args:
input (torch.Tensor): target sequences, with shape `(B, U)` and each element
mapping to a target symbol, i.e. in range `[0, num_symbols)`.
lengths (torch.Tensor): with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in ``input``.
state (List[List[torch.Tensor]] or None, optional): list of lists of tensors
representing internal state generated in preceding invocation
of ``forward``. (Default: ``None``)
Returns:
(torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
torch.Tensor
output encoding sequences, with shape `(B, U, output_dim)`
torch.Tensor
output lengths, with shape `(B,)` and i-th element representing
number of valid elements for i-th batch element in output encoding sequences.
List[List[torch.Tensor]]
output states; list of lists of tensors
representing internal state generated in current invocation of ``forward``.
"""
input_tb = input.permute(1, 0)
embedding_out = self.embedding(input_tb)
input_layer_norm_out = self.input_layer_norm(embedding_out)
lstm_out = input_layer_norm_out
state_out: List[List[torch.Tensor]] = []
for layer_idx, lstm in enumerate(self.lstm_layers):
lstm_out, lstm_state_out = lstm(lstm_out, None if state is None else state[layer_idx])
lstm_out = self.dropout(lstm_out)
state_out.append(lstm_state_out)
linear_out = self.linear(lstm_out)
output_layer_norm_out = self.output_layer_norm(linear_out)
return output_layer_norm_out.permute(1, 0, 2), lengths, state_out
class _Joiner(torch.nn.Module):
r"""Recurrent neural network transducer (RNN-T) joint network.
Args:
input_dim (int): source and target input dimension.
output_dim (int): output dimension.
activation (str, optional): activation function to use in the joiner.
Must be one of ("relu", "tanh"). (Default: "relu")
"""
def __init__(self, input_dim: int, output_dim: int, activation: str = "relu") -> None:
super().__init__()
self.linear = torch.nn.Linear(input_dim, output_dim, bias=True)
if activation == "relu":
self.activation = torch.nn.ReLU()
elif activation == "tanh":
self.activation = torch.nn.Tanh()
else:
raise ValueError(f"Unsupported activation {activation}")
def forward(
self,
source_encodings: torch.Tensor,
source_lengths: torch.Tensor,
target_encodings: torch.Tensor,
target_lengths: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Forward pass for training.
B: batch size;
T: maximum source sequence length in batch;
U: maximum target sequence length in batch;
D: dimension of each source and target sequence encoding.
Args:
source_encodings (torch.Tensor): source encoding sequences, with
shape `(B, T, D)`.
source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
valid sequence length of i-th batch element in ``source_encodings``.
target_encodings (torch.Tensor): target encoding sequences, with shape `(B, U, D)`.
target_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
valid sequence length of i-th batch element in ``target_encodings``.
Returns:
(torch.Tensor, torch.Tensor, torch.Tensor):
torch.Tensor
joint network output, with shape `(B, T, U, output_dim)`.
torch.Tensor
output source lengths, with shape `(B,)` and i-th element representing
number of valid elements along dim 1 for i-th batch element in joint network output.
torch.Tensor
output target lengths, with shape `(B,)` and i-th element representing
number of valid elements along dim 2 for i-th batch element in joint network output.
"""
joint_encodings = source_encodings.unsqueeze(2).contiguous() + target_encodings.unsqueeze(1).contiguous()
activation_out = self.activation(joint_encodings)
output = self.linear(activation_out)
return output, source_lengths, target_lengths
class RNNT(torch.nn.Module):
r"""torchaudio.models.RNNT()
Recurrent neural network transducer (RNN-T) model.
Note:
To build the model, please use one of the factory functions.
See Also:
:class:`torchaudio.pipelines.RNNTBundle`: ASR pipeline with pre-trained models.
Args:
transcriber (torch.nn.Module): transcription network.
predictor (torch.nn.Module): prediction network.
joiner (torch.nn.Module): joint network.
"""
def __init__(self, transcriber: _Transcriber, predictor: _Predictor, joiner: _Joiner) -> None:
super().__init__()
self.transcriber = transcriber
self.predictor = predictor
self.joiner = joiner
def forward(
self,
sources: torch.Tensor,
source_lengths: torch.Tensor,
targets: torch.Tensor,
target_lengths: torch.Tensor,
predictor_state: Optional[List[List[torch.Tensor]]] = None,idx =1.0,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
r"""Forward pass for training.
B: batch size;
T: maximum source sequence length in batch;
U: maximum target sequence length in batch;
D: feature dimension of each source sequence element.
Args:
sources (torch.Tensor): source frame sequences right-padded with right context, with
shape `(B, T, D)`.
source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in ``sources``.
targets (torch.Tensor): target sequences, with shape `(B, U)` and each element
mapping to a target symbol.
target_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in ``targets``.
predictor_state (List[List[torch.Tensor]] or None, optional): list of lists of tensors
representing prediction network internal state generated in preceding invocation
of ``forward``. (Default: ``None``)
Returns:
(torch.Tensor, torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
torch.Tensor
joint network output, with shape
`(B, max output source length, max output target length, output_dim (number of target symbols))`.
torch.Tensor
output source lengths, with shape `(B,)` and i-th element representing
number of valid elements along dim 1 for i-th batch element in joint network output.
torch.Tensor
output target lengths, with shape `(B,)` and i-th element representing
number of valid elements along dim 2 for i-th batch element in joint network output.
List[List[torch.Tensor]]
output states; list of lists of tensors
representing prediction network internal state generated in current invocation
of ``forward``.
"""
source_encodings, source_lengths = self.transcriber(
input=sources,
lengths=source_lengths,idx = idx,
)
target_encodings, target_lengths, predictor_state = self.predictor(
input=targets,
lengths=target_lengths,
state=predictor_state,
)
output, source_lengths, target_lengths = self.joiner(
source_encodings=source_encodings,
source_lengths=source_lengths,
target_encodings=target_encodings,
target_lengths=target_lengths,
)
return (
output,
source_lengths,
target_lengths,
predictor_state,
)
@torch.jit.export
def transcribe_streaming(
self,
sources: torch.Tensor,
source_lengths: torch.Tensor,
state: Optional[List[List[torch.Tensor]]],
) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
r"""Applies transcription network to sources in streaming mode.
B: batch size;
T: maximum source sequence segment length in batch;
D: feature dimension of each source sequence frame.
Args:
sources (torch.Tensor): source frame sequence segments right-padded with right context, with
shape `(B, T + right context length, D)`.
source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in ``sources``.
state (List[List[torch.Tensor]] or None): list of lists of tensors
representing transcription network internal state generated in preceding invocation
of ``transcribe_streaming``.
Returns:
(torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
torch.Tensor
output frame sequences, with
shape `(B, T // time_reduction_stride, output_dim)`.
torch.Tensor
output lengths, with shape `(B,)` and i-th element representing
number of valid elements for i-th batch element in output.
List[List[torch.Tensor]]
output states; list of lists of tensors
representing transcription network internal state generated in current invocation
of ``transcribe_streaming``.
"""
return self.transcriber.infer(sources, source_lengths, state)
@torch.jit.export
def transcribe(
self,
sources: torch.Tensor,
source_lengths: torch.Tensor,
idx =1.0,
) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Applies transcription network to sources in non-streaming mode.
B: batch size;
T: maximum source sequence length in batch;
D: feature dimension of each source sequence frame.
Args:
sources (torch.Tensor): source frame sequences right-padded with right context, with
shape `(B, T + right context length, D)`.
source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in ``sources``.
Returns:
(torch.Tensor, torch.Tensor):
torch.Tensor
output frame sequences, with
shape `(B, T // time_reduction_stride, output_dim)`.
torch.Tensor
output lengths, with shape `(B,)` and i-th element representing
number of valid elements for i-th batch element in output frame sequences.
"""
return self.transcriber(sources, source_lengths,idx = idx)
@torch.jit.export
def predict(
self,
targets: torch.Tensor,
target_lengths: torch.Tensor,
state: Optional[List[List[torch.Tensor]]],
) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
r"""Applies prediction network to targets.
B: batch size;
U: maximum target sequence length in batch;
D: feature dimension of each target sequence frame.
Args:
targets (torch.Tensor): target sequences, with shape `(B, U)` and each element
mapping to a target symbol, i.e. in range `[0, num_symbols)`.
target_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
number of valid frames for i-th batch element in ``targets``.
state (List[List[torch.Tensor]] or None): list of lists of tensors
representing internal state generated in preceding invocation
of ``predict``.
Returns:
(torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
torch.Tensor
output frame sequences, with shape `(B, U, output_dim)`.
torch.Tensor
output lengths, with shape `(B,)` and i-th element representing
number of valid elements for i-th batch element in output.
List[List[torch.Tensor]]
output states; list of lists of tensors
representing internal state generated in current invocation of ``predict``.
"""
return self.predictor(input=targets, lengths=target_lengths, state=state)
@torch.jit.export
def join(
self,
source_encodings: torch.Tensor,
source_lengths: torch.Tensor,
target_encodings: torch.Tensor,
target_lengths: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Applies joint network to source and target encodings.
B: batch size;
T: maximum source sequence length in batch;
U: maximum target sequence length in batch;
D: dimension of each source and target sequence encoding.
Args:
source_encodings (torch.Tensor): source encoding sequences, with
shape `(B, T, D)`.
source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
valid sequence length of i-th batch element in ``source_encodings``.
target_encodings (torch.Tensor): target encoding sequences, with shape `(B, U, D)`.
target_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
valid sequence length of i-th batch element in ``target_encodings``.
Returns:
(torch.Tensor, torch.Tensor, torch.Tensor):
torch.Tensor
joint network output, with shape `(B, T, U, output_dim)`.
torch.Tensor
output source lengths, with shape `(B,)` and i-th element representing
number of valid elements along dim 1 for i-th batch element in joint network output.
torch.Tensor
output target lengths, with shape `(B,)` and i-th element representing
number of valid elements along dim 2 for i-th batch element in joint network output.
"""
output, source_lengths, target_lengths = self.joiner(
source_encodings=source_encodings,
source_lengths=source_lengths,
target_encodings=target_encodings,
target_lengths=target_lengths,
)
return output, source_lengths, target_lengths
def emformer_rnnt_model(
*,
input_dim: int,
encoding_dim: int,
num_symbols: int,
segment_length: int,
right_context_length: int,
time_reduction_input_dim: int,
time_reduction_stride: int,
transformer_num_heads: int,
transformer_ffn_dim: int,
transformer_num_layers: int,
transformer_dropout: float,
transformer_activation: str,
transformer_left_context_length: int,
transformer_max_memory_size: int,
transformer_weight_init_scale_strategy: str,
transformer_tanh_on_mem: bool,
symbol_embedding_dim: int,
num_lstm_layers: int,
lstm_layer_norm: bool,
lstm_layer_norm_epsilon: float,
lstm_dropout: float,
) -> RNNT:
r"""Builds Emformer-based :class:`~torchaudio.models.RNNT`.
Note:
For non-streaming inference, the expectation is for `transcribe` to be called on input
sequences right-concatenated with `right_context_length` frames.
For streaming inference, the expectation is for `transcribe_streaming` to be called
on input chunks comprising `segment_length` frames right-concatenated with `right_context_length`
frames.
Args:
input_dim (int): dimension of input sequence frames passed to transcription network.
encoding_dim (int): dimension of transcription- and prediction-network-generated encodings
passed to joint network.
num_symbols (int): cardinality of set of target tokens.
segment_length (int): length of input segment expressed as number of frames.
right_context_length (int): length of right context expressed as number of frames.
time_reduction_input_dim (int): dimension to scale each element in input sequences to
prior to applying time reduction block.
time_reduction_stride (int): factor by which to reduce length of input sequence.
transformer_num_heads (int): number of attention heads in each Emformer layer.
transformer_ffn_dim (int): hidden layer dimension of each Emformer layer's feedforward network.
transformer_num_layers (int): number of Emformer layers to instantiate.
transformer_left_context_length (int): length of left context considered by Emformer.
transformer_dropout (float): Emformer dropout probability.
transformer_activation (str): activation function to use in each Emformer layer's
feedforward network. Must be one of ("relu", "gelu", "silu").
transformer_max_memory_size (int): maximum number of memory elements to use.
transformer_weight_init_scale_strategy (str): per-layer weight initialization scaling
strategy. Must be one of ("depthwise", "constant", ``None``).
transformer_tanh_on_mem (bool): if ``True``, applies tanh to memory elements.
symbol_embedding_dim (int): dimension of each target token embedding.
num_lstm_layers (int): number of LSTM layers to instantiate.
lstm_layer_norm (bool): if ``True``, enables layer normalization for LSTM layers.
lstm_layer_norm_epsilon (float): value of epsilon to use in LSTM layer normalization layers.
lstm_dropout (float): LSTM dropout probability.
Returns:
RNNT:
Emformer RNN-T model.
"""
encoder = _EmformerEncoder(
input_dim=input_dim,
output_dim=encoding_dim,
segment_length=segment_length,
right_context_length=right_context_length,
time_reduction_input_dim=time_reduction_input_dim,
time_reduction_stride=time_reduction_stride,
transformer_num_heads=transformer_num_heads,
transformer_ffn_dim=transformer_ffn_dim,
transformer_num_layers=transformer_num_layers,
transformer_dropout=transformer_dropout,
transformer_activation=transformer_activation,
transformer_left_context_length=transformer_left_context_length,
transformer_max_memory_size=transformer_max_memory_size,
transformer_weight_init_scale_strategy=transformer_weight_init_scale_strategy,
transformer_tanh_on_mem=transformer_tanh_on_mem,
)
predictor = _Predictor(
num_symbols,
encoding_dim,
symbol_embedding_dim=symbol_embedding_dim,
num_lstm_layers=num_lstm_layers,
lstm_hidden_dim=symbol_embedding_dim,
lstm_layer_norm=lstm_layer_norm,
lstm_layer_norm_epsilon=lstm_layer_norm_epsilon,
lstm_dropout=lstm_dropout,
)
joiner = _Joiner(encoding_dim, num_symbols)
return RNNT(encoder, predictor, joiner)
def emformer_rnnt_base(num_symbols: int) -> RNNT:
r"""Builds basic version of Emformer-based :class:`~torchaudio.models.RNNT`.
Args:
num_symbols (int): The size of target token lexicon.
Returns:
RNNT:
Emformer RNN-T model.
"""
return emformer_rnnt_model(
input_dim=80,
encoding_dim=1024,
num_symbols=num_symbols,
segment_length=16,
right_context_length=4,
time_reduction_input_dim=128,
time_reduction_stride=4,
transformer_num_heads=8,
transformer_ffn_dim=2048,
transformer_num_layers=20,
transformer_dropout=0.1,
transformer_activation="gelu",
transformer_left_context_length=30,
transformer_max_memory_size=0,
transformer_weight_init_scale_strategy="depthwise",
transformer_tanh_on_mem=True,
symbol_embedding_dim=512,
num_lstm_layers=3,
lstm_layer_norm=True,
lstm_layer_norm_epsilon=1e-3,
lstm_dropout=0.3,
)