#!/usr/bin/env python3 """ Selectivity-Corrected Visual Subspace ======================================= The constructive experiment: build directions that are DISTRIBUTION-SPECIFIC (from image tokens) but with BACKBONE GEOMETRY removed (orthogonalized against Vicuna PCA). If the corrected directions: 1. PASS the gibberish test (Gib/Vis < 0.5) 2. AND still reduce hallucination via VGCD → We have the first valid visual subspace → Paper goes from "everything fails" to "here's how to do it right" → Acceptance jumps to 85-90% Pipeline: Phase A: Build image-token PCA and backbone PCA (or load from prior) Phase B: Orthogonalize image PCA against backbone PCA Phase C: Gibberish test on corrected directions (Vicuna) Phase D: VGCD with corrected directions (LLaVA) 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 warnings.filterwarnings("ignore") from google.colab import drive drive.mount("/content/drive", force_remount=False) OUT = Path("/content/drive/MyDrive/topohd_corrected") OUT.mkdir(exist_ok=True, parents=True) print("=" * 65) print("Selectivity-Corrected Visual Subspace") 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=False, chair_i=0.0, n_mentioned=0) h = mentioned - gt return dict(halluc=len(h) > 0, chair_i=len(h)/len(mentioned), n_mentioned=len(mentioned)) 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 K_SUB = 48 LAYER = 16 N_CALIB = 200 CHECKPOINT = OUT / "corrected_checkpoint.json" results = {} if CHECKPOINT.exists(): with open(CHECKPOINT) as f: results = json.load(f) # ================================================================ # PHASE A: Build image-token PCA + backbone PCA # ================================================================ # Try to load from prior experiments VICUNA_PCA_PATH = Path("/content/drive/MyDrive/topohd_vicuna_vgcd/vicuna_pca_basis.npy") if "bases_built" not in results: # --- Build image-token PCA from LLaVA --- print("\n[A1] Loading LLaVA to build image-token PCA ...") from transformers import LlavaForConditionalGeneration, AutoProcessor llava = 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") llava.eval() HDIM = llava.config.text_config.hidden_size img_tok_id = getattr(llava.config, "image_token_index", 32000) PROMPT = "USER: \nDescribe this image in detail.\nASSISTANT:" img_vecs = [] for iid in tqdm(cands[:N_CALIB], desc="Image PCA", ncols=80): try: image = load_img(iid) except: continue inp = proc(text=PROMPT, images=image, return_tensors="pt") inp = {k: v.to(llava.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 = llava(**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_img = np.concatenate(img_vecs) image_basis = PCA(n_components=K_SUB).fit(all_img).components_ print(f" Image PCA: {K_SUB} components from {all_img.shape[0]} vectors") del llava, proc, img_vecs, all_img; gc.collect(); torch.cuda.empty_cache() # --- Build backbone PCA from Vicuna --- if VICUNA_PCA_PATH.exists(): print(" Loading Vicuna PCA from prior experiment ...") backbone_basis = np.load(VICUNA_PCA_PATH) print(f" Backbone PCA: {backbone_basis.shape}") else: print("\n[A2] Loading Vicuna to build backbone PCA ...") from transformers import AutoModelForCausalLM, AutoTokenizer vicuna = AutoModelForCausalLM.from_pretrained( "lmsys/vicuna-7b-v1.5", torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto") tok = AutoTokenizer.from_pretrained("lmsys/vicuna-7b-v1.5") vicuna.eval() DIVERSE_PROMPTS = [ "A kitchen with a table and chairs.", "Explain photosynthesis.", "Prove sqrt 2 is irrational.", "def fib(n): return n if n<2 else fib(n-1)+fib(n-2)", "Once upon a time there was a knight.", "Xkq plm wvt zzz brrn.", ] * 10 # 60 prompts bb_vecs = [] for p in tqdm(DIVERSE_PROMPTS, desc="Backbone PCA", ncols=80): inp = tok(p, return_tensors="pt") inp = {k: v.to(vicuna.device) for k, v in inp.items()} with torch.no_grad(): out = vicuna(**inp, output_hidden_states=True) h = out.hidden_states[LAYER][0].cpu().float().numpy() valid = ~np.isnan(h).any(axis=1) & ~np.isinf(h).any(axis=1) if valid.sum() > 0: bb_vecs.append(h[valid]) del out; torch.cuda.empty_cache() all_bb = np.concatenate(bb_vecs) backbone_basis = PCA(n_components=K_SUB).fit(all_bb).components_ print(f" Backbone PCA: {K_SUB} components from {all_bb.shape[0]} vectors") del vicuna, tok, bb_vecs, all_bb; gc.collect(); torch.cuda.empty_cache() # --- Build random basis --- rng = np.random.RandomState(42) random_basis = np.linalg.qr(rng.randn(HDIM, K_SUB))[0].T[:K_SUB] # Save all bases np.savez_compressed(OUT / "all_bases.npz", image_basis=image_basis, backbone_basis=backbone_basis, random_basis=random_basis) results["bases_built"] = True results["HDIM"] = HDIM with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2) else: print("\n[A] Loading pre-built bases ...") data = np.load(OUT / "all_bases.npz") image_basis = data["image_basis"] backbone_basis = data["backbone_basis"] random_basis = data["random_basis"] HDIM = results["HDIM"] # ================================================================ # PHASE B: Orthogonalize image PCA against backbone PCA # ================================================================ print("\n[B] Orthogonalizing image PCA against backbone PCA ...") def orthogonalize_basis(V, B): """Remove projection of each row of V onto subspace B. V: (k, d) - directions to clean B: (k, d) - directions to remove Returns cleaned and re-orthogonalized basis.""" # For each v in V, remove component along B V_proj = (V @ B.T) @ B # projection onto B V_orth = V - V_proj # residual # Some may collapse norms = np.linalg.norm(V_orth, axis=1) valid = norms > 1e-6 V_orth = V_orth[valid] # Re-orthogonalize via QR if V_orth.shape[0] < 2: return V_orth Q, R = np.linalg.qr(V_orth.T) return Q.T[:V_orth.shape[0]] corrected_basis = orthogonalize_basis(image_basis, backbone_basis) n_survived = corrected_basis.shape[0] print(f" {K_SUB} -> {n_survived} directions survived ({n_survived/K_SUB:.0%})") # Also compute overlap between bases cos_matrix = np.abs(image_basis @ backbone_basis.T) mean_overlap = cos_matrix.mean() max_overlap = cos_matrix.max() print(f" Image-Backbone overlap: mean|cos|={mean_overlap:.4f}, max={max_overlap:.4f}") # ================================================================ # PHASE C: Gibberish test on corrected directions # ================================================================ print(f"\n[C] Gibberish test on corrected directions ...") if "gibberish_done" not in results: from transformers import AutoModelForCausalLM, AutoTokenizer vicuna = AutoModelForCausalLM.from_pretrained( "lmsys/vicuna-7b-v1.5", torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto") tok = AutoTokenizer.from_pretrained("lmsys/vicuna-7b-v1.5") vicuna.eval() PROMPTS = { "visual": [ "A kitchen with a table, chairs, and a refrigerator.", "A beach with surfers and umbrellas in the sun.", "A park with dogs, children, and tall oak trees.", "A street with cars, buses, and traffic lights.", "A farm with cows grazing near a red barn.", "A zoo with elephants and visitors behind a fence.", "A restaurant with plates and wine glasses on tables.", "A bedroom with a bed, lamp, and curtains.", "A classroom with desks, a whiteboard, and students.", "A grocery store with produce and shopping carts.", "A harbor with boats docked at wooden piers.", "A mountain trail with hikers carrying backpacks.", "A construction site with cranes and cement trucks.", "An office with computers, desks, and whiteboards.", "A playground with swings, slides, and children.", "A hospital room with a bed and medical equipment.", "A bakery with bread, pastries, and a display case.", "A parking lot with cars, trucks, and motorcycles.", "A swimming pool with swimmers and lounge chairs.", "A garden with flowers, trees, and a fountain.", ], "gibberish": [ "Xkq plm wvt zzz brrn flmp.", "Qwzyx nkl jjj hhh ttttt.", "Aaaa bbbb cccc dddd eeee.", "Mlkj hgfd sapo iuyt rewq.", "Fghjkl zxcvbnm qwerty.", "Jjjjj kkkkk lllll mmmmm.", "Bnmz xkwq plrv tsyg.", "Wwww xxxx yyyy zzzz aaaa.", "Vcxz nmbl kpoj ihug.", "Rrrr ssss tttt uuuu vvvv.", "Plkm bnvx czsd fghj.", "Tyyy uiii oppp aass ddff.", "Qqww eerr ttyy uuii.", "Zzxx ccvv bbnn mmll kkjj.", "Ggff ddss aaqq wwee.", "Hhjj kkll zzxx ccvv bbnn.", "Mmnn qqww eerr ttyy.", "Ppoo iiuu yyttl rrww eeqq.", "Llkk jjhh ggff ddss.", "Aazz xxcc vvbb nnmm llkk.", ], } ALL_BASES = { "image_pca": image_basis, "corrected": corrected_basis, "backbone_pca": backbone_basis, "random": random_basis[:corrected_basis.shape[0]], } gib_results = {} for pt, prompts in PROMPTS.items(): for bname, basis in ALL_BASES.items(): key = f"{pt}_{bname}" gib_results[key] = [] for prompt in tqdm(prompts, desc=f"{pt[:4]}_{bname[:6]}", ncols=80): inp = tok(prompt, return_tensors="pt") inp = {k: v.to(vicuna.device) for k, v in inp.items()} with torch.no_grad(): out = vicuna(**inp, output_hidden_states=True) h = out.hidden_states[LAYER][0, -1, :].cpu().float().numpy() if not np.isnan(h).any() and np.linalg.norm(h) > 1e-12: hn = np.linalg.norm(h) proj = (basis @ h) @ basis gib_results[key].append(float(np.linalg.norm(proj) / hn)) del out; torch.cuda.empty_cache() results["gibberish_done"] = True results["gib_results"] = {k: v for k, v in gib_results.items()} with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2) del vicuna, tok; gc.collect(); torch.cuda.empty_cache() else: gib_results = results["gib_results"] # Report print(f"\n Gibberish Test Results:") print(f" {'Method':<18} {'Visual':>8} {'Gibber':>8} {'Gib/Vis':>8} {'PASS?':>6}") print(f" {'-'*48}") for bname in ["image_pca", "corrected", "backbone_pca", "random"]: vk = f"visual_{bname}" gk = f"gibberish_{bname}" v = gib_results.get(vk, []) g = gib_results.get(gk, []) rk_v = gib_results.get("visual_random", []) rk_g = gib_results.get("gibberish_random", []) if v and g and rk_v and rk_g: mv = np.mean(v) / (np.mean(rk_v) + 1e-8) mg = np.mean(g) / (np.mean(rk_g) + 1e-8) gv = mg / (mv + 1e-8) passed = "PASS" if gv < 0.5 and mv > 1.5 else \ "MARGINAL" if gv < 0.7 else "FAIL" marker = " <<<" if passed == "PASS" else "" print(f" {bname:<18} {mv:>7.2f}x {mg:>7.2f}x {gv:>7.2f} {passed:>6}{marker}") # ================================================================ # PHASE D: VGCD with corrected directions # ================================================================ if n_survived >= 2: print(f"\n[D] VGCD with corrected directions on LLaVA ...") if "vgcd_done" not in results: from transformers import LlavaForConditionalGeneration, AutoProcessor llava = 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") llava.eval() lm_head = None for name, mod in llava.named_modules(): if name.endswith("lm_head"): lm_head = mod; break PROMPT_CAP = ("USER: \nDescribe this image in detail. " "Mention all objects you can see.\nASSISTANT:") N_EVAL = 200 eval_ids = cands[N_CALIB:N_CALIB + N_EVAL] class VGCDSteering: 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: 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 DIRECTIONS_VGCD = { "image_pca": torch.tensor(image_basis, dtype=torch.float32), "corrected": torch.tensor(corrected_basis, dtype=torch.float32), "random": torch.tensor(random_basis[:corrected_basis.shape[0]], dtype=torch.float32), } ALPHA = 1.0 vgcd_results = {} for dname, basis_t in DIRECTIONS_VGCD.items(): key = f"vgcd_{dname}" vgcd = VGCDSteering(lm_head, basis_t, ALPHA if dname != "baseline" else 0) h1 = lm_head.register_forward_pre_hook(vgcd.capture) h2 = lm_head.register_forward_hook(vgcd.steer) records = [] for iid in tqdm(eval_ids, desc=f"VGCD {dname[:8]}", ncols=80): try: image = load_img(iid) gt = img2cats[iid] inp = proc(text=PROMPT_CAP, images=image, return_tensors="pt") inp = {k: v.to(llava.device) for k, v in inp.items()} n_prompt = inp["input_ids"].shape[1] with torch.no_grad(): gen = llava.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) records.append(ch) del gen; torch.cuda.empty_cache() except: torch.cuda.empty_cache() h1.remove(); h2.remove() hr = sum(r["halluc"] for r in records) / len(records) ci = np.mean([r["chair_i"] for r in records]) mt = np.mean([r["n_tokens"] for r in records]) vgcd_results[dname] = dict(halluc=hr, chair_i=ci, tokens=mt, n=len(records)) print(f" {dname}: halluc={hr*100:.1f}% CHAIR_I={ci:.4f} tokens={mt:.0f}") # Also run baseline (alpha=0) vgcd = VGCDSteering(lm_head, DIRECTIONS_VGCD["image_pca"], 0.0) h1 = lm_head.register_forward_pre_hook(vgcd.capture) h2 = lm_head.register_forward_hook(vgcd.steer) records = [] for iid in tqdm(eval_ids, desc="Baseline", ncols=80): try: image = load_img(iid) gt = img2cats[iid] inp = proc(text=PROMPT_CAP, images=image, return_tensors="pt") inp = {k: v.to(llava.device) for k, v in inp.items()} n_prompt = inp["input_ids"].shape[1] with torch.no_grad(): gen = llava.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) records.append(ch) del gen; torch.cuda.empty_cache() except: torch.cuda.empty_cache() h1.remove(); h2.remove() hr = sum(r["halluc"] for r in records) / len(records) ci = np.mean([r["chair_i"] for r in records]) mt = np.mean([r["n_tokens"] for r in records]) vgcd_results["baseline"] = dict(halluc=hr, chair_i=ci, tokens=mt, n=len(records)) results["vgcd_done"] = True results["vgcd_results"] = {k: {kk: float(vv) for kk, vv in v.items()} for k, v in vgcd_results.items()} with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2) del llava, proc; gc.collect(); torch.cuda.empty_cache() else: vgcd_results = results["vgcd_results"] # ================================================================ # VERDICT # ================================================================ print(f"\n{'='*65}") print("VERDICT: Does the Corrected Subspace Work?") print(f"{'='*65}") bl = vgcd_results.get("baseline", {}).get("halluc", 0.625) print(f"\n {'Method':<18} {'Halluc%':>8} {'Delta':>8} {'CHAIR_I':>8}") print(f" {'-'*42}") for dname in ["baseline", "image_pca", "corrected", "random"]: d = vgcd_results.get(dname, {}) hr = d.get("halluc", 0) ci = d.get("chair_i", 0) delta = f"({(hr-bl)*100:+.1f}pp)" if dname != "baseline" else "(base)" print(f" {dname:<18} {hr*100:>7.1f}% {delta:>8} {ci:>8.4f}") # Check gibberish test for corrected v_corr = gib_results.get("visual_corrected", []) g_corr = gib_results.get("gibberish_corrected", []) r_v = gib_results.get("visual_random", []) r_g = gib_results.get("gibberish_random", []) if v_corr and g_corr and r_v and r_g: mv = np.mean(v_corr) / (np.mean(r_v) + 1e-8) mg = np.mean(g_corr) / (np.mean(r_g) + 1e-8) gv_corr = mg / (mv + 1e-8) corr_halluc = vgcd_results.get("corrected", {}).get("halluc", 0) corr_helps = corr_halluc < bl print(f"\n Corrected subspace:") print(f" Gibberish test: Gib/Vis = {gv_corr:.2f} " f"({'PASS' if gv_corr < 0.5 else 'FAIL'})") print(f" VGCD effect: {(corr_halluc-bl)*100:+.1f}pp " f"({'helps' if corr_helps else 'hurts'})") if gv_corr < 0.5 and corr_helps: print(f"\n >>> THE CORRECTED SUBSPACE PASSES BOTH TESTS <<<") print(f" First valid visual subspace: passes gibberish test") print(f" AND reduces hallucination via VGCD.") print(f" Paper acceptance: 85-90%.") elif gv_corr < 0.5 and not corr_helps: print(f"\n >>> PASSES GIBBERISH BUT DOESN'T HELP VGCD <<<") print(f" Valid visual directions exist but don't help steering.") print(f" Interesting finding but less impactful.") elif gv_corr >= 0.5 and corr_helps: print(f"\n >>> FAILS GIBBERISH BUT HELPS VGCD <<<") print(f" Still captures backbone geometry after correction.") else: print(f"\n >>> FAILS BOTH <<<") print(f" Correction insufficient. No valid visual subspace found.") with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2) print(f"\n Saved to {OUT}/")