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.
@@ -0,0 +1,335 @@
1
+ # Copyright 2026-present Yehor Smoliakov. Licensed under the Apache License, Version 2.0.
2
+ """Experimental beam search backend built on flashlight-text.
3
+
4
+ Uses the C++ lexicon decoder of `flashlight-text <https://github.com/flashlight/text>`_ with a
5
+ KenLM word language model. Install it with ``pip install flashctc[flashlight]``.
6
+
7
+ This backend covers the common case of a KenLM word model with a word list, for character
8
+ alphabets and, given the SentencePiece model that defines the pieces, for BPE alphabets.
9
+ Compared to :class:`flashctc.BeamSearchDecoderCTC` it:
10
+
11
+ - decodes from the word list: an out-of-vocabulary word is spelled in parts, each scored as the
12
+ language model's unk word, and a word the language model knows but the list leaves out is
13
+ scored as unk too. A part that begins a known word also gets ``unk_score_offset``, at the
14
+ frame where it ends, while the beams that go on spelling the known word pay nothing yet, so
15
+ beam pruning drops it unless the offset is small or the beam wide. The defaults are therefore
16
+ ``unk_score_offset=-5`` and ``beam_prune_logp=-15`` rather than the Python decoder's -10 and -10.
17
+ On a BPE model (512 SentencePiece pieces, 8.7% of the words out of the list) they gave WER
18
+ 5.76% against the Python decoder's 5.72%, decoding 5.7x faster; its values gave 17.1%.
19
+ On LibriSpeech logits (characters, 200k words) they gave the same text as the Python decoder at
20
+ about its speed; -10 and -10 there decode 3-11x faster with nearly the same text,
21
+ - spells each word of the list in pieces the way the SentencePiece model does, so for BPE
22
+ alphabets it only follows that segmentation of a word,
23
+ - does not support hotwords, multiple language models or streaming (``decode_beams`` over the
24
+ whole utterance only),
25
+ - scores a word with the language model once it is complete, like the Python decoder; with
26
+ ``lm_lookahead=True`` a partial word is scored ahead with the best unigram score of the words
27
+ it starts (flashlight's trie smearing), which prunes more but can drop words that are unlikely
28
+ on their own and likely in context,
29
+ - applies ``token_min_logp`` like the Python decoder: tokens below it (except the best one of a
30
+ frame) are masked, and each frame tries only as many of its best tokens as the frame with the
31
+ most kept tokens has. ``beam_size_token`` additionally caps the number of tokens tried per frame.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import logging
37
+ from typing import Collection, List, Optional
38
+
39
+ import numpy as np
40
+ from numpy.typing import NDArray
41
+
42
+ from .alphabet import BPE_TOKEN, UNK_BPE_TOKEN, UNK_TOKEN, Alphabet
43
+ from .constants import (
44
+ DEFAULT_ALPHA,
45
+ DEFAULT_BEAM_WIDTH,
46
+ DEFAULT_BETA,
47
+ DEFAULT_MIN_TOKEN_LOGP,
48
+ LOG_BASE_CHANGE_FACTOR,
49
+ MIN_TOKEN_CLIP_P,
50
+ )
51
+ from .decoder import NpFloat, OutputBeam, WordFrames, _to_log_probs
52
+ from .language_model import load_unigram_set_from_arpa
53
+
54
+ try:
55
+ from flashlight.lib.text.decoder import ( # type: ignore
56
+ CriterionType,
57
+ LexiconDecoder,
58
+ LexiconDecoderOptions,
59
+ SmearingMode,
60
+ Trie,
61
+ )
62
+ from flashlight.lib.text.decoder.kenlm import KenLM # type: ignore
63
+ from flashlight.lib.text.dictionary import create_word_dict # type: ignore
64
+ except ImportError: # pragma: no cover
65
+ LexiconDecoder = None
66
+
67
+
68
+ logger = logging.getLogger(__name__)
69
+
70
+ UNK_WORD = "<unk>"
71
+ # defaults that differ from the Python decoder's (-10 and -10), see the module notes
72
+ FLASHLIGHT_UNK_LOGP_OFFSET = -5.0
73
+ FLASHLIGHT_PRUNE_LOGP = -15.0
74
+ _SPECIAL_WORDS = {"<s>", "</s>", UNK_WORD}
75
+
76
+
77
+ def _spell_words(
78
+ tokens: List[int], labels: List[str], blank_idx: int, sil_idx: Optional[int]
79
+ ) -> List[WordFrames]:
80
+ """Spell the words of a frame-aligned CTC token sequence, with their (start, end) frames.
81
+
82
+ Spelling from the tokens rather than the word ids also gives the text of out-of-vocabulary
83
+ words, which the decoder only reports as the unk word. With a space token (``sil_idx``) it
84
+ separates words; without one (BPE) a token starting with ``▁`` starts a new word.
85
+ """
86
+ words: List[WordFrames] = []
87
+ pieces: List[str] = []
88
+ start = end = 0
89
+ prev_token = blank_idx
90
+ for frame_idx, token in enumerate(tokens):
91
+ if token == sil_idx:
92
+ if pieces:
93
+ words.append(("".join(pieces), (start, end)))
94
+ pieces = []
95
+ elif token != blank_idx:
96
+ if token != prev_token:
97
+ piece = labels[token]
98
+ if sil_idx is None and piece.startswith(BPE_TOKEN):
99
+ if pieces:
100
+ words.append(("".join(pieces), (start, end)))
101
+ pieces = []
102
+ piece = piece.replace(BPE_TOKEN, "", 1)
103
+ if not pieces:
104
+ start = frame_idx
105
+ pieces.append(piece)
106
+ end = frame_idx + 1
107
+ prev_token = token
108
+ if pieces:
109
+ words.append(("".join(pieces), (start, end)))
110
+ return [(word, frames) for word, frames in words if word]
111
+
112
+
113
+ def _spell_with_sentencepiece(
114
+ words: List[str], tokenizer_model_path: str
115
+ ) -> List[Optional[List[str]]]:
116
+ """Split each word into pieces with a SentencePiece model."""
117
+ try:
118
+ import sentencepiece # type: ignore
119
+ except ImportError as err: # pragma: no cover
120
+ raise ImportError(
121
+ "BPE alphabets need sentencepiece: pip install flashctc[flashlight]"
122
+ ) from err
123
+ processor = sentencepiece.SentencePieceProcessor(model_file=tokenizer_model_path)
124
+ return processor.encode( # type: ignore[no-any-return]
125
+ words, out_type=str
126
+ )
127
+
128
+
129
+ class FlashlightBeamSearchDecoderCTC:
130
+ """CTC beam search decoder using the flashlight-text lexicon decoder and KenLM."""
131
+
132
+ def __init__(
133
+ self,
134
+ labels: List[str],
135
+ kenlm_model_path: str,
136
+ unigrams: Optional[Collection[str]] = None,
137
+ alpha: float = DEFAULT_ALPHA,
138
+ beta: float = DEFAULT_BETA,
139
+ unk_score_offset: float = FLASHLIGHT_UNK_LOGP_OFFSET,
140
+ beam_width: int = DEFAULT_BEAM_WIDTH,
141
+ beam_prune_logp: float = FLASHLIGHT_PRUNE_LOGP,
142
+ token_min_logp: Optional[float] = DEFAULT_MIN_TOKEN_LOGP,
143
+ beam_size_token: Optional[int] = None,
144
+ tokenizer_model_path: Optional[str] = None,
145
+ lm_lookahead: bool = False,
146
+ ) -> None:
147
+ """Build the decoder.
148
+
149
+ Args:
150
+ labels: class containing the labels for input logit matrices
151
+ kenlm_model_path: path to kenlm n-gram language model (arpa or binary)
152
+ unigrams: list of known word unigrams, read from the arpa file if not given
153
+ alpha: weight for language model during shallow fusion
154
+ beta: weight for length score adjustment of during scoring
155
+ unk_score_offset: score added when the decoder ends an out-of-vocabulary word part
156
+ on a node of a known word; it applies at once, so a low offset with a narrow beam
157
+ prunes out-of-vocabulary words (see the module notes)
158
+ beam_width: maximum number of beams kept at each step
159
+ beam_prune_logp: beams that are much worse than best beam will be pruned
160
+ token_min_logp: tokens below this logp are skipped unless they are argmax of frame;
161
+ None tries every token
162
+ beam_size_token: maximum number of tokens tried per frame, all if None
163
+ tokenizer_model_path: path to the SentencePiece model of a BPE alphabet, used to spell
164
+ the words of the list in pieces; required for BPE alphabets
165
+ lm_lookahead: score partial words with the best unigram score of the words they start
166
+ """
167
+ if LexiconDecoder is None:
168
+ raise ImportError(
169
+ "The flashlight backend needs flashlight-text: pip install flashctc[flashlight]"
170
+ )
171
+ alphabet = Alphabet.build_alphabet(labels)
172
+ self._is_bpe = alphabet.is_bpe
173
+ self._labels = alphabet.labels
174
+ self._blank_idx = self._labels.index("")
175
+ if self._is_bpe:
176
+ if tokenizer_model_path is None:
177
+ raise ValueError(
178
+ "BPE alphabets need the SentencePiece model: pass tokenizer_model_path."
179
+ )
180
+ # pieces carry the word boundaries, there is no space token
181
+ self._sil_idx: Optional[int] = None
182
+ elif " " not in self._labels:
183
+ raise ValueError("The flashlight backend needs a space token in the alphabet.")
184
+ else:
185
+ self._sil_idx = self._labels.index(" ")
186
+ token_idx = {char: idx for idx, char in enumerate(self._labels)}
187
+
188
+ if unigrams is None:
189
+ if not kenlm_model_path.endswith(".arpa"):
190
+ raise ValueError(
191
+ "Pass the unigrams with a binary KenLM model: the word list is only read "
192
+ "from .arpa files."
193
+ )
194
+ unigrams = load_unigram_set_from_arpa(kenlm_model_path)
195
+ candidates = sorted({word for word in unigrams if word and word not in _SPECIAL_WORDS})
196
+ if self._is_bpe:
197
+ assert tokenizer_model_path is not None # nosec # for mypy
198
+ piece_lists = _spell_with_sentencepiece(candidates, tokenizer_model_path)
199
+ else:
200
+ piece_lists = [list(word) for word in candidates]
201
+ # each spelling of a character alphabet ends on the space token, which completes the word;
202
+ # a BPE word is complete after its last piece
203
+ spellings = {}
204
+ for word, pieces in zip(candidates, piece_lists, strict=True):
205
+ if pieces and all(piece in token_idx for piece in pieces):
206
+ spelling = [token_idx[piece] for piece in pieces]
207
+ spellings[word] = spelling if self._is_bpe else [*spelling, token_idx[" "]]
208
+ # words the alphabet cannot spell can never be decoded
209
+ if len(spellings) < len(candidates):
210
+ logger.warning(
211
+ "Dropped %d unigrams that cannot be spelled with the alphabet.",
212
+ len(candidates) - len(spellings),
213
+ )
214
+ if not spellings:
215
+ raise ValueError("No unigram can be spelled with the alphabet.")
216
+ words = list(spellings)
217
+
218
+ self._word_dict = create_word_dict({word: [] for word in [*words, UNK_WORD]})
219
+ self._lm = KenLM(kenlm_model_path, self._word_dict)
220
+ unk_word_idx = self._word_dict.get_index(UNK_WORD)
221
+
222
+ # between words the decoder scores the frames with the silence token; BPE has none, and
223
+ # blank is what CTC emits there
224
+ decoder_sil_idx = self._blank_idx if self._sil_idx is None else self._sil_idx
225
+ trie = Trie(len(self._labels), decoder_sil_idx)
226
+ # lookahead scores are unigram scores: no context, not the start of a sentence
227
+ start_state = self._lm.start(True)
228
+ for word, spelling in spellings.items():
229
+ word_idx = self._word_dict.get_index(word)
230
+ score = self._lm.score(start_state, word_idx)[1] if lm_lookahead else 0.0
231
+ trie.insert(spelling, word_idx, score)
232
+ if self._is_bpe:
233
+ # the decoder returns to the root after a word, where it cannot repeat the last
234
+ # piece: this spelling lets a beam stay on the last piece over repeated frames
235
+ # and emit the word on the last of them
236
+ trie.insert(spelling + spelling[-1:], word_idx, score)
237
+ # out-of-vocabulary words: the decoder can emit the unk word at a node of the trie that
238
+ # ends no word, so it spells them in parts that start known words. Tokens that start no
239
+ # known word (BPE pieces that continue a word, rare characters) become one-token unk
240
+ # words, so that any token sequence can be decoded.
241
+ word_starts = {spelling[0] for spelling in spellings.values()}
242
+ skipped = {self._blank_idx, self._sil_idx, token_idx.get(UNK_TOKEN)}
243
+ skipped.add(token_idx.get(UNK_BPE_TOKEN))
244
+ for idx in range(len(self._labels)):
245
+ if idx not in word_starts and idx not in skipped:
246
+ trie.insert([idx], unk_word_idx, 0.0)
247
+ trie.smear(SmearingMode.MAX)
248
+ self._trie = trie
249
+
250
+ self._options = {
251
+ "beam_size": beam_width,
252
+ "beam_threshold": -beam_prune_logp,
253
+ # kenlm returns log10 probabilities, the Python decoder weights natural logs
254
+ "lm_weight": alpha * LOG_BASE_CHANGE_FACTOR,
255
+ "word_score": beta,
256
+ "unk_score": unk_score_offset,
257
+ "sil_score": 0.0,
258
+ "log_add": False,
259
+ "criterion_type": CriterionType.CTC,
260
+ }
261
+ self._beam_size_token = beam_size_token or len(self._labels)
262
+ self._token_min_logp = token_min_logp
263
+ self._decoder_args = (trie, self._lm, decoder_sil_idx, self._blank_idx, unk_word_idx)
264
+
265
+ def _get_decoder(self, beam_size_token: int) -> "LexiconDecoder":
266
+ """Build a decoder (cheap: it shares the trie and the language model)."""
267
+ options = LexiconDecoderOptions(beam_size_token=beam_size_token, **self._options)
268
+ return LexiconDecoder(options, *self._decoder_args, [], False)
269
+
270
+ def decode_beams(self, logits: NDArray[NpFloat]) -> List[OutputBeam]:
271
+ """Decode the logits of one utterance into beams, best first.
272
+
273
+ Args:
274
+ logits: logit matrix of token log probabilities, shape (frames, labels)
275
+
276
+ Returns:
277
+ list of beams of type OutputBeam with the text, word frames and scores
278
+ """
279
+ if logits.ndim != 2 or logits.shape[1] != len(self._labels):
280
+ raise ValueError(
281
+ f"Input logits shape is {logits.shape}, but vocabulary is size "
282
+ f"{len(self._labels)}. Need logits of shape: (time, vocabulary)"
283
+ )
284
+ log_probs = _to_log_probs(logits)
285
+ beam_size_token = self._beam_size_token
286
+ if self._token_min_logp is not None:
287
+ keep = (log_probs >= self._token_min_logp) | (
288
+ log_probs == log_probs.max(axis=1, keepdims=True)
289
+ )
290
+ log_probs = np.where(keep, log_probs, np.log(MIN_TOKEN_CLIP_P))
291
+ # the decoder tries the best tokens of each frame: no more than the most kept in one
292
+ beam_size_token = min(beam_size_token, int(keep.sum(axis=1).max(initial=1)))
293
+ if self._sil_idx is not None:
294
+ # the decoder only ends hypotheses on a word boundary, so close the last word with a
295
+ # final frame that is certainly the space token
296
+ end_frame = np.full((1, len(self._labels)), np.log(MIN_TOKEN_CLIP_P))
297
+ end_frame[0, self._sil_idx] = 0.0
298
+ log_probs = np.vstack([log_probs, end_frame])
299
+ emissions = np.ascontiguousarray(log_probs, dtype=np.float32)
300
+ n_frames, n_labels = emissions.shape
301
+ decoder = self._get_decoder(beam_size_token)
302
+ results = decoder.decode(emissions.ctypes.data, n_frames, n_labels)
303
+ output_beams = []
304
+ for result in results:
305
+ # tokens are aligned to the frames, with one padding token on each side
306
+ text_frames = _spell_words(
307
+ result.tokens[1:-1], self._labels, self._blank_idx, self._sil_idx
308
+ )
309
+ output_beams.append(
310
+ OutputBeam(
311
+ text=" ".join(word for word, _ in text_frames),
312
+ last_lm_state=None,
313
+ text_frames=text_frames,
314
+ logit_score=result.emittingModelScore,
315
+ lm_score=result.score,
316
+ )
317
+ )
318
+ return output_beams
319
+
320
+ def decode(self, logits: NDArray[NpFloat]) -> str:
321
+ """Decode the logits of one utterance into the best text."""
322
+ beams = self.decode_beams(logits)
323
+ return beams[0].text if beams else ""
324
+
325
+ def decode_batch(self, logits_list: List[NDArray[NpFloat]]) -> List[str]:
326
+ """Decode a list of utterances one after another."""
327
+ return [self.decode(logits) for logits in logits_list]
328
+
329
+
330
+ def flashlight_backend_available() -> bool:
331
+ """Whether flashlight-text with KenLM support is installed."""
332
+ return LexiconDecoder is not None
333
+
334
+
335
+ __all__ = ["FlashlightBeamSearchDecoderCTC", "flashlight_backend_available"]