File size: 5,965 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""CPU diagnosis of arm A4 (HTR-VT design) from its latest resume.pt: raw (non-EMA) and EMA greedy output, blank probability, logit scale
before and after the parameter-free output layer norm, CTC loss as a function of a logit temperature, and gradient norms by module.
20 training crops of the mix_v1 training manifests (fixed seed), evaluation transform (no augmentation, no masking). Reads only; changes nothing.
"""
import json
import sys

import numpy as np
import torch
import torch.nn.functional as F

from . import data as D
from .common import DATA, LD_CKPT, LD_OUT, load_json, save_json
from .models import _plain_ln, build_arm_for_inference

torch.set_num_threads(4)


def greedy(lp, l2c):
    best = lp.argmax(-1)
    out, prev = [], 0
    for k in best.tolist():
        if k != prev and k != 0:
            out.append(l2c.get(k, "?"))
        prev = k
    return "".join(out)


def ctc_mean(logits, targets, tl):
    lp = logits.float().log_softmax(-1).permute(1, 0, 2)
    T = lp.shape[0]
    il = torch.full((lp.shape[1],), T, dtype=torch.long)
    return float(F.ctc_loss(lp, targets, il, tl, blank=0, zero_infinity=True, reduction="mean"))


def main():
    from kraken.lib.codec import PytorchCodec
    codec = PytorchCodec(load_json(LD_OUT + "/codec_union.json")["c2l"])
    l2c = codec.l2c_single
    ck = torch.load(LD_CKPT + "/A4/resume.pt", map_location="cpu", weights_only=False)
    out = {"resume_step": ck["step"], "resume_samples_seen": ck["seen"], "n_classes": codec.max_label + 1}
    arm = build_arm_for_inference("A4", codec)
    st = ck["state"]
    arm.net.load_state_dict(st["net"])
    arm.ema.load_state_dict(st["ema"])
    arm.net.eval()
    arm.ema.eval()
    comps = D.load_components(D.load_mix(DATA + "/data/processed/r5/mix_v1.yaml"), "train")
    flat = D.FlatItems(comps)
    ds = D.LineDS(flat, D.SPECS["A4"], codec, train=True)   # train=True only so that targets are encoded; no augmentation (aug is created lazily and not used below)
    ds.aug = None
    ds._aug = lambda: None
    rng = np.random.default_rng(0)
    samples, gids = [], []
    for g in rng.permutation(len(flat)).tolist():
        try:
            samples.append(ds.get_one(g))
            gids.append(g)
        except Exception:
            continue
        if len(samples) == 20:
            break
    x = torch.stack([s["image"] for s in samples])
    tg = torch.cat([s["target"] for s in samples]).long()
    tl = torch.LongTensor([len(s["target"]) for s in samples])
    refs = [s["text"] for s in samples]
    kinds = [flat.items[g][2] for g in gids]
    out["kinds"] = {k: kinds.count(k) for k in set(kinds)}
    net = arm.net
    with torch.no_grad():
        for name, m in (("raw", arm.net), ("ema", arm.ema)):
            xx = _plain_ln(x)
            f = m.stem(xx)
            b, c = f.shape[:2]
            f = f.reshape(b, c, -1).permute(0, 2, 1) + m.pos_embed
            for blk in m.blocks:
                f = blk(f)
            pre = m.head(m.norm(f))                 # logits before the output layer norm
            post = _plain_ln(pre)                   # what the training loss sees
            res = {}
            for nm, lg in (("post_ln", post), ("pre_ln", pre)):
                pr = lg.softmax(-1)
                blank = pr[..., 0]
                nb = pr[..., 1:].max(-1).values
                hyps = [greedy(lg[i], l2c) for i in range(len(x))]
                res[nm] = {"mean_blank_prob": float(blank.mean()), "frac_frames_blank_argmax": float((lg.argmax(-1) == 0).float().mean()),
                           "mean_max_nonblank_prob": float(nb.mean()), "max_nonblank_prob_any_frame": float(nb.max()),
                           "logit_mean": float(lg.mean()), "logit_std": float(lg.std()), "logit_max": float(lg.max()), "logit_min": float(lg.min()),
                           "n_empty_outputs_of_20": sum(1 for h in hyps if h == ""), "ctc_loss_mean": ctc_mean(lg, tg, tl),
                           "example_outputs": [(refs[i][:30], hyps[i][:30]) for i in range(5)]}
            # temperature test on the post-LN logits: is the loss limited by the scale that the layer norm fixes?
            res["post_ln_times_s_ctc_loss"] = {str(s): ctc_mean(post * s, tg, tl) for s in (0.5, 1, 2, 4, 8, 16, 32, 64)}
            res["post_ln_times_s_mean_blank_prob"] = {str(s): float((post * s).softmax(-1)[..., 0].mean()) for s in (1, 4, 16, 64)}
            # uniform prediction for reference: loss of logits = 0
            res["uniform_logits_ctc_loss"] = ctc_mean(torch.zeros_like(post), tg, tl)
            out[name] = res
    # gradient norms of the CTC loss (post-LN, as trained) on 16 of the crops, raw model, train mode off for BN stability
    net.zero_grad()
    xs = x[:16]
    lg = net(xs, 0.0, 1, use_masking=False)
    lp = lg.float().log_softmax(-1).permute(1, 0, 2)
    il = torch.full((16,), lp.shape[0], dtype=torch.long)
    n_t = int(tl[:16].sum())
    loss = F.ctc_loss(lp, tg[:n_t], il, tl[:16], blank=0, zero_infinity=True, reduction="mean")
    loss.backward()
    gn = {}
    for nme, p in net.named_parameters():
        if p.grad is None:
            continue
        key = nme.split(".")[0] if not nme.startswith("blocks") else ".".join(nme.split(".")[:2])
        gn.setdefault(key, 0.0)
        gn[key] += float(p.grad.pow(2).sum())
    out["grad_norm_by_module"] = {k: v ** 0.5 for k, v in gn.items()}
    out["param_norm_by_module"] = {}
    for nme, p in net.named_parameters():
        key = nme.split(".")[0] if not nme.startswith("blocks") else ".".join(nme.split(".")[:2])
        out["param_norm_by_module"][key] = out["param_norm_by_module"].get(key, 0.0) + float(p.detach().pow(2).sum())
    out["param_norm_by_module"] = {k: v ** 0.5 for k, v in out["param_norm_by_module"].items()}
    out["ctc_loss_of_gradient_batch"] = float(loss)
    save_json(LD_OUT + "/diag_a4.json", out)
    print(json.dumps(out, indent=1, ensure_ascii=False))


if __name__ == "__main__":
    main()