Automatic Speech Recognition
PyTorch
Safetensors
conformer
ctc
streaming
ghana
bfloat16
griot-edge / flashlight_decode.py
DeeNA95's picture
Add Flashlight decoding and optimized container presets with matched benchmarks
d1d837e verified
Raw History Blame Contribute Delete
5.8 kB
"""Experimental native CTC decoder using the bundled word KenLM and lexicon.
The lexicon constrains words, unlike pyctcdecode's open-vocabulary search.
Flashlight KenLM scores are base-10; acoustic scores use natural logarithms.
"""
from __future__ import annotations
import math
import threading
import time
from pathlib import Path
import numpy as np
class FlashlightDecoder:
def __init__(
self,
vocab,
model_path,
*,
alpha=0.5,
beta=1.0,
beam_width=25,
beam_threshold=10.0,
token_beam_size=None,
unigrams_path=None,
max_word_characters=128,
):
try:
from flashlight.lib.text.decoder import (
CriterionType,
LexiconDecoder,
LexiconDecoderOptions,
SmearingMode,
Trie,
)
from flashlight.lib.text.decoder.kenlm import KenLM
from flashlight.lib.text.dictionary import Dictionary
except ImportError as error:
raise RuntimeError(
"Flashlight decoding requires flashlight-text with KenLM support"
) from error
if beam_width < 1 or not math.isfinite(beam_threshold) or beam_threshold <= 0:
raise ValueError("Flashlight beam size and threshold must be positive")
self.labels = [None] * len(vocab)
for token, index in vocab.items():
self.labels[index] = token
if any(label is None for label in self.labels):
raise ValueError("Vocabulary IDs must be contiguous")
if token_beam_size is not None and not 1 <= token_beam_size <= len(vocab):
raise ValueError("Token beam size must be between 1 and vocabulary size")
self.blank = vocab["<blank>"]
self.silence = vocab[" "]
self.non_emitting = {vocab[t] for t in ["<pad>", "<unk>"] if t in vocab}
model_path = Path(model_path)
lexicon_path = (
Path(unigrams_path)
if unigrams_path
else model_path.with_suffix(".unigrams.txt")
)
alphabet = {t for t in vocab if len(t) == 1 and not t.isspace()}
supported_words = {
word
for word in lexicon_path.read_text().splitlines()
if word and set(word) <= alphabet
}
if max_word_characters < 1:
raise ValueError("Maximum lexicon word length must be positive")
# The release list contains giant concatenated entries (>65k chars).
# Native recursive trie insertion/smearing can exhaust the stack.
words = sorted(
word for word in supported_words if len(word) <= max_word_characters
)
excluded_long_words = len(supported_words) - len(words)
del supported_words
if not words:
raise ValueError("The bundled unigram list contains no supported words")
started = time.perf_counter()
dictionary = Dictionary()
dictionary.add_entry("<unk>")
for word in words:
dictionary.add_entry(word)
self.lm = KenLM(str(model_path), dictionary)
self.trie = Trie(len(vocab), self.silence)
initial = self.lm.start(False)
for word in words:
index = dictionary.get_index(word)
_, score = self.lm.score(initial, index)
self.trie.insert([vocab[t] for t in word], index, score)
self.trie.smear(SmearingMode.MAX)
self.options = LexiconDecoderOptions(
beam_width,
token_beam_size or len(vocab),
beam_threshold,
alpha * math.log(10),
beta,
-math.inf,
0.0,
True,
CriterionType.CTC,
)
self.decoder_class = LexiconDecoder
self.dictionary = dictionary
self.unknown = dictionary.get_index("<unk>")
self.local = threading.local()
self.metadata = {
"backend": "flashlight",
"lexicon_words": len(words),
"lexicon_build_seconds": time.perf_counter() - started,
"beam_width": beam_width,
"token_beam_size": token_beam_size or len(vocab),
"beam_threshold": beam_threshold,
"lm_weight": alpha * math.log(10),
"word_score": beta,
"open_vocabulary": False,
"max_word_characters": max_word_characters,
"excluded_long_words": excluded_long_words,
}
def decode(self, scores):
emissions = np.array(scores, dtype=np.float32, order="C", copy=True)
if emissions.ndim != 2 or emissions.shape[1] != len(self.labels):
raise ValueError("Expected [frames, vocabulary] scores")
if not np.isfinite(emissions).all():
raise ValueError("Scores must be finite")
if len(emissions) == 0:
return ""
for index in self.non_emitting:
emissions[:, index] = -1e9
if not hasattr(self.local, "decoder"):
self.local.decoder = self.decoder_class(
self.options,
self.trie,
self.lm,
self.silence,
self.blank,
self.unknown,
[],
False,
)
results = self.local.decoder.decode(emissions.ctypes.data, *emissions.shape)
if not results:
return ""
# Word completions can occur without an emitted space token. The
# native word sequence, rather than collapsed acoustic tokens, is the
# lexical decoder's transcript and defines its word boundaries.
return " ".join(
self.dictionary.get_entry(index) for index in results[0].words if index >= 0
)