Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

models.py 7.2 KB

You have to be logged in to leave a comment. Sign In
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
  1. import math
  2. import torch
  3. from torch import nn
  4. from torch.nn import TransformerEncoder
  5. import torch.nn.functional as F
  6. from layers import MFCC, Attention, LinearNorm, ConvNorm, ConvBlock
  7. def build_model(model_params={}, model_type='asr'):
  8. model = ASRCNN(**model_params)
  9. return model
  10. class ASRCNN(nn.Module):
  11. def __init__(self,
  12. input_dim=80,
  13. hidden_dim=256,
  14. n_token=35,
  15. n_layers=6,
  16. token_embedding_dim=256,
  17. ):
  18. super().__init__()
  19. self.n_token = n_token
  20. self.n_down = 1
  21. self.to_mfcc = MFCC()
  22. self.init_cnn = ConvNorm(input_dim//2, hidden_dim, kernel_size=7, padding=3, stride=2)
  23. self.cnns = nn.Sequential(
  24. *[nn.Sequential(
  25. ConvBlock(hidden_dim),
  26. nn.GroupNorm(num_groups=1, num_channels=hidden_dim)
  27. ) for n in range(n_layers)])
  28. self.projection = ConvNorm(hidden_dim, hidden_dim // 2)
  29. self.ctc_linear = nn.Sequential(
  30. LinearNorm(hidden_dim//2, hidden_dim),
  31. nn.ReLU(),
  32. LinearNorm(hidden_dim, n_token))
  33. self.asr_s2s = ASRS2S(
  34. embedding_dim=token_embedding_dim,
  35. hidden_dim=hidden_dim//2,
  36. n_token=n_token)
  37. def forward(self, x, src_key_padding_mask=None, text_input=None):
  38. x = self.to_mfcc(x)
  39. x = self.init_cnn(x)
  40. x = self.cnns(x)
  41. x = self.projection(x)
  42. x = x.transpose(1, 2)
  43. ctc_logit = self.ctc_linear(x)
  44. if text_input is not None:
  45. _, s2s_logit, s2s_attn = self.asr_s2s(x, src_key_padding_mask, text_input)
  46. return ctc_logit, s2s_logit, s2s_attn
  47. else:
  48. return ctc_logit
  49. def get_feature(self, x):
  50. x = self.to_mfcc(x)
  51. x = self.init_cnn(x)
  52. x = self.cnns(x)
  53. x = self.instance_norm(x)
  54. x = self.projection(x)
  55. return x
  56. def length_to_mask(self, lengths):
  57. mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
  58. mask = torch.gt(mask+1, lengths.unsqueeze(1)).to(lengths.device)
  59. return mask
  60. def get_future_mask(self, out_length, unmask_future_steps=0):
  61. """
  62. Args:
  63. out_length (int): returned mask shape is (out_length, out_length).
  64. unmask_futre_steps (int): unmasking future step size.
  65. Return:
  66. mask (torch.BoolTensor): mask future timesteps mask[i, j] = True if i > j + unmask_future_steps else False
  67. """
  68. index_tensor = torch.arange(out_length).unsqueeze(0).expand(out_length, -1)
  69. mask = torch.gt(index_tensor, index_tensor.T + unmask_future_steps)
  70. return mask
  71. class ASRS2S(nn.Module):
  72. def __init__(self,
  73. embedding_dim=256,
  74. hidden_dim=512,
  75. n_location_filters=32,
  76. location_kernel_size=63,
  77. n_token=40):
  78. super(ASRS2S, self).__init__()
  79. self.embedding = nn.Embedding(n_token, embedding_dim)
  80. val_range = math.sqrt(6 / hidden_dim)
  81. self.embedding.weight.data.uniform_(-val_range, val_range)
  82. self.decoder_rnn_dim = hidden_dim
  83. self.project_to_n_symbols = nn.Linear(self.decoder_rnn_dim, n_token)
  84. self.attention_layer = Attention(
  85. self.decoder_rnn_dim,
  86. hidden_dim,
  87. hidden_dim,
  88. n_location_filters,
  89. location_kernel_size
  90. )
  91. self.decoder_rnn = nn.LSTMCell(self.decoder_rnn_dim + embedding_dim, self.decoder_rnn_dim)
  92. self.project_to_hidden = nn.Sequential(
  93. LinearNorm(self.decoder_rnn_dim * 2, hidden_dim),
  94. nn.Tanh())
  95. self.sos = 1
  96. self.eos = 2
  97. def initialize_decoder_states(self, memory, mask):
  98. """
  99. moemory.shape = (B, L, H) = (Batchsize, Maxtimestep, Hiddendim)
  100. """
  101. B, L, H = memory.shape
  102. self.decoder_hidden = torch.zeros((B, self.decoder_rnn_dim)).type_as(memory)
  103. self.decoder_cell = torch.zeros((B, self.decoder_rnn_dim)).type_as(memory)
  104. self.attention_weights = torch.zeros((B, L)).type_as(memory)
  105. self.attention_weights_cum = torch.zeros((B, L)).type_as(memory)
  106. self.attention_context = torch.zeros((B, H)).type_as(memory)
  107. self.memory = memory
  108. self.processed_memory = self.attention_layer.memory_layer(memory)
  109. self.mask = mask
  110. self.unk_index = 3
  111. self.random_mask = 0.1
  112. def forward(self, memory, memory_mask, text_input):
  113. """
  114. moemory.shape = (B, L, H) = (Batchsize, Maxtimestep, Hiddendim)
  115. moemory_mask.shape = (B, L, )
  116. texts_input.shape = (B, T)
  117. """
  118. self.initialize_decoder_states(memory, memory_mask)
  119. # text random mask
  120. random_mask = (torch.rand(text_input.shape) < self.random_mask).to(text_input.device)
  121. _text_input = text_input.clone()
  122. _text_input.masked_fill_(random_mask, self.unk_index)
  123. decoder_inputs = self.embedding(_text_input).transpose(0, 1) # -> [T, B, channel]
  124. start_embedding = self.embedding(
  125. torch.LongTensor([self.sos]*decoder_inputs.size(1)).to(decoder_inputs.device))
  126. decoder_inputs = torch.cat((start_embedding.unsqueeze(0), decoder_inputs), dim=0)
  127. hidden_outputs, logit_outputs, alignments = [], [], []
  128. while len(hidden_outputs) < decoder_inputs.size(0):
  129. decoder_input = decoder_inputs[len(hidden_outputs)]
  130. hidden, logit, attention_weights = self.decode(decoder_input)
  131. hidden_outputs += [hidden]
  132. logit_outputs += [logit]
  133. alignments += [attention_weights]
  134. hidden_outputs, logit_outputs, alignments = \
  135. self.parse_decoder_outputs(
  136. hidden_outputs, logit_outputs, alignments)
  137. return hidden_outputs, logit_outputs, alignments
  138. def decode(self, decoder_input):
  139. cell_input = torch.cat((decoder_input, self.attention_context), -1)
  140. self.decoder_hidden, self.decoder_cell = self.decoder_rnn(
  141. cell_input,
  142. (self.decoder_hidden, self.decoder_cell))
  143. attention_weights_cat = torch.cat(
  144. (self.attention_weights.unsqueeze(1),
  145. self.attention_weights_cum.unsqueeze(1)),dim=1)
  146. self.attention_context, self.attention_weights = self.attention_layer(
  147. self.decoder_hidden,
  148. self.memory,
  149. self.processed_memory,
  150. attention_weights_cat,
  151. self.mask)
  152. self.attention_weights_cum += self.attention_weights
  153. hidden_and_context = torch.cat((self.decoder_hidden, self.attention_context), -1)
  154. hidden = self.project_to_hidden(hidden_and_context)
  155. # dropout to increasing g
  156. logit = self.project_to_n_symbols(F.dropout(hidden, 0.5, self.training))
  157. return hidden, logit, self.attention_weights
  158. def parse_decoder_outputs(self, hidden, logit, alignments):
  159. # -> [B, T_out + 1, max_time]
  160. alignments = torch.stack(alignments).transpose(0,1)
  161. # [T_out + 1, B, n_symbols] -> [B, T_out + 1, n_symbols]
  162. logit = torch.stack(logit).transpose(0, 1).contiguous()
  163. hidden = torch.stack(hidden).transpose(0, 1).contiguous()
  164. return hidden, logit, alignments
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...