axis-numeric / axis_numeric /ctc_topk.py
serety95's picture
Update numeric space
f1ba785 verified
Raw History Blame Contribute Delete
1.36 kB
"""Top-k CTC frames from a logit matrix. Full softmax stays in numpy."""
from __future__ import annotations
import numpy as np
from .ctc_frames import CtcFrame, select_candidates
def frames_from_logits(logits: np.ndarray, vocabulary: str, top_k: int = 5) -> list[CtcFrame]:
blank = len(vocabulary)
shifted = logits - logits.max(axis=1, keepdims=True)
exp = np.exp(shifted)
probs = exp / exp.sum(axis=1, keepdims=True)
width = probs.shape[1]
take = min(width, top_k + 2)
frames: list[CtcFrame] = []
for row in probs:
ranked = _ranked(row, take)
selected = select_candidates(ranked, top_k, blank)
margin = _margin(row)
alternatives = tuple((vocabulary[index], prob) for index, prob in selected if index != blank)
frames.append(CtcFrame(tuple(selected), alternatives, margin))
return frames
def _ranked(row: np.ndarray, take: int) -> list[tuple[int, float]]:
if row.shape[0] == 1:
return [(0, float(row[0]))]
part = np.argpartition(row, -take)[-take:]
return sorted(((int(index), float(row[index])) for index in part), key=lambda item: (-item[1], item[0]))
def _margin(row: np.ndarray) -> float:
if row.shape[0] <= 1:
return 1.0
top2 = np.partition(row, -2)[-2:]
return float(top2.max() - top2.min())