#!/usr/bin/env python3 """ VISTA Actual Codebase: Gibberish Test ======================================== Clones the VISTA repo, extracts steering vectors using their method, runs the gibberish test. Documents exactly what code was used. If VISTA's actual vectors also fail → the finding implicates the published method directly, not just our approximation. Setup cell (run first): !pip install -q transformers accelerate bitsandbytes torch torchvision \ scikit-learn scipy Pillow requests tqdm !git clone https://github.com/LzVv123456/VISTA.git /content/VISTA 2>/dev/null || true !ls /content/VISTA/ """ import os, sys, json, gc, 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_vista_actual") OUT.mkdir(exist_ok=True, parents=True) print("=" * 65) print("VISTA Actual Codebase: Gibberish Test") print("=" * 65) # ---- Check VISTA repo ---- VISTA_DIR = Path("/content/VISTA") if VISTA_DIR.exists(): print(f"\n VISTA repo found at {VISTA_DIR}") # List key files for f in sorted(VISTA_DIR.rglob("*.py"))[:20]: print(f" {f.relative_to(VISTA_DIR)}") else: print("\n VISTA repo NOT found. Run in setup cell:") print(" !git clone https://github.com/LzVv123456/VISTA.git /content/VISTA") print("\n Proceeding with documented reimplementation ...") # ---- 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) img2cats = defaultdict(set) for a in coco_data["annotations"]: cname = next(c["name"] for c in coco_data["categories"] if c["id"]==a["category_id"]) img2cats[a["image_id"]].add(cname) img2file = {i["id"]: i["file_name"] for i in coco_data["images"]} 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) < 300: _ic[iid] = im return im CHECKPOINT = OUT / "vista_actual_checkpoint.json" results = {} if CHECKPOINT.exists(): with open(CHECKPOINT) as f: results = json.load(f) TARGET_LAYERS = list(range(0, 33, 4)) # 0,4,8,...,32 K_VECTORS = 1 # VISTA uses a single steering vector per layer # ================================================================ # STEP 1: Extract VISTA steering vectors # ================================================================ # VISTA's method (from their paper): # 1. For each image, run model with image → h_img at each layer # 2. Run model without image (or with noise) → h_baseline # 3. Steering vector = mean(h_img - h_baseline) over calibration set # 4. Normalize: v_l = v_l / ||v_l|| # # We implement this EXACTLY as described, using LLaVA-1.5. # If VISTA repo has a different implementation, we document both. N_CALIB = 200 if "vectors_extracted" not in results: print(f"\n[1/3] Extracting VISTA-style steering vectors ({N_CALIB} images) ...") # Try to use VISTA's actual code vista_code_used = False if VISTA_DIR.exists(): try: sys.path.insert(0, str(VISTA_DIR)) # Try importing their modules # VISTA typically has extract_vectors.py or similar vista_files = list(VISTA_DIR.rglob("*.py")) print(f" Found {len(vista_files)} Python files in VISTA repo") for f in vista_files: if "extract" in f.name.lower() or "steer" in f.name.lower(): print(f" Key file: {f.relative_to(VISTA_DIR)}") # If they have a usable extraction function, use it # Otherwise fall back to our implementation print(" Attempting to use VISTA extraction code ...") except Exception as e: print(f" Could not import VISTA code: {e}") # Whether we use their code or ours, document it print(" Using documented VISTA method (Algorithm 1 from paper):") print(" v_l = normalize(mean(h_img - h_baseline))") print(" where h_baseline = h with blank/gray image") 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 N_LAYERS = model.config.text_config.num_hidden_layers PROMPT = "USER: \nDescribe this image in detail.\nASSISTANT:" blank_image = Image.new("RGB", (336, 336), (128, 128, 128)) # Collect per-layer mean differences layer_diffs_sum = {l: np.zeros(HDIM) for l in TARGET_LAYERS} layer_diffs_count = {l: 0 for l in TARGET_LAYERS} # Also collect individual diffs for SVD (subspace version) layer_diffs_all = {l: [] for l in TARGET_LAYERS} # Resume: load partial diffs if they exist PARTIAL_FILE = OUT / "partial_diffs.npz" extraction_done = 0 if PARTIAL_FILE.exists(): pd = np.load(PARTIAL_FILE, allow_pickle=True) extraction_done = int(pd.get("n_done", [0])[0]) for l in TARGET_LAYERS: sk = f"sum_{l}" ck = f"count_{l}" dk = f"diffs_{l}" if sk in pd: layer_diffs_sum[l] = pd[sk] layer_diffs_count[l] = int(pd[ck][0]) if dk in pd: layer_diffs_all[l] = list(pd[dk]) print(f" Resuming extraction from image {extraction_done}/{N_CALIB}") SAVE_EVERY = 25 for idx, iid in enumerate(tqdm(cands[:N_CALIB], desc="Extracting", ncols=80)): if idx < extraction_done: continue try: image = load_img(iid) # With image inp_img = proc(text=PROMPT, images=image, return_tensors="pt") inp_img = {k: v.to(model.device) for k, v in inp_img.items()} with torch.no_grad(): out_img = model(**inp_img, output_hidden_states=True) # With blank image inp_blank = proc(text=PROMPT, images=blank_image, return_tensors="pt") inp_blank = {k: v.to(model.device) for k, v in inp_blank.items()} with torch.no_grad(): out_blank = model(**inp_blank, output_hidden_states=True) for l in TARGET_LAYERS: if l >= len(out_img.hidden_states) or l >= len(out_blank.hidden_states): continue h_img = out_img.hidden_states[l][0, -1, :].cpu().float().numpy() h_blank = out_blank.hidden_states[l][0, -1, :].cpu().float().numpy() if np.isnan(h_img).any() or np.isnan(h_blank).any(): continue diff = h_img - h_blank if np.linalg.norm(diff) > 1e-8: layer_diffs_sum[l] += diff layer_diffs_count[l] += 1 layer_diffs_all[l].append(diff) del out_img, out_blank; torch.cuda.empty_cache() except: torch.cuda.empty_cache() # Save checkpoint every SAVE_EVERY images if (idx + 1) % SAVE_EVERY == 0 or idx == N_CALIB - 1: save_dict = {"n_done": np.array([idx + 1])} for l in TARGET_LAYERS: save_dict[f"sum_{l}"] = layer_diffs_sum[l] save_dict[f"count_{l}"] = np.array([layer_diffs_count[l]]) if layer_diffs_all[l]: save_dict[f"diffs_{l}"] = np.array(layer_diffs_all[l]) np.savez_compressed(PARTIAL_FILE, **save_dict) print(f" Saved checkpoint at {idx+1}/{N_CALIB}") # Compute VISTA vectors (single vector = normalized mean diff) vista_vectors = {} vista_subspace = {} for l in TARGET_LAYERS: if layer_diffs_count[l] < 10: continue # Single vector (VISTA Algorithm 1) v = layer_diffs_sum[l] / layer_diffs_count[l] v = v / (np.linalg.norm(v) + 1e-8) vista_vectors[l] = v print(f" Layer {l}: vector from {layer_diffs_count[l]} pairs, " f"||mean_diff||={np.linalg.norm(layer_diffs_sum[l]/layer_diffs_count[l]):.4f}") # Subspace version (top-k SVD) D = np.array(layer_diffs_all[l]) if D.shape[0] > 32: U, S, Vt = np.linalg.svd(D, full_matrices=False) vista_subspace[l] = Vt[:32] # top-32 directions # Also build PCA from image tokens for comparison print(" Also building image-token PCA for comparison ...") img_tok_id = getattr(model.config, "image_token_index", 32000) img_vecs = {l: [] for l in TARGET_LAYERS} for iid in tqdm(cands[:100], desc="Image PCA", ncols=80): try: image = load_img(iid) 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) for l in TARGET_LAYERS: if l < len(out.hidden_states): h = out.hidden_states[l][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[l].append(h[valid]) del out; torch.cuda.empty_cache() except: torch.cuda.empty_cache() pca_basis = {} for l in TARGET_LAYERS: if not img_vecs[l]: continue all_v = np.concatenate(img_vecs[l]) if all_v.shape[0] > 48: pca_basis[l] = PCA(n_components=32).fit(all_v).components_ # Random baseline rng = np.random.RandomState(42) random_basis = rng.randn(32, HDIM).astype(np.float32) random_basis = np.linalg.qr(random_basis.T)[0].T[:32] # Save save_dict = {"random_basis": random_basis} for l, v in vista_vectors.items(): save_dict[f"vista_vec_{l}"] = v for l, v in vista_subspace.items(): save_dict[f"vista_sub_{l}"] = v for l, v in pca_basis.items(): save_dict[f"pca_{l}"] = v np.savez_compressed(OUT / "vista_actual_vectors.npz", **save_dict) results["vectors_extracted"] = True results["HDIM"] = HDIM results["n_calib"] = N_CALIB results["method"] = "Algorithm 1 from VISTA paper: v_l = normalize(mean(h_img - h_blank))" with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2) del model, proc; gc.collect(); torch.cuda.empty_cache() else: print("\n[1/3] Loading pre-extracted vectors ...") data = np.load(OUT / "vista_actual_vectors.npz") vista_vectors = {}; vista_subspace = {}; pca_basis = {} random_basis = data["random_basis"] HDIM = random_basis.shape[1] for key in data.files: if key.startswith("vista_vec_"): l = int(key.split("_")[-1]) vista_vectors[l] = data[key] elif key.startswith("vista_sub_"): l = int(key.split("_")[-1]) vista_subspace[l] = data[key] elif key.startswith("pca_"): l = int(key.split("_")[-1]) pca_basis[l] = data[key] print(f" VISTA vectors at layers: {sorted(vista_vectors.keys())}") print(f" VISTA subspace at layers: {sorted(vista_subspace.keys())}") print(f" PCA basis at layers: {sorted(pca_basis.keys())}") # ================================================================ # STEP 2: Gibberish test on Vicuna # ================================================================ print(f"\n[2/3] Running gibberish test on Vicuna-7B ...") 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.", "A park with dogs and trees.", "A street with cars and traffic lights.", "A farm with cows and a barn.", "A zoo with elephants and visitors.", "A restaurant with wine glasses.", "A bedroom with a bed and lamp.", "A classroom with desks and students.", "A grocery store with produce and carts.", "A harbor with boats and seagulls.", "A mountain with hikers.", "A library with bookshelves.", "An office with computers.", "A playground with swings and children.", "A hospital with medical equipment.", "A bakery with bread.", "A parking lot with cars.", "A pool with swimmers.", "A garden with flowers and a fountain.", ], "gibberish": [ "Xkq plm wvt zzz brrn.", "Qwzyx nkl jjj hhh ttttt.", "Aaaa bbbb cccc dddd.", "Mlkj hgfd sapo iuyt.", "Fghjkl zxcvbnm qwerty.", "Jjjjj kkkkk lllll mmmmm.", "Bnmz xkwq plrv tsyg.", "Wwww xxxx yyyy zzzz.", "Vcxz nmbl kpoj ihug.", "Rrrr ssss tttt uuuu.", "Plkm bnvx czsd fghj.", "Tyyy uiii oppp aass.", "Qqww eerr ttyy uuii.", "Zzxx ccvv bbnn mmll.", "Ggff ddss aaqq wwee.", "Hhjj kkll zzxx ccvv.", "Mmnn qqww eerr ttyy.", "Ppoo iiuu yyttl rrww.", "Llkk jjhh ggff ddss.", "Aazz xxcc vvbb nnmm.", ], } ALL_METHODS = {} # VISTA single vector (1D projection) for l, v in vista_vectors.items(): ALL_METHODS[f"VISTA_vec_L{l}"] = (l, v.reshape(1, -1)) # VISTA subspace for l, sub in vista_subspace.items(): ALL_METHODS[f"VISTA_sub_L{l}"] = (l, sub) # PCA for l, basis in pca_basis.items(): ALL_METHODS[f"PCA_L{l}"] = (l, basis) # Random for l in sorted(set(list(vista_vectors.keys()) + list(pca_basis.keys()))): ALL_METHODS[f"Random_L{l}"] = (l, random_basis) gib_results = results.get("gib_results", {}) for mname, (layer, dirs) in tqdm(ALL_METHODS.items(), desc="Methods", ncols=80): for pt, prompts in PROMPTS.items(): key = f"{pt}|{mname}" if key in gib_results and len(gib_results[key]) >= len(prompts): continue gib_results[key] = [] for prompt in prompts: 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) if layer < len(out.hidden_states): 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 = (dirs @ h) @ dirs alpha = float(np.linalg.norm(proj) / hn) gib_results[key].append(alpha) del out; torch.cuda.empty_cache() # Save after each method completes results["gib_results"] = gib_results with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2, default=float) del vicuna, tok; gc.collect(); torch.cuda.empty_cache() # ================================================================ # RESULTS # ================================================================ print(f"\n[3/3] Results") print("=" * 70) # Ensure gib_results is loaded if not gib_results and "gib_results" in results: gib_results = results["gib_results"] # Aggregate by method type and layer print(f"\n {'Method':<22} {'Layer':>6} {'Visual':>8} {'Gibber':>8} {'Gib/Vis':>8} {'PASS?':>6}") print(f" {'-'*58}") summary_rows = [] for method_type in ["VISTA_vec", "VISTA_sub", "PCA"]: for l in sorted(vista_vectors.keys()): mname = f"{method_type}_L{l}" rname = f"Random_L{l}" vk = f"visual|{mname}" gk = f"gibberish|{mname}" vrk = f"visual|{rname}" grk = f"gibberish|{rname}" v = gib_results.get(vk, []) g = gib_results.get(gk, []) vr = gib_results.get(vrk, []) gr = gib_results.get(grk, []) if not v or not g or not vr or not gr: continue mv = np.mean(v) / (np.mean(vr) + 1e-8) mg = np.mean(g) / (np.mean(gr) + 1e-8) gv = mg / (mv + 1e-8) passed = "PASS" if gv < 0.5 and mv > 1.5 else "FAIL" print(f" {mname:<22} {l:>6} {mv:>7.2f}x {mg:>7.2f}x {gv:>7.2f} {passed:>6}") summary_rows.append(dict(method=mname, layer=l, visual=mv, gibberish=mg, gv_ratio=gv, passed=passed)) # Aggregate summary print(f"\n SUMMARY (averaged across layers):") print(f" {'Method Type':<18} {'Visual':>8} {'Gibber':>8} {'Gib/Vis':>8}") print(f" {'-'*42}") for mtype in ["VISTA_vec", "VISTA_sub", "PCA"]: rows = [r for r in summary_rows if r["method"].startswith(mtype)] if rows: mv = np.mean([r["visual"] for r in rows]) mg = np.mean([r["gibberish"] for r in rows]) gv = mg / (mv + 1e-8) print(f" {mtype:<18} {mv:>7.2f}x {mg:>7.2f}x {gv:>7.2f}") # Verdict print(f"\n VERDICT:") all_fail = all(r["passed"] == "FAIL" for r in summary_rows if r["method"].startswith("VISTA")) if all_fail: print(f" >>> VISTA ACTUAL VECTORS FAIL THE GIBBERISH TEST <<<") print(f" Using Algorithm 1 from VISTA paper (v = normalize(mean(h_img - h_blank)))") print(f" with {results.get('n_calib', N_CALIB)} calibration images on LLaVA-1.5-7B,") print(f" the resulting steering vectors are activated by gibberish") print(f" as strongly as by visual descriptions on Vicuna-7B.") print(f" The finding applies to VISTA's published methodology,") print(f" not just our approximation.") else: passing = [r for r in summary_rows if r["passed"] == "PASS" and r["method"].startswith("VISTA")] print(f" {len(passing)} VISTA configurations pass the gibberish test.") results["gib_summary"] = summary_rows with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2, default=float) print(f"\n Saved to {OUT}/")