File size: 8,415 Bytes
ad16788
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""RNN decoder for transducer-based models."""

import torch

from espnet.nets.transducer_decoder_interface import TransducerDecoderInterface


class DecoderRNNT(TransducerDecoderInterface, torch.nn.Module):
    """RNN-T Decoder module.

    Args:
        odim (int): dimension of outputs
        dtype (str): gru or lstm
        dlayers (int): # prediction layers
        dunits (int): # prediction units
        blank (int): blank symbol id
        embed_dim (int): dimension of embeddings
        dropout (float): dropout rate
        dropout_embed (float): embedding dropout rate

    """

    def __init__(
        self,
        odim,
        dtype,
        dlayers,
        dunits,
        blank,
        embed_dim,
        dropout=0.0,
        dropout_embed=0.0,
    ):
        """Transducer initializer."""
        super().__init__()

        self.embed = torch.nn.Embedding(odim, embed_dim, padding_idx=blank)
        self.dropout_embed = torch.nn.Dropout(p=dropout_embed)

        dec_net = torch.nn.LSTM if dtype == "lstm" else torch.nn.GRU

        self.decoder = torch.nn.ModuleList(
            [dec_net(embed_dim, dunits, 1, batch_first=True)]
        )
        self.dropout_dec = torch.nn.Dropout(p=dropout)

        for _ in range(1, dlayers):
            self.decoder += [dec_net(dunits, dunits, 1, batch_first=True)]

        self.dlayers = dlayers
        self.dunits = dunits
        self.dtype = dtype

        self.odim = odim

        self.ignore_id = -1
        self.blank = blank

        self.multi_gpus = torch.cuda.device_count() > 1

    def set_device(self, device):
        """Set GPU device to use.

        Args:
            device (torch.device): device id

        """
        self.device = device

    def set_data_type(self, data_type):
        """Set GPU device to use.

        Args:
            data_type (torch.dtype): Tensor data type

        """
        self.data_type = data_type

    def init_state(self, batch_size):
        """Initialize decoder states.

        Args:
            batch_size (int): Batch size

        Returns:
            (tuple): batch of decoder states
                ((L, B, dec_dim), (L, B, dec_dim))

        """
        h_n = torch.zeros(
            self.dlayers,
            batch_size,
            self.dunits,
            device=self.device,
            dtype=self.data_type,
        )

        if self.dtype == "lstm":
            c_n = torch.zeros(
                self.dlayers,
                batch_size,
                self.dunits,
                device=self.device,
                dtype=self.data_type,
            )

            return (h_n, c_n)

        return (h_n, None)

    def rnn_forward(self, y, state):
        """RNN forward.

        Args:
            y (torch.Tensor): batch of input features (B, emb_dim)
            state (tuple): batch of decoder states
                ((L, B, dec_dim), (L, B, dec_dim))

        Returns:
            y (torch.Tensor): batch of output features (B, dec_dim)
            (tuple): batch of decoder states
                (L, B, dec_dim), (L, B, dec_dim))

        """
        h_prev, c_prev = state
        h_next, c_next = self.init_state(y.size(0))

        for layer in range(self.dlayers):
            if self.dtype == "lstm":
                y, (
                    h_next[layer : layer + 1],
                    c_next[layer : layer + 1],
                ) = self.decoder[layer](
                    y, hx=(h_prev[layer : layer + 1], c_prev[layer : layer + 1])
                )
            else:
                y, h_next[layer : layer + 1] = self.decoder[layer](
                    y, hx=h_prev[layer : layer + 1]
                )

            y = self.dropout_dec(y)

        return y, (h_next, c_next)

    def forward(self, hs_pad, ys_in_pad):
        """Forward function for transducer.

        Args:
            hs_pad (torch.Tensor):
                batch of padded hidden state sequences (B, Tmax, D)
            ys_in_pad (torch.Tensor):
                batch of padded character id sequence tensor (B, Lmax+1)

        Returns:
            z (torch.Tensor): output (B, T, U, odim)

        """
        self.set_device(hs_pad.device)
        self.set_data_type(hs_pad.dtype)

        state = self.init_state(hs_pad.size(0))
        eys = self.dropout_embed(self.embed(ys_in_pad))

        h_dec, _ = self.rnn_forward(eys, state)

        return h_dec

    def score(self, hyp, cache):
        """Forward one step.

        Args:
            hyp (dataclass): hypothesis
            cache (dict): states cache

        Returns:
            y (torch.Tensor): decoder outputs (1, dec_dim)
            state (tuple): decoder states
                ((L, 1, dec_dim), (L, 1, dec_dim)),
            (torch.Tensor): token id for LM (1,)

        """
        vy = torch.full((1, 1), hyp.yseq[-1], dtype=torch.long, device=self.device)

        str_yseq = "".join(list(map(str, hyp.yseq)))

        if str_yseq in cache:
            y, state = cache[str_yseq]
        else:
            ey = self.embed(vy)

            y, state = self.rnn_forward(ey, hyp.dec_state)
            cache[str_yseq] = (y, state)

        return y[0][0], state, vy[0]

    def batch_score(self, hyps, batch_states, cache, use_lm):
        """Forward batch one step.

        Args:
            hyps (list): batch of hypotheses
            batch_states (tuple): batch of decoder states
                ((L, B, dec_dim), (L, B, dec_dim))
            cache (dict): states cache
            use_lm (bool): whether a LM is used for decoding

        Returns:
            batch_y (torch.Tensor): decoder output (B, dec_dim)
            batch_states (tuple): batch of decoder states
                ((L, B, dec_dim), (L, B, dec_dim))
            lm_tokens (torch.Tensor): batch of token ids for LM (B)

        """
        final_batch = len(hyps)

        process = []
        done = [None] * final_batch

        for i, hyp in enumerate(hyps):
            str_yseq = "".join(list(map(str, hyp.yseq)))

            if str_yseq in cache:
                done[i] = cache[str_yseq]
            else:
                process.append((str_yseq, hyp.yseq[-1], hyp.dec_state))

        if process:
            tokens = torch.LongTensor([[p[1]] for p in process], device=self.device)
            dec_state = self.create_batch_states(
                self.init_state(tokens.size(0)), [p[2] for p in process]
            )

            ey = self.embed(tokens)
            y, dec_state = self.rnn_forward(ey, dec_state)

        j = 0
        for i in range(final_batch):
            if done[i] is None:
                new_state = self.select_state(dec_state, j)

                done[i] = (y[j], new_state)
                cache[process[j][0]] = (y[j], new_state)

                j += 1

        batch_y = torch.cat([d[0] for d in done], dim=0)
        batch_states = self.create_batch_states(batch_states, [d[1] for d in done])

        if use_lm:
            lm_tokens = torch.LongTensor([h.yseq[-1] for h in hyps], device=self.device)

            return batch_y, batch_states, lm_tokens

        return batch_y, batch_states, None

    def select_state(self, batch_states, idx):
        """Get decoder state from batch of states, for given id.

        Args:
            batch_states (tuple): batch of decoder states
                ((L, B, dec_dim), (L, B, dec_dim))
            idx (int): index to extract state from batch of states

        Returns:
            (tuple): decoder states for given id
                ((L, 1, dec_dim), (L, 1, dec_dim))

        """
        return (
            batch_states[0][:, idx : idx + 1, :],
            batch_states[1][:, idx : idx + 1, :] if self.dtype == "lstm" else None,
        )

    def create_batch_states(self, batch_states, l_states, l_tokens=None):
        """Create batch of decoder states.

        Args:
            batch_states (tuple): batch of decoder states
               ((L, B, dec_dim), (L, B, dec_dim))
            l_states (list): list of decoder states
               [L x ((1, dec_dim), (1, dec_dim))]

        Returns:
            batch_states (tuple): batch of decoder states
                ((L, B, dec_dim), (L, B, dec_dim))

        """
        return (
            torch.cat([s[0] for s in l_states], dim=1),
            torch.cat([s[1] for s in l_states], dim=1)
            if self.dtype == "lstm"
            else None,
        )