tiny-dictation-en / runtime /multiview_decode.py
Hansda's picture
Release Tiny Dictation English and complete benchmarks
531b9c5 verified
Raw History Blame Contribute Delete
3.64 kB
'Decode multiple playback rates with one encoder and exact CTC sequence scores.'
from functools import lru_cache
import numpy as np
import torch
from torch.nn import functional as F
from decoder import beam_candidates
def change_rate(waveform, rate):
if rate == 1 or not len(waveform):
return waveform
positions = np.arange(0, len(waveform), rate)
return np.interp(positions, np.arange(len(waveform)), waveform).astype(np.float32)
@lru_cache(maxsize=16)
def filter_response(kind, cutoff):
from scipy.signal import butter
return butter(4, cutoff, btype=kind, fs=16000, output="sos")
def view_specs(settings):
rates = settings["rates"]
filters = settings.get("filters", [None] * len(rates))
return tuple(zip(rates, filters, strict=True))
def transform_view(waveform, rate, band):
result = change_rate(waveform, rate)
if band is None or len(result) < 16:
return result
from scipy.signal import sosfiltfilt
return sosfiltfilt(filter_response(*band), result).astype(np.float32)
def ctc_likelihoods(logits, paths, blank):
scores = torch.from_numpy(logits).log_softmax(-1)
targets = torch.tensor([token for path in paths for token in path], dtype=torch.long)
input_lengths = torch.full((len(paths),), len(scores), dtype=torch.long)
target_lengths = torch.tensor([len(path) for path in paths], dtype=torch.long)
loss = F.ctc_loss(scores[:, None, :].expand(-1, len(paths), -1), targets, input_lengths,
target_lengths, blank=blank, reduction="none")
return (-loss).numpy()
def candidate_paths(model, views):
settings = model.multiview
paths = {}
for logits in views:
acoustic = torch.from_numpy(np.roll(logits, 1, axis=-1))
for candidate, _ in beam_candidates(acoustic, model.language, settings["beam"], settings["token_limit"]):
paths[candidate] = model.render_tokens(candidate)
return paths
def text_prior(model, path, text):
from train import normalize
sequence = [0, *(token + 1 for token in path)]
subword = sum(model.language[a][b] for a, b in zip(sequence, sequence[1:]))
if model.word_language is None:
return subword, 0.0
words = normalize(text).split()
settings = model.word_settings
return subword, settings["alpha"] * model.word_language.score(words) + settings["bonus"] * len(words)
def score_paths(model, views, paths, blank):
candidates = list(paths)
if not candidates:
return np.empty(0)
weights = np.asarray(model.multiview["weights"])
if weights.shape != (len(views),) or not np.isfinite(weights).all() or (weights < 0).any() or not weights.any():
raise ValueError("Each view needs a finite nonnegative weight and at least one must be positive")
active = weights > 0
likelihoods = np.stack([ctc_likelihoods(logits, candidates, blank)
for logits, use in zip(views, active, strict=True) if use])
valid = np.flatnonzero(np.isfinite(likelihoods).all(0))
result = np.full(len(candidates), -np.inf)
score = weights[active] @ likelihoods[:, valid]
for index, candidate in enumerate(valid):
path = candidates[candidate]
subword, word = text_prior(model, path, paths[path])
score[index] += subword
score[index] += word
result[valid] = score
return result
def rerank(model, views, blank):
paths = candidate_paths(model, views)
score = score_paths(model, views, paths, blank)
if not np.isfinite(score).any():
return model.decode_logits(views[0])
return list(paths.values())[score.argmax()]