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