#!/usr/bin/env python3 """ POPE Evaluation: The GRH Validation Experiment ================================================= GRH predicts: VGCD reduces CHAIR (verbosity-confounded) but NOT POPE (properly controlled yes/no questions). If confirmed: GRH is empirically validated. The mechanism is confidence regularization (reduces verbosity → inflates CHAIR) not visual grounding improvement (which POPE would detect). Generates POPE-style questions from COCO annotations. Runs baseline vs VGCD (image PCA, α=1.5). Reports accuracy, precision, recall, F1, yes-rate. 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, Counter import numpy as np import requests import torch from PIL import Image from tqdm import tqdm from sklearn.decomposition import PCA from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score warnings.filterwarnings("ignore") from google.colab import drive drive.mount("/content/drive", force_remount=False) OUT = Path("/content/drive/MyDrive/topohd_pope") OUT.mkdir(exist_ok=True, parents=True) print("=" * 65) print("POPE Evaluation: GRH Validation") 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"]} all_categories = list(cat_id2name.values()) 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"]} # Count category frequency for "popular" setting cat_freq = Counter() for cats in img2cats.values(): cat_freq.update(cats) popular_cats = [c for c, _ in cat_freq.most_common(20)] # Co-occurrence for "adversarial" setting cooccur = defaultdict(Counter) for cats in img2cats.values(): for c1 in cats: for c2 in cats: if c1 != c2: cooccur[c1][c2] += 1 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 # ================================================================ # STEP 1: Generate POPE questions # ================================================================ N_IMAGES = 500 N_PER_IMAGE = 6 # 3 positive + 3 negative per image CHECKPOINT = OUT / "pope_checkpoint.json" results = {} if CHECKPOINT.exists(): with open(CHECKPOINT) as f: results = json.load(f) if "questions_built" not in results: print("\n[1/4] Generating POPE questions ...") rng = np.random.RandomState(42) questions = {"random": [], "popular": [], "adversarial": []} for iid in cands[:N_IMAGES]: gt = img2cats[iid] gt_list = list(gt) absent = [c for c in all_categories if c not in gt] if len(gt_list) < 2 or len(absent) < 3: continue # Positive questions (objects that ARE present) pos_objs = rng.choice(gt_list, size=min(3, len(gt_list)), replace=False) for obj in pos_objs: q = f"Is there a {obj} in the image?" for setting in questions: questions[setting].append(dict( iid=iid, question=q, object=obj, label=1, setting=setting)) # Negative questions - RANDOM neg_random = rng.choice(absent, size=min(3, len(absent)), replace=False) for obj in neg_random: questions["random"].append(dict( iid=iid, question=f"Is there a {obj} in the image?", object=obj, label=0, setting="random")) # Negative questions - POPULAR (most frequent categories not in image) neg_popular = [c for c in popular_cats if c not in gt][:3] for obj in neg_popular: questions["popular"].append(dict( iid=iid, question=f"Is there a {obj} in the image?", object=obj, label=0, setting="popular")) # Negative questions - ADVERSARIAL (co-occurring categories not in image) cooccur_candidates = [] for c in gt_list: for co, freq in cooccur[c].most_common(10): if co not in gt: cooccur_candidates.append((co, freq)) cooccur_candidates.sort(key=lambda x: -x[1]) neg_adv = list(dict(cooccur_candidates).keys())[:3] if len(neg_adv) < 3: neg_adv.extend(rng.choice(absent, size=3-len(neg_adv), replace=False).tolist()) for obj in neg_adv[:3]: questions["adversarial"].append(dict( iid=iid, question=f"Is there a {obj} in the image?", object=obj, label=0, setting="adversarial")) for s, qs in questions.items(): print(f" {s}: {len(qs)} questions " f"({sum(q['label'] for q in qs)} pos, {sum(1-q['label'] for q in qs)} neg)") results["questions"] = questions results["questions_built"] = True with open(CHECKPOINT, "w") as f: json.dump(results, f) else: questions = results["questions"] print("\n[1/4] Loaded pre-built questions") for s, qs in questions.items(): print(f" {s}: {len(qs)} questions") # ================================================================ # STEP 2: Load model + build VGCD basis # ================================================================ print("\n[2/4] Loading LLaVA + building VGCD basis ...") 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 # Build or load visual PCA basis K_SUB = 48; LAYER = 16; N_CALIB = 200 BASES_FILE = OUT / "pope_bases.npz" if BASES_FILE.exists(): bd = np.load(BASES_FILE) visual_basis = bd["visual"] print(f" Loaded visual PCA basis: {visual_basis.shape}") else: print(f" Building visual PCA from {N_CALIB} images ...") CALIB_PROMPT = "USER: \nDescribe.\nASSISTANT:" img_vecs = [] for iid in tqdm(cands[:N_CALIB], desc="Calibrate", ncols=80): try: image = load_img(iid) except: continue inp = proc(text=CALIB_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_ np.savez_compressed(BASES_FILE, visual=visual_basis) del img_vecs, all_v print(f" Built visual PCA: {visual_basis.shape}") visual_basis_t = torch.tensor(visual_basis, dtype=torch.float32) # ================================================================ # STEP 3: 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 # ================================================================ # STEP 4: Run POPE evaluation # ================================================================ print("\n[3/4] Running POPE evaluation ...") CONDITIONS = [ ("baseline", 0.0), ("vgcd_a1.0", 1.0), ("vgcd_a1.5", 1.5), ] SETTINGS = ["random", "popular", "adversarial"] BATCH_SAVE = 50 def parse_answer(text): """Extract yes/no from model response.""" text = text.strip().lower() if text.startswith("yes"): return 1 elif text.startswith("no"): return 0 # Check for yes/no anywhere if "yes" in text.split()[:3]: return 1 if "no" in text.split()[:3]: return 0 return -1 # unparseable for cond_name, alpha in CONDITIONS: for setting in SETTINGS: key = f"{cond_name}_{setting}" existing = results.get(key, []) qs = questions[setting] done = len(existing) if done >= len(qs): print(f" {key}: already complete ({done}/{len(qs)})") continue print(f"\n {key}: starting from {done}/{len(qs)} ...") vgcd = VGCDHook(lm_head, visual_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, len(qs), BATCH_SAVE): batch_end = min(batch_start + BATCH_SAVE, len(qs)) batch = qs[batch_start:batch_end] for q in tqdm(batch, desc=f"{key}[{batch_start}:{batch_end}]", ncols=80): try: image = load_img(q["iid"]) prompt = f"USER: \n{q['question']} Answer with yes or no.\nASSISTANT:" 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=20, do_sample=False) answer = proc.decode(gen[0, n_prompt:], skip_special_tokens=True) pred = parse_answer(answer) existing.append(dict( iid=q["iid"], object=q["object"], label=q["label"], pred=pred, answer=answer[:50])) del gen; torch.cuda.empty_cache() except: torch.cuda.empty_cache() # Checkpoint results[key] = existing with open(CHECKPOINT, "w") as f: json.dump(results, f) h1.remove(); h2.remove() # ================================================================ # RESULTS # ================================================================ print(f"\n[4/4] Results: POPE Evaluation") print("=" * 70) print(f"\n {'Condition':<22} {'Setting':<14} {'Acc':>6} {'Prec':>6} " f"{'Rec':>6} {'F1':>6} {'Yes%':>6} {'N':>5}") print(f" {'-'*68}") summary = {} for cond_name, alpha in CONDITIONS: for setting in SETTINGS: key = f"{cond_name}_{setting}" recs = results.get(key, []) if not recs: continue # Filter unparseable valid = [r for r in recs if r["pred"] >= 0] if len(valid) < 10: continue labels = [r["label"] for r in valid] preds = [r["pred"] for r in valid] acc = accuracy_score(labels, preds) prec = precision_score(labels, preds, zero_division=0) rec = recall_score(labels, preds, zero_division=0) f1 = f1_score(labels, preds, zero_division=0) yes_rate = sum(preds) / len(preds) summary[key] = dict(acc=acc, prec=prec, rec=rec, f1=f1, yes_rate=yes_rate, n=len(valid)) print(f" {cond_name:<22} {setting:<14} {acc:.3f} {prec:.3f} " f"{rec:.3f} {f1:.3f} {yes_rate:.3f} {len(valid):>5}") # ---- GRH Validation ---- print(f"\n{'='*70}") print("GRH VALIDATION: Does VGCD help on POPE?") print(f"{'='*70}") for setting in SETTINGS: bl_key = f"baseline_{setting}" vgcd_key = f"vgcd_a1.5_{setting}" bl = summary.get(bl_key, {}) vg = summary.get(vgcd_key, {}) if bl and vg: acc_diff = vg["acc"] - bl["acc"] f1_diff = vg["f1"] - bl["f1"] yes_diff = vg["yes_rate"] - bl["yes_rate"] print(f"\n {setting}:") print(f" Baseline: acc={bl['acc']:.3f} F1={bl['f1']:.3f} yes={bl['yes_rate']:.3f}") print(f" VGCD 1.5: acc={vg['acc']:.3f} F1={vg['f1']:.3f} yes={vg['yes_rate']:.3f}") print(f" Diff: acc={acc_diff:+.3f} F1={f1_diff:+.3f} yes={yes_diff:+.3f}") # Overall bl_accs = [summary.get(f"baseline_{s}", {}).get("acc", 0) for s in SETTINGS] vg_accs = [summary.get(f"vgcd_a1.5_{s}", {}).get("acc", 0) for s in SETTINGS] if all(a > 0 for a in bl_accs) and all(a > 0 for a in vg_accs): mean_bl = np.mean(bl_accs) mean_vg = np.mean(vg_accs) diff = mean_vg - mean_bl print(f"\n OVERALL:") print(f" Mean baseline POPE accuracy: {mean_bl:.3f}") print(f" Mean VGCD POPE accuracy: {mean_vg:.3f}") print(f" Difference: {diff:+.3f}") # Compare with CHAIR result print(f"\n CHAIR result (from makebreak):") print(f" Baseline: 62.5% hallucination") print(f" VGCD α=1.5: 57.5% hallucination (-5.0pp)") if abs(diff) < 0.02: # less than 2% change on POPE print(f"\n >>> GRH VALIDATED <<<") print(f" VGCD reduces CHAIR by 5pp (verbosity-confounded metric)") print(f" but does NOT improve POPE accuracy ({diff:+.3f})") print(f" (properly controlled yes/no questions).") print(f" The mechanism is confidence regularization,") print(f" not visual grounding improvement.") elif diff > 0.02: print(f"\n >>> GRH PARTIALLY REFUTED <<<") print(f" VGCD improves POPE by {diff:+.3f}.") print(f" Some genuine grounding improvement exists") print(f" beyond verbosity reduction.") elif diff < -0.02: print(f"\n >>> VGCD HURTS POPE <<<") print(f" VGCD reduces POPE accuracy by {diff:.3f}.") print(f" Geometric regularization degrades grounding") print(f" on controlled evaluation.") results["summary"] = {k: {kk: float(vv) for kk, vv in v.items()} for k, v in summary.items()} with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2, default=float) print(f"\n Saved to {OUT}/")