"""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()