"""One command, one verdict: did this training run learn anything controllable? Four layers, in the order that actually matters: 1. optimisation health - did the loss go down without diverging 2. held-out decomposition - text CE vs image CE vs the unigram baseline; image-token accuracy split by position inside the 64-code grid 3. word-level sensitivity - swap ONE word in a held-out prompt and measure how much the predicted distribution over the first code moves (TV distance) 4. behaviour - greedy decode per attribute value, hue + code identity Why not plain val loss: the image codes are a stochastic draw, so a model that memorises drives held-out CE *up* while train CE goes down. Val loss here is a memorisation detector, not a quality score. Examples python train_report.py --ckpt out_car_e/ckpt.pt --data_dir ../data_mm_car_s \ --log /tmp/arme.log --template "a {c} car" """ import argparse import colorsys import itertools import os import re import numpy as np import torch import torch.nn.functional as F from model import GPT, BOS, IMAGE_OFFSET, IMAGE_VOCAB, IMG_S, TXT_S, TXT_E from tokenizers import Tokenizer COLOURS = ["red", "blue", "green", "yellow", "white", "black", "silver", "grey", "orange", "brown"] TEST = ["red", "blue", "green", "yellow"] CRE = re.compile(r"\b(" + "|".join(COLOURS) + r")\b", re.I) HUE_RANGE = {"red": (335, 25), "blue": (195, 265), "green": (75, 165), "yellow": (35, 70)} BUCKETS = [(0, 1), (1, 4), (4, 16), (16, 64)] IMG_LO, IMG_HI = IMAGE_OFFSET, IMAGE_OFFSET + IMAGE_VOCAB def rule(ch="=", n=62): print(ch * n) def hue_of(img): a = np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0 h, w, _ = a.shape flat = a[h // 4 : 3 * h // 4, w // 4 : 3 * w // 4].reshape(-1, 3) mx, mn = flat.max(1), flat.min(1) sat = np.where(mx > 1e-6, (mx - mn) / np.maximum(mx, 1e-6), 0.0) keep = sat > 0.35 if keep.sum() < 20: return float("nan") px = flat[keep][:4000] hs = [colorsys.rgb_to_hsv(float(r), float(g), float(b))[0] * 360 for r, g, b in px] return float(np.median(hs)) def in_hue(h, rng): if np.isnan(h): return False lo, hi = rng return (h >= lo or h <= hi) if lo > hi else (lo <= h <= hi) @torch.no_grad() def forward_stats(model, rows, device, unigram, bs=32): """CE split by modality, plus image-token accuracy by position.""" text_ce = img_ce = base_ce = 0.0 text_n = img_n = 0 acc = {b: [0, 0] for b in BUCKETS} for i in range(0, len(rows), bs): blk = torch.from_numpy(rows[i : i + bs].astype(np.int64)).to(device) logits = model(blk[:, :-1])["logits"] y = blk[:, 1:] lp = F.log_softmax(logits.float(), -1) tgt = lp.gather(-1, y.unsqueeze(-1)).squeeze(-1) m_txt = (y >= 0) & (y < 16000) m_img = (y >= IMG_LO) & (y < IMG_HI) text_ce += float(-tgt[m_txt].sum()) text_n += int(m_txt.sum()) img_ce += float(-tgt[m_img].sum()) img_n += int(m_img.sum()) base_ce += float(-np.log(unigram[y[m_img].cpu().numpy() - IMG_LO] + 1e-12).sum()) pred = logits.argmax(-1) for r in range(blk.shape[0]): pos = torch.nonzero(m_img[r]).flatten() if len(pos) < 64: continue ids = blk[r].tolist() if ids.index(IMG_S) < ids.index(TXT_S): continue for k, (lo, hi) in enumerate(BUCKETS): for j in range(lo, min(hi, 64)): p = pos[j] acc[BUCKETS[k]][0] += int(pred[r, p] == y[r, p]) acc[BUCKETS[k]][1] += 1 return dict(text_ce=text_ce / max(1, text_n), img_ce=img_ce / max(1, img_n), base_ce=base_ce / max(1, img_n), acc=acc) @torch.no_grad() def colour_swap_tv(model, rows, tok, device): caps = [] for r in rows: ids = [int(t) for t in r] if ids.index(IMG_S) < ids.index(TXT_S): continue text = tok.decode([t for t in ids[ids.index(TXT_S) + 1 : ids.index(TXT_E)] if 0 <= t < 16000]) if CRE.search(text): caps.append(text.strip()) if len(caps) < 4: return None tvs, agrees = [], [] for cap in caps[:60]: probs, tops = {}, {} for c in TEST: pids = [t for t in tok.encode(CRE.sub(c, cap, count=1)).ids if t < 16000] x = torch.tensor([[BOS, TXT_S, *pids, TXT_E, IMG_S]], device=device) p = F.softmax(model(x)["logits"][0, -1].float(), -1)[IMG_LO:IMG_HI].cpu().numpy() probs[c] = p tops[c] = int(p.argmax()) for a, b in itertools.combinations(TEST, 2): tvs.append(0.5 * np.abs(probs[a] - probs[b]).sum()) v = list(tops.values()) agrees.append(sum(1 for x in v if x == v[0]) / len(v)) return float(np.mean(tvs)), float(np.mean(agrees)), len(caps) def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--data_dir", default="../data_mm_car_q") ap.add_argument("--row_len", type=int, default=128) ap.add_argument("--log", default="") ap.add_argument("--template", default="a {c} car") ap.add_argument("--templates", default="", help="comma separated; lets the report catch attribute combinations, " 'e.g. "a {c} car,a {c} sedan,a {c} suv"') ap.add_argument("--no_images", action="store_true") args = ap.parse_args() rule() print(f"train report {os.path.basename(os.path.dirname(args.ckpt))}/{os.path.basename(args.ckpt)}") print(f"data {args.data_dir}") rule() device = "cuda" if torch.cuda.is_available() else "cpu" tok = Tokenizer.from_file(os.path.join(args.data_dir, "tokenizer.json")) ck = torch.load(args.ckpt, map_location=device, weights_only=False) model = GPT(ck["cfg"]).to(device) model.load_state_dict(ck["model"]) model.eval() c = ck["cfg"] print(f"[1] 模型 {model.num_params()/1e6:.2f}M 总参数 / " f"{model.num_params(non_embedding=True)/1e6:.2f}M 非嵌入") print(f" layers={c.n_layer} embd={c.n_embd} heads={c.n_head}/{c.n_kv_head} " f"streams={c.n_stream} mlp={c.mlp_hidden} ngram={c.ngram_vocab}x{c.ngram_dim} " f"mtp={c.use_mtp}") if args.log and os.path.exists(args.log): ev = [l for l in open(args.log, errors="ignore") if re.match(r"^eval\s+\d+:", l)] if ev: def nums(line): return [float(x) for x in re.findall(r"train ([\d.]+)\s+val ([\d.]+)", line)[0]] t0, v0 = nums(ev[0]) t1, v1 = nums(ev[-1]) print(f"\n[2] 训练曲线 {len(ev)} 次 eval,{ev[0].split(':')[0].split()[1]}→" f"{ev[-1].split(':')[0].split()[1]} 步") print(f" train {t0:.4f} -> {t1:.4f} val {v0:.4f} -> {v1:.4f} " f"Δval {v1-v0:+.2f}") raw = np.asarray(np.memmap(os.path.join(args.data_dir, "train.bin"), dtype=np.uint16, mode="r")) tr_rows = raw.reshape(-1, args.row_len) in_img = (tr_rows >= IMG_LO) & (tr_rows < IMG_HI) counts = np.bincount(tr_rows[in_img].astype(np.int64) - IMG_LO, minlength=IMAGE_VOCAB) + 1e-3 unigram = counts / counts.sum() # marginal code distribution of the training set val = np.asarray(np.memmap(os.path.join(args.data_dir, "val.bin"), dtype=np.uint16, mode="r")) va_rows = val.reshape(-1, args.row_len) st = forward_stats(model, va_rows, device, unigram) base_ce = st["base_ce"] print(f"\n[3] 留出集({len(va_rows)} 行)") print(f" 文本位置 CE {st['text_ce']:.3f} 图像位置 CE {st['img_ce']:.3f}" f" 一元分布基线 {base_ce:.3f}") accs = " ".join(f"{b[0]}-{b[1]-1}: {st['acc'][b][0]/max(1,st['acc'][b][1]):.3f}" for b in BUCKETS) print(f" 图像码 top-1(文本在前行): {accs}") tvres = colour_swap_tv(model, va_rows, tok, device) print(f"\n[4] 词级敏感度(只换颜色词,其余不动)") if tvres is None: print(" 留出集里没有带颜色词的 prompt,跳过") else: tv, agree, ncap = tvres print(f" TV(首个码) {tv:.3f} 换词后 argmax 不变 {agree:.2f} n={ncap}") hues = ident = None if not args.no_images: import generate as G G.IMG_SIDE, G.LATENT, G.N_IMG = 128, 8, 64 vq = G.load_vq("../ckpt/vq_ds16_t2i.pt", device) def decode_codes(codes): return G.codes_to_pil(vq, codes, device) tpls = [t.strip() for t in (args.templates.split(",") if args.templates else [args.template]) if t.strip()] print("") print(f"[5] 行为(贪心,{len(tpls)} 个模板)") hues, ident = [], [] hit = 0 cell = 0 for tpl in tpls: codes, hh = {}, {} for col in TEST: torch.manual_seed(0) pids = [t for t in tok.encode(tpl.format(c=col)).ids if t < 16000] x = torch.tensor([[BOS, TXT_S, *pids, TXT_E, IMG_S]], device=device) out = [] for _ in range(64): lg = model(x[:, -model.cfg.block_size :])["logits"][:, -1] mask = torch.full_like(lg, float("-inf")) mask[:, IMG_LO:IMG_HI] = lg[:, IMG_LO:IMG_HI] nxt = mask.argmax(-1, keepdim=True) out.append(int(nxt)) x = torch.cat([x, nxt], dim=1) codes[col] = out cd = torch.tensor([[i - IMG_LO for i in out]], device=device) hh[col] = hue_of(decode_codes(cd)) ident.append(float(np.mean([sum(1 for a, b in zip(codes[x], codes[y]) if a == b) / 64 for x, y in itertools.combinations(TEST, 2)]))) hits = sum(1 for k in TEST if in_hue(hh[k], HUE_RANGE[k])) hit += hits cell += len(TEST) hues.append(hh) print(" %-22s 色相 %s 命中 %d/%d 码一致率 %.3f" % (tpl, " ".join(f"{k}={v:.0f}" for k, v in hh.items()), hits, len(TEST), ident[-1])) print(f" 合计 色相命中 {hit}/{cell} 平均码一致率 {np.mean(ident):.3f}") rule() print("[6] 判定") verdicts = [] if st["text_ce"] < 2.0: verdicts.append(f"文本侧在留出集上可预测(CE {st['text_ce']:.2f})") else: verdicts.append(f"文本侧未收敛(CE {st['text_ce']:.2f})") if st["img_ce"] < base_ce - 0.5: verdicts.append(f"图像码比一元基线还自信 {base_ce-st['img_ce']:.2f} nat -> 记忆信号强") elif st["img_ce"] > base_ce + 0.5: verdicts.append(f"图像码比一元基线差 {st['img_ce']-base_ce:.2f} nat -> 过度自信、偏离边缘分布") else: verdicts.append("图像码接近一元基线 -> 基本只学了边缘分布") if tvres is None: verdicts.append("词级敏感度不可测(无属性词)") elif tvres[0] >= 0.6 and tvres[1] <= 0.5: verdicts.append(f"属性词已进入预测(TV {tvres[0]:.2f})") else: verdicts.append(f"属性词影响弱(TV {tvres[0]:.2f},argmax 不变 {tvres[1]:.2f})") if hues: verdicts.append(f"行为可控 {hit}/{cell}" + ("(可用)" if hit >= 0.75 * cell else "(不可用)")) for v in verdicts: print(" - " + v) if hues and tvres is not None: hit = sum(1 for hh in hues for k in TEST if in_hue(hh[k], HUE_RANGE[k])) memorised = st["img_ce"] > base_ce + 1.0 sensitive = tvres[0] >= 0.6 total = cell if hues else 4 if hit >= 0.75 * total and sensitive: tag = "可用:属性可控(跨模板都稳)" elif sensitive and hit < 0.75 * total: tag = "半通:属性进了预测,但整段生成跑偏" elif memorised: tag = "不可用:在背题,属性被忽略" else: tag = "不可用:只学到边缘分布" print(f" 综合 {tag}") rule() if __name__ == "__main__": main()