File size: 3,640 Bytes
531b9c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'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()]