File size: 7,280 Bytes
cf8c8d4 | 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 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | """Read a training run's telemetry and show trends, per-language / per-source breakdowns and alerts.
Reads <run>/metrics.jsonl (per sample, from common.vlm_sft), steps.jsonl (optimizer steps: grad norm, lr),
probes.jsonl (held-out pages read with generation during training) and data_report.json.
python -m common.train_monitor data/runs/x/adapter # tables + alerts
python -m common.train_monitor data/runs/x/adapter --plot # also curves.png (needs matplotlib)
Alerts (each one is a real signal, not a guess):
forgetting share of tokens the start model got right that the model now gets wrong ('broken') > 2%,
or 3x its first-window value
drift KL to the start model rising for 3 windows in a row, or above 0.05
collapse prediction entropy down by more than half from the first window
instability a gradient norm above 5x the median
probe a held-out page read worse than at step 0 (CER +0.01), a loop, or the token limit hit
"""
import argparse
import json
import statistics as st
from collections import defaultdict
from pathlib import Path
def read(p):
p = Path(p)
return [json.loads(l) for l in open(p, encoding="utf-8") if l.strip()] if p.exists() else []
def mean(rows, k):
v = [r[k] for r in rows if isinstance(r.get(k), (int, float))]
return sum(v) / len(v) if v else float("nan")
COLS = [("loss", "{:.3f}"), ("ce", "{:.3f}"), ("kl", "{:.4f}"), ("acc", "{:.3f}"), ("ref_acc", "{:.3f}"),
("focus_share", "{:.1%}"), ("fixed", "{:.1%}"), ("broken", "{:.2%}"), ("entropy", "{:.3f}"), ("sec", "{:.2f}")]
def fmt(rows):
out = []
for k, f in COLS:
m = mean(rows, k)
out.append("-" if m != m else f.format(m))
return out
def table(title, groups):
print(f"\n== {title}")
print(f"{'':22s}" + "".join(f"{k:>13s}" for k, _ in COLS) + f"{'n':>6s}")
for name, rows in groups:
print(f"{name:22s}" + "".join(f"{v:>13s}" for v in fmt(rows)) + f"{len(rows):>6d}")
def windows(rows, n):
return [rows[i:i + n] for i in range(0, len(rows), n) if rows[i:i + n]]
def alerts(rows, steps, probes, win):
out = []
ws = windows(rows, win)
if len(ws) >= 2 and any("broken" in r for r in rows):
b0, b = mean(ws[0], "broken"), mean(ws[-1], "broken")
if b > 0.02 or (b0 > 0 and b > 3 * b0 and b > 0.005):
out.append(f"forgetting: broken {b:.2%} in the last window (first window {b0:.2%})")
kls = [mean(w, "kl") for w in ws]
if kls[-1] > 0.05 or (len(kls) >= 4 and kls[-4] < kls[-3] < kls[-2] < kls[-1]):
out.append(f"drift: KL to the start model {kls[-1]:.4f} (trend {', '.join(f'{x:.4f}' for x in kls[-4:])})")
if len(ws) >= 2:
h0, h = mean(ws[0], "entropy"), mean(ws[-1], "entropy")
if h0 == h0 and h < 0.5 * h0:
out.append(f"collapse: prediction entropy {h:.3f} vs {h0:.3f} at the start")
g = [s["grad_norm"] for s in steps if isinstance(s.get("grad_norm"), (int, float))]
if len(g) >= 10:
med = st.median(g)
spikes = [s["step"] for s in steps if isinstance(s.get("grad_norm"), (int, float)) and s["grad_norm"] > 5 * med]
if spikes:
out.append(f"instability: gradient norm > 5x median ({med:.2f}) at steps {spikes[:10]}")
by = defaultdict(dict)
for p in probes:
by[p["id"]][p["step"]] = p
for pid, seq in by.items():
s0, last = min(seq), max(seq)
a, b = seq[s0], seq[last]
tag = b.get("tag") or pid[:24]
if b["cer"] > a["cer"] + 0.01:
out.append(f"probe {tag}: CER {a['cer']:.3f} -> {b['cer']:.3f} (step {s0} -> {last})")
if b.get("loop") or b.get("hit_limit"):
out.append(f"probe {tag}: loop / token limit at step {last}")
return out
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("run", help="the --output folder of common.vlm_sft")
ap.add_argument("--window", type=int, default=100, help="samples per row of the trend table")
ap.add_argument("--plot", action="store_true")
a = ap.parse_args(argv)
run = Path(a.run)
rows, steps, probes = read(run / "metrics.jsonl"), read(run / "steps.jsonl"), read(run / "probes.jsonl")
rep = run / "data_report.json"
if rep.exists():
print("== data\n" + rep.read_text(encoding="utf-8"))
if not rows:
print("no metrics yet")
return
table(f"trend ({a.window} samples per row)",
[(f"samples {i * a.window}-{i * a.window + len(w) - 1} s{w[-1]['step']}", w)
for i, w in enumerate(windows(rows, a.window))])
last = rows[-max(a.window, len(rows) // 5):]
table("by language (last window)", [(lg, [r for r in last if r.get("language") == lg])
for lg in sorted({r.get("language") for r in last})])
srcs = sorted({r.get("source") for r in last})
table("by source (last window)", [(str(s)[-22:], [r for r in last if r.get("source") == s]) for s in srcs])
lu = [(r["step"], r["lora_update_norm"]) for r in rows if "lora_update_norm" in r]
if lu:
print("\n== LoRA update norm |dW| by step: " + ", ".join(f"s{s}:{v:.4f}" for s, v in lu[-10:]))
if steps:
g = [s.get("grad_norm") for s in steps if isinstance(s.get("grad_norm"), (int, float))]
if g:
print(f"== gradient norm: median {st.median(g):.2f}, last {g[-1]:.2f}, max {max(g):.2f} "
f"over {len(g)} logged steps; lr now {steps[-1].get('learning_rate', '-')}")
if probes:
by = defaultdict(list)
for p in probes:
by[p["step"]].append(p)
ids = sorted({p["id"] for p in probes})
tags = {p["id"]: (p.get("tag") or p["id"][:14]) for p in probes}
print("\n== probes (held-out pages read with generation): CER per page")
print(f"{'step':>6s}" + "".join(f"{tags[i][:14]:>16s}" for i in ids) + f"{'mean':>9s}")
for s in sorted(by):
cer = {p["id"]: p for p in by[s]}
cells = "".join(f"{(str(round(cer[i]['cer'], 3)) + ('L' if cer[i]['loop'] or cer[i]['hit_limit'] else '')) if i in cer else '-':>16s}"
for i in ids)
print(f"{s:>6d}" + cells + f"{mean(by[s], 'cer'):>9.4f}")
al = alerts(rows, steps, probes, a.window)
print("\n== alerts: " + ("none" if not al else "\n - " + "\n - ".join(al)))
if a.plot:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
ws = windows(rows, max(10, a.window // 4))
x = [w[-1]["sample"] for w in ws]
fig, ax = plt.subplots(2, 3, figsize=(15, 8))
for axis, k in zip(ax.flat, ["loss", "ce", "kl", "fixed", "broken", "acc"]):
axis.plot(x, [mean(w, k) for w in ws], label="model")
if k == "acc":
axis.plot(x, [mean(w, "ref_acc") for w in ws], label="start model")
axis.legend()
axis.set_title(k)
axis.set_xlabel("samples")
fig.tight_layout()
fig.savefig(run / "curves.png", dpi=110)
print(f"curves -> {run / 'curves.png'}")
if __name__ == "__main__":
main()
|