flashctc 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flashctc/__init__.py +6 -0
- flashctc/alphabet.py +176 -0
- flashctc/constants.py +18 -0
- flashctc/decoder.py +1151 -0
- flashctc/flashlight_backend.py +335 -0
- flashctc/language_model.py +519 -0
- flashctc/py.typed +0 -0
- flashctc-0.7.0.dist-info/METADATA +213 -0
- flashctc-0.7.0.dist-info/RECORD +13 -0
- flashctc-0.7.0.dist-info/WHEEL +4 -0
- flashctc-0.7.0.dist-info/licenses/AUTHORS.md +10 -0
- flashctc-0.7.0.dist-info/licenses/LICENSE +202 -0
- flashctc-0.7.0.dist-info/licenses/NOTICE +12 -0
flashctc/decoder.py
ADDED
|
@@ -0,0 +1,1151 @@
|
|
|
1
|
+
# Copyright 2021-present Kensho Technologies, LLC.
|
|
2
|
+
from __future__ import annotations, division
|
|
3
|
+
|
|
4
|
+
import dataclasses
|
|
5
|
+
import functools
|
|
6
|
+
import heapq
|
|
7
|
+
import logging
|
|
8
|
+
import math
|
|
9
|
+
import multiprocessing as mp
|
|
10
|
+
from multiprocessing.pool import Pool
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import sys
|
|
14
|
+
from typing import (
|
|
15
|
+
TYPE_CHECKING,
|
|
16
|
+
Any,
|
|
17
|
+
ClassVar,
|
|
18
|
+
Collection,
|
|
19
|
+
Dict,
|
|
20
|
+
Iterable,
|
|
21
|
+
Iterator,
|
|
22
|
+
List,
|
|
23
|
+
Optional,
|
|
24
|
+
Sequence,
|
|
25
|
+
Tuple,
|
|
26
|
+
Union,
|
|
27
|
+
)
|
|
28
|
+
import weakref
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
from numpy.typing import NBitBase, NDArray
|
|
32
|
+
|
|
33
|
+
from .alphabet import BPE_TOKEN, Alphabet, verify_alphabet_coverage
|
|
34
|
+
from .constants import (
|
|
35
|
+
DEFAULT_ALPHA,
|
|
36
|
+
DEFAULT_BEAM_WIDTH,
|
|
37
|
+
DEFAULT_BETA,
|
|
38
|
+
DEFAULT_HOTWORD_WEIGHT,
|
|
39
|
+
DEFAULT_MIN_TOKEN_LOGP,
|
|
40
|
+
DEFAULT_PRUNE_BEAMS,
|
|
41
|
+
DEFAULT_PRUNE_LOGP,
|
|
42
|
+
DEFAULT_SCORE_LM_BOUNDARY,
|
|
43
|
+
DEFAULT_UNK_LOGP_OFFSET,
|
|
44
|
+
MIN_TOKEN_CLIP_P,
|
|
45
|
+
)
|
|
46
|
+
from .language_model import (
|
|
47
|
+
AbstractLanguageModel,
|
|
48
|
+
AbstractLMState,
|
|
49
|
+
HotwordScorer,
|
|
50
|
+
LanguageModel,
|
|
51
|
+
load_unigram_set_from_arpa,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
logger = logging.getLogger(__name__)
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
import kenlm # type: ignore
|
|
58
|
+
except ImportError:
|
|
59
|
+
logger.warning(
|
|
60
|
+
"kenlm python bindings are not installed, so language models are not available. "
|
|
61
|
+
"Install them with: pip install camel-kenlm"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
# type hints
|
|
65
|
+
# store frame information for each word, where frame is the logit index of (start_frame, end_frame)
|
|
66
|
+
Frames = Tuple[int, int]
|
|
67
|
+
WordFrames = Tuple[str, Frames]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclasses.dataclass(frozen=True, slots=True)
|
|
71
|
+
class Beam:
|
|
72
|
+
"""Contains all the info needed for decoding a beam."""
|
|
73
|
+
|
|
74
|
+
text: str
|
|
75
|
+
next_word: str
|
|
76
|
+
partial_word: str
|
|
77
|
+
last_char: Optional[str]
|
|
78
|
+
text_frames: List[Frames]
|
|
79
|
+
partial_frames: Frames
|
|
80
|
+
logit_score: float
|
|
81
|
+
# BPE: the last token ended in a word boundary (like "▁⁇▁"), so the next one starts a new word
|
|
82
|
+
word_break_pending: bool = dataclasses.field(default=False, kw_only=True)
|
|
83
|
+
|
|
84
|
+
@classmethod
|
|
85
|
+
def from_lm_beam(cls, lm_beam: "Beam") -> "Beam":
|
|
86
|
+
"""Create a Beam from an LMBeam by stripping out the LM score."""
|
|
87
|
+
return Beam(
|
|
88
|
+
text=lm_beam.text,
|
|
89
|
+
next_word=lm_beam.next_word,
|
|
90
|
+
partial_word=lm_beam.partial_word,
|
|
91
|
+
last_char=lm_beam.last_char,
|
|
92
|
+
text_frames=lm_beam.text_frames,
|
|
93
|
+
partial_frames=lm_beam.partial_frames,
|
|
94
|
+
logit_score=lm_beam.logit_score,
|
|
95
|
+
word_break_pending=lm_beam.word_break_pending,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclasses.dataclass(frozen=True, slots=True)
|
|
100
|
+
class LMBeam(Beam):
|
|
101
|
+
"""Contains everything in a beam plus an additional language model score."""
|
|
102
|
+
|
|
103
|
+
lm_score: float
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclasses.dataclass(frozen=True)
|
|
107
|
+
class OutputBeam:
|
|
108
|
+
"""Output information."""
|
|
109
|
+
|
|
110
|
+
text: str
|
|
111
|
+
last_lm_state: Optional[AbstractLMState]
|
|
112
|
+
text_frames: List[WordFrames]
|
|
113
|
+
logit_score: float # Cumulative logit score
|
|
114
|
+
lm_score: float # Cumulative language model + logit score
|
|
115
|
+
|
|
116
|
+
def get_mp_safe_beam(self) -> "OutputBeam":
|
|
117
|
+
"""Get a multiprocessing-safe version of the beam."""
|
|
118
|
+
if self.last_lm_state is None:
|
|
119
|
+
last_lm_state = None
|
|
120
|
+
else:
|
|
121
|
+
last_lm_state = self.last_lm_state.get_mp_safe_state()
|
|
122
|
+
return dataclasses.replace(self, last_lm_state=last_lm_state)
|
|
123
|
+
|
|
124
|
+
def _as_tuple(self) -> Tuple[Any, ...]:
|
|
125
|
+
# shallow, unlike dataclasses.astuple which deep-copies the fields
|
|
126
|
+
return (self.text, self.last_lm_state, self.text_frames, self.logit_score, self.lm_score)
|
|
127
|
+
|
|
128
|
+
def __getitem__(self, index: Union[int, slice]) -> Any:
|
|
129
|
+
"""Support indexing for backwards compatibility with the former tuple format."""
|
|
130
|
+
try:
|
|
131
|
+
return self._as_tuple()[index]
|
|
132
|
+
except IndexError:
|
|
133
|
+
raise IndexError(f"OutputBeam index out of range: {index}") from None
|
|
134
|
+
|
|
135
|
+
def __iter__(self) -> Iterator[Any]:
|
|
136
|
+
"""Support tuple unpacking for backwards compatibility with the former tuple format."""
|
|
137
|
+
return iter(self._as_tuple())
|
|
138
|
+
|
|
139
|
+
def __len__(self) -> int:
|
|
140
|
+
"""Return the number of fields of the former tuple format."""
|
|
141
|
+
return 5
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# Key for the language model score cache
|
|
145
|
+
# text, is_eos
|
|
146
|
+
LMScoreCacheKey = Tuple[str, bool]
|
|
147
|
+
# LM score with hotword score, raw LM score, AbstracatLMState
|
|
148
|
+
LMScoreCacheValue = Tuple[float, float, AbstractLMState]
|
|
149
|
+
LMScoreCache = Dict[LMScoreCacheKey, LMScoreCacheValue]
|
|
150
|
+
|
|
151
|
+
# constants
|
|
152
|
+
NULL_FRAMES: Frames = (-1, -1) # placeholder that gets replaced with positive integer frame indices
|
|
153
|
+
EMPTY_START_BEAM = Beam("", "", "", None, [], NULL_FRAMES, 0.0)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# Generic float type
|
|
157
|
+
if sys.version_info < (3, 8):
|
|
158
|
+
NpFloat = Any
|
|
159
|
+
else:
|
|
160
|
+
if sys.version_info < (3, 9) and not TYPE_CHECKING:
|
|
161
|
+
NpFloat = Any
|
|
162
|
+
else:
|
|
163
|
+
NpFloat = np.floating[NBitBase]
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _get_valid_pool(pool: Optional[Pool]) -> Optional[Pool]:
|
|
167
|
+
"""Return the pool if the pool is appropriate for multiprocessing."""
|
|
168
|
+
if pool is None:
|
|
169
|
+
return None
|
|
170
|
+
context = pool._ctx # type: ignore
|
|
171
|
+
# the language model lives in a class variable, which only forked workers inherit; spawn and
|
|
172
|
+
# forkserver (the Linux default since Python 3.14) start workers without it
|
|
173
|
+
if (
|
|
174
|
+
isinstance(context, mp.context.SpawnContext)
|
|
175
|
+
or type(context).__name__ == "ForkServerContext"
|
|
176
|
+
):
|
|
177
|
+
logger.warning(
|
|
178
|
+
"Specified pool object has a %s context, which is not supported: use "
|
|
179
|
+
'multiprocessing.get_context("fork").Pool(). '
|
|
180
|
+
"See https://github.com/kensho-technologies/pyctcdecode/issues/65."
|
|
181
|
+
"\nFalling back to sequential decoding.",
|
|
182
|
+
context.get_start_method(),
|
|
183
|
+
)
|
|
184
|
+
return None
|
|
185
|
+
return pool
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _normalize_whitespace(text: str) -> str:
|
|
189
|
+
"""Efficiently normalize whitespace."""
|
|
190
|
+
return " ".join(text.split())
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _sort_and_trim_beams(beams: List[LMBeam], beam_width: int) -> List[LMBeam]:
|
|
194
|
+
"""Take top N beams by score."""
|
|
195
|
+
return heapq.nlargest(beam_width, beams, key=lambda x: x.lm_score)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _sum_log_scores(s1: float, s2: float) -> float:
|
|
199
|
+
"""Sum log odds in a numerically stable way."""
|
|
200
|
+
# this is slightly faster than using max
|
|
201
|
+
if s1 >= s2:
|
|
202
|
+
log_sum = s1 + math.log(1 + math.exp(s2 - s1))
|
|
203
|
+
else:
|
|
204
|
+
log_sum = s2 + math.log(1 + math.exp(s1 - s2))
|
|
205
|
+
return log_sum
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _log_softmax(x: NDArray[NpFloat], axis: Optional[int] = None) -> NDArray[NpFloat]:
|
|
209
|
+
"""Logarithm of softmax function, following implementation of scipy.special."""
|
|
210
|
+
x_max = np.amax(x, axis=axis, keepdims=True)
|
|
211
|
+
if x_max.ndim > 0:
|
|
212
|
+
x_max[~np.isfinite(x_max)] = 0
|
|
213
|
+
elif not np.isfinite(x_max):
|
|
214
|
+
x_max = np.zeros_like(x_max)
|
|
215
|
+
tmp = x - x_max
|
|
216
|
+
exp_tmp = np.exp(tmp)
|
|
217
|
+
# suppress warnings about log of zero
|
|
218
|
+
with np.errstate(divide="ignore"):
|
|
219
|
+
s = np.sum(exp_tmp, axis=axis, keepdims=True)
|
|
220
|
+
out = np.log(s)
|
|
221
|
+
return tmp - out # type: ignore[no-any-return]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _to_log_probs(logits: NDArray[NpFloat]) -> NDArray[NpFloat]:
|
|
225
|
+
"""Convert a logit matrix (or probabilities) into clipped log probabilities."""
|
|
226
|
+
if math.isclose(logits.sum(axis=1).mean(), 1):
|
|
227
|
+
# input looks like probabilities, so take log
|
|
228
|
+
return np.log(np.clip(logits, MIN_TOKEN_CLIP_P, 1))
|
|
229
|
+
# convert logits into log probs
|
|
230
|
+
return np.clip(_log_softmax(logits, axis=1), np.log(MIN_TOKEN_CLIP_P), 0)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _merge_tokens(token_1: str, token_2: str) -> str:
|
|
234
|
+
"""Fast, whitespace safe merging of tokens."""
|
|
235
|
+
if len(token_2) == 0:
|
|
236
|
+
text = token_1
|
|
237
|
+
elif len(token_1) == 0:
|
|
238
|
+
text = token_2
|
|
239
|
+
else:
|
|
240
|
+
text = token_1 + " " + token_2
|
|
241
|
+
return text
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _merge_beams(beams: List[Beam]) -> List[Beam]:
|
|
245
|
+
"""Merge beams with same prefix together."""
|
|
246
|
+
beam_dict = {}
|
|
247
|
+
for beam in beams:
|
|
248
|
+
new_text = _merge_tokens(beam.text, beam.next_word)
|
|
249
|
+
hash_idx = (new_text, beam.partial_word, beam.last_char, beam.word_break_pending)
|
|
250
|
+
if hash_idx not in beam_dict:
|
|
251
|
+
beam_dict[hash_idx] = beam
|
|
252
|
+
else:
|
|
253
|
+
# We've already seen this text - we want to combine the scores
|
|
254
|
+
beam_dict[hash_idx] = dataclasses.replace(
|
|
255
|
+
beam, logit_score=_sum_log_scores(beam_dict[hash_idx].logit_score, beam.logit_score)
|
|
256
|
+
)
|
|
257
|
+
return list(beam_dict.values())
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _prune_history(beams: List[LMBeam], lm_order: int) -> List[Beam]:
|
|
261
|
+
"""Filter out beams that are the same over max_ngram history.
|
|
262
|
+
|
|
263
|
+
Since n-gram language models have a finite history when scoring a new token, we can use that
|
|
264
|
+
fact to prune beams that only differ early on (more than n tokens in the past) and keep only the
|
|
265
|
+
higher scoring ones. Note that this helps speed up the decoding process but comes at the cost of
|
|
266
|
+
some amount of beam diversity. If more than the top beam is used in the output it should
|
|
267
|
+
potentially be disabled.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
beams: list of LMBeam
|
|
271
|
+
lm_order: int, the order of the n-gram model
|
|
272
|
+
|
|
273
|
+
Returns:
|
|
274
|
+
list of Beam
|
|
275
|
+
"""
|
|
276
|
+
# let's keep at least 1 word of history
|
|
277
|
+
min_n_history = max(1, lm_order - 1)
|
|
278
|
+
seen_hashes = set()
|
|
279
|
+
filtered_beams = []
|
|
280
|
+
# for each beam after this, check if we need to add it
|
|
281
|
+
for lm_beam in beams:
|
|
282
|
+
# hash based on history that can still affect lm scoring going forward
|
|
283
|
+
hash_idx = (
|
|
284
|
+
tuple(lm_beam.text.split()[-min_n_history:]),
|
|
285
|
+
lm_beam.partial_word,
|
|
286
|
+
lm_beam.last_char,
|
|
287
|
+
lm_beam.word_break_pending,
|
|
288
|
+
)
|
|
289
|
+
if hash_idx not in seen_hashes:
|
|
290
|
+
filtered_beams.append(Beam.from_lm_beam(lm_beam))
|
|
291
|
+
seen_hashes.add(hash_idx)
|
|
292
|
+
return filtered_beams
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class BeamSearchDecoderCTC:
|
|
296
|
+
# Note that we store the language model (large object) as a class variable.
|
|
297
|
+
# The advantage of this is that during multiprocessing they won't cause and overhead in time.
|
|
298
|
+
# This somewhat breaks conventional garbage collection which is why there are
|
|
299
|
+
# specific functions for cleaning up the class variables manually if space needs to be freed up.
|
|
300
|
+
# Specifically we create a random dictionary key during object instantiation which becomes the
|
|
301
|
+
# storage key for the class variable model_container. This allows for multiple model instances
|
|
302
|
+
# to be loaded at the same time.
|
|
303
|
+
model_container: ClassVar[Dict[bytes, Optional[AbstractLanguageModel]]] = {}
|
|
304
|
+
# live decoders per model key in this process: copies share the key of their original
|
|
305
|
+
_model_refs: ClassVar[Dict[bytes, int]] = {}
|
|
306
|
+
|
|
307
|
+
# serialization filenames
|
|
308
|
+
_ALPHABET_SERIALIZED_FILENAME = "alphabet.json"
|
|
309
|
+
_LANGUAGE_MODEL_SERIALIZED_DIRECTORY = "language_model"
|
|
310
|
+
|
|
311
|
+
def __init__(
|
|
312
|
+
self,
|
|
313
|
+
alphabet: Alphabet,
|
|
314
|
+
language_model: Optional[AbstractLanguageModel] = None,
|
|
315
|
+
) -> None:
|
|
316
|
+
"""CTC beam search decoder for token logit matrix.
|
|
317
|
+
|
|
318
|
+
Args:
|
|
319
|
+
alphabet: class containing the labels for input logit matrices
|
|
320
|
+
language_model: convenience class to store language model functionality
|
|
321
|
+
"""
|
|
322
|
+
self._alphabet = alphabet
|
|
323
|
+
self._idx2vocab = dict(enumerate(self._alphabet.labels))
|
|
324
|
+
self._is_bpe = alphabet.is_bpe
|
|
325
|
+
self._model_key = os.urandom(16)
|
|
326
|
+
BeamSearchDecoderCTC.model_container[self._model_key] = language_model
|
|
327
|
+
self._track_model_ref()
|
|
328
|
+
|
|
329
|
+
def __setstate__(self, state: Dict[str, Any]) -> None:
|
|
330
|
+
"""Restore a copied or unpickled decoder, which shares the model key of its original."""
|
|
331
|
+
self.__dict__.update(state)
|
|
332
|
+
self._track_model_ref()
|
|
333
|
+
|
|
334
|
+
def _track_model_ref(self) -> None:
|
|
335
|
+
"""Release the language model once the last decoder using it is garbage collected."""
|
|
336
|
+
refs = BeamSearchDecoderCTC._model_refs
|
|
337
|
+
refs[self._model_key] = refs.get(self._model_key, 0) + 1
|
|
338
|
+
weakref.finalize(self, BeamSearchDecoderCTC._release_model_ref, self._model_key)
|
|
339
|
+
|
|
340
|
+
@classmethod
|
|
341
|
+
def _release_model_ref(cls, model_key: bytes) -> None:
|
|
342
|
+
"""Drop one reference to a model, removing the model with the last one."""
|
|
343
|
+
count = cls._model_refs.get(model_key, 0) - 1
|
|
344
|
+
if count > 0:
|
|
345
|
+
cls._model_refs[model_key] = count
|
|
346
|
+
else:
|
|
347
|
+
cls._model_refs.pop(model_key, None)
|
|
348
|
+
cls.model_container.pop(model_key, None)
|
|
349
|
+
|
|
350
|
+
def reset_params(
|
|
351
|
+
self,
|
|
352
|
+
alpha: Optional[float] = None,
|
|
353
|
+
beta: Optional[float] = None,
|
|
354
|
+
unk_score_offset: Optional[float] = None,
|
|
355
|
+
lm_score_boundary: Optional[bool] = None,
|
|
356
|
+
) -> None:
|
|
357
|
+
"""Reset parameters that don't require re-instantiating the model."""
|
|
358
|
+
# todo: make more generic to accomodate other language models
|
|
359
|
+
language_model = self._language_model
|
|
360
|
+
if language_model is None:
|
|
361
|
+
return
|
|
362
|
+
params: Dict[str, Any] = {}
|
|
363
|
+
if alpha is not None:
|
|
364
|
+
params["alpha"] = alpha
|
|
365
|
+
if beta is not None:
|
|
366
|
+
params["beta"] = beta
|
|
367
|
+
if unk_score_offset is not None:
|
|
368
|
+
params["unk_score_offset"] = unk_score_offset
|
|
369
|
+
if lm_score_boundary is not None:
|
|
370
|
+
params["score_boundary"] = lm_score_boundary
|
|
371
|
+
language_model.reset_params(**params)
|
|
372
|
+
|
|
373
|
+
@classmethod
|
|
374
|
+
def clear_class_models(cls) -> None:
|
|
375
|
+
"""Clear all models from class variable."""
|
|
376
|
+
cls.model_container = {}
|
|
377
|
+
|
|
378
|
+
def cleanup(self) -> None:
|
|
379
|
+
"""Manual cleanup of models in class variable."""
|
|
380
|
+
if self._model_key in BeamSearchDecoderCTC.model_container:
|
|
381
|
+
del BeamSearchDecoderCTC.model_container[self._model_key]
|
|
382
|
+
|
|
383
|
+
@property
|
|
384
|
+
def _language_model(self) -> Optional[AbstractLanguageModel]:
|
|
385
|
+
"""Retrieve the language model."""
|
|
386
|
+
return BeamSearchDecoderCTC.model_container[self._model_key]
|
|
387
|
+
|
|
388
|
+
def _check_logits_dimension(
|
|
389
|
+
self,
|
|
390
|
+
logits: NDArray[NpFloat],
|
|
391
|
+
) -> None:
|
|
392
|
+
"""Verify correct shape and dimensions for input logits."""
|
|
393
|
+
if len(logits.shape) != 2:
|
|
394
|
+
raise ValueError(
|
|
395
|
+
"Input logits have %s dimensions, but need 2: (time, vocabulary)"
|
|
396
|
+
% len(logits.shape)
|
|
397
|
+
)
|
|
398
|
+
if logits.shape[-1] != len(self._idx2vocab):
|
|
399
|
+
raise ValueError(
|
|
400
|
+
"Input logits shape is %s, but vocabulary is size %s. "
|
|
401
|
+
"Need logits of shape: (time, vocabulary)" % (logits.shape, len(self._idx2vocab))
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
def _get_lm_beams(
|
|
405
|
+
self,
|
|
406
|
+
beams: List[Beam],
|
|
407
|
+
hotword_scorer: HotwordScorer,
|
|
408
|
+
cached_lm_scores: Dict[LMScoreCacheKey, LMScoreCacheValue],
|
|
409
|
+
cached_partial_token_scores: Dict[str, float],
|
|
410
|
+
is_eos: bool = False,
|
|
411
|
+
) -> List[LMBeam]:
|
|
412
|
+
"""Update score by averaging logit_score and lm_score."""
|
|
413
|
+
# get language model and see if exists
|
|
414
|
+
language_model = self._language_model
|
|
415
|
+
# if no language model available then return raw score + hotwords as lm score
|
|
416
|
+
if language_model is None:
|
|
417
|
+
has_hotwords = not hotword_scorer.is_empty
|
|
418
|
+
new_beams = []
|
|
419
|
+
for beam in beams:
|
|
420
|
+
new_text = _merge_tokens(beam.text, beam.next_word)
|
|
421
|
+
# note that usually this gets scaled with alpha
|
|
422
|
+
lm_hw_score = beam.logit_score
|
|
423
|
+
if has_hotwords:
|
|
424
|
+
lm_hw_score += hotword_scorer.score(
|
|
425
|
+
new_text
|
|
426
|
+
) + hotword_scorer.score_partial_token(beam.partial_word)
|
|
427
|
+
|
|
428
|
+
new_beams.append(
|
|
429
|
+
LMBeam(
|
|
430
|
+
text=new_text,
|
|
431
|
+
next_word="",
|
|
432
|
+
partial_word=beam.partial_word,
|
|
433
|
+
last_char=beam.last_char,
|
|
434
|
+
text_frames=beam.text_frames,
|
|
435
|
+
partial_frames=beam.partial_frames,
|
|
436
|
+
logit_score=beam.logit_score,
|
|
437
|
+
lm_score=lm_hw_score,
|
|
438
|
+
word_break_pending=beam.word_break_pending,
|
|
439
|
+
)
|
|
440
|
+
)
|
|
441
|
+
return new_beams
|
|
442
|
+
|
|
443
|
+
new_beams = []
|
|
444
|
+
for beam in beams:
|
|
445
|
+
# fast token merge
|
|
446
|
+
new_text = _merge_tokens(beam.text, beam.next_word)
|
|
447
|
+
cache_key = (new_text, is_eos)
|
|
448
|
+
if cache_key not in cached_lm_scores:
|
|
449
|
+
_, prev_raw_lm_score, start_state = cached_lm_scores[(beam.text, False)]
|
|
450
|
+
score, end_state = language_model.score(
|
|
451
|
+
start_state, beam.next_word, is_last_word=is_eos
|
|
452
|
+
)
|
|
453
|
+
raw_lm_score = prev_raw_lm_score + score
|
|
454
|
+
lm_hw_score = raw_lm_score + hotword_scorer.score(new_text)
|
|
455
|
+
cached_lm_scores[cache_key] = (lm_hw_score, raw_lm_score, end_state)
|
|
456
|
+
lm_score, _, _ = cached_lm_scores[cache_key]
|
|
457
|
+
word_part = beam.partial_word
|
|
458
|
+
if len(word_part) > 0:
|
|
459
|
+
if word_part not in cached_partial_token_scores:
|
|
460
|
+
# if prefix available in hotword trie use that, otherwise default to char trie
|
|
461
|
+
if word_part in hotword_scorer:
|
|
462
|
+
cached_partial_token_scores[word_part] = hotword_scorer.score_partial_token(
|
|
463
|
+
word_part
|
|
464
|
+
)
|
|
465
|
+
else:
|
|
466
|
+
cached_partial_token_scores[word_part] = language_model.score_partial_token(
|
|
467
|
+
word_part
|
|
468
|
+
)
|
|
469
|
+
lm_score += cached_partial_token_scores[word_part]
|
|
470
|
+
|
|
471
|
+
new_beams.append(
|
|
472
|
+
LMBeam(
|
|
473
|
+
text=new_text,
|
|
474
|
+
next_word="",
|
|
475
|
+
partial_word=word_part,
|
|
476
|
+
last_char=beam.last_char,
|
|
477
|
+
text_frames=beam.text_frames,
|
|
478
|
+
partial_frames=beam.partial_frames,
|
|
479
|
+
logit_score=beam.logit_score,
|
|
480
|
+
lm_score=beam.logit_score + lm_score,
|
|
481
|
+
word_break_pending=beam.word_break_pending,
|
|
482
|
+
)
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
return new_beams
|
|
486
|
+
|
|
487
|
+
def _partial_decode_logits(
|
|
488
|
+
self,
|
|
489
|
+
logits: NDArray[NpFloat],
|
|
490
|
+
beams: List[Beam],
|
|
491
|
+
beam_width: int,
|
|
492
|
+
beam_prune_logp: float,
|
|
493
|
+
token_min_logp: float,
|
|
494
|
+
prune_history: bool,
|
|
495
|
+
hotword_scorer: HotwordScorer,
|
|
496
|
+
cached_lm_scores: LMScoreCache,
|
|
497
|
+
cached_p_lm_scores: Dict[str, float],
|
|
498
|
+
processed_frames: int = 0,
|
|
499
|
+
) -> List[Beam]:
|
|
500
|
+
"""Decode logits for a set of beams with warmed score caches."""
|
|
501
|
+
language_model = self._language_model
|
|
502
|
+
for frame_idx, logit_col in enumerate(logits, start=processed_frames):
|
|
503
|
+
# plain python numbers: arithmetic on numpy scalars is several times slower
|
|
504
|
+
max_idx = int(logit_col.argmax())
|
|
505
|
+
idx_list = set(np.flatnonzero(logit_col >= token_min_logp).tolist()) | {max_idx}
|
|
506
|
+
logit_list = logit_col.tolist()
|
|
507
|
+
new_beams: List[Beam] = []
|
|
508
|
+
for idx_char in idx_list:
|
|
509
|
+
p_char = logit_list[idx_char]
|
|
510
|
+
char = self._idx2vocab[idx_char]
|
|
511
|
+
for beam in beams:
|
|
512
|
+
# if only blank token or same token
|
|
513
|
+
if char == "" or beam.last_char == char:
|
|
514
|
+
new_part_frames = (
|
|
515
|
+
beam.partial_frames
|
|
516
|
+
if char == ""
|
|
517
|
+
else (beam.partial_frames[0], frame_idx + 1)
|
|
518
|
+
)
|
|
519
|
+
new_beams.append(
|
|
520
|
+
Beam(
|
|
521
|
+
text=beam.text,
|
|
522
|
+
next_word=beam.next_word,
|
|
523
|
+
partial_word=beam.partial_word,
|
|
524
|
+
last_char=char,
|
|
525
|
+
text_frames=beam.text_frames,
|
|
526
|
+
partial_frames=new_part_frames,
|
|
527
|
+
logit_score=beam.logit_score + p_char,
|
|
528
|
+
word_break_pending=beam.word_break_pending,
|
|
529
|
+
)
|
|
530
|
+
)
|
|
531
|
+
# if bpe and leading space char, or the beam's last token ended a word
|
|
532
|
+
elif self._is_bpe and (char[:1] == BPE_TOKEN or beam.word_break_pending):
|
|
533
|
+
# some tokens are bounded on both sides like ▁⁇▁
|
|
534
|
+
clean_char = char
|
|
535
|
+
if char[:1] == BPE_TOKEN:
|
|
536
|
+
clean_char = clean_char[1:]
|
|
537
|
+
# the lone BPE_TOKEN already leaves an empty partial word, so the next
|
|
538
|
+
# token starts a new word without a pending break
|
|
539
|
+
word_break = len(char) > 1 and char[-1:] == BPE_TOKEN
|
|
540
|
+
if word_break:
|
|
541
|
+
clean_char = clean_char[:-1]
|
|
542
|
+
new_frame_list = (
|
|
543
|
+
beam.text_frames
|
|
544
|
+
if beam.partial_word == ""
|
|
545
|
+
else [*beam.text_frames, beam.partial_frames]
|
|
546
|
+
)
|
|
547
|
+
new_beams.append(
|
|
548
|
+
Beam(
|
|
549
|
+
text=beam.text,
|
|
550
|
+
next_word=beam.partial_word,
|
|
551
|
+
partial_word=clean_char,
|
|
552
|
+
last_char=char,
|
|
553
|
+
text_frames=new_frame_list,
|
|
554
|
+
partial_frames=(frame_idx, frame_idx + 1),
|
|
555
|
+
logit_score=beam.logit_score + p_char,
|
|
556
|
+
word_break_pending=word_break,
|
|
557
|
+
)
|
|
558
|
+
)
|
|
559
|
+
# if not bpe and space char
|
|
560
|
+
elif not self._is_bpe and char == " ":
|
|
561
|
+
new_frame_list = (
|
|
562
|
+
beam.text_frames
|
|
563
|
+
if beam.partial_word == ""
|
|
564
|
+
else [*beam.text_frames, beam.partial_frames]
|
|
565
|
+
)
|
|
566
|
+
new_beams.append(
|
|
567
|
+
Beam(
|
|
568
|
+
text=beam.text,
|
|
569
|
+
next_word=beam.partial_word,
|
|
570
|
+
partial_word="",
|
|
571
|
+
last_char=char,
|
|
572
|
+
text_frames=new_frame_list,
|
|
573
|
+
partial_frames=NULL_FRAMES,
|
|
574
|
+
logit_score=beam.logit_score + p_char,
|
|
575
|
+
)
|
|
576
|
+
)
|
|
577
|
+
# general update of continuing token without space
|
|
578
|
+
else:
|
|
579
|
+
new_part_frames = (
|
|
580
|
+
(frame_idx, frame_idx + 1)
|
|
581
|
+
if beam.partial_frames[0] < 0
|
|
582
|
+
else (beam.partial_frames[0], frame_idx + 1)
|
|
583
|
+
)
|
|
584
|
+
new_beams.append(
|
|
585
|
+
Beam(
|
|
586
|
+
beam.text,
|
|
587
|
+
beam.next_word,
|
|
588
|
+
beam.partial_word + char,
|
|
589
|
+
char,
|
|
590
|
+
beam.text_frames,
|
|
591
|
+
new_part_frames,
|
|
592
|
+
beam.logit_score + p_char,
|
|
593
|
+
)
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
# lm scoring and beam pruning
|
|
597
|
+
new_beams = _merge_beams(new_beams)
|
|
598
|
+
scored_beams = self._get_lm_beams(
|
|
599
|
+
new_beams,
|
|
600
|
+
hotword_scorer,
|
|
601
|
+
cached_lm_scores,
|
|
602
|
+
cached_p_lm_scores,
|
|
603
|
+
)
|
|
604
|
+
# remove beam outliers
|
|
605
|
+
max_score = max(b.lm_score for b in scored_beams)
|
|
606
|
+
scored_beams = [b for b in scored_beams if b.lm_score >= max_score + beam_prune_logp]
|
|
607
|
+
# beam pruning by taking highest N prefixes and then filtering down
|
|
608
|
+
trimmed_beams = _sort_and_trim_beams(scored_beams, beam_width)
|
|
609
|
+
# prune history and remove lm score from beams
|
|
610
|
+
if prune_history:
|
|
611
|
+
lm_order = 1 if language_model is None else language_model.order
|
|
612
|
+
beams = _prune_history(trimmed_beams, lm_order=lm_order)
|
|
613
|
+
else:
|
|
614
|
+
# an LMBeam is a Beam: the next frame reads only the Beam fields
|
|
615
|
+
beams = list(trimmed_beams)
|
|
616
|
+
|
|
617
|
+
return [b if type(b) is Beam else Beam.from_lm_beam(b) for b in beams]
|
|
618
|
+
|
|
619
|
+
def _finalize_beams(
|
|
620
|
+
self,
|
|
621
|
+
beams: Sequence[Beam],
|
|
622
|
+
beam_width: int,
|
|
623
|
+
beam_prune_logp: float,
|
|
624
|
+
hotword_scorer: HotwordScorer,
|
|
625
|
+
cached_lm_scores: LMScoreCache,
|
|
626
|
+
cached_p_lm_scores: Dict[str, float],
|
|
627
|
+
force_next_word: bool = False,
|
|
628
|
+
is_end: bool = False,
|
|
629
|
+
) -> List[LMBeam]:
|
|
630
|
+
"""Perform final language model scoring and sorting."""
|
|
631
|
+
if force_next_word or is_end:
|
|
632
|
+
new_beams = []
|
|
633
|
+
for beam in beams:
|
|
634
|
+
new_token_times = (
|
|
635
|
+
beam.text_frames
|
|
636
|
+
if beam.partial_word == ""
|
|
637
|
+
else [*beam.text_frames, beam.partial_frames]
|
|
638
|
+
)
|
|
639
|
+
new_beams.append(
|
|
640
|
+
Beam(
|
|
641
|
+
text=beam.text,
|
|
642
|
+
next_word=beam.partial_word,
|
|
643
|
+
partial_word="",
|
|
644
|
+
last_char=None,
|
|
645
|
+
text_frames=new_token_times,
|
|
646
|
+
partial_frames=(-1, -1),
|
|
647
|
+
logit_score=beam.logit_score,
|
|
648
|
+
),
|
|
649
|
+
)
|
|
650
|
+
new_beams = _merge_beams(new_beams)
|
|
651
|
+
else:
|
|
652
|
+
new_beams = list(beams)
|
|
653
|
+
scored_beams = self._get_lm_beams(
|
|
654
|
+
new_beams,
|
|
655
|
+
hotword_scorer,
|
|
656
|
+
cached_lm_scores,
|
|
657
|
+
cached_p_lm_scores,
|
|
658
|
+
is_eos=is_end,
|
|
659
|
+
)
|
|
660
|
+
# remove beam outliers
|
|
661
|
+
max_score = max([b.lm_score for b in scored_beams])
|
|
662
|
+
scored_beams = [b for b in scored_beams if b.lm_score >= max_score + beam_prune_logp]
|
|
663
|
+
return _sort_and_trim_beams(scored_beams, beam_width)
|
|
664
|
+
|
|
665
|
+
def _decode_logits(
|
|
666
|
+
self,
|
|
667
|
+
logits: NDArray[NpFloat],
|
|
668
|
+
beam_width: int,
|
|
669
|
+
beam_prune_logp: float,
|
|
670
|
+
token_min_logp: float,
|
|
671
|
+
prune_history: bool,
|
|
672
|
+
hotword_scorer: HotwordScorer,
|
|
673
|
+
lm_start_state: Optional[AbstractLMState] = None,
|
|
674
|
+
) -> List[OutputBeam]:
|
|
675
|
+
"""Perform beam search decoding."""
|
|
676
|
+
# local dictionaries to cache scores during decoding
|
|
677
|
+
# we can pass in an input start state to keep the decoder stateful and working on realtime
|
|
678
|
+
language_model = self._language_model
|
|
679
|
+
if language_model is None:
|
|
680
|
+
cached_lm_scores: LMScoreCache = {}
|
|
681
|
+
else:
|
|
682
|
+
if lm_start_state is None:
|
|
683
|
+
start_state = language_model.get_start_state()
|
|
684
|
+
else:
|
|
685
|
+
start_state = lm_start_state
|
|
686
|
+
cached_lm_scores = {("", False): (0.0, 0.0, start_state)}
|
|
687
|
+
cached_p_lm_scores: Dict[str, float] = {}
|
|
688
|
+
# start with single beam to expand on
|
|
689
|
+
beams = [EMPTY_START_BEAM]
|
|
690
|
+
|
|
691
|
+
beams = self._partial_decode_logits(
|
|
692
|
+
logits,
|
|
693
|
+
beams,
|
|
694
|
+
beam_width,
|
|
695
|
+
beam_prune_logp,
|
|
696
|
+
token_min_logp,
|
|
697
|
+
prune_history,
|
|
698
|
+
hotword_scorer,
|
|
699
|
+
cached_lm_scores,
|
|
700
|
+
cached_p_lm_scores,
|
|
701
|
+
)
|
|
702
|
+
trimmed_beams = self._finalize_beams(
|
|
703
|
+
beams,
|
|
704
|
+
beam_width,
|
|
705
|
+
beam_prune_logp,
|
|
706
|
+
hotword_scorer,
|
|
707
|
+
cached_lm_scores,
|
|
708
|
+
cached_p_lm_scores,
|
|
709
|
+
force_next_word=True,
|
|
710
|
+
is_end=True,
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
# remove unnecessary information from beams
|
|
714
|
+
output_beams = [
|
|
715
|
+
OutputBeam(
|
|
716
|
+
text=_normalize_whitespace(lm_beam.text),
|
|
717
|
+
last_lm_state=(
|
|
718
|
+
cached_lm_scores[(lm_beam.text, True)][-1]
|
|
719
|
+
if (lm_beam.text, True) in cached_lm_scores
|
|
720
|
+
else None
|
|
721
|
+
),
|
|
722
|
+
text_frames=list(zip(lm_beam.text.split(), lm_beam.text_frames, strict=False)),
|
|
723
|
+
logit_score=lm_beam.logit_score,
|
|
724
|
+
lm_score=lm_beam.lm_score, # same as logit_score if lm is missing
|
|
725
|
+
)
|
|
726
|
+
for lm_beam in trimmed_beams
|
|
727
|
+
]
|
|
728
|
+
return output_beams
|
|
729
|
+
|
|
730
|
+
def get_starting_state(self) -> Tuple[List[Beam], LMScoreCache, Dict[str, float]]:
|
|
731
|
+
"""Get the starting beams and initial caches."""
|
|
732
|
+
start_beam = [EMPTY_START_BEAM]
|
|
733
|
+
language_model = self._language_model
|
|
734
|
+
if language_model is None:
|
|
735
|
+
cached_lm_scores: LMScoreCache = {}
|
|
736
|
+
else:
|
|
737
|
+
start_state = language_model.get_start_state()
|
|
738
|
+
cached_lm_scores = {("", False): (0.0, 0.0, start_state)}
|
|
739
|
+
cached_p_lm_scores: Dict[str, float] = {}
|
|
740
|
+
return start_beam, cached_lm_scores, cached_p_lm_scores
|
|
741
|
+
|
|
742
|
+
def partial_decode_beams(
|
|
743
|
+
self,
|
|
744
|
+
logits: NDArray[NpFloat],
|
|
745
|
+
cached_lm_scores: LMScoreCache,
|
|
746
|
+
cached_p_lm_scores: Dict[str, float],
|
|
747
|
+
beams: List[Beam],
|
|
748
|
+
processed_frames: int,
|
|
749
|
+
beam_width: int = DEFAULT_BEAM_WIDTH,
|
|
750
|
+
beam_prune_logp: float = DEFAULT_PRUNE_LOGP,
|
|
751
|
+
token_min_logp: float = DEFAULT_MIN_TOKEN_LOGP,
|
|
752
|
+
prune_history: bool = DEFAULT_PRUNE_BEAMS,
|
|
753
|
+
hotword_scorer: Optional[HotwordScorer] = None,
|
|
754
|
+
force_next_word: bool = False,
|
|
755
|
+
is_end: bool = False,
|
|
756
|
+
) -> List[LMBeam]:
|
|
757
|
+
"""Decode beams for the given logits, allowing for additional decoding steps."""
|
|
758
|
+
self._check_logits_dimension(logits)
|
|
759
|
+
hotword_scorer = hotword_scorer or HotwordScorer.build_scorer([], weight=0.0)
|
|
760
|
+
# make sure we have log probs as input
|
|
761
|
+
logits = _to_log_probs(logits)
|
|
762
|
+
beams = self._partial_decode_logits(
|
|
763
|
+
logits,
|
|
764
|
+
beams,
|
|
765
|
+
beam_width,
|
|
766
|
+
beam_prune_logp,
|
|
767
|
+
token_min_logp,
|
|
768
|
+
prune_history,
|
|
769
|
+
hotword_scorer,
|
|
770
|
+
cached_lm_scores,
|
|
771
|
+
cached_p_lm_scores,
|
|
772
|
+
processed_frames=processed_frames,
|
|
773
|
+
)
|
|
774
|
+
trimmed_beams = self._finalize_beams(
|
|
775
|
+
beams,
|
|
776
|
+
beam_width,
|
|
777
|
+
beam_prune_logp,
|
|
778
|
+
hotword_scorer,
|
|
779
|
+
cached_lm_scores,
|
|
780
|
+
cached_p_lm_scores,
|
|
781
|
+
force_next_word=force_next_word,
|
|
782
|
+
is_end=is_end,
|
|
783
|
+
)
|
|
784
|
+
return trimmed_beams
|
|
785
|
+
|
|
786
|
+
def decode_beams(
|
|
787
|
+
self,
|
|
788
|
+
logits: NDArray[NpFloat],
|
|
789
|
+
beam_width: int = DEFAULT_BEAM_WIDTH,
|
|
790
|
+
beam_prune_logp: float = DEFAULT_PRUNE_LOGP,
|
|
791
|
+
token_min_logp: float = DEFAULT_MIN_TOKEN_LOGP,
|
|
792
|
+
prune_history: bool = DEFAULT_PRUNE_BEAMS,
|
|
793
|
+
hotwords: Optional[Iterable[str]] = None,
|
|
794
|
+
hotword_weight: float = DEFAULT_HOTWORD_WEIGHT,
|
|
795
|
+
lm_start_state: Optional[AbstractLMState] = None,
|
|
796
|
+
) -> List[OutputBeam]:
|
|
797
|
+
"""Convert input token logit matrix to decoded beams including meta information.
|
|
798
|
+
|
|
799
|
+
Args:
|
|
800
|
+
logits: logit matrix of token log probabilities
|
|
801
|
+
beam_width: maximum number of beams at each step in decoding
|
|
802
|
+
beam_prune_logp: beams that are much worse than best beam will be pruned
|
|
803
|
+
token_min_logp: tokens below this logp are skipped unless they are argmax of frame
|
|
804
|
+
prune_history: prune beams based on shared recent history at the cost of beam diversity
|
|
805
|
+
hotwords: list of words with extra importance, can be OOV for LM
|
|
806
|
+
hotword_weight: weight factor for hotword importance
|
|
807
|
+
lm_start_state: language model start state for stateful predictions
|
|
808
|
+
|
|
809
|
+
Returns:
|
|
810
|
+
List of beams of type OutputBeam with various meta information
|
|
811
|
+
"""
|
|
812
|
+
self._check_logits_dimension(logits)
|
|
813
|
+
# prepare hotword input
|
|
814
|
+
hotword_scorer = HotwordScorer.build_scorer(hotwords, weight=hotword_weight)
|
|
815
|
+
# make sure we have log probs as input
|
|
816
|
+
logits = _to_log_probs(logits)
|
|
817
|
+
decoded_beams = self._decode_logits(
|
|
818
|
+
logits,
|
|
819
|
+
beam_width=beam_width,
|
|
820
|
+
beam_prune_logp=beam_prune_logp,
|
|
821
|
+
token_min_logp=token_min_logp,
|
|
822
|
+
prune_history=prune_history,
|
|
823
|
+
hotword_scorer=hotword_scorer,
|
|
824
|
+
lm_start_state=lm_start_state,
|
|
825
|
+
)
|
|
826
|
+
return decoded_beams
|
|
827
|
+
|
|
828
|
+
def _decode_beams_mp_safe(
|
|
829
|
+
self,
|
|
830
|
+
logits: NDArray[NpFloat],
|
|
831
|
+
beam_width: int,
|
|
832
|
+
beam_prune_logp: float,
|
|
833
|
+
token_min_logp: float,
|
|
834
|
+
prune_history: bool,
|
|
835
|
+
hotwords: Optional[Iterable[str]],
|
|
836
|
+
hotword_weight: float,
|
|
837
|
+
) -> List[OutputBeam]:
|
|
838
|
+
"""Thing wrapper around self.decode_beams to allow for multiprocessing."""
|
|
839
|
+
decoded_beams = self.decode_beams(
|
|
840
|
+
logits=logits,
|
|
841
|
+
beam_width=beam_width,
|
|
842
|
+
beam_prune_logp=beam_prune_logp,
|
|
843
|
+
token_min_logp=token_min_logp,
|
|
844
|
+
prune_history=prune_history,
|
|
845
|
+
hotwords=hotwords,
|
|
846
|
+
hotword_weight=hotword_weight,
|
|
847
|
+
)
|
|
848
|
+
# remove state to allow multiprocessing
|
|
849
|
+
decoded_beams_mp_safe = [output_beam.get_mp_safe_beam() for output_beam in decoded_beams]
|
|
850
|
+
return decoded_beams_mp_safe
|
|
851
|
+
|
|
852
|
+
def decode_beams_batch(
|
|
853
|
+
self,
|
|
854
|
+
pool: Optional[Pool],
|
|
855
|
+
logits_list: NDArray[NpFloat],
|
|
856
|
+
beam_width: int = DEFAULT_BEAM_WIDTH,
|
|
857
|
+
beam_prune_logp: float = DEFAULT_PRUNE_LOGP,
|
|
858
|
+
token_min_logp: float = DEFAULT_MIN_TOKEN_LOGP,
|
|
859
|
+
prune_history: bool = DEFAULT_PRUNE_BEAMS,
|
|
860
|
+
hotwords: Optional[Iterable[str]] = None,
|
|
861
|
+
hotword_weight: float = DEFAULT_HOTWORD_WEIGHT,
|
|
862
|
+
) -> List[List[OutputBeam]]:
|
|
863
|
+
"""Use multiprocessing pool to batch decode input logits.
|
|
864
|
+
|
|
865
|
+
Note that multiprocessing here does not work for a spawn context, so in that case
|
|
866
|
+
or with no pool, just runs a loop in a single process.
|
|
867
|
+
|
|
868
|
+
Args:
|
|
869
|
+
pool: multiprocessing pool for parallel execution
|
|
870
|
+
logits_list: list of logit matrices of token log probabilities
|
|
871
|
+
beam_width: maximum number of beams at each step in decoding
|
|
872
|
+
beam_prune_logp: beams that are much worse than best beam will be pruned
|
|
873
|
+
token_min_logp: tokens below this logp are skipped unless they are argmax of frame
|
|
874
|
+
prune_history: prune beams based on shared recent history at the cost of beam diversity
|
|
875
|
+
hotwords: list of words with extra importance, can be OOV for LM
|
|
876
|
+
hotword_weight: weight factor for hotword importance
|
|
877
|
+
|
|
878
|
+
Returns:
|
|
879
|
+
List of list of multiprocessing-safe OutputBeams with various meta information
|
|
880
|
+
"""
|
|
881
|
+
valid_pool = _get_valid_pool(pool)
|
|
882
|
+
if valid_pool is None:
|
|
883
|
+
return [
|
|
884
|
+
self._decode_beams_mp_safe(
|
|
885
|
+
logits,
|
|
886
|
+
beam_width=beam_width,
|
|
887
|
+
beam_prune_logp=beam_prune_logp,
|
|
888
|
+
token_min_logp=token_min_logp,
|
|
889
|
+
hotwords=hotwords,
|
|
890
|
+
prune_history=prune_history,
|
|
891
|
+
hotword_weight=hotword_weight,
|
|
892
|
+
)
|
|
893
|
+
for logits in logits_list
|
|
894
|
+
]
|
|
895
|
+
|
|
896
|
+
for logits in logits_list:
|
|
897
|
+
self._check_logits_dimension(logits)
|
|
898
|
+
p_decode = functools.partial(
|
|
899
|
+
self._decode_beams_mp_safe,
|
|
900
|
+
beam_width=beam_width,
|
|
901
|
+
beam_prune_logp=beam_prune_logp,
|
|
902
|
+
token_min_logp=token_min_logp,
|
|
903
|
+
hotwords=hotwords,
|
|
904
|
+
prune_history=prune_history,
|
|
905
|
+
hotword_weight=hotword_weight,
|
|
906
|
+
)
|
|
907
|
+
decoded_beams_list: List[List[OutputBeam]] = valid_pool.map(p_decode, logits_list)
|
|
908
|
+
return decoded_beams_list
|
|
909
|
+
|
|
910
|
+
def decode(
|
|
911
|
+
self,
|
|
912
|
+
logits: NDArray[NpFloat],
|
|
913
|
+
beam_width: int = DEFAULT_BEAM_WIDTH,
|
|
914
|
+
beam_prune_logp: float = DEFAULT_PRUNE_LOGP,
|
|
915
|
+
token_min_logp: float = DEFAULT_MIN_TOKEN_LOGP,
|
|
916
|
+
hotwords: Optional[Iterable[str]] = None,
|
|
917
|
+
hotword_weight: float = DEFAULT_HOTWORD_WEIGHT,
|
|
918
|
+
lm_start_state: Optional[AbstractLMState] = None,
|
|
919
|
+
) -> str:
|
|
920
|
+
"""Convert input token logit matrix to decoded text.
|
|
921
|
+
|
|
922
|
+
Args:
|
|
923
|
+
logits: logit matrix of token log probabilities
|
|
924
|
+
beam_width: maximum number of beams at each step in decoding
|
|
925
|
+
beam_prune_logp: beams that are much worse than best beam will be pruned
|
|
926
|
+
token_min_logp: tokens below this logp are skipped unless they are argmax of frame
|
|
927
|
+
hotwords: list of words with extra importance, can be OOV for LM
|
|
928
|
+
hotword_weight: weight factor for hotword importance
|
|
929
|
+
lm_start_state: language model start state for stateful predictions
|
|
930
|
+
|
|
931
|
+
Returns:
|
|
932
|
+
The decoded text (str)
|
|
933
|
+
"""
|
|
934
|
+
decoded_beams = self.decode_beams(
|
|
935
|
+
logits,
|
|
936
|
+
beam_width=beam_width,
|
|
937
|
+
beam_prune_logp=beam_prune_logp,
|
|
938
|
+
token_min_logp=token_min_logp,
|
|
939
|
+
prune_history=True, # we can set this to True since we only care about top 1 beam
|
|
940
|
+
hotwords=hotwords,
|
|
941
|
+
hotword_weight=hotword_weight,
|
|
942
|
+
lm_start_state=lm_start_state,
|
|
943
|
+
)
|
|
944
|
+
return decoded_beams[0].text
|
|
945
|
+
|
|
946
|
+
def decode_batch(
|
|
947
|
+
self,
|
|
948
|
+
pool: Optional[Pool],
|
|
949
|
+
logits_list: NDArray[NpFloat],
|
|
950
|
+
beam_width: int = DEFAULT_BEAM_WIDTH,
|
|
951
|
+
beam_prune_logp: float = DEFAULT_PRUNE_LOGP,
|
|
952
|
+
token_min_logp: float = DEFAULT_MIN_TOKEN_LOGP,
|
|
953
|
+
hotwords: Optional[Iterable[str]] = None,
|
|
954
|
+
hotword_weight: float = DEFAULT_HOTWORD_WEIGHT,
|
|
955
|
+
) -> List[str]:
|
|
956
|
+
"""Use multiprocessing pool to batch decode input logits.
|
|
957
|
+
|
|
958
|
+
Note that multiprocessing here does not work for a spawn context, so in that case
|
|
959
|
+
or with no pool, just runs a loop in a single process.
|
|
960
|
+
|
|
961
|
+
Args:
|
|
962
|
+
pool: multiprocessing pool for parallel execution
|
|
963
|
+
logits_list: list of logit matrices of token log probabilities
|
|
964
|
+
beam_width: maximum number of beams at each step in decoding
|
|
965
|
+
beam_prune_logp: beams that are much worse than best beam will be pruned
|
|
966
|
+
token_min_logp: tokens below this logp are skipped unless they are argmax of frame
|
|
967
|
+
hotwords: list of words with extra importance, can be OOV for LM
|
|
968
|
+
hotword_weight: weight factor for hotword importance
|
|
969
|
+
|
|
970
|
+
Returns:
|
|
971
|
+
The decoded texts (list of str)
|
|
972
|
+
"""
|
|
973
|
+
valid_pool = _get_valid_pool(pool)
|
|
974
|
+
if valid_pool is None:
|
|
975
|
+
return [
|
|
976
|
+
self.decode(
|
|
977
|
+
logits,
|
|
978
|
+
beam_width=beam_width,
|
|
979
|
+
beam_prune_logp=beam_prune_logp,
|
|
980
|
+
token_min_logp=token_min_logp,
|
|
981
|
+
hotwords=hotwords,
|
|
982
|
+
hotword_weight=hotword_weight,
|
|
983
|
+
)
|
|
984
|
+
for logits in logits_list
|
|
985
|
+
]
|
|
986
|
+
|
|
987
|
+
p_decode = functools.partial(
|
|
988
|
+
self.decode,
|
|
989
|
+
beam_width=beam_width,
|
|
990
|
+
beam_prune_logp=beam_prune_logp,
|
|
991
|
+
token_min_logp=token_min_logp,
|
|
992
|
+
hotwords=hotwords,
|
|
993
|
+
hotword_weight=hotword_weight,
|
|
994
|
+
)
|
|
995
|
+
decoded_text_list: List[str] = valid_pool.map(p_decode, logits_list)
|
|
996
|
+
return decoded_text_list
|
|
997
|
+
|
|
998
|
+
def save_to_dir(self, filepath: str) -> None:
|
|
999
|
+
"""Save a decoder to a directory."""
|
|
1000
|
+
alphabet_path = os.path.join(filepath, self._ALPHABET_SERIALIZED_FILENAME)
|
|
1001
|
+
with open(alphabet_path, "w") as fi:
|
|
1002
|
+
fi.write(self._alphabet.dumps())
|
|
1003
|
+
|
|
1004
|
+
lm = self._language_model
|
|
1005
|
+
if lm is None:
|
|
1006
|
+
logger.info("decoder has no language model.")
|
|
1007
|
+
else:
|
|
1008
|
+
lm_path = os.path.join(filepath, self._LANGUAGE_MODEL_SERIALIZED_DIRECTORY)
|
|
1009
|
+
os.makedirs(lm_path)
|
|
1010
|
+
logger.info("Saving language model to %s", lm_path)
|
|
1011
|
+
lm.save_to_dir(lm_path)
|
|
1012
|
+
|
|
1013
|
+
@staticmethod
|
|
1014
|
+
def parse_directory_contents(filepath: str) -> Dict[str, Union[str, None]]:
|
|
1015
|
+
"""Check contents of a directory for correct BeamSearchDecoderCTC files."""
|
|
1016
|
+
contents = os.listdir(filepath)
|
|
1017
|
+
# filter out hidden files
|
|
1018
|
+
contents = [c for c in contents if not c.startswith(".") and not c.startswith("__")]
|
|
1019
|
+
if BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME not in contents:
|
|
1020
|
+
raise ValueError(
|
|
1021
|
+
f"Could not find alphabet file "
|
|
1022
|
+
f"{BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME}. Found {contents}"
|
|
1023
|
+
)
|
|
1024
|
+
alphabet_filepath = os.path.join(
|
|
1025
|
+
filepath, BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME
|
|
1026
|
+
)
|
|
1027
|
+
contents.remove(BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME)
|
|
1028
|
+
# other files, such as the README.md of a Hugging Face Hub repository, are ignored
|
|
1029
|
+
lm_directory: Optional[str] = None
|
|
1030
|
+
if BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY in contents:
|
|
1031
|
+
lm_directory = os.path.join(
|
|
1032
|
+
filepath, BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY
|
|
1033
|
+
)
|
|
1034
|
+
return {"alphabet": alphabet_filepath, "language_model": lm_directory}
|
|
1035
|
+
|
|
1036
|
+
@classmethod
|
|
1037
|
+
def load_from_dir(
|
|
1038
|
+
cls, filepath: str, unigram_encoding: Optional[str] = None
|
|
1039
|
+
) -> "BeamSearchDecoderCTC":
|
|
1040
|
+
"""Load a decoder from a directory."""
|
|
1041
|
+
filenames = cls.parse_directory_contents(filepath)
|
|
1042
|
+
with open(filenames["alphabet"], "r") as fi: # type: ignore
|
|
1043
|
+
alphabet = Alphabet.loads(fi.read())
|
|
1044
|
+
if filenames["language_model"] is None:
|
|
1045
|
+
language_model = None
|
|
1046
|
+
else:
|
|
1047
|
+
language_model = LanguageModel.load_from_dir(
|
|
1048
|
+
filenames["language_model"], unigram_encoding=unigram_encoding
|
|
1049
|
+
)
|
|
1050
|
+
return cls(alphabet, language_model=language_model)
|
|
1051
|
+
|
|
1052
|
+
@classmethod
|
|
1053
|
+
def load_from_hf_hub( # type: ignore
|
|
1054
|
+
cls,
|
|
1055
|
+
model_id: str,
|
|
1056
|
+
cache_dir: Optional[str] = None,
|
|
1057
|
+
revision: Optional[str] = None,
|
|
1058
|
+
**kwargs: Any,
|
|
1059
|
+
) -> "BeamSearchDecoderCTC":
|
|
1060
|
+
"""Class method to load model from https://huggingface.co/ .
|
|
1061
|
+
|
|
1062
|
+
Args:
|
|
1063
|
+
model_id: string, the `model id` of a pretrained model hosted inside a model
|
|
1064
|
+
repo on https://huggingface.co/. Valid model ids can be namespaced under a user or
|
|
1065
|
+
organization name, like ``kensho/5gram-spanish-kenLM``. For more information, please
|
|
1066
|
+
take a look at https://huggingface.co/docs/hub/main.
|
|
1067
|
+
cache_dir: path to where the language model should be downloaded and cached.
|
|
1068
|
+
revision: git revision (branch, tag or commit hash) of the model repo to download;
|
|
1069
|
+
the latest version if None. Pin a commit hash to always load the same files.
|
|
1070
|
+
kwargs: passed to ``huggingface_hub.snapshot_download``
|
|
1071
|
+
|
|
1072
|
+
Returns:
|
|
1073
|
+
instance of BeamSearchDecoderCTC
|
|
1074
|
+
"""
|
|
1075
|
+
if sys.version_info >= (3, 8):
|
|
1076
|
+
from importlib.metadata import metadata
|
|
1077
|
+
else:
|
|
1078
|
+
from importlib_metadata import metadata
|
|
1079
|
+
|
|
1080
|
+
library_name = metadata("flashctc")["Name"]
|
|
1081
|
+
cache_dir = cache_dir or os.path.join(Path.home(), ".cache", library_name)
|
|
1082
|
+
|
|
1083
|
+
try:
|
|
1084
|
+
from huggingface_hub import snapshot_download # type: ignore
|
|
1085
|
+
except ImportError as err:
|
|
1086
|
+
raise ImportError(
|
|
1087
|
+
"You need to install huggingface_hub to use `load_from_hf_hub`. "
|
|
1088
|
+
"See https://pypi.org/project/huggingface-hub/ for installation."
|
|
1089
|
+
) from err
|
|
1090
|
+
|
|
1091
|
+
cached_directory = snapshot_download(
|
|
1092
|
+
model_id, cache_dir=cache_dir, revision=revision, **kwargs
|
|
1093
|
+
)
|
|
1094
|
+
|
|
1095
|
+
return cls.load_from_dir(cached_directory)
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
##########################################################################################
|
|
1099
|
+
# Main entry point and convenience function to create BeamSearchDecoderCTC object ########
|
|
1100
|
+
##########################################################################################
|
|
1101
|
+
|
|
1102
|
+
|
|
1103
|
+
def build_ctcdecoder(
|
|
1104
|
+
labels: List[str],
|
|
1105
|
+
kenlm_model_path: Optional[str] = None,
|
|
1106
|
+
unigrams: Optional[Collection[str]] = None,
|
|
1107
|
+
alpha: float = DEFAULT_ALPHA,
|
|
1108
|
+
beta: float = DEFAULT_BETA,
|
|
1109
|
+
unk_score_offset: float = DEFAULT_UNK_LOGP_OFFSET,
|
|
1110
|
+
lm_score_boundary: bool = DEFAULT_SCORE_LM_BOUNDARY,
|
|
1111
|
+
) -> BeamSearchDecoderCTC:
|
|
1112
|
+
"""Build a BeamSearchDecoderCTC instance with main functionality.
|
|
1113
|
+
|
|
1114
|
+
Args:
|
|
1115
|
+
labels: class containing the labels for input logit matrices
|
|
1116
|
+
kenlm_model_path: path to kenlm n-gram language model
|
|
1117
|
+
unigrams: list of known word unigrams
|
|
1118
|
+
alpha: weight for language model during shallow fusion
|
|
1119
|
+
beta: weight for length score adjustment of during scoring
|
|
1120
|
+
unk_score_offset: amount of log score offset for unknown tokens
|
|
1121
|
+
lm_score_boundary: whether to have kenlm respect boundaries when scoring
|
|
1122
|
+
|
|
1123
|
+
Returns:
|
|
1124
|
+
instance of BeamSearchDecoderCTC
|
|
1125
|
+
"""
|
|
1126
|
+
kenlm_model = None if kenlm_model_path is None else kenlm.Model(kenlm_model_path)
|
|
1127
|
+
if kenlm_model_path is not None and kenlm_model_path.endswith(".arpa"):
|
|
1128
|
+
logger.info("Using arpa instead of binary LM file, decoder instantiation might be slow.")
|
|
1129
|
+
if unigrams is None and kenlm_model_path is not None:
|
|
1130
|
+
if kenlm_model_path.endswith(".arpa"):
|
|
1131
|
+
unigrams = load_unigram_set_from_arpa(kenlm_model_path)
|
|
1132
|
+
else:
|
|
1133
|
+
logger.warning(
|
|
1134
|
+
"Unigrams not provided and cannot be automatically determined from LM file (only "
|
|
1135
|
+
"arpa format). Decoding accuracy might be reduced."
|
|
1136
|
+
)
|
|
1137
|
+
alphabet = Alphabet.build_alphabet(labels)
|
|
1138
|
+
if unigrams is not None:
|
|
1139
|
+
verify_alphabet_coverage(alphabet, unigrams)
|
|
1140
|
+
if kenlm_model is not None:
|
|
1141
|
+
language_model: Optional[AbstractLanguageModel] = LanguageModel(
|
|
1142
|
+
kenlm_model,
|
|
1143
|
+
unigrams,
|
|
1144
|
+
alpha=alpha,
|
|
1145
|
+
beta=beta,
|
|
1146
|
+
unk_score_offset=unk_score_offset,
|
|
1147
|
+
score_boundary=lm_score_boundary,
|
|
1148
|
+
)
|
|
1149
|
+
else:
|
|
1150
|
+
language_model = None
|
|
1151
|
+
return BeamSearchDecoderCTC(alphabet, language_model)
|