File size: 1,946 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Accuracy metrics of the gates (pure python / torch): edit distance, CER, TVD against golden top-k packs, PCC."""

from __future__ import annotations

from typing import Dict, List, Sequence, Tuple


def edit_distance(a: Sequence, b: Sequence) -> int:
    if len(a) < len(b):
        a, b = b, a
    prev = list(range(len(b) + 1))
    for i, x in enumerate(a, 1):
        cur = [i] + [0] * len(b)
        for j, y in enumerate(b, 1):
            cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y))
        prev = cur
    return prev[-1]


def cer(hyp: str, ref: str) -> float:
    """Character error rate of hyp vs ref (edit distance / len(ref); 0 for two empty strings)."""
    if not ref:
        return 0.0 if not hyp else 1.0
    return edit_distance(hyp, ref) / len(ref)


def tvd_vs_pack(logits, pack: Dict, steps: int) -> Tuple[List[float], List[int]]:
    """Per-step TVD between softmax(logits[s]) (full, [n, V]) and a golden top-k pack (top_v, top_i, lse; the golden
    mass outside its top-k is spread nowhere: TVD counts it once), plus top-1 agreement."""
    import torch

    tv, t1 = [], []
    for s in range(steps):
        p = torch.softmax(logits[s].float(), -1)
        q = torch.zeros_like(p)
        q[pack["top_i"][s].long()] = torch.exp(pack["top_v"][s].float() - pack["lse"][s].float())
        tail = float(1.0 - q.sum())
        tv.append(0.5 * (float((p - q).abs().sum()) + tail))
        t1.append(int(int(torch.argmax(p)) == int(pack["top_i"][s, 0])))
    return tv, t1


def pcc(a, b) -> float:
    a, b = a.double().flatten(), b.double().flatten()
    a, b = a - a.mean(), b - b.mean()
    return float((a @ b) / (a.norm() * b.norm() + 1e-30))


def summarize(xs: Sequence[float]) -> Dict[str, float]:
    s = sorted(xs)
    if not s:
        return {"n": 0}
    return {"n": len(s), "mean": sum(s) / len(s), "p95": s[int(0.95 * (len(s) - 1))], "max": s[-1]}