#!/usr/bin/env python3 """ BLIP-2 Gibberish Test: Third Architecture Validation ====================================================== BLIP-2 is architecturally DIFFERENT from LLaVA: - Vision: EVA-CLIP ViT - Bridge: Q-Former (learned queries, NOT linear projection) - LLM: OPT-2.7B (NOT Vicuna/LLaMA) If the gibberish test fails on BLIP-2 too, the finding is truly architecture-independent, not a LLaVA artifact. Pipeline: 1. Load BLIP-2 (OPT-2.7B), run 100 COCO images, build PCA from Q-Former output tokens at each LLM layer 2. Unload BLIP-2 3. Load OPT-2.7B (text-only backbone) 4. Run gibberish test: visual/factual/math/gibberish prompts 5. Compare projections Setup: !pip install -q transformers accelerate bitsandbytes torch torchvision \ scikit-learn scipy Pillow requests tqdm """ import os, 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_blip2") OUT.mkdir(exist_ok=True, parents=True) print("=" * 65) print("BLIP-2 Gibberish Test: Third Architecture") 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) 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) < 200: _ic[iid] = im return im K_SUB = 48 N_CALIB = 100 CHECKPOINT = OUT / "blip2_checkpoint.json" results = {} if CHECKPOINT.exists(): with open(CHECKPOINT) as f: results = json.load(f) # ================================================================ # STEP 1: Load BLIP-2, build PCA from image token hidden states # ================================================================ if "pca_built" not in results: print("\n[1/3] Loading BLIP-2 (OPT-2.7B) ...") from transformers import Blip2ForConditionalGeneration, Blip2Processor blip2 = Blip2ForConditionalGeneration.from_pretrained( "Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto") blip2_proc = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b") blip2.eval() # Get LLM config llm_config = blip2.language_model.config HDIM = llm_config.hidden_size N_LAYERS = llm_config.num_hidden_layers print(f" OPT backbone: hidden_size={HDIM}, layers={N_LAYERS}") # Target layers (spread across the network) TARGET_LAYERS = [0, N_LAYERS//4, N_LAYERS//2, 3*N_LAYERS//4, N_LAYERS] TARGET_LAYERS = sorted(set(l for l in TARGET_LAYERS if l <= N_LAYERS)) print(f" Target layers: {TARGET_LAYERS}") # Q-Former produces 32 query tokens that are projected into the LLM # These are the "image tokens" in BLIP-2 N_QUERY = 32 # BLIP-2 uses 32 learned queries print(f" Building PCA from Q-Former outputs ({N_CALIB} images) ...") layer_vecs = {l: [] for l in TARGET_LAYERS} PROMPT = "Describe this image in detail." for iid in tqdm(cands[:N_CALIB], desc="BLIP-2 PCA", ncols=80): try: image = load_img(iid) inp = blip2_proc(images=image, text=PROMPT, return_tensors="pt") inp = {k: v.to(blip2.device) for k, v in inp.items()} with torch.no_grad(): out = blip2(**inp, output_hidden_states=True) # The LLM's hidden states include the Q-Former output tokens # first N_QUERY positions are image tokens if hasattr(out, 'language_model_outputs') and \ hasattr(out.language_model_outputs, 'hidden_states'): hs_tuple = out.language_model_outputs.hidden_states elif hasattr(out, 'hidden_states') and out.hidden_states is not None: hs_tuple = out.hidden_states else: # Try to get hidden states by running language model directly hs_tuple = None if hs_tuple is not None: for l in TARGET_LAYERS: if l < len(hs_tuple): h = hs_tuple[l][0, :N_QUERY, :].cpu().float().numpy() valid = ~np.isnan(h).any(axis=1) & ~np.isinf(h).any(axis=1) if valid.sum() > 0: layer_vecs[l].append(h[valid]) del out; torch.cuda.empty_cache() except Exception as e: if len(layer_vecs[TARGET_LAYERS[0]]) < 3: print(f" Error: {e}") torch.cuda.empty_cache() # Build PCA layer_basis = {} rng = np.random.RandomState(42) random_basis = np.linalg.qr(rng.randn(HDIM, K_SUB))[0].T[:K_SUB] for l in TARGET_LAYERS: if not layer_vecs[l]: continue all_v = np.concatenate(layer_vecs[l]) valid = ~np.isnan(all_v).any(axis=1) & ~np.isinf(all_v).any(axis=1) all_v = all_v[valid] if all_v.shape[0] < K_SUB + 5: continue k = min(K_SUB, all_v.shape[0]-1, all_v.shape[1]-1) if k < 2: continue layer_basis[l] = PCA(n_components=k).fit(all_v).components_ print(f" Layer {l}: PCA from {all_v.shape[0]} vectors, k={k}") if not layer_basis: print(" WARNING: Could not build PCA. Trying alternative hidden state access...") # If standard access failed, the model structure might be different # Save what we have and note the issue np.savez_compressed(OUT / "blip2_pca.npz", random_basis=random_basis, **{f"layer_{l}": v for l, v in layer_basis.items()}) results["pca_built"] = True results["HDIM"] = HDIM results["N_LAYERS"] = N_LAYERS results["TARGET_LAYERS"] = TARGET_LAYERS results["n_images_used"] = len(layer_vecs.get(TARGET_LAYERS[0], [])) with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2) del blip2, blip2_proc, layer_vecs gc.collect(); torch.cuda.empty_cache() else: print("\n[1/3] Loading pre-built BLIP-2 PCA ...") pca_data = np.load(OUT / "blip2_pca.npz") random_basis = pca_data["random_basis"] layer_basis = {} for key in pca_data.files: if key.startswith("layer_"): l = int(key.split("_")[1]) layer_basis[l] = pca_data[key] HDIM = results["HDIM"] N_LAYERS = results["N_LAYERS"] TARGET_LAYERS = results["TARGET_LAYERS"] print(f" PCA built at {len(layer_basis)} layers, HDIM={HDIM}") # ================================================================ # STEP 2: Load OPT-2.7B (text-only backbone), run gibberish test # ================================================================ print(f"\n[2/3] Loading OPT-2.7B (text-only backbone) ...") from transformers import AutoModelForCausalLM, AutoTokenizer opt = AutoModelForCausalLM.from_pretrained( "facebook/opt-2.7b", torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto") opt_tok = AutoTokenizer.from_pretrained("facebook/opt-2.7b") opt.eval() print(f" OPT-2.7B loaded. Hidden size: {opt.config.hidden_size}") 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 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 library with tall bookshelves and reading desks.", "An office with computers and whiteboards on walls.", "A playground with swings, slides, and children playing.", ], "factual": [ "Explain how photosynthesis works in plants.", "What caused the French Revolution in 1789?", "How does the immune system fight viral infections?", "What is quantum entanglement in physics?", "Explain supply and demand in economics.", "What is the significance of the Magna Carta?", "How does public key encryption work?", "What caused the extinction of the dinosaurs?", "How does a nuclear fission reactor generate power?", "Explain the process of cellular mitosis.", "What is the theory of general relativity?", "How do antibiotics kill bacteria?", "What is the Pythagorean theorem?", "Explain how semiconductors work in computers.", "What causes ocean tides?", ], "math": [ "Prove that the square root of two is irrational.", "State the fundamental theorem of calculus.", "Derive the quadratic formula step by step.", "Explain Euler's identity and why it is remarkable.", "Prove that there are infinitely many prime numbers.", "What is the P versus NP problem?", "Define eigenvalues and eigenvectors.", "What is a topological space in mathematics?", "State Goedels first incompleteness theorem.", "What is the Riemann hypothesis about?", "Explain the concept of mathematical limits.", "What is a Banach space?", "Prove the triangle inequality for real numbers.", "What is the central limit theorem?", "Explain modular arithmetic with examples.", ], "gibberish": [ "Xkq plm wvt zzz brrn flmp qrst.", "Qwzyx nkl jjj hhh ttttt pppp mmm.", "Aaaa bbbb cccc dddd eeee ffff gggg.", "Mlkj hgfd sapo iuyt rewq zxcv bnm.", "Fghjkl zxcvbnm qwertyuiop asdfg.", "Jjjjj kkkkk lllll mmmmm nnnnn ooooo.", "Bnmz xkwq plrv tsyg hdjf kcmw.", "Wwww xxxx yyyy zzzz aaaa bbbb cccc.", "Vcxz nmbl kpoj ihug yftd rews qasx.", "Rrrr ssss tttt uuuu vvvv wwww xxxx.", "Plkm bnvx czsd fghj wert qazu.", "Tyyy uiii oppp aass ddff gghh jjkk.", "Qqww eerr ttyy uuii oopp aasd.", "Zzxx ccvv bbnn mmll kkjj hhgg.", "Ggff ddss aaqq wwee rrtt yyuu.", ], } print(f" Running gibberish test ({sum(len(v) for v in PROMPTS.values())} prompts) ...") test_results = {} for pt, prompts in PROMPTS.items(): test_results[pt] = {str(l): [] for l in layer_basis} test_results[f"{pt}_rnd"] = {str(l): [] for l in layer_basis} for prompt in tqdm(prompts, desc=pt[:8], ncols=80): inp = opt_tok(prompt, return_tensors="pt") inp = {k: v.to(opt.device) for k, v in inp.items()} with torch.no_grad(): out = opt(**inp, output_hidden_states=True) for l in layer_basis: 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) basis = layer_basis[l] proj = (basis @ h) @ basis test_results[pt][str(l)].append(float(np.linalg.norm(proj) / hn)) rb = random_basis[:basis.shape[0]] pr = (rb @ h) @ rb test_results[f"{pt}_rnd"][str(l)].append(float(np.linalg.norm(pr) / hn)) del out; torch.cuda.empty_cache() del opt, opt_tok; gc.collect(); torch.cuda.empty_cache() # ================================================================ # RESULTS # ================================================================ print(f"\n[3/3] Results: BLIP-2 Gibberish Test") print("=" * 70) print(f"\n OPT-2.7B (text-only) projected onto BLIP-2 image-token PCA:") print(f"\n {'Type':<12}", end="") for l in sorted(layer_basis.keys()): print(f" L{l:>2}", end="") print(f" {'Mean':>6} {'Gib/Type':>8}") print(f" {'-'*55}") type_means = {} for pt in ["visual", "factual", "math", "gibberish"]: ratios = [] print(f" {pt:<12}", end="") for l in sorted(layer_basis.keys()): v = test_results[pt].get(str(l), []) r = test_results[f"{pt}_rnd"].get(str(l), []) if v and r: ratio = np.mean(v) / (np.mean(r) + 1e-8) ratios.append(ratio) print(f" {ratio:>4.1f}x", end="") mean_r = np.mean(ratios) if ratios else 0 type_means[pt] = mean_r gv = type_means.get("gibberish", 0) / (mean_r + 1e-8) if pt != "gibberish" else "" print(f" {mean_r:>5.2f}x {gv if isinstance(gv, str) else f'{gv:.2f}':>8}") # Verdict gv_ratio = type_means.get("gibberish", 0) / (type_means.get("visual", 0) + 1e-8) print(f"\n Gib/Visual ratio: {gv_ratio:.2f}") if gv_ratio > 0.7: print(f"\n >>> BLIP-2 FAILS THE GIBBERISH TEST <<<") print(f" The Visual Subspace Illusion holds for BLIP-2 (Q-Former + OPT).") print(f" This is a DIFFERENT architecture from LLaVA (linear proj + Vicuna).") print(f" Finding is architecture-independent.") elif gv_ratio < 0.5: print(f"\n >>> BLIP-2 PASSES THE GIBBERISH TEST <<<") print(f" The Q-Former produces genuinely visual-specific directions.") print(f" The illusion is specific to linear-projection VLMs (LLaVA family).") else: print(f"\n >>> BLIP-2 MARGINAL <<<") print(f" Some visual specificity but not strong.") # Save results["gibberish_test"] = { pt: float(type_means.get(pt, 0)) for pt in PROMPTS } results["gib_vis_ratio"] = float(gv_ratio) with open(CHECKPOINT, "w") as f: json.dump(results, f, indent=2) print(f"\n Saved to {OUT}/") # Cross-architecture summary print(f"\n{'='*70}") print("CROSS-ARCHITECTURE SUMMARY") print(f"{'='*70}") print(f" Architecture Vision Bridge LLM Gib/Vis") print(f" {'-'*60}") print(f" LLaVA-1.5 CLIP-ViT-L Linear proj Vicuna-7B 1.00") print(f" LLaVA-Next CLIP-ViT-L Linear proj Mistral-7B 1.00*") print(f" BLIP-2 EVA-CLIP Q-Former OPT-2.7B {gv_ratio:>8.2f}") print(f" * Tested on Mistral backbone, not full LLaVA-Next PCA")