#!/usr/bin/env python3 """ Gibberish Test on Mistral-7B (Second Backbone Validation) =========================================================== Proves the Visual Subspace Illusion is not Vicuna-specific. Uses the SAME directions built from LLaVA-1.5 image tokens. Tests on Mistral-7B-v0.1 (LLaVA-Next's backbone, zero multimodal training). If Mistral also scores high on gibberish -> finding is backbone-independent. Setup: !pip install -q transformers accelerate bitsandbytes torch torchvision \ scikit-learn scipy Pillow requests tqdm """ import os, json, gc, warnings from pathlib import Path import numpy as np import torch from tqdm import tqdm warnings.filterwarnings("ignore") from google.colab import drive drive.mount("/content/drive", force_remount=False) # Load saved directions from vista_nullu_test.py PRIOR_DIR = Path("/content/drive/MyDrive/topohd_vista_nullu") assert (PRIOR_DIR / "directions.npz").exists(), \ "Run vista_nullu_test.py first" OUT = Path("/content/drive/MyDrive/topohd_mistral_test") OUT.mkdir(exist_ok=True, parents=True) print("=" * 65) print("Gibberish Test: Mistral-7B Backbone") print("=" * 65) # Load directions data = np.load(PRIOR_DIR / "directions.npz") HDIM = int(data["HDIM"][0]) random_basis = data["random_basis"] TARGET_LAYERS = [8, 16, 24, 32] K_SUB = 32 # Collect all methods all_directions = {} METHOD_NAMES = ["vista", "vista_subspace", "nullu_alltoken", "nullu_halluc"] for method in METHOD_NAMES: all_directions[method] = {} for l in TARGET_LAYERS: key = f"{method}_{l}" if key in data: all_directions[method][l] = data[key] all_directions["random"] = {l: random_basis[:K_SUB] for l in TARGET_LAYERS} # Also load PCA basis from illusion experiment if available ILLUSION_DIR = Path("/content/drive/MyDrive/topohd_illusion") if (ILLUSION_DIR / "subspaces.npz").exists(): ill_data = np.load(ILLUSION_DIR / "subspaces.npz") all_directions["pca_img"] = {} all_directions["pca_txt"] = {} for l in TARGET_LAYERS: if f"img_{l}" in ill_data: all_directions["pca_img"][l] = ill_data[f"img_{l}"] if f"txt_{l}" in ill_data: all_directions["pca_txt"][l] = ill_data[f"txt_{l}"] METHOD_NAMES.extend(["pca_img", "pca_txt"]) print(" Also loaded PCA bases from illusion experiment") methods_available = [m for m in METHOD_NAMES if all_directions.get(m)] print(f" Methods: {methods_available}") # ---- Prompts ---- 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 trees.", "A street with cars, buses, and traffic lights.", "A farm with cows grazing near a red barn.", "A zoo with elephants and visitors.", "A restaurant with plates and wine glasses.", "A bedroom with a bed, lamp, and curtains.", "A classroom with desks, whiteboard, and students.", "A grocery store with produce and shopping carts.", "A construction site with cranes and workers.", "A mountain trail with hikers and pine trees.", "A harbor with boats, docks, and seagulls.", "A library with bookshelves and reading tables.", "An office with computers, desks, and whiteboards.", ], "factual": [ "Explain photosynthesis in plants.", "What caused the French Revolution?", "How do vaccines prevent disease?", "What is quantum entanglement?", "Explain supply and demand in economics.", "What is the Magna Carta?", "How does encryption protect data?", "What caused dinosaur extinction?", "How does a nuclear reactor work?", "Explain cellular mitosis.", "What is the theory of general relativity?", "How does the immune system work?", "What is the Pythagorean theorem?", "Explain how semiconductors work.", "What causes tides in the ocean?", ], "math": [ "Prove sqrt of 2 is irrational.", "State the fundamental theorem of calculus.", "Derive the quadratic formula.", "Explain Euler's identity.", "Prove infinitely many primes exist.", "What is the P vs NP problem?", "Define eigenvalues and eigenvectors.", "What is a topological space?", "State Goedels incompleteness theorem.", "What is the Riemann hypothesis?", "Explain the concept of a limit.", "What is a Banach space?", "Prove the triangle inequality.", "What is the central limit theorem?", "Explain modular arithmetic.", ], "gibberish": [ "Xkq plm wvt zzz brrn flmp.", "Qwzyx nkl jjj hhh ttttt pppp.", "Aaaa bbbb cccc dddd eeee ffff.", "Mlkj hgfd sapo iuyt rewq.", "Fghjkl zxcvbnm qwertyuiop.", "Jjjjj kkkkk lllll mmmmm nnnnn.", "Bnmz xkwq plrv tsyg.", "Wwww xxxx yyyy zzzz aaaa bbbb.", "Vcxz nmbl kpoj ihug yftd.", "Rrrr ssss tttt uuuu vvvv wwww.", "Plkm bnvx czsd fghj.", "Tyyy uiii oppp aass ddff.", "Qqww eerr ttyy uuii oopp.", "Zzxx ccvv bbnn mmll kkjj.", "Ggff ddss aaqq wwee rrtt.", ], } # ---- Load Mistral-7B ---- print("\n Loading Mistral-7B-v0.1 ...") from transformers import AutoModelForCausalLM, AutoTokenizer mistral = AutoModelForCausalLM.from_pretrained( "mistralai/Mistral-7B-v0.1", torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto") tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1") mistral.eval() print(f" Mistral loaded. Hidden size: {mistral.config.hidden_size}") assert mistral.config.hidden_size == HDIM, \ f"Hidden size mismatch: Mistral={mistral.config.hidden_size} vs directions={HDIM}" # ---- Run gibberish test ---- print(f"\n Running gibberish test ({sum(len(v) for v in PROMPTS.values())} prompts) ...") test_results = {} for pt, prompts in PROMPTS.items(): test_results[pt] = {} for mname in methods_available + ["random"]: test_results[pt][mname] = {str(l): [] for l in TARGET_LAYERS} for prompt in tqdm(prompts, desc=pt[:8], ncols=80): inp = tokenizer(prompt, return_tensors="pt") inp = {k: v.to(mistral.device) for k, v in inp.items()} with torch.no_grad(): out = mistral(**inp, output_hidden_states=True) for l in TARGET_LAYERS: if l >= len(out.hidden_states): continue h = out.hidden_states[l][0, -1, :].cpu().float().numpy() if np.isnan(h).any() or np.linalg.norm(h) < 1e-12: continue hn = np.linalg.norm(h) for mname in methods_available + ["random"]: if l not in all_directions.get(mname, {}): continue dirs = all_directions[mname][l] proj = (dirs @ h) @ dirs alpha = float(np.linalg.norm(proj) / hn) test_results[pt][mname][str(l)].append(alpha) del out; torch.cuda.empty_cache() del mistral, tokenizer; gc.collect(); torch.cuda.empty_cache() # ---- Results ---- print(f"\n{'='*70}") print("RESULTS: Mistral-7B Gibberish Test") print(f"{'='*70}") print(f"\n {'Method':<20} {'Visual':>8} {'Factual':>8} {'Math':>8} " f"{'Gibber':>8} {'Gib/Vis':>8} {'PASS?':>6}") print(f" {'-'*62}") for mname in methods_available: means = {} for pt in ["visual", "factual", "math", "gibberish"]: vals = [] for l in TARGET_LAYERS: v = test_results[pt][mname].get(str(l), []) r = test_results[pt]["random"].get(str(l), []) if v and r: vals.append(np.mean(v) / (np.mean(r) + 1e-8)) means[pt] = np.mean(vals) if vals else 0 gv = means["gibberish"] / (means["visual"] + 1e-8) passed = "PASS" if gv < 0.5 and means["visual"] > 1.5 else \ "MARGINAL" if gv < 0.7 else "FAIL" print(f" {mname:<20} {means['visual']:>7.2f}x {means['factual']:>7.2f}x " f"{means['math']:>7.2f}x {means['gibberish']:>7.2f}x " f"{gv:>7.2f} {passed:>6}") # ---- Comparison with Vicuna ---- print(f"\n COMPARISON: Vicuna vs Mistral on PCA gibberish test") print(f" (Check if finding is backbone-independent)") vicuna_results = {} VICUNA_CKPT = Path("/content/drive/MyDrive/topohd_illusion/illusion_checkpoint.json") if VICUNA_CKPT.exists(): with open(VICUNA_CKPT) as f: vicuna_data = json.load(f) vpt = vicuna_data.get("vicuna_prompt_types", {}) for pt in ["visual", "gibberish"]: if pt in vpt and "pca_img" in methods_available: # Rough comparison pass print(" (Vicuna data available for comparison)") print(f"\n VERDICT:") # Check if ANY method passes on Mistral any_pass = False for mname in methods_available: vis_vals = [np.mean(test_results["visual"][mname].get(str(l), [0])) / (np.mean(test_results["visual"]["random"].get(str(l), [1])) + 1e-8) for l in TARGET_LAYERS] gib_vals = [np.mean(test_results["gibberish"][mname].get(str(l), [0])) / (np.mean(test_results["gibberish"]["random"].get(str(l), [1])) + 1e-8) for l in TARGET_LAYERS] mv = np.mean(vis_vals) mg = np.mean(gib_vals) if mg < mv * 0.5 and mv > 1.5: any_pass = True if not any_pass: print(" ALL methods FAIL the gibberish test on Mistral-7B.") print(" The Visual Subspace Illusion is BACKBONE-INDEPENDENT.") print(" It affects both Vicuna-7B and Mistral-7B.") else: print(" Some methods pass on Mistral. Further investigation needed.") # Save results_summary = { mname: { pt: float(np.mean([np.mean(test_results[pt][mname].get(str(l), [0])) / (np.mean(test_results[pt]["random"].get(str(l), [1])) + 1e-8) for l in TARGET_LAYERS])) for pt in PROMPTS } for mname in methods_available } with open(OUT / "mistral_results.json", "w") as f: json.dump(results_summary, f, indent=2) print(f"\n Saved to {OUT}/")