Files
tiny-gpt/mm/probe_ctrl.py
T
liuhuajie 5d2d3a2fb5 feat(eval): 行为探针与统一训练报告
核心教训:loss 判断不了可控性,必须看行为。

- colour_eval: 色相统计(粗指标,会被场景带偏)
- probe_ctrl: 反事实换词,只改颜色词看 64 个 VQ 码变多少
- probe_simple / probe_body: 单轴 / 双轴贪心生成
- probe_cross: 颜色x车身 4x5 交叉积,唯一能照出“只会背格子”的工具
- probe_cf_tv: 词级 TV,测一个词进入预测的程度
- pos_eval: 图像码按位置分桶,区分 prompt 依赖与上下文续写
- stream_probe: 实测 4 路流耦合度(层 7-9 余弦 0.995+)
- train_report: 四层体检合成一条命令

chk/curve/split/distcheck/modecheck/vqres/smoke 为早期诊断小工具,一并归档。
2026-12-03 10:37:55 +08:00

149 lines
5.6 KiB
Python

"""Memorisation + counterfactual colour control, no eyeballing needed.
1) Memorisation: teacher-forced top-1 accuracy on IMAGE token positions,
on train rows vs held-out val rows.
2) Counterfactual control: take real training captions, swap ONLY the colour
adjective, greedy-decode the image, and see whether the output image moves.
A model that memorised "caption -> codes" will emit the same image for every
colour; a model that learned the attribute will move.
"""
import argparse
import colorsys
import itertools
import json
import os
import re
import numpy as np
import torch
import generate as G
from model import GPT, IMAGE_OFFSET, IMAGE_VOCAB
from tokenizers import Tokenizer
ALL_COLOURS = ["red", "blue", "green", "yellow", "white", "black", "silver", "grey", "gray", "orange", "brown"]
TEST_COLOURS = ["red", "blue", "green", "yellow"]
HUE_RANGE = {"red": (335, 25), "blue": (195, 265), "green": (75, 165), "yellow": (35, 70)}
COLOUR_RE = re.compile(r"\b(" + "|".join(ALL_COLOURS) + r")\b", re.I)
def load_rows(path, row_len):
raw = np.memmap(path, dtype=np.uint16, mode="r")
assert len(raw) % row_len == 0
return np.asarray(raw).reshape(-1, row_len)
@torch.no_grad()
def image_token_acc(model, rows, device, max_rows=200, bs=32):
model.eval()
tot = hit = 0
sel = rows[:max_rows]
for i in range(0, len(sel), bs):
blk = torch.from_numpy(sel[i : i + bs].astype(np.int64)).to(device)
x, y = blk[:, :-1], blk[:, 1:]
pred = model(x)["logits"].argmax(-1)
m = (y >= IMAGE_OFFSET) & (y < IMAGE_OFFSET + IMAGE_VOCAB)
hit += int((pred[m] == y[m]).sum())
tot += int(m.sum())
return hit / max(1, tot), tot
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)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", required=True)
ap.add_argument("--tok", default="../data_mm_car_q/tokenizer.json")
ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt")
ap.add_argument("--train_bin", default="../data_mm_car_q/train.bin")
ap.add_argument("--val_bin", default="../data_mm_car_q/val.bin")
ap.add_argument("--captions", default="../data_mm_car_q/captions.jsonl")
ap.add_argument("--row_len", type=int, default=128)
ap.add_argument("--n_caps", type=int, default=24)
ap.add_argument("--out", default="../data_mm/colour_eval")
ap.add_argument("--label", default="probe")
args = ap.parse_args()
device = "cuda"
G.IMG_SIDE, G.LATENT, G.N_IMG = 128, 8, 64
tok = Tokenizer.from_file(args.tok)
vq = G.load_vq(args.vq_ckpt, device)
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()
print(f"model: {model.num_params()/1e6:.2f}M total, "
f"{model.num_params(non_embedding=True)/1e6:.2f}M non-emb")
# ---------- 1. memorisation ----------
tr = load_rows(args.train_bin, args.row_len)
va = load_rows(args.val_bin, args.row_len)
a_tr, n_tr = image_token_acc(model, tr, device)
a_va, n_va = image_token_acc(model, va, device, max_rows=10_000)
print(f"image-token top-1 train {a_tr:.3f} (n={n_tr}) val {a_va:.3f} (n={n_va})"
f" gap {a_tr - a_va:+.3f}")
# ---------- 2. counterfactual colour control ----------
caps = []
with open(args.captions) as f:
for line in f:
try:
d = json.loads(line)
except Exception:
continue
text = d["new"]
if COLOUR_RE.search(text):
caps.append(text)
if len(caps) >= args.n_caps:
break
print(f"counterfactual captions: {len(caps)}")
os.makedirs(args.out, exist_ok=True)
ident, hue_hits, spreads = [], [], []
for ci, cap in enumerate(caps):
codes, hues = {}, {}
for c in TEST_COLOURS:
prompt = COLOUR_RE.sub(c, cap, count=1)
torch.manual_seed(0)
cd, _ = G.text_to_image(model, tok, prompt, device, 1e-5, 1)
codes[c] = cd.cpu().tolist()
im = G.codes_to_pil(vq, cd, device)
if ci < 6:
im.save(os.path.join(args.out, f"{args.label}_cf{ci}_{c}.png"))
hues[c] = hue_of(im)
for a, b in itertools.combinations(TEST_COLOURS, 2):
ident.append(sum(1 for x, y in zip(codes[a], codes[b]) if x == y) / len(codes[a]))
hs = [h for h in hues.values() if not np.isnan(h)]
if len(hs) >= 2:
spreads.append(max(hs) - min(hs))
hue_hits.append(sum(1 for c, h in hues.items() if in_hue(h, HUE_RANGE[c])) / len(TEST_COLOURS))
print(f"\ncounterfactual (same caption, colour word swapped):")
print(f" identical VQ codes across colours : {np.mean(ident):.3f} (1.0 = word ignored)")
print(f" cue-consistent hue hit rate : {np.mean(hue_hits):.3f} (0.25 = chance)")
print(f" mean hue spread within caption : {np.mean(spreads) if spreads else float('nan'):.1f} deg")
if __name__ == "__main__":
main()