核心教训: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 为早期诊断小工具,一并归档。
121 lines
4.3 KiB
Python
121 lines
4.3 KiB
Python
"""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()
|