/
rnnt_decode.py
297 lines (263 loc) · 11.6 KB
/
rnnt_decode.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
# Copyright 2022 Xiaomi Corp. (author: Wei Kang)
#
# See ../../../LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import List
from typing import Tuple
import k2
import torch
import _k2
from k2 import Fsa
from k2 import RaggedShape
from k2 import RaggedTensor
from torch import Tensor
from .ops import index_select
from _k2 import RnntDecodingConfig
class RnntDecodingStream(object):
def __init__(self, fsa: Fsa) -> None:
"""Create a new rnnt decoding stream.
Every sequence(wave data) needs a decoding stream, this function is
expected to be called when a new sequence comes. We support different
decoding graphs for different streams.
Args:
fsa:
The decoding graph used in this stream.
Returns:
A rnnt decoding stream object, which will be combined into
:class:`RnntDecodingStreams` to do decoding together with other
sequences in parallel.
"""
self.fsa = fsa
self.stream = _k2.create_rnnt_decoding_stream(fsa.arcs)
self.device = fsa.device
def __str__(self) -> str:
"""Return a string representation of this object
For visualization and debug only.
"""
return f"{self.stream}, device : {self.device}\n"
class RnntDecodingStreams(object):
"""See https://github.com/k2-fsa/icefall/blob/master/egs/librispeech/ASR/pruned_transducer_stateless/beam_search.py # noqa
for how this class is used in RNN-T decoding.
"""
def __init__(
self, src_streams: List[RnntDecodingStream], config: RnntDecodingConfig
) -> None:
"""
Combines multiple RnntDecodingStream objects to create a
RnntDecodingStreams object, then all these RnntDecodingStreams can do
decoding in parallel.
Args:
src_streams:
A list of RnntDecodingStream object to be combined.
config:
A configuration object which contains decoding parameters like
`vocab-size`, `decoder_history_len`, `beam`, `max_states`,
`max_contexts` etc.
Returns:
Return a RnntDecodingStreams object.
"""
assert len(src_streams) > 0
self.num_streams = len(src_streams)
self.src_streams = src_streams
self.device = self.src_streams[0].device
streams = [x.stream for x in self.src_streams]
self.streams = _k2.RnntDecodingStreams(streams, config)
def __str__(self) -> str:
"""Return a string representation of this object
For visualization and debug only.
"""
s = f"num_streams : {self.num_streams}\n"
for i in range(self.num_streams):
s += f"stream[{i}] : {self.src_streams[i]}"
return s
def get_contexts(self) -> Tuple[RaggedShape, Tensor]:
"""
This function must be called prior to evaluating the joiner network
for a particular frame. It tells the calling code for which contexts
it must evaluate the joiner network.
Returns:
Return a two-element tuple containing a RaggedShape and a tensor.
shape:
A RaggedShape with 2 axes, representing [stream][context].
contexts:
A tensor of shape [tot_contexts][decoder_history_len], where
tot_contexts == shape->TotSize(1) and decoder_history_len comes from
the config, it represents the number of symbols in the context of
the decoder network (assumed to be finite). It contains the token
ids into the vocabulary(i.e. `0 <= value < vocab_size`).
Its dtype is torch.int32.
"""
return self.streams.get_contexts()
def advance(self, logprobs: Tensor) -> None:
"""
Advance decoding streams by one frame.
Args:
logprobs:
A tensor of shape [tot_contexts][num_symbols], containing log-probs
of symbols given the contexts output by `get_contexts()`. It
satisfies `logprobs.Dim0() == shape.TotSize(1)`, shape is returned
by `get_contexts()`.
"""
self.streams.advance(logprobs)
def terminate_and_flush_to_streams(self) -> None:
"""
Terminate the decoding process of current RnntDecodingStreams object.
It will update the decoding states and store the decoding results
currently got to each of the individual streams.
Note:
We can not decode with this object anymore after calling
terminate_and_flush_to_streams().
"""
self.streams.terminate_and_flush_to_streams()
def format_output(
self,
num_frames: List[int],
allow_partial: bool = False,
log_probs: torch.Tensor = None,
t2s2c_shape: RaggedShape = None,
) -> Fsa:
"""
Generate the lattice Fsa currently got.
Note:
The attributes of the generated lattice is a union of the attributes
of all the decoding graphs. For example, if `self` contains three
individual stream, each stream has its own decoding graphs, graph[0]
has attributes attr1, attr2; graph[1] has attributes attr1, attr3;
graph[2] has attributes attr3, attr4; then the generated lattice has
attributes attr1, attr2, attr3, attr4.
Args:
num_frames:
A List containing the number of frames we want to gather for each
stream (note: the frames we have ever received for the corresponding
stream). It MUST satisfy `len(num_frames) == self.num_streams`.
allow_partial:
If true and there is no final state active, we will treat all the
states on the last frame to be final state.
If false, we only care about the real final state in the
decoding graph on the last frame when generating lattice.
Default False.
log_probs:
A tensor of shape [t2s2c_shape.tot_size(2)][num_symbols].
It's a stacked tensor of logprobs passed to function `advance`
during decoding.
t2s2c_shape:
It is short for time2stream2context_shape,
which describes shape of log_probs used to generate lattice.
Used to generate arc_map_token
and make the whole decoding process differentiable.
Returns:
Return the lattice Fsa with all the attributes propagated.
The returned Fsa has 3 axes with `fsa.dim0==self.num_streams`.
"""
assert len(num_frames) == self.num_streams
if log_probs is not None:
assert t2s2c_shape is not None
assert t2s2c_shape.tot_size(2) == log_probs.shape[0]
ragged_arcs, out_map, arc_map_token = self.streams.format_output(
num_frames, allow_partial, t2s2c_shape
)
else:
ragged_arcs, out_map = self.streams.format_output(
num_frames, allow_partial
)
fsa = Fsa(ragged_arcs)
# propagate attributes
tensor_attr_info = dict()
# gather the attributes info of all the decoding graphs,
for i in range(self.num_streams):
src = self.src_streams[i].fsa
for name, value in src.named_tensor_attr(include_scores=False):
if name not in tensor_attr_info:
filler = 0
if isinstance(value, Tensor):
filler = float(src.get_filler(name))
dtype = value.dtype
tensor_type = "Tensor"
else:
assert isinstance(value, k2.RaggedTensor)
# Only integer types ragged attributes are supported now
assert value.dtype == torch.int32
assert value.num_axes == 2
dtype = torch.int32
tensor_type = "RaggedTensor"
tensor_attr_info[name] = {
"filler": filler,
"dtype": dtype,
"tensor_type": tensor_type,
}
# combine the attributes propagating from different decoding graphs
for name, info in tensor_attr_info.items():
values = list()
start = 0
for i in range(self.num_streams):
src = self.src_streams[i].fsa
device = self.device
num_arcs = fsa[i].num_arcs
arc_map = out_map[start: start + num_arcs]
start = start + num_arcs
if hasattr(src, name):
value = getattr(src, name)
if info["tensor_type"] == "Tensor":
assert isinstance(value, Tensor)
new_value = index_select(
value, arc_map, default_value=filler
)
else:
assert isinstance(value, RaggedTensor)
# Only integer types ragged attributes are supported now
assert value.num_axes == 2
assert value.dtype == torch.int32
new_value, _ = value.index(
arc_map, axis=0, need_value_indexes=False
)
else:
if info["tensor_type"] == "Tensor":
# fill with filler value
new_value = torch.tensor(
[filler] * num_arcs,
dtype=info["dtype"],
device=device,
)
else:
# fill with empty RaggedTensor
new_value = RaggedTensor(
torch.empty(
(num_arcs, 0),
dtype=info["dtype"],
device=device,
)
)
values.append(new_value)
if info["tensor_type"] == "Tensor":
new_value = torch.cat(values)
else:
new_value = k2.ragged.cat(values, axis=0)
setattr(fsa, name, new_value)
# set non_tensor_attrs
for i in range(self.num_streams):
src = self.src_streams[i].fsa
for name, value in src.named_non_tensor_attr():
setattr(fsa, name, value)
if log_probs is not None:
# Make fsa.scores tracked by autograd
# to make the whole decoding process differentiable.
scores_tracked_by_autograd = index_select(
log_probs.reshape(-1), arc_map_token, default_value=0.0)
# Decoding graph may contain non-zero scores on arcs.
graph_scores = \
fsa.scores.detach() - scores_tracked_by_autograd.detach()
scores_tracked_by_autograd = \
scores_tracked_by_autograd + graph_scores
fsa.scores = scores_tracked_by_autograd
return fsa