File size: 3,414 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 | 'Small subword bigram and CTC prefix beam search.'
import math
import numpy as np
NEG_INF = -math.inf
BIGRAM_ORDER = 24
BIGRAM_SCALE = 8
ALPHA = 0.25
INSERTION_BONUS = 0.8
def index_dtype(vocabulary_size):
return np.dtype("u1" if vocabulary_size <= 257 else "<u2")
def read_bigram(blob, vocabulary_size, alpha=ALPHA, insertion_bonus=INSERTION_BONUS, order=BIGRAM_ORDER):
if not 0 < order < vocabulary_size:
raise ValueError("Bigram successor count must fit the vocabulary")
size = vocabulary_size - 1
front = size + vocabulary_size
dtype = index_dtype(vocabulary_size)
back = front + vocabulary_size * order * dtype.itemsize
backoff = np.frombuffer(blob[:size], dtype=np.int8)
bias = np.frombuffer(blob[size:front], dtype=np.int8)
indices = np.frombuffer(blob[front:back], dtype=dtype).reshape(vocabulary_size, order)
scores = np.frombuffer(blob[back:], dtype=np.int8).reshape(vocabulary_size, order)
table = np.empty((vocabulary_size, vocabulary_size), dtype=np.float32)
table[:, 0] = 0
table[:, 1:] = backoff.astype(np.float32) + bias[:, None]
np.put_along_axis(table, indices.astype(np.int32) + 1, scores, axis=1)
table *= alpha / BIGRAM_SCALE
table += insertion_bonus
return table.tolist()
def logadd(a, b):
if a < b:
a, b = b, a
return a if b == NEG_INF else a + math.log1p(math.exp(b - a))
def beam_candidates(logits, language, width=6, token_limit=5):
"""Return scored SentencePiece paths from framewise CTC logits."""
scores = logits.float().log_softmax(dim=-1).cpu()
top_scores, top_tokens = scores[:, 1:].topk(min(token_limit, scores.size(-1) - 1))
prefixes = {(): (0.0, NEG_INF)}
frames = zip((top_tokens + 1).tolist(), top_scores.tolist(), scores[:, 0].tolist())
for tokens, values, blank in frames:
floor = max(values[0], blank) - 10
options = [(token, value) for token, value in zip(tokens, values) if value > floor]
next_prefixes = {}
for prefix, (p_blank, p_token) in prefixes.items():
p_total = logadd(p_blank, p_token)
old_blank, old_token = next_prefixes.get(prefix, (NEG_INF, NEG_INF))
next_prefixes[prefix] = (logadd(old_blank, p_total + blank), old_token)
last = prefix[-1] if prefix else 0
for token, score in options:
extend = p_total
if token == last:
old_blank, old_token = next_prefixes[prefix]
next_prefixes[prefix] = (old_blank, logadd(old_token, p_token + score))
extend = p_blank
if extend == NEG_INF:
continue
extension = prefix + (token,)
old_blank, old_token = next_prefixes.get(extension, (NEG_INF, NEG_INF))
next_prefixes[extension] = (
old_blank, logadd(old_token, extend + score + language[last][token])
)
ranked = sorted(next_prefixes.items(), key=lambda item: logadd(*item[1]), reverse=True)
prefixes = dict(ranked[:width])
return [(tuple(token - 1 for token in prefix), logadd(*probability))
for prefix, probability in prefixes.items()]
def beam_tokens(logits, language, width=6):
"""Return the best SentencePiece path for one utterance."""
return list(beam_candidates(logits, language, width)[0][0])
|