#!/usr/bin/env python3 """ Scaled Makebreak: 500 Images with Statistical Tests ===================================================== 3 key conditions: baseline, visual PCA (α=1.5), random (α=1.5) Statistical tests: McNemar, bootstrap CI, z-test for proportions Resume-safe with checkpoint every 25 images. Setup: !pip install -q transformers accelerate bitsandbytes torch torchvision \ scikit-learn scipy Pillow requests tqdm """ import os, json, gc, re, warnings from pathlib import Path from io import BytesIO from collections import defaultdict import numpy as np import requests import torch from PIL import Image from tqdm import tqdm from sklearn.decomposition import PCA from scipy import stats as sp warnings.filterwarnings("ignore") from google.colab import drive drive.mount("/content/drive", force_remount=False) OUT = Path("/content/drive/MyDrive/topohd_scaled_makebreak") OUT.mkdir(exist_ok=True, parents=True) print("=" * 65) print("Scaled Makebreak: 500 Images + Statistical Tests") print("=" * 65) # ---- COCO ---- ANNO_DIR = Path("/content/coco_anno") INST = ANNO_DIR / "annotations" / "instances_val2014.json" if not INST.exists(): import zipfile ANNO_DIR.mkdir(exist_ok=True, parents=True) zp = ANNO_DIR / "annotations.zip" if not zp.exists(): r = requests.get("http://images.cocodataset.org/annotations/" "annotations_trainval2014.zip", stream=True, timeout=60) r.raise_for_status() with open(zp, "wb") as f: for chunk in r.iter_content(8192): f.write(chunk) with zipfile.ZipFile(zp) as z: z.extractall(ANNO_DIR) with open(INST) as f: coco_data = json.load(f) cat_id2name = {c["id"]: c["name"] for c in coco_data["categories"]} img2cats = defaultdict(set) for a in coco_data["annotations"]: img2cats[a["image_id"]].add(cat_id2name[a["category_id"]]) img2file = {i["id"]: i["file_name"] for i in coco_data["images"]} SYNS={"person":["person","man","woman","boy","girl","child","people","men","women","lady","kid","children","guy","player","rider"],"bicycle":["bicycle","bike"],"car":["car","automobile","vehicle"],"motorcycle":["motorcycle","motorbike"],"airplane":["airplane","plane","aircraft","jet"],"bus":["bus"],"train":["train"],"truck":["truck"],"boat":["boat","ship","sailboat"],"traffic light":["traffic light","stoplight"],"fire hydrant":["fire hydrant","hydrant"],"stop sign":["stop sign"],"bench":["bench"],"bird":["bird"],"cat":["cat","kitten"],"dog":["dog","puppy"],"horse":["horse","pony"],"sheep":["sheep","lamb"],"cow":["cow","cattle","bull"],"elephant":["elephant"],"bear":["bear"],"zebra":["zebra"],"giraffe":["giraffe"],"backpack":["backpack","bag","rucksack"],"umbrella":["umbrella"],"handbag":["handbag","purse"],"tie":["tie","necktie"],"suitcase":["suitcase","luggage"],"frisbee":["frisbee"],"skis":["skis","ski"],"snowboard":["snowboard"],"sports ball":["ball","baseball","football","soccer ball","tennis ball","basketball"],"kite":["kite"],"baseball bat":["baseball bat","bat"],"baseball glove":["baseball glove","glove","mitt"],"skateboard":["skateboard"],"surfboard":["surfboard"],"tennis racket":["tennis racket","racket"],"bottle":["bottle"],"wine glass":["wine glass","glass","goblet"],"cup":["cup","mug"],"fork":["fork"],"knife":["knife"],"spoon":["spoon"],"bowl":["bowl"],"banana":["banana"],"apple":["apple"],"sandwich":["sandwich"],"orange":["orange"],"broccoli":["broccoli"],"carrot":["carrot"],"hot dog":["hot dog","hotdog"],"pizza":["pizza"],"donut":["donut","doughnut"],"cake":["cake"],"chair":["chair","seat"],"couch":["couch","sofa"],"potted plant":["potted plant","plant","flower","flowers"],"bed":["bed"],"dining table":["dining table","table","desk"],"toilet":["toilet"],"tv":["tv","television","monitor","screen"],"laptop":["laptop","computer"],"mouse":["mouse"],"remote":["remote"],"keyboard":["keyboard"],"cell phone":["cell phone","phone","cellphone","smartphone"],"microwave":["microwave"],"oven":["oven","stove"],"toaster":["toaster"],"sink":["sink"],"refrigerator":["refrigerator","fridge"],"book":["book","books"],"clock":["clock"],"vase":["vase"],"scissors":["scissors"],"teddy bear":["teddy bear","stuffed animal"],"hair drier":["hair drier","hair dryer"],"toothbrush":["toothbrush"]} S2C={} for c,ss in SYNS.items(): for s in ss: S2C[s.lower()]=c def chair_eval(cap, gt): cl = cap.lower(); mentioned = set() for s in sorted(S2C, key=len, reverse=True): if re.search(r'\b'+re.escape(s)+r'\b', cl): mentioned.add(S2C[s]) if not mentioned: return dict(halluc=0, chair_i=0.0, n_mentioned=0, n_halluc=0, n_correct=0) h = mentioned - gt; c = mentioned & gt return dict(halluc=1 if len(h)>0 else 0, chair_i=len(h)/len(mentioned), n_mentioned=len(mentioned), n_halluc=len(h), n_correct=len(c)) COCO_URL = "http://images.cocodataset.org/val2014/{}" cands = [i for i, c in img2cats.items() if len(c) >= 2] np.random.seed(42); np.random.shuffle(cands) _ic = {} def load_img(iid): if iid in _ic: return _ic[iid] r = requests.get(COCO_URL.format(img2file[iid]), timeout=15) r.raise_for_status() im = Image.open(BytesIO(r.content)).convert("RGB") if len(_ic) < 600: _ic[iid] = im return im # ================================================================ # Setup # ================================================================ N_CALIB = 200 N_EVAL = 500 K_SUB = 48 LAYER = 16 ALPHA = 1.5 BATCH_SAVE = 25 CHECKPOINT = OUT / "checkpoint.json" results = {} if CHECKPOINT.exists(): with open(CHECKPOINT) as f: results = json.load(f) # ================================================================ # Build directions (or load from prior) # ================================================================ print("\n[1/4] Loading model + building directions ...") from transformers import LlavaForConditionalGeneration, AutoProcessor model = LlavaForConditionalGeneration.from_pretrained( "llava-hf/llava-1.5-7b-hf", torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto", attn_implementation="eager") proc = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf") model.eval() HDIM = model.config.text_config.hidden_size img_tok_id = getattr(model.config, "image_token_index", 32000) lm_head = None for name, mod in model.named_modules(): if name.endswith("lm_head"): lm_head = mod; break assert lm_head is not None PROMPT = ("USER: \nDescribe this image in detail. " "Mention all objects you can see.\nASSISTANT:") BASES_FILE = OUT / "bases.npz" if BASES_FILE.exists(): print(" Loading pre-built bases ...") bd = np.load(BASES_FILE) visual_basis = bd["visual"] random_basis = bd["random"] else: print(f" Building visual PCA from {N_CALIB} images ...") img_vecs = [] for iid in tqdm(cands[:N_CALIB], desc="Calibrate", ncols=80): try: image = load_img(iid) except: continue inp = proc(text=PROMPT, images=image, return_tensors="pt") inp = {k: v.to(model.device) for k, v in inp.items()} ids = inp["input_ids"][0].cpu().tolist() try: i0 = ids.index(img_tok_id) except: i0 = 1 i1 = min(i0+576, len(ids)) with torch.no_grad(): out = model(**inp, output_hidden_states=True) h = out.hidden_states[LAYER][0, i0:i1].cpu().float().numpy() valid = ~np.isnan(h).any(axis=1) & ~np.isinf(h).any(axis=1) if valid.sum()>0: img_vecs.append(h[valid]) del out; torch.cuda.empty_cache() all_v = np.concatenate(img_vecs) visual_basis = PCA(n_components=K_SUB).fit(all_v).components_ rng = np.random.RandomState(42) random_basis = np.linalg.qr(rng.randn(HDIM, K_SUB))[0].T[:K_SUB] np.savez_compressed(BASES_FILE, visual=visual_basis, random=random_basis) del img_vecs, all_v; gc.collect() print(f" Visual PCA + random basis saved") DIRECTIONS = { "baseline": None, "visual_pca": torch.tensor(visual_basis, dtype=torch.float32), "random": torch.tensor(random_basis, dtype=torch.float32), } # ================================================================ # VGCD Hook # ================================================================ class VGCDHook: def __init__(self, lm_head_mod, basis_t, alpha): self.lm_head = lm_head_mod self.basis = basis_t self.alpha = alpha self.last_h = None def capture(self, module, args): try: self.last_h = args[0][:, -1, :].detach() except: pass return args def steer(self, module, input, output): if self.alpha == 0 or self.last_h is None or self.basis is None: return output try: h = self.last_h.float() scores = output[:, -1:, :].float() B = self.basis.to(h.device) proj = (h @ B.T) @ B h_ling = h - proj W = self.lm_head.weight.float().to(h.device) ll = h_ling @ W.T if self.lm_head.bias is not None: ll = ll + self.lm_head.bias.float().to(h.device) ns = scores + self.alpha * (scores - ll.unsqueeze(1)) output = output.clone() output[:, -1:, :] = ns.half() except: pass return output # ================================================================ # Run evaluations # ================================================================ print(f"\n[2/4] Running {N_EVAL} images × 3 conditions ...") eval_ids = cands[N_CALIB:N_CALIB + N_EVAL] for cond_name, basis_t in DIRECTIONS.items(): alpha = ALPHA if cond_name != "baseline" else 0.0 cond_key = f"{cond_name}_a{alpha}" # Check progress existing = results.get(cond_key, []) done = len(existing) if done >= N_EVAL: print(f" {cond_key}: already complete ({done}/{N_EVAL})") continue print(f"\n {cond_key}: starting from {done}/{N_EVAL} ...") vgcd = VGCDHook(lm_head, basis_t, alpha) h1 = lm_head.register_forward_pre_hook(vgcd.capture) h2 = lm_head.register_forward_hook(vgcd.steer) for batch_start in range(done, N_EVAL, BATCH_SAVE): batch_end = min(batch_start + BATCH_SAVE, N_EVAL) batch_ids = eval_ids[batch_start:batch_end] for iid in tqdm(batch_ids, desc=f"{cond_name}[{batch_start}:{batch_end}]", ncols=80): try: image = load_img(iid) gt = img2cats[iid] inp = proc(text=PROMPT, images=image, return_tensors="pt") inp = {k: v.to(model.device) for k, v in inp.items()} n_prompt = inp["input_ids"].shape[1] with torch.no_grad(): gen = model.generate(**inp, max_new_tokens=200, do_sample=False) cap = proc.decode(gen[0, n_prompt:], skip_special_tokens=True).strip() ch = chair_eval(cap, gt) ch["n_tokens"] = int(gen.shape[1] - n_prompt) ch["iid"] = iid existing.append(ch) del gen; torch.cuda.empty_cache() except: torch.cuda.empty_cache() # Checkpoint results[cond_key] = existing with open(CHECKPOINT, "w") as f: json.dump(results, f) hr = sum(r["halluc"] for r in existing) / len(existing) print(f" [{batch_end}/{N_EVAL}] halluc={hr*100:.1f}%") h1.remove(); h2.remove() # ================================================================ # Statistical Analysis # ================================================================ print(f"\n[3/4] Statistical Analysis") print("=" * 70) bl_key = "baseline_a0.0" vp_key = "visual_pca_a1.5" rn_key = "random_a1.5" bl = results.get(bl_key, []) vp = results.get(vp_key, []) rn = results.get(rn_key, []) def summarize(records, name): if not records: return n = len(records) hr = sum(r["halluc"] for r in records) / n ci = np.mean([r["chair_i"] for r in records]) mt = np.mean([r["n_tokens"] for r in records]) mo = np.mean([r["n_mentioned"] for r in records]) mc = np.mean([r.get("n_correct", 0) for r in records]) # Bootstrap CI on hallucination rate halluc_arr = np.array([r["halluc"] for r in records]) boot = [np.mean(np.random.choice(halluc_arr, n, replace=True)) for _ in range(10000)] ci_lo, ci_hi = np.percentile(boot, [2.5, 97.5]) print(f" {name:<20} n={n:>4} halluc={hr*100:.1f}% " f"[{ci_lo*100:.1f},{ci_hi*100:.1f}] " f"CHAIR_I={ci:.4f} tok={mt:.0f} obj={mo:.1f} correct={mc:.1f}") return hr, halluc_arr print(f"\n Condition n Halluc% [95% CI] CHAIR_I tok obj correct") print(f" {'-'*75}") bl_hr, bl_arr = summarize(bl, "Baseline") vp_hr, vp_arr = summarize(vp, "Visual PCA α=1.5") rn_hr, rn_arr = summarize(rn, "Random α=1.5") # ---- Z-test for two proportions ---- print(f"\n Z-test for proportions:") def z_test_proportions(p1, n1, p2, n2): p_pool = (p1*n1 + p2*n2) / (n1 + n2) se = np.sqrt(p_pool * (1-p_pool) * (1/n1 + 1/n2)) z = (p1 - p2) / (se + 1e-10) p_val = 2 * (1 - sp.norm.cdf(abs(z))) return z, p_val if bl_arr is not None and vp_arr is not None: z, p = z_test_proportions(vp_hr, len(vp), bl_hr, len(bl)) sig = "***" if p<0.001 else "**" if p<0.01 else "*" if p<0.05 else "ns" print(f" Visual PCA vs Baseline: z={z:.3f}, p={p:.6f} {sig}") print(f" Effect: {(vp_hr-bl_hr)*100:+.1f}pp") if bl_arr is not None and rn_arr is not None: z, p = z_test_proportions(rn_hr, len(rn), bl_hr, len(bl)) sig = "***" if p<0.001 else "**" if p<0.01 else "*" if p<0.05 else "ns" print(f" Random vs Baseline: z={z:.3f}, p={p:.6f} {sig}") print(f" Effect: {(rn_hr-bl_hr)*100:+.1f}pp") if vp_arr is not None and rn_arr is not None: z, p = z_test_proportions(vp_hr, len(vp), rn_hr, len(rn)) sig = "***" if p<0.001 else "**" if p<0.01 else "*" if p<0.05 else "ns" print(f" Visual PCA vs Random: z={z:.3f}, p={p:.6f} {sig}") print(f" Effect: {(vp_hr-rn_hr)*100:+.1f}pp") # ---- McNemar's test (paired) ---- print(f"\n McNemar's test (paired, same images):") def mcnemar_test(arr1, arr2, name): n = min(len(arr1), len(arr2)) a1, a2 = arr1[:n], arr2[:n] # b = arr1 correct, arr2 wrong; c = arr1 wrong, arr2 correct b = np.sum((a1 == 0) & (a2 == 1)) # visual correct, other wrong c = np.sum((a1 == 1) & (a2 == 0)) # visual wrong, other correct if b + c == 0: print(f" {name}: no discordant pairs") return chi2 = (abs(b - c) - 1)**2 / (b + c) # with continuity correction p = 1 - sp.chi2.cdf(chi2, df=1) sig = "***" if p<0.001 else "**" if p<0.01 else "*" if p<0.05 else "ns" print(f" {name}: b={b}, c={c}, χ²={chi2:.2f}, p={p:.6f} {sig}") if vp_arr is not None and bl_arr is not None: mcnemar_test(vp_arr, bl_arr, "Visual PCA vs Baseline") if rn_arr is not None and bl_arr is not None: mcnemar_test(rn_arr, bl_arr, "Random vs Baseline") if vp_arr is not None and rn_arr is not None: mcnemar_test(vp_arr, rn_arr, "Visual PCA vs Random") # ---- Cohen's h (effect size for proportions) ---- print(f"\n Effect sizes (Cohen's h):") def cohens_h(p1, p2): return 2 * (np.arcsin(np.sqrt(p1)) - np.arcsin(np.sqrt(p2))) if vp_hr is not None and bl_hr is not None: h = cohens_h(vp_hr, bl_hr) print(f" Visual PCA vs Baseline: h={h:.3f} " f"({'small' if abs(h)<0.5 else 'medium' if abs(h)<0.8 else 'large'})") if rn_hr is not None and bl_hr is not None: h = cohens_h(rn_hr, bl_hr) print(f" Random vs Baseline: h={h:.3f}") if vp_hr is not None and rn_hr is not None: h = cohens_h(vp_hr, rn_hr) print(f" Visual PCA vs Random: h={h:.3f}") # ================================================================ # Verdict # ================================================================ print(f"\n[4/4] Verdict") print("=" * 70) if vp_hr is not None and rn_hr is not None and bl_hr is not None: spread = (rn_hr - vp_hr) * 100 print(f"\n Baseline: {bl_hr*100:.1f}%") print(f" Visual PCA: {vp_hr*100:.1f}% ({(vp_hr-bl_hr)*100:+.1f}pp)") print(f" Random: {rn_hr*100:.1f}% ({(rn_hr-bl_hr)*100:+.1f}pp)") print(f" Spread: {spread:.1f}pp") z_vr, p_vr = z_test_proportions(vp_hr, len(vp), rn_hr, len(rn)) if p_vr < 0.001: print(f"\n >>> STATISTICALLY SIGNIFICANT (p={p_vr:.2e}) <<<") print(f" Visual PCA directions are NOT interchangeable with random.") print(f" The directions are distribution-specific (from image tokens)") print(f" but not content-specific (gibberish test).") elif p_vr < 0.05: print(f"\n >>> SIGNIFICANT (p={p_vr:.4f}) <<<") else: print(f"\n >>> NOT SIGNIFICANT (p={p_vr:.4f}) <<<") with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2, default=float) print(f"\n Saved to {OUT}/")