核心教训: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 为早期诊断小工具,一并归档。
107 lines
4.2 KiB
Python
107 lines
4.2 KiB
Python
"""Where in the image sequence did training actually put information?
|
|
|
|
Teacher-forced accuracy on image tokens is dominated by autoregressive
|
|
continuation: after a few codes the model can copy the texture it just emitted.
|
|
So split it by position:
|
|
pos 0 - only the prompt is available; this measures prompt -> image transfer
|
|
pos 1-3 - first few codes
|
|
pos 4-15 - local grid structure
|
|
pos 16-63 - mostly texture continuation
|
|
|
|
Also computes the total-variation distance between the model's predicted
|
|
distribution over the FIRST image code, grouped by prompt colour. TV ~ 0 means
|
|
the colour word does not move the first code at all.
|
|
"""
|
|
import argparse
|
|
import itertools
|
|
import os
|
|
import re
|
|
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn.functional as F
|
|
|
|
from model import GPT, 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"]
|
|
CRE = re.compile(r"\b(" + "|".join(COLOURS) + r")\b", re.I)
|
|
BUCKETS = [(0, 1), (1, 4), (4, 16), (16, 64)]
|
|
|
|
|
|
@torch.no_grad()
|
|
def run(model, rows, tok, device, bs=32, max_rows=1500):
|
|
acc = {b: [0, 0] for b in BUCKETS}
|
|
first_by_colour = {}
|
|
rows = rows[:max_rows]
|
|
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:]
|
|
pred = logits.argmax(-1)
|
|
img_pos = (y >= IMAGE_OFFSET) & (y < IMAGE_OFFSET + IMAGE_VOCAB)
|
|
for r in range(blk.shape[0]):
|
|
pos = torch.nonzero(img_pos[r]).flatten()
|
|
if len(pos) < 64:
|
|
continue
|
|
# text-first rows only: otherwise pos 0 is a copy, not a prediction
|
|
ids = blk[r].tolist()
|
|
if ids.index(IMG_S) < ids.index(TXT_S):
|
|
continue
|
|
t0, t1 = ids.index(TXT_S), ids.index(TXT_E)
|
|
text = tok.decode([t for t in ids[t0 + 1 : t1] if 0 <= t < 16000])
|
|
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
|
|
m = CRE.search(text)
|
|
if m:
|
|
c = m.group(1).lower()
|
|
if c == "gray":
|
|
c = "grey"
|
|
p0 = pos[0]
|
|
pr = F.softmax(logits[r, p0].float(), -1)[IMAGE_OFFSET : IMAGE_OFFSET + IMAGE_VOCAB]
|
|
first_by_colour.setdefault(c, []).append(pr.cpu().numpy())
|
|
return acc, first_by_colour
|
|
|
|
|
|
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)
|
|
args = ap.parse_args()
|
|
|
|
device = "cuda"
|
|
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()
|
|
|
|
raw = np.asarray(np.memmap(os.path.join(args.data_dir, "val.bin"), dtype=np.uint16, mode="r"))
|
|
rows = raw.reshape(-1, args.row_len)
|
|
acc, fbc = run(model, rows, tok, device)
|
|
parts = []
|
|
for b in BUCKETS:
|
|
h, n = acc[b]
|
|
parts.append(f"{b[0]:>2}-{b[1]-1:<2} {h/max(1,n):.3f}")
|
|
print(" held-out image-token top-1 by position: " + " ".join(parts))
|
|
|
|
groups = {c: np.mean(v, 0) for c, v in fbc.items() if len(v) >= 8}
|
|
if len(groups) >= 2:
|
|
tvs = []
|
|
for a, b in itertools.combinations(groups, 2):
|
|
tvs.append(0.5 * np.abs(groups[a] - groups[b]).sum())
|
|
top = sorted(((c, float(g.max()), int(g.argmax())) for c, g in groups.items()),
|
|
key=lambda x: -x[1])[:4]
|
|
print(f" colour groups {sorted(groups)} mean TV(first code) {np.mean(tvs):.3f}"
|
|
f" (0 = colour word does not move the first code)")
|
|
else:
|
|
print(" not enough colour groups in held-out set", {c: len(v) for c, v in fbc.items()})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|