turkic-ocr-code / src /linedet /diag_a4_grad.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
3.26 kB
"""A4 diagnosis, part 3: gradient norms per module of the CTC loss on 16 training crops for (a) the current raw weights and (b) a freshly initialised
A4, each with the logits after the parameter-free output layer norm (as trained) and before it (the same weights, loss on the plain logits).
Shows whether the output layer norm starves the body of gradient. CPU only, no change to any run."""
import json
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 HTRVT, _plain_ln, build_arm_for_inference
torch.set_num_threads(4)
def grads(net, x, tg, tl, with_ln):
net.zero_grad()
xx = _plain_ln(x)
f = net.stem(xx)
b, c = f.shape[:2]
f = f.reshape(b, c, -1).permute(0, 2, 1) + net.pos_embed
for blk in net.blocks:
f = blk(f)
lg = net.head(net.norm(f))
if with_ln:
lg = _plain_ln(lg)
lp = lg.float().log_softmax(-1).permute(1, 0, 2)
il = torch.full((x.shape[0],), lp.shape[0], dtype=torch.long)
loss = F.ctc_loss(lp, tg, il, tl, 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[key] = gn.get(key, 0.0) + float(p.grad.pow(2).sum())
return float(loss), {k: v ** 0.5 for k, v in gn.items()}
def main():
from kraken.lib.codec import PytorchCodec
codec = PytorchCodec(load_json(LD_OUT + "/codec_union.json")["c2l"])
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)
samples = []
for g in rng.permutation(len(flat)).tolist():
try:
samples.append(ds.get_one(g))
except Exception:
continue
if len(samples) == 16:
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])
res = {}
ck = torch.load(LD_CKPT + "/A4/resume.pt", map_location="cpu", weights_only=False)
trained = build_arm_for_inference("A4", codec).net
trained.load_state_dict(ck["state"]["net"])
trained.eval()
torch.manual_seed(0)
fresh = build_arm_for_inference("A4", codec).net
fresh.eval()
for nm, net in (("trained_step_%d" % ck["step"], trained), ("fresh_init", fresh)):
for ln in (True, False):
loss, gn = grads(net, x, tg, tl, ln)
body = max(v for k, v in gn.items() if k.startswith("blocks") or k == "stem")
res["%s_%s" % (nm, "with_output_LN" if ln else "without_output_LN")] = {"ctc_loss": loss, "grad_norm": gn, "head_over_largest_body_grad": gn["head"] / body}
print(nm, "LN" if ln else "noLN", round(loss, 3), "head %.4g" % gn["head"], "largest body %.4g" % body, "ratio %.0f" % (gn["head"] / body), flush=True)
save_json(LD_OUT + "/diag_a4_grad.json", res)
if __name__ == "__main__":
main()