#!/usr/bin/env python3 """ PART 2 (GPU): Run Vicuna forward passes on 1000 prompts × 4 types ==================================================================== Loads prompts from Part 1. Loads directions from prior experiments. Saves raw alpha values with checkpoint every 50 prompts. Setup: !pip install -q transformers accelerate bitsandbytes torch tqdm """ import 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) OUT = Path("/content/drive/MyDrive/topohd_scaled_gib") # ---- Load prompts ---- print("Loading prompts ...") with open(OUT / "prompts_1000.json") as f: PROMPTS = json.load(f) for k, v in PROMPTS.items(): print(f" {k}: {len(v)}") # ---- Load directions ---- print("\nLoading directions ...") TARGET_LAYERS = [8, 16, 24, 32] all_directions = {} random_basis = None HDIM = None DIRS_PATHS = [ Path("/content/drive/MyDrive/topohd_vista_nullu/directions.npz"), Path("/content/drive/MyDrive/topohd_illusion/subspaces.npz"), Path("/content/drive/MyDrive/topohd_contrastive_valid/subspaces_3methods.npz"), ] for dp in DIRS_PATHS: if not dp.exists(): print(f" SKIP: {dp}") continue print(f" Loading: {dp}") data = np.load(dp) if "random_basis" in data and random_basis is None: random_basis = data["random_basis"] HDIM = random_basis.shape[1] if "HDIM" in data and HDIM is None: HDIM = int(data["HDIM"][0]) for key in data.files: if key in ["random_basis", "HDIM"]: continue for l in TARGET_LAYERS: suffix = f"_{l}" if key.endswith(suffix): mname = key[:-len(suffix)] if mname not in all_directions: all_directions[mname] = {} all_directions[mname][l] = data[key] # Add random baseline if random_basis is not None: all_directions["random"] = {l: random_basis[:32] for l in TARGET_LAYERS} methods = [m for m in all_directions if m != "random" and all_directions[m]] print(f"\nMethods to test: {methods}") print(f"HDIM: {HDIM}") if not methods: print("ERROR: No direction files found! Run vista_nullu_test.py or visual_illusion.py first.") raise SystemExit # ---- Load checkpoint ---- CHECKPOINT = OUT / "gpu_checkpoint.json" results = {} if CHECKPOINT.exists(): with open(CHECKPOINT) as f: results = json.load(f) print(f"Resuming from checkpoint ({len(results)} keys)") # ---- Load Vicuna ---- print("\nLoading 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") tokenizer = AutoTokenizer.from_pretrained("lmsys/vicuna-7b-v1.5") vicuna.eval() print(" Loaded.") # ---- Run forward passes ---- BATCH_SAVE = 50 for pt_name in ["visual", "factual", "math", "gibberish"]: prompts = PROMPTS[pt_name] progress_key = f"_progress_{pt_name}" done = results.get(progress_key, 0) if done >= len(prompts): print(f"\n{pt_name}: already complete ({done}/{len(prompts)})") continue print(f"\n{pt_name}: starting from {done}/{len(prompts)} ...") for batch_start in range(done, len(prompts), BATCH_SAVE): batch_end = min(batch_start + BATCH_SAVE, len(prompts)) batch = prompts[batch_start:batch_end] for i, prompt in enumerate(tqdm(batch, desc=f"{pt_name}[{batch_start}:{batch_end}]", ncols=80)): inp = tokenizer(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) 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 + ["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) key = f"{pt_name}|{mname}|{l}" if key not in results: results[key] = [] results[key].append(alpha) del out; torch.cuda.empty_cache() # Save checkpoint results[progress_key] = batch_end with open(CHECKPOINT, "w") as f: json.dump(results, f) print(f" {pt_name}: done ({len(prompts)} prompts)") del vicuna, tokenizer; gc.collect(); torch.cuda.empty_cache() # ---- Summary ---- print(f"\n{'='*60}") print("GPU PASS COMPLETE") print(f"{'='*60}") for pt in ["visual", "factual", "math", "gibberish"]: n = results.get(f"_progress_{pt}", 0) print(f" {pt}: {n} prompts processed") # Quick peek at ratios print(f"\n Quick ratios (first available method):") m0 = methods[0] if methods else None if m0: for pt in ["visual", "factual", "math", "gibberish"]: vals = [] rnds = [] for l in TARGET_LAYERS: v = results.get(f"{pt}|{m0}|{l}", []) r = results.get(f"{pt}|random|{l}", []) if v and r: vals.append(np.mean(v)) rnds.append(np.mean(r)) if vals and rnds: ratio = np.mean(vals) / (np.mean(rnds) + 1e-8) print(f" {pt}: {m0} ratio = {ratio:.2f}x (n={len(results.get(f'{pt}|{m0}|{TARGET_LAYERS[0]}', []))})") print(f"\n Next: run PART 3 (CPU) for statistical analysis") print(f" Checkpoint: {CHECKPOINT}")