Download code/tinyear/decode.py from sanjithrj/tiny-ear-asr: direct link, hf CLI and curl.
- Browser
- Download file 2.2 kB
-
https://huggingface.co/sanjithrj/tiny-ear-asr/resolve/main/code/tinyear/decode.py
- Command line
-
hf download hf://sanjithrj/tiny-ear-asr/code/tinyear/decode.py
-
curl -L -o decode.py https://huggingface.co/sanjithrj/tiny-ear-asr/resolve/main/code/tinyear/decode.py
2.2 kB
| """Greedy decoding. Token ids are sentencepiece id + 1 (0 = blank).""" | |
| import torch | |
| import torch.nn.functional as F | |
| from tinyear.model import DURATIONS | |
| def ctc_greedy(logits, lens): | |
| out = [] | |
| for ids, n in zip(logits.argmax(-1), lens): | |
| ids = torch.unique_consecutive(ids[:n]) | |
| out.append([i - 1 for i in ids.tolist() if i]) | |
| return out | |
| def _pred_step(model, y2, y1): | |
| """Predictor state from the previous two tokens (B,) -> (B, d); matches ASR.predict.""" | |
| e = model.pred_emb(torch.stack([y2, y1], 1)).transpose(1, 2) | |
| return F.relu(model.pred_conv(e))[:, :, 0] | |
| def tdt_greedy(model, enc, lens, max_symbols=5): | |
| """Batched TDT greedy (label-looping): every active utterance emits one (token, duration) per iteration and | |
| jumps ahead by the duration. Blank never stays put; at most max_symbols tokens per frame.""" | |
| B, T, _ = enc.shape | |
| dev = enc.device | |
| nd, durs = len(DURATIONS), torch.tensor(DURATIONS, device=dev) | |
| t = torch.zeros(B, dtype=torch.long, device=dev) | |
| y2 = y1 = torch.zeros(B, dtype=torch.long, device=dev) | |
| sym = torch.zeros(B, dtype=torch.long, device=dev) | |
| hyps = [[] for _ in range(B)] | |
| enc_j = model.j_enc(enc) | |
| pred_j = model.j_pred(_pred_step(model, y2, y1)) | |
| ar = torch.arange(B, device=dev) | |
| while True: | |
| active = t < lens | |
| if not active.any(): | |
| return hyps | |
| tt = t.clamp(max=T - 1) | |
| logits = model.j_out(F.relu(enc_j[ar, tt] + pred_j)) | |
| tok, dur = logits[:, :-nd].argmax(-1), durs[logits[:, -nd:].argmax(-1)] | |
| emit = active & (tok != 0) | |
| sym = torch.where(emit & (dur == 0), sym + 1, torch.zeros_like(sym)) | |
| dur = torch.where(~emit | (sym >= max_symbols), dur.clamp(min=1), dur) # never loop forever on a frame | |
| sym = torch.where(dur > 0, torch.zeros_like(sym), sym) | |
| for b in emit.nonzero()[:, 0].tolist(): | |
| hyps[b].append(tok[b].item() - 1) | |
| if emit.any(): | |
| y2, y1 = torch.where(emit, y1, y2), torch.where(emit, tok, y1) | |
| pred_j = torch.where(emit[:, None], model.j_pred(_pred_step(model, y2, y1)), pred_j) | |
| t = torch.where(active, t + dur, t) | |