File size: 6,485 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
127
128
129
130
131
132
133
134
135
136
137
"""Result of the four A4 diagnostic variants (clarification H8): 1,000 iterations each at batch 128 from scratch on the frozen mix_v1 sequence.

Per variant: mean non-blank probability on 20 fixed training crops (the same crops as diag_a4.py; EMA weights of short.pt, and the raw weights of
resume.pt), V1 CER (greedy, from the variant's own prediction file), PASS if non-blank > 0.1 and V1 CER < 1.0. The passing variant with the lowest V1
CER is written to a4b_choice.json (read by the A4b tasks of the line block). Controls: A4 as specified at its P_short checkpoint and at the stop.
Training crops and V1 only (validation); no test set.
"""
import json
import os

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

from . import data as D
from . import models as M
from .common import DATA, LD_OUT, load_json, save_json, utcnow

torch.set_num_threads(4)
VARS = {"v1": {"no_output_ln": True, "desc": "no output layer norm"},
        "v2": {"stretch": True, "desc": "crops stretched to fill the 1,024 px canvas"},
        "v3": {"no_amp": True, "desc": "fp32 instead of bf16"},
        "v4": {"lr": 3e-4, "desc": "peak learning rate 3e-4"}}
A = LD_OUT + "/a4diag"
CK = DATA + "/checkpoints/r5/linedet_a4diag"


def crops(codec, stretch):
    D.SPECS["A4"].stretch = stretch
    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)
    ds._aug = lambda: None
    rng = np.random.default_rng(0)
    smp = []
    for g in rng.permutation(len(flat)).tolist():
        try:
            smp.append(ds.get_one(g))
        except Exception:
            continue
        if len(smp) == 20:
            break
    x = torch.stack([s["image"] for s in smp])
    tg = torch.cat([s["target"] for s in smp]).long()
    tl = torch.LongTensor([len(s["target"]) for s in smp])
    return x, tg, tl


def stats(net, x, tg, tl):
    with torch.no_grad():
        lg = net(x)
    pr = lg.softmax(-1)
    lp = lg.float().log_softmax(-1).permute(1, 0, 2)
    il = torch.full((x.shape[0],), lp.shape[0], dtype=torch.long)
    loss = float(F.ctc_loss(lp, tg, il, tl, blank=0, zero_infinity=True, reduction="mean"))
    return {"mean_nonblank_prob": float(1 - pr[..., 0].mean()), "max_nonblank_prob_any_frame": float(pr[..., 1:].max()), "ctc_loss_20_crops": loss,
            "frac_frames_nonblank_argmax": float((lg.argmax(-1) != 0).float().mean())}


def log_summary(path):
    ev = []
    for line in open(path):
        try:
            d = json.loads(line)
        except Exception:
            continue
        if d.get("event") == "step":
            ev.append(d)
    if not ev:
        return None
    k = max(1, len(ev) // 5)
    return {"logged_steps": len(ev), "last_step": ev[-1]["step"], "samples_seen": ev[-1]["samples_seen"], "loss_first_fifth_mean": float(np.mean([e["loss"] for e in ev[:k]])),
            "loss_last_fifth_mean": float(np.mean([e["loss"] for e in ev[-k:]])), "peak_lr_logged": max(e["lr"] for e in ev), "samples_per_s_mean": float(np.mean([e["samples_per_s"] for e in ev]))}


def v1_cer(label):
    p = "%s/preds/%s/short/meta.json" % (A, label)
    if not os.path.exists(p):
        return None
    m = load_json(p)
    return m["per_set"].get("V1", {}).get("cer")


def main():
    from kraken.lib.codec import PytorchCodec
    codec = PytorchCodec(load_json(LD_OUT + "/codec_union.json")["c2l"])
    res = {"created": utcnow(), "rule": "PASS if mean non-blank probability on the 20 fixed training crops > 0.1 and V1 CER < 1.0 (clarification H8)", "variants": {}}
    for v, o in VARS.items():
        d = {"setting": o}
        short = "%s/%s/A4/short.pt" % (CK, v)
        if not os.path.exists(short):
            d["missing"] = short
            res["variants"][v] = d
            continue
        ck = torch.load(short, map_location="cpu", weights_only=False)
        opts = ck.get("opts") or {}
        M.A4_OPTS["output_ln"] = opts.get("a4_output_ln", True)
        x, tg, tl = crops(codec, bool(opts.get("a4_stretch")))
        arm = M.build_arm_for_inference("A4", codec)
        arm.load_inference_state(ck["state"])
        arm.ema.eval()
        d["ema_short"] = stats(arm.ema, x, tg, tl)
        d["samples_seen"] = ck["samples_seen"]
        rp = "%s/%s/A4/resume.pt" % (CK, v)
        if os.path.exists(rp):
            rk = torch.load(rp, map_location="cpu", weights_only=False)
            arm.net.load_state_dict(rk["state"]["net"])
            arm.net.eval()
            d["raw_short"] = stats(arm.net, x, tg, tl)
        d["v1_cer_greedy"] = v1_cer("a4diag_" + v)
        d["train_log"] = log_summary("%s/logs/%s/A4.jsonl" % (A, v))
        d["pass"] = bool(d["ema_short"]["mean_nonblank_prob"] > 0.1 and d["v1_cer_greedy"] is not None and d["v1_cer_greedy"] < 1.0)
        res["variants"][v] = d
        M.A4_OPTS["output_ln"] = True
        D.SPECS["A4"].stretch = False
    # control: A4 as specified
    ctl = load_json(LD_OUT + "/diag_a4_curve.json") if os.path.exists(LD_OUT + "/diag_a4_curve.json") else []
    res["control_A4_as_specified"] = {"ema_20_crops": [{"checkpoint": r["checkpoint"], "samples_seen": r["samples_seen"], "mean_nonblank_prob": 1 - r["mean_blank_prob"], "ctc_loss": r["ema_ctc_loss_20_crops"]} for r in ctl],
                                      "v1_cer_at_p_short": (load_json(DATA + "/outputs/r5/preds/A4/short/meta.json")["per_set"].get("V1", {}).get("cer")
                                                            if os.path.exists(DATA + "/outputs/r5/preds/A4/short/meta.json") else None)}
    passing = [(d["v1_cer_greedy"], v) for v, d in res["variants"].items() if d.get("pass")]
    if passing:
        best = min(passing)[1]
        res["chosen_A4b"] = {"variant": best, "v1_cer_greedy": min(passing)[0], "setting": VARS[best]}
        o = VARS[best]
        save_json(LD_OUT + "/a4b_choice.json", {"variant": best, "no_output_ln": bool(o.get("no_output_ln")), "stretch": bool(o.get("stretch")), "lr": o.get("lr", 0),
                                                "no_amp": bool(o.get("no_amp")), "from": "a4_variants.py, clarification H8", "v1_cer_greedy": min(passing)[0]})
    else:
        res["chosen_A4b"] = None
        res["note"] = "no variant passed: A4 stays BROKEN RUN and no rerun is made (clarification H8, point 4)"
    save_json(A + "/variants.json", res)
    print(json.dumps(res, indent=1, ensure_ascii=False))


if __name__ == "__main__":
    main()