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 为早期诊断小工具,一并归档。
This commit is contained in:
1 parent
a16ac3dc45
commit
5d2d3a2fb5
16 files changed
+1254
No files matched your search
@@ -0,0 +1,17 @@
|
||||
import numpy as np, torch
|
||||
from model import GPT
|
||||
from train import get_batch_rows
|
||||
tr = np.memmap("../data_mm/train.bin", dtype=np.uint16, mode="r").reshape(-1,128)
|
||||
va = np.memmap("../data_mm/val.bin", dtype=np.uint16, mode="r").reshape(-1,128)
|
||||
for p in ["out_128/ckpt_iter1200.pt","out_128/ckpt_iter6000.pt"]:
|
||||
ck = torch.load(p, map_location="cuda", weights_only=False)
|
||||
m = GPT(ck["cfg"]).cuda(); m.load_state_dict(ck["model"]); m.eval()
|
||||
r={}
|
||||
with torch.no_grad():
|
||||
for name,d in (("train",tr),("val",va)):
|
||||
s=0.0
|
||||
for _ in range(25):
|
||||
x,y,_=get_batch_rows(d,128,64,"cuda",False)
|
||||
with torch.amp.autocast("cuda",dtype=torch.bfloat16): s+=m(x,y,None)["loss"].item()
|
||||
r[name]=s/25
|
||||
print("%s train %.4f val %.4f gap %+.4f" % (p.split("/")[-1], r["train"], r["val"], r["val"]-r["train"]))
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Measure whether colour instructions actually control generation.
|
||||
|
||||
For each colour prompt, sample N images and compute the hue of the most
|
||||
saturated pixels in the centre crop (where the subject usually sits). If the
|
||||
model learned colour from captions, the hue distributions must separate.
|
||||
"""
|
||||
import argparse
|
||||
import colorsys
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
|
||||
import generate as G
|
||||
from model import GPT
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
COLOURS = {
|
||||
"red": (340, 20),
|
||||
"blue": (200, 260),
|
||||
"green": (80, 160),
|
||||
"yellow": (40, 70),
|
||||
"white": None,
|
||||
"black": None,
|
||||
}
|
||||
|
||||
|
||||
def hue_stats(img: Image.Image):
|
||||
"""Return (mean hue of saturated pixels, saturation, value)."""
|
||||
a = np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0
|
||||
h, w, _ = a.shape
|
||||
c = a[h // 4 : 3 * h // 4, w // 4 : 3 * w // 4] # centre crop
|
||||
flat = c.reshape(-1, 3)
|
||||
mx = flat.max(1)
|
||||
mn = 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 None, float(sat.mean()), float(mx.mean())
|
||||
px = flat[keep]
|
||||
hues = []
|
||||
for r, g, b in px[:4000]:
|
||||
hh, _, _ = colorsys.rgb_to_hsv(float(r), float(g), float(b))
|
||||
hues.append(hh * 360.0)
|
||||
return float(np.median(hues)), float(sat.mean()), float(mx.mean())
|
||||
|
||||
|
||||
def in_range(h, rng):
|
||||
if rng is None:
|
||||
return None
|
||||
lo, hi = rng
|
||||
if lo > hi: # wraps around 0
|
||||
return h >= lo or h <= hi
|
||||
return lo <= h <= hi
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--ckpt", required=True)
|
||||
ap.add_argument("--tok", default="../data_mm_car/tokenizer.json")
|
||||
ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt")
|
||||
ap.add_argument("--template", default="a {c} car")
|
||||
ap.add_argument("--n", type=int, default=8)
|
||||
ap.add_argument("--temperature", type=float, default=1.0)
|
||||
ap.add_argument("--top_k", type=int, default=100)
|
||||
ap.add_argument("--out", default="../data_mm/colour_eval")
|
||||
ap.add_argument("--label", default="run")
|
||||
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()
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
|
||||
print(f"{'colour':>8} {'n':>3} {'hit':>5} {'med_hue':>8} {'sat':>6} {'val':>6}")
|
||||
summary = {}
|
||||
for cname, rng in COLOURS.items():
|
||||
prompt = args.template.format(c=cname)
|
||||
hits, hues, sats, vals = 0, [], [], []
|
||||
for i in range(args.n):
|
||||
torch.manual_seed(2000 + i)
|
||||
codes, _ = G.text_to_image(model, tok, prompt, device, args.temperature, args.top_k)
|
||||
im = G.codes_to_pil(vq, codes, device)
|
||||
im.save(os.path.join(args.out, f"{args.label}_{cname}_{i}.png"))
|
||||
h, s, v = hue_stats(im)
|
||||
if rng is None:
|
||||
# achromatic: judge by brightness instead of hue
|
||||
ok = (v > 0.6) if cname == "white" else (v < 0.35)
|
||||
hits += int(ok)
|
||||
hues.append(float("nan"))
|
||||
else:
|
||||
if h is not None:
|
||||
hits += int(in_range(h, rng))
|
||||
hues.append(h)
|
||||
sats.append(s)
|
||||
vals.append(v)
|
||||
med_hue = float(np.nanmedian(hues)) if hues else float("nan")
|
||||
summary[cname] = dict(hit=hits / args.n, hue=med_hue,
|
||||
sat=float(np.mean(sats)), val=float(np.mean(vals)))
|
||||
print(f"{cname:>8} {args.n:3d} {hits/args.n:5.2f} {med_hue:8.1f} "
|
||||
f"{np.mean(sats):6.2f} {np.mean(vals):6.2f}")
|
||||
|
||||
# separation score: how distinct are the hue medians across chromatic colours
|
||||
chroma = [v["hue"] for k, v in summary.items() if COLOURS[k] is not None]
|
||||
chroma = [h for h in chroma if not np.isnan(h)]
|
||||
if len(chroma) >= 2:
|
||||
print(f"\nhue spread across prompts: {max(chroma)-min(chroma):.1f} deg "
|
||||
f"(0 = no control, larger = colour instruction works)")
|
||||
acc = np.mean([v["hit"] for k, v in summary.items() if COLOURS[k] is not None])
|
||||
print(f"mean colour accuracy (chromatic prompts): {acc:.2f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import numpy as np, torch, glob, os
|
||||
from model import GPT
|
||||
from train import get_batch_rows
|
||||
tr = np.memmap("../data_mm/train.bin", dtype=np.uint16, mode="r").reshape(-1,128)
|
||||
va = np.memmap("../data_mm/val.bin", dtype=np.uint16, mode="r").reshape(-1,128)
|
||||
print("train rows %d val rows %d" % (tr.shape[0], va.shape[0]))
|
||||
print("%-22s %8s %8s %8s" % ("ckpt","train","val","gap"))
|
||||
for p in sorted(glob.glob("out_v2a/ckpt_iter*.pt"), key=lambda s: int(s.split("iter")[1].split(".")[0])):
|
||||
ck = torch.load(p, map_location="cuda", weights_only=False)
|
||||
m = GPT(ck["cfg"]).cuda(); m.load_state_dict(ck["model"]); m.eval()
|
||||
r={}
|
||||
with torch.no_grad():
|
||||
for name,d in (("train",tr),("val",va)):
|
||||
s=0.0
|
||||
for _ in range(20):
|
||||
x,y,_=get_batch_rows(d,128,64,"cuda",False)
|
||||
with torch.amp.autocast("cuda",dtype=torch.bfloat16): s+=m(x,y,None)["loss"].item()
|
||||
r[name]=s/20
|
||||
print("%-22s %8.4f %8.4f %+8.4f" % (os.path.basename(p), r["train"], r["val"], r["val"]-r["train"]))
|
||||
del m; torch.cuda.empty_cache()
|
||||
@@ -0,0 +1,42 @@
|
||||
import io, os, tarfile, numpy as np, torch
|
||||
from PIL import Image
|
||||
import generate as G
|
||||
from model import GPT
|
||||
from tokenizers import Tokenizer
|
||||
G.IMG_SIDE, G.LATENT, G.N_IMG = 128, 8, 64
|
||||
tok = Tokenizer.from_file("../data_mm/tokenizer.json")
|
||||
vq = G.load_vq("../ckpt/vq_ds16_t2i.pt", "cuda")
|
||||
def prep(im):
|
||||
im = im.convert("RGB").resize((128,128), Image.BICUBIC)
|
||||
return np.asarray(im, dtype=np.float32)/127.5-1.0
|
||||
real=[]
|
||||
tf = tarfile.open("../data_mm/shards/cc3m-0000.tar")
|
||||
for m in tf:
|
||||
if m.isfile() and m.name.endswith(".jpg"):
|
||||
real.append(prep(Image.open(io.BytesIO(tf.extractfile(m).read()))))
|
||||
if len(real)>=60: break
|
||||
x = torch.from_numpy(np.stack(real)).permute(0,3,1,2).cuda()
|
||||
with torch.no_grad(): rc = vq.encode(x)[2][2].view(-1,64).cpu().numpy()
|
||||
ck = torch.load("out_v2a/ckpt_iter5100.pt", map_location="cuda", weights_only=False)
|
||||
mt = GPT(ck["cfg"]).cuda(); mt.load_state_dict(ck["model"]); mt.eval()
|
||||
torch.manual_seed(0)
|
||||
with torch.device("cuda"): mr = GPT(ck["cfg"])
|
||||
mr.eval()
|
||||
gen={}
|
||||
for nm,mo in (("trained",mt),("random",mr)):
|
||||
out=[]
|
||||
for i in range(20):
|
||||
torch.manual_seed(500+i)
|
||||
c,_ = G.text_to_image(mo, tok, "a duck on a pond", "cuda", 0.9, 50)
|
||||
out.append(c.cpu().numpy())
|
||||
gen[nm]=np.stack(out)
|
||||
print("%-10s %10s %12s" % ("source","uniq/img","top10 overlap"))
|
||||
ref_hist = np.bincount(rc.ravel(), minlength=16384).astype(float); ref_hist/=ref_hist.sum()
|
||||
ref_top = set(np.argsort(-ref_hist)[:10])
|
||||
print("%-10s %10.1f %12s" % ("real", rc.reshape(len(rc),-1).shape[1] and np.mean([len(np.unique(r)) for r in rc]), "-"))
|
||||
for nm in ("trained","random"):
|
||||
g = gen[nm].reshape(-1,64)
|
||||
h = np.bincount(g.ravel(), minlength=16384).astype(float); h/=h.sum()
|
||||
top = set(np.argsort(-h)[:10])
|
||||
print("%-10s %10.1f %12d/10" % (nm, np.mean([len(np.unique(r)) for r in g]), len(top & ref_top)))
|
||||
print(" cosine vs real: %.3f" % (h@ref_hist/(np.linalg.norm(h)*np.linalg.norm(ref_hist)+1e-9)))
|
||||
@@ -0,0 +1,22 @@
|
||||
import numpy as np, torch, hashlib
|
||||
import generate as G
|
||||
from model import GPT
|
||||
from tokenizers import Tokenizer
|
||||
G.IMG_SIDE, G.LATENT, G.N_IMG = 128, 8, 64
|
||||
tok = Tokenizer.from_file("../data_mm_car/tokenizer.json")
|
||||
vq = G.load_vq("../ckpt/vq_ds16_t2i.pt", "cuda")
|
||||
ck = torch.load("out_car/ckpt.pt", map_location="cuda", weights_only=False)
|
||||
m = GPT(ck["cfg"]).cuda(); m.load_state_dict(ck["model"]); m.eval()
|
||||
for prompt in ["a car parked on a street", "a red car on the road"]:
|
||||
hs=set(); seqs=[]
|
||||
for i in range(8):
|
||||
torch.manual_seed(1000+i)
|
||||
c,_ = G.text_to_image(m, tok, prompt, "cuda", 1.0, 100)
|
||||
a = c.cpu().numpy()
|
||||
hs.add(hashlib.md5(a.tobytes()).hexdigest()[:8])
|
||||
seqs.append(a)
|
||||
print("%-30s unique %d/8" % (prompt, len(hs)))
|
||||
# token-level agreement between samples
|
||||
s = np.stack(seqs)
|
||||
agree = (s == s[0:1]).mean()
|
||||
print(" avg token agreement with sample0: %.1f%%" % (100*agree))
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Two-axis control probe: does the colour word move hue, does the body word move shape?
|
||||
|
||||
Colour axis: body fixed, 4 colour words -> hue + identical-code rate.
|
||||
Body axis: colour fixed, 6 body words -> identical-code rate (1.0 = ignored).
|
||||
"""
|
||||
import argparse
|
||||
import itertools
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
import generate as G
|
||||
from model import GPT
|
||||
from probe_ctrl import HUE_RANGE, hue_of, image_token_acc, in_hue, load_rows
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
COLOURS = ["red", "blue", "green", "yellow"]
|
||||
BODIES = ["sedan", "suv", "truck", "convertible", "sports"] # hatchback only 187 total
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--ckpt", required=True)
|
||||
ap.add_argument("--data_dir", default="../data_mm_car_t")
|
||||
ap.add_argument("--tok", default="../data_mm_car_t/tokenizer.json")
|
||||
ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt")
|
||||
ap.add_argument("--row_len", type=int, default=128)
|
||||
ap.add_argument("--n", type=int, default=4)
|
||||
ap.add_argument("--temperature", type=float, default=0.6)
|
||||
ap.add_argument("--top_k", type=int, default=20)
|
||||
ap.add_argument("--out", default="../data_mm/colour_eval")
|
||||
ap.add_argument("--label", default="armF")
|
||||
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")
|
||||
|
||||
tr = load_rows(os.path.join(args.data_dir, "train.bin"), args.row_len)
|
||||
va = load_rows(os.path.join(args.data_dir, "val.bin"), args.row_len)
|
||||
a_tr, _ = image_token_acc(model, tr, device)
|
||||
a_va, _ = image_token_acc(model, va, device, max_rows=10_000)
|
||||
print(f"image-token top-1 train {a_tr:.3f} val {a_va:.3f}")
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
|
||||
def gen(prompt, save):
|
||||
torch.manual_seed(0)
|
||||
cd, _ = G.text_to_image(model, tok, prompt, device, 1e-5, 1)
|
||||
if save:
|
||||
G.codes_to_pil(vq, cd, device).save(os.path.join(args.out, f"{args.label}_{save}.png"))
|
||||
return cd.cpu().tolist()
|
||||
|
||||
# ---- colour axis, body fixed ----
|
||||
# "car" is the bucket where the VLM caption named no body type; it has the
|
||||
# widest per-colour support (158-532 rows) so the colour axis is measured cleanly.
|
||||
body0 = "car"
|
||||
cc, ch = {}, {}
|
||||
for c in COLOURS:
|
||||
cc[c] = gen(f"a {c} {body0}", f"c_{c}")
|
||||
ch[c] = hue_of(G.codes_to_pil(vq, torch.tensor([cc[c]], device=device), device))
|
||||
idc = [sum(1 for x, y in zip(cc[a], cc[b]) if x == y) / 64
|
||||
for a, b in itertools.combinations(COLOURS, 2)]
|
||||
hs = [h for h in ch.values() if not np.isnan(h)]
|
||||
print(f"\ncolour axis (body={body0}) greedy hue: " + " ".join(f"{c}={ch[c]:.0f}" for c in COLOURS))
|
||||
print(f" hue spread {max(hs)-min(hs):.1f} deg hit "
|
||||
f"{sum(1 for c in COLOURS if in_hue(ch[c], HUE_RANGE[c]))}/{len(COLOURS)}"
|
||||
f" cross-colour code identity {np.mean(idc):.3f}")
|
||||
|
||||
# ---- body axis, colour fixed ----
|
||||
col0 = "white" # widest body coverage: sedan 73, suv 67, truck 40, conv 48, sports 47
|
||||
bb = {}
|
||||
for b in BODIES:
|
||||
bb[b] = gen(f"a {col0} {b}", f"b_{b}")
|
||||
idb = [sum(1 for x, y in zip(bb[a], bb[b]) if x == y) / 64
|
||||
for a, b in itertools.combinations(BODIES, 2)]
|
||||
print(f"body axis (colour={col0}) cross-body code identity {np.mean(idb):.3f}"
|
||||
f" (1.0 = body word ignored)")
|
||||
|
||||
# ---- stochastic colour, low temperature ----
|
||||
print(f"stochastic colour {args.temperature}/top{args.top_k}:")
|
||||
hits = 0
|
||||
for c in COLOURS:
|
||||
hs2 = []
|
||||
for i in range(args.n):
|
||||
torch.manual_seed(2000 + i)
|
||||
cd, _ = G.text_to_image(model, tok, f"a {c} {body0}", device, args.temperature, args.top_k)
|
||||
G.codes_to_pil(vq, cd, device).save(os.path.join(args.out, f"{args.label}_{c}_{i}.png"))
|
||||
hs2.append(hue_of(G.codes_to_pil(vq, cd, device)))
|
||||
mh = float(np.nanmedian(hs2))
|
||||
ok = in_hue(mh, HUE_RANGE[c])
|
||||
hits += int(ok)
|
||||
print(f" {c:>7} hue={mh:6.1f} {'HIT' if ok else ' '}")
|
||||
print(f" hit {hits}/{len(COLOURS)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,83 @@
|
||||
"""How much does training let ONE word change the prediction?
|
||||
|
||||
Take a held-out caption that mentions a colour, swap only that word for
|
||||
red/blue/green/yellow, and compare the model's distribution over the FIRST VQ
|
||||
code. Everything else in the prompt is identical, so any difference is the
|
||||
colour word's contribution and nothing else.
|
||||
|
||||
TV = 0.0 -> the word is ignored
|
||||
TV = 1.0 -> the word fully decides the first code
|
||||
"""
|
||||
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, BOS
|
||||
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)
|
||||
|
||||
|
||||
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("--n_caps", type=int, default=60)
|
||||
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)
|
||||
|
||||
caps = []
|
||||
for r in rows:
|
||||
ids = [int(t) for t in r]
|
||||
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]).strip()
|
||||
if CRE.search(text):
|
||||
caps.append(text)
|
||||
if len(caps) >= args.n_caps:
|
||||
break
|
||||
print(f"held-out captions with a colour word: {len(caps)}")
|
||||
|
||||
tvs, argmax_agree, mass_entropy = [], [], []
|
||||
for cap in caps:
|
||||
probs, tops = {}, {}
|
||||
for c in TEST:
|
||||
prompt = CRE.sub(c, cap, count=1)
|
||||
pids = [t for t in tok.encode(prompt).ids if t < 16000]
|
||||
x = torch.tensor([[BOS, TXT_S, *pids, TXT_E, IMG_S]], device=device)
|
||||
with torch.no_grad():
|
||||
logits = model(x)["logits"][0, -1]
|
||||
p = F.softmax(logits.float(), -1)[IMAGE_OFFSET : IMAGE_OFFSET + IMAGE_VOCAB]
|
||||
probs[c] = p.cpu().numpy()
|
||||
tops[c] = int(p.argmax())
|
||||
for a, b in itertools.combinations(TEST, 2):
|
||||
tvs.append(0.5 * np.abs(probs[a] - probs[b]).sum())
|
||||
vals = list(tops.values())
|
||||
argmax_agree.append(sum(1 for x in vals if x == vals[0]) / len(vals))
|
||||
mass_entropy.append(float(np.mean([-(p * np.log(p + 1e-12)).sum() for p in probs.values()])))
|
||||
|
||||
print(f" mean TV between colour swaps (first code): {np.mean(tvs):.3f} (0 = ignored)")
|
||||
print(f" fraction of swaps keeping the same argmax : {np.mean(argmax_agree):.2f}"
|
||||
f" (1.0 = greedy output identical, i.e. no control)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Cross-product probe: colour x body, greedy, all 20 cells.
|
||||
|
||||
If the two attributes compose, hue must depend on the COLOUR (row) and be roughly
|
||||
constant down a column, and the pixel structure must depend on the BODY (column).
|
||||
Outputs:
|
||||
- 4x5 hue matrix
|
||||
- mean hue spread within a body (across colours) vs within a colour (across bodies)
|
||||
- pairwise 32x32 pixel distance, split into same-body / same-colour / different-both
|
||||
"""
|
||||
import argparse
|
||||
import itertools
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
import generate as G
|
||||
from model import GPT
|
||||
from probe_ctrl import hue_of
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
COLOURS = ["red", "blue", "green", "yellow"]
|
||||
BODIES = ["sedan", "suv", "truck", "convertible", "sports"]
|
||||
|
||||
|
||||
def thumb(im, side=32):
|
||||
a = np.asarray(im.convert("RGB").resize((side, side)), dtype=np.float32) / 255.0
|
||||
return a.reshape(-1)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--ckpt", required=True)
|
||||
ap.add_argument("--tok", default="../data_mm_car_t/tokenizer.json")
|
||||
ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt")
|
||||
ap.add_argument("--out", default="../data_mm/colour_eval")
|
||||
ap.add_argument("--label", default="cross")
|
||||
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()
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
|
||||
hue, vec, imgs = {}, {}, {}
|
||||
for c in COLOURS:
|
||||
for b in BODIES:
|
||||
torch.manual_seed(0)
|
||||
cd, _ = G.text_to_image(model, tok, f"a {c} {b}", device, 1e-5, 1)
|
||||
im = G.codes_to_pil(vq, cd, device)
|
||||
imgs[(c, b)] = im
|
||||
im.save(os.path.join(args.out, f"{args.label}_{c}_{b}.png"))
|
||||
hue[(c, b)] = hue_of(im)
|
||||
vec[(c, b)] = thumb(im)
|
||||
|
||||
print("hue matrix (rows=colour, cols=body):")
|
||||
print(" " + "".join(f"{b[:9]:>10}" for b in BODIES))
|
||||
for c in COLOURS:
|
||||
print(f"{c:>7} " + "".join(f"{hue[(c,b)]:>10.0f}" for b in BODIES))
|
||||
|
||||
within_body = [np.nanmax([hue[(c, b)] for c in COLOURS]) - np.nanmin([hue[(c, b)] for c in COLOURS])
|
||||
for b in BODIES]
|
||||
within_col = [np.nanmax([hue[(c, b)] for b in BODIES]) - np.nanmin([hue[(c, b)] for b in BODIES])
|
||||
for c in COLOURS]
|
||||
print(f"\nmean hue spread within a body (across colours): {np.nanmean(within_body):5.1f} deg")
|
||||
print(f"mean hue spread within a colour (across bodies): {np.nanmean(within_col):5.1f} deg")
|
||||
print(" -> colour works if the first number is large and the second small")
|
||||
|
||||
keys = list(vec.keys())
|
||||
d = {(a, b): float(np.linalg.norm(vec[a] - vec[b])) for a, b in itertools.combinations(keys, 2)}
|
||||
same_body = [v for (x, y), v in d.items() if x[1] == y[1]]
|
||||
same_col = [v for (x, y), v in d.items() if x[0] == y[0] and x[1] != y[1]]
|
||||
diff = [v for (x, y), v in d.items() if x[0] != y[0] and x[1] != y[1]]
|
||||
print(f"\npixel distance same body {np.mean(same_body):.3f} same colour {np.mean(same_col):.3f}"
|
||||
f" different both {np.mean(diff):.3f}")
|
||||
print(" -> structure follows the body if same-body is the smallest")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,148 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Control probe for models trained on short shared prompts.
|
||||
|
||||
Same tests as probe_ctrl.py, but the prompt is the in-distribution template
|
||||
"a {colour} car" instead of a counterfactual rewrite of a long caption.
|
||||
"""
|
||||
import argparse
|
||||
import itertools
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
import generate as G
|
||||
from model import GPT
|
||||
from probe_ctrl import HUE_RANGE, hue_of, image_token_acc, in_hue, load_rows
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
COLOURS = ["red", "blue", "green", "yellow"]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--ckpt", required=True)
|
||||
ap.add_argument("--tok", default="../data_mm_car_s/tokenizer.json")
|
||||
ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt")
|
||||
ap.add_argument("--train_bin", default="../data_mm_car_s/train.bin")
|
||||
ap.add_argument("--val_bin", default="../data_mm_car_s/val.bin")
|
||||
ap.add_argument("--row_len", type=int, default=128)
|
||||
ap.add_argument("--n", type=int, default=6)
|
||||
ap.add_argument("--temperature", type=float, default=0.9)
|
||||
ap.add_argument("--top_k", type=int, default=50)
|
||||
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")
|
||||
|
||||
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}")
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
greedy, ghue = {}, {}
|
||||
for c in COLOURS:
|
||||
torch.manual_seed(0)
|
||||
cd, _ = G.text_to_image(model, tok, f"a {c} car", device, 1e-5, 1)
|
||||
greedy[c] = cd.cpu().tolist()
|
||||
im = G.codes_to_pil(vq, cd, device)
|
||||
im.save(os.path.join(args.out, f"{args.label}_greedy_{c}.png"))
|
||||
ghue[c] = hue_of(im)
|
||||
|
||||
print("greedy hue: " + " ".join(f"{c}={ghue[c]:.0f}" for c in COLOURS))
|
||||
gs = [h for h in ghue.values() if not np.isnan(h)]
|
||||
print(f"greedy hue spread: {max(gs)-min(gs):.1f} deg hit "
|
||||
f"{sum(1 for c in COLOURS if in_hue(ghue[c], HUE_RANGE[c]))}/{len(COLOURS)}")
|
||||
ident = [sum(1 for x, y in zip(greedy[a], greedy[b]) if x == y) / 64
|
||||
for a, b in itertools.combinations(COLOURS, 2)]
|
||||
print(f"greedy cross-colour identical codes: {np.mean(ident):.3f} (1.0 = ignored)")
|
||||
|
||||
print(f"stochastic {args.temperature}/top{args.top_k}:")
|
||||
shue, hits = {}, 0
|
||||
for c in COLOURS:
|
||||
hs = []
|
||||
for i in range(args.n):
|
||||
torch.manual_seed(2000 + i)
|
||||
cd, _ = G.text_to_image(model, tok, f"a {c} car", device, args.temperature, args.top_k)
|
||||
im = G.codes_to_pil(vq, cd, device)
|
||||
im.save(os.path.join(args.out, f"{args.label}_{c}_{i}.png"))
|
||||
hs.append(hue_of(im))
|
||||
mh = float(np.nanmedian(hs))
|
||||
shue[c] = mh
|
||||
ok = in_hue(mh, HUE_RANGE[c])
|
||||
hits += int(ok)
|
||||
print(f" {c:>7} hue={mh:6.1f} {'HIT' if ok else ' '}")
|
||||
ss = [h for h in shue.values() if not np.isnan(h)]
|
||||
print(f"stochastic hue spread: {max(ss)-min(ss):.1f} deg hit {hits}/{len(COLOURS)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import torch
|
||||
from model import GPT, MMConfig
|
||||
cfg = MMConfig()
|
||||
m = GPT(cfg).cuda()
|
||||
print("params total %.2fM non-emb %.2fM" % (m.num_params()/1e6, m.num_params(True)/1e6))
|
||||
x = torch.randint(0, cfg.vocab_size, (2, 64), device="cuda")
|
||||
y = torch.randint(0, cfg.vocab_size, (2, 64), device="cuda")
|
||||
out = m(x, y, y)
|
||||
print("logits", tuple(out["logits"].shape))
|
||||
print("loss %.4f mtp %.4f total %.4f" % (out["loss"].item(), out["loss_mtp"].item(), out["loss_total"].item()))
|
||||
out["loss_total"].backward()
|
||||
gn = sum((p.grad.norm()**2).item() for p in m.parameters() if p.grad is not None)**0.5
|
||||
print("grad norm %.4f" % gn)
|
||||
print("mem %.2f GB" % (torch.cuda.max_memory_allocated()/1e9))
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import numpy as np, torch, torch.nn.functional as F
|
||||
from model import GPT, TEXT_VOCAB, IMAGE_OFFSET, IMAGE_VOCAB
|
||||
from train import get_batch_rows
|
||||
raw = np.memmap("../data_mm/val.bin", dtype=np.uint16, mode="r").reshape(-1,320)
|
||||
for p in ["out_mm2/ckpt_iter2000.pt","out_mm2/ckpt_iter6000.pt"]:
|
||||
ck = torch.load(p, map_location="cuda", weights_only=False)
|
||||
m = GPT(ck["cfg"]).cuda(); m.load_state_dict(ck["model"]); m.eval()
|
||||
st = {"txt_n":0,"txt_l":0.0,"img_n":0,"img_l":0.0}
|
||||
with torch.no_grad():
|
||||
for _ in range(20):
|
||||
x,y,_ = get_batch_rows(raw, 320, 32, "cuda", False)
|
||||
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
|
||||
logits = m(x)["logits"].float()
|
||||
l = F.cross_entropy(logits.view(-1,logits.size(-1)), y.reshape(-1), ignore_index=-100, reduction="none")
|
||||
valid = (y.reshape(-1) != -100)
|
||||
tg = y.reshape(-1)
|
||||
is_img = valid & (tg >= IMAGE_OFFSET) & (tg < IMAGE_OFFSET+IMAGE_VOCAB)
|
||||
is_txt = valid & (tg < TEXT_VOCAB)
|
||||
st["img_n"] += is_img.sum().item(); st["img_l"] += l[is_img].sum().item()
|
||||
st["txt_n"] += is_txt.sum().item(); st["txt_l"] += l[is_txt].sum().item()
|
||||
print("%s text %.4f (ppl %.1f) image %.4f (ppl %.1f)" % (
|
||||
p.split("/")[-1], st["txt_l"]/st["txt_n"], np.exp(st["txt_l"]/st["txt_n"]),
|
||||
st["img_l"]/st["img_n"], np.exp(st["img_l"]/st["img_n"])))
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Is the 4-stream gated residual actually doing anything?
|
||||
|
||||
Each block computes ONE output y and adds it to every stream scaled by a scalar
|
||||
beta_i(t). The streams start identical. If they stay near-collinear after
|
||||
training, the mechanism is effectively a single residual stream with a fancy
|
||||
input mixer, and "N parallel streams" overstates it.
|
||||
|
||||
Reports, per layer: mean pairwise cosine similarity between streams, relative
|
||||
deviation from the stream mean, and the spread of the gate inputs.
|
||||
"""
|
||||
import argparse
|
||||
import itertools
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from model import GPT
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--ckpt", required=True)
|
||||
ap.add_argument("--data_dir", default="../data_mm_car_s")
|
||||
ap.add_argument("--row_len", type=int, default=128)
|
||||
ap.add_argument("--batch", type=int, default=16)
|
||||
args = ap.parse_args()
|
||||
|
||||
device = "cuda"
|
||||
tok = Tokenizer.from_file(os.path.join(args.data_dir, "tokenizer.json")) # noqa: F841
|
||||
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)[: args.batch]
|
||||
idx = torch.from_numpy(rows.astype(np.int64)).to(device)
|
||||
|
||||
cos = model.rope_cos[: idx.shape[1]].to(device)
|
||||
sin = model.rope_sin[: idx.shape[1]].to(device)
|
||||
x = model.tok_emb(idx)
|
||||
streams = x.unsqueeze(0).expand(model.cfg.n_stream, -1, -1, -1).contiguous()
|
||||
ngram = model.ngram_emb(model.ngram_ids(idx))
|
||||
|
||||
print(f"streams={model.cfg.n_stream} layers={model.cfg.n_layer}")
|
||||
print(f"{'layer':>5} {'pairwise cos':>13} {'rel dev':>9} {'alpha max':>10} {'beta spread':>12}")
|
||||
for i, (blk, pre, post) in enumerate(zip(model.blocks, model.pre_gate, model.post_gate)):
|
||||
h = streams.mean(0)
|
||||
alpha = F.softmax(pre(h), dim=-1)
|
||||
x_in = (alpha.permute(2, 0, 1).unsqueeze(-1) * streams).sum(0)
|
||||
y = blk(x_in, cos, sin, ngram)
|
||||
beta = 2.0 * torch.sigmoid(post(h))
|
||||
streams = streams + beta.permute(2, 0, 1).unsqueeze(-1) * y.unsqueeze(0)
|
||||
|
||||
flat = streams.reshape(streams.shape[0], -1)
|
||||
flat = F.normalize(flat, dim=-1)
|
||||
cosines = [float(flat[a] @ flat[b]) for a, b in itertools.combinations(range(len(flat)), 2)]
|
||||
dev = float((streams - streams.mean(0)).norm() / streams.mean(0).norm())
|
||||
print(f"{i:>5} {np.mean(cosines):>13.6f} {dev:>9.4f} "
|
||||
f"{float(alpha.max(-1).values.mean()):>10.3f} "
|
||||
f"{float(beta.std(dim=-1).mean()):>12.4f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,285 @@
|
||||
"""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()
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import sys, io, tarfile, numpy as np, torch
|
||||
from PIL import Image
|
||||
sys.path.insert(0,"../vendor/llamagen_vq")
|
||||
from vq_model import VQ_16
|
||||
m = VQ_16(); sd = torch.load("../ckpt/vq_ds16_t2i.pt", map_location="cpu", weights_only=False)
|
||||
if isinstance(sd,dict) and "model" in sd: sd = sd["model"]
|
||||
m.load_state_dict(sd, strict=False); m.eval().cuda()
|
||||
tf = tarfile.open("../data_mm/shards/cc3m-0000.tar")
|
||||
blobs=[tf.extractfile(x).read() for x in tf if x.isfile() and x.name.endswith(".jpg")][:6]
|
||||
for side in (256,128):
|
||||
arrs=[]
|
||||
for b in blobs:
|
||||
im=Image.open(io.BytesIO(b)).convert("RGB").resize((side,side), Image.BICUBIC)
|
||||
arrs.append(np.asarray(im,dtype=np.float32)/127.5-1.0)
|
||||
x=torch.from_numpy(np.stack(arrs)).permute(0,3,1,2).cuda()
|
||||
with torch.no_grad():
|
||||
q,_,info=m.encode(x); rec=m.decode(q).clamp(-1,1)
|
||||
mse=torch.mean((rec-x)**2).item()
|
||||
g=side//16
|
||||
print("side=%d grid=%dx%d tokens=%d MSE=%.5f PSNR=%.2f dB" % (side,g,g,g*g,mse,10*np.log10(4.0/mse)))
|
||||
a=((rec[0].float().cpu()+1)*127.5).clamp(0,255).byte().permute(1,2,0).numpy()
|
||||
Image.fromarray(a).save("../data_mm/vq_check/rec_%d.png" % side)
|
||||
Reference in new issue
Block a user