#!/usr/bin/env python3 """ Distributional Match Principle: Quantitative Validation ========================================================= CPU only. Loads saved bases from prior experiments. Computes subspace similarity between each basis and image-token PCA. Correlates with VGCD hallucination reduction. If correlation is strong (r > 0.9): DMP is quantitatively validated. """ import json import numpy as np from pathlib import Path from scipy import stats as sp from google.colab import drive drive.mount("/content/drive", force_remount=False) print("=" * 65) print("Distributional Match Principle: Quantitative Validation") print("=" * 65) # ---- Load bases from multiple sources ---- print("\n[1/3] Loading bases ...") SEARCH_PATHS = { "makebreak": Path("/content/drive/MyDrive/topohd_makebreak"), "corrected": Path("/content/drive/MyDrive/topohd_corrected"), "vicuna_vgcd": Path("/content/drive/MyDrive/topohd_vicuna_vgcd"), "illusion": Path("/content/drive/MyDrive/topohd_illusion"), "vista_nullu": Path("/content/drive/MyDrive/topohd_vista_nullu"), "scaled_makebreak": Path("/content/drive/MyDrive/topohd_scaled_makebreak"), } bases = {} # Try corrected_subspace first (has image, backbone, random) cp = SEARCH_PATHS["corrected"] / "all_bases.npz" if cp.exists(): d = np.load(cp) if "image_basis" in d: bases["image_pca"] = d["image_basis"] if "backbone_basis" in d: bases["backbone_pca"] = d["backbone_basis"] if "random_basis" in d: bases["random"] = d["random_basis"] print(f" Loaded from corrected: {[k for k in ['image_pca','backbone_pca','random'] if k in bases]}") # Try makebreak (has visual, random, maybe text) for mp in [SEARCH_PATHS["makebreak"] / "bases.npz", SEARCH_PATHS["scaled_makebreak"] / "bases.npz"]: if mp.exists(): d = np.load(mp) if "visual" in d and "image_pca" not in bases: bases["image_pca"] = d["visual"] if "random" in d and "random" not in bases: bases["random"] = d["random"] print(f" Loaded from {mp.parent.name}: {list(d.files)}") # Try illusion (has img PCA and txt PCA) ip = SEARCH_PATHS["illusion"] / "subspaces.npz" if ip.exists(): d = np.load(ip) # These are per-layer; take layer 16 if available for key in d.files: if key.startswith("img_16"): bases["image_pca_L16"] = d[key] elif key.startswith("txt_16"): bases["text_pca_L16"] = d[key] elif key.startswith("img_") and "image_pca" not in bases: bases["image_pca"] = d[key] elif key.startswith("txt_") and "text_pca" not in bases: bases["text_pca"] = d[key] print(f" Loaded from illusion: {[k for k in bases if 'L16' in k or k in ['image_pca','text_pca']]}") # Try vicuna_vgcd (has vicuna PCA) vp = SEARCH_PATHS["vicuna_vgcd"] / "vicuna_pca_basis.npy" if vp.exists(): bases["backbone_pca"] = np.load(vp) print(f" Loaded backbone PCA from vicuna_vgcd: {bases['backbone_pca'].shape}") print(f"\n Available bases: {list(bases.keys())}") # Use image_pca as the reference ref_key = "image_pca" if ref_key not in bases and "image_pca_L16" in bases: ref_key = "image_pca_L16" assert ref_key in bases, f"No image PCA basis found! Available: {list(bases.keys())}" ref_basis = bases[ref_key] print(f" Reference basis: {ref_key}, shape {ref_basis.shape}") # ---- Compute subspace similarities ---- print(f"\n[2/3] Computing subspace similarities ...") def subspace_similarity(A, B): """Compute similarity between two subspaces. Returns multiple measures.""" # Ensure same number of directions k = min(A.shape[0], B.shape[0]) A, B = A[:k], B[:k] # 1. Mean absolute cosine: for each dir in A, find best match in B cos_matrix = np.abs(A @ B.T) # (k, k) best_match_A = cos_matrix.max(axis=1).mean() # avg best match for A dirs best_match_B = cos_matrix.max(axis=0).mean() # avg best match for B dirs # 2. Projection Frobenius: ||A @ B^T||_F^2 / k proj_frob = np.sum(cos_matrix**2) / k # 3. Mean cosine (all pairs) mean_cos = cos_matrix.mean() # 4. Top-1 principal angle cosine U, S, Vt = np.linalg.svd(A @ B.T) top_cos = S[0] # cosine of first principal angle return dict( best_match_mean=(best_match_A + best_match_B) / 2, proj_frobenius=proj_frob, mean_cosine=mean_cos, top_principal_cos=top_cos, ) # VGCD results from makebreak (alpha=1.5) VGCD_RESULTS = { "image_pca": -5.0, # 57.5% vs 62.5% baseline "text_pca": -2.0, # 60.5% "backbone_pca": +3.5, # 66.0% "random": +5.0, # 67.5% } # Compute similarities print(f"\n {'Basis':<20} {'BestMatch':>10} {'ProjFrob':>10} {'MeanCos':>10} " f"{'TopPC':>10} {'VGCD Δpp':>10}") print(f" {'-'*70}") sim_data = [] for bname, basis in bases.items(): if bname == ref_key: continue if bname.endswith("_L16"): continue # skip duplicates # Map to VGCD results vgcd_key = bname if vgcd_key not in VGCD_RESULTS: # Try without suffix for vk in VGCD_RESULTS: if vk in bname: vgcd_key = vk break if vgcd_key not in VGCD_RESULTS: print(f" {bname:<20} (no VGCD data, skipping)") continue sim = subspace_similarity(ref_basis, basis) vgcd_delta = VGCD_RESULTS[vgcd_key] print(f" {bname:<20} {sim['best_match_mean']:>10.4f} " f"{sim['proj_frobenius']:>10.4f} {sim['mean_cosine']:>10.4f} " f"{sim['top_principal_cos']:>10.4f} {vgcd_delta:>+10.1f}") sim_data.append(dict(name=bname, vgcd=vgcd_delta, **sim)) # Add self-similarity for image_pca self_sim = subspace_similarity(ref_basis, ref_basis) sim_data.append(dict(name=ref_key, vgcd=VGCD_RESULTS.get("image_pca", -5.0), **self_sim)) print(f" {ref_key:<20} {self_sim['best_match_mean']:>10.4f} " f"{self_sim['proj_frobenius']:>10.4f} {self_sim['mean_cosine']:>10.4f} " f"{self_sim['top_principal_cos']:>10.4f} {VGCD_RESULTS.get('image_pca', -5.0):>+10.1f}") # ---- Correlation analysis ---- print(f"\n[3/3] Correlation: Distributional Match vs VGCD Effectiveness") print("=" * 65) if len(sim_data) < 3: print(" Not enough data points for correlation.") else: vgcd_vals = np.array([d["vgcd"] for d in sim_data]) for metric in ["best_match_mean", "proj_frobenius", "mean_cosine", "top_principal_cos"]: sim_vals = np.array([d[metric] for d in sim_data]) # Pearson correlation r, p = sp.pearsonr(sim_vals, vgcd_vals) # Spearman rank correlation rho, p_rho = sp.spearmanr(sim_vals, vgcd_vals) print(f"\n {metric}:") print(f" Pearson r = {r:+.4f} (p = {p:.4f})") print(f" Spearman ρ = {rho:+.4f} (p = {p_rho:.4f})") if abs(r) > 0.9: print(f" >>> STRONG correlation: higher similarity → lower hallucination") elif abs(r) > 0.7: print(f" >> Moderate correlation") else: print(f" > Weak correlation") # Print the data points for the figure print(f"\n Data points for Figure (best_match_mean vs VGCD):") for d in sorted(sim_data, key=lambda x: x["best_match_mean"], reverse=True): print(f" {d['name']:<20} similarity={d['best_match_mean']:.4f} " f"VGCD={d['vgcd']:+.1f}pp") # ---- Verdict ---- print(f"\n{'='*65}") print("VERDICT: Distributional Match Principle") print(f"{'='*65}") if len(sim_data) >= 3: r_best, _ = sp.pearsonr( [d["best_match_mean"] for d in sim_data], [d["vgcd"] for d in sim_data]) if r_best < -0.85: # negative: higher similarity → more negative VGCD (less halluc) print(f"\n >>> DMP VALIDATED (r = {r_best:.3f}) <<<") print(f" Subspace similarity to image-token PCA strongly predicts") print(f" VGCD hallucination reduction. The closer the basis matches") print(f" the image-token distribution, the better the steering.") print(f"\n This resolves the paradox:") print(f" - Directions fail content-specificity (gibberish test)") print(f" - But succeed at steering when distribution-matched") print(f" - Content ≠ distribution: the mechanism is geometric,") print(f" not semantic") print(f"\n DMP provides a principled selection criterion:") print(f" 'Use PCA of the target distribution, not a content-specific basis.'") elif r_best < -0.7: print(f"\n >> DMP PARTIALLY SUPPORTED (r = {r_best:.3f})") print(f" Moderate correlation between similarity and effectiveness.") else: print(f"\n > DMP NOT SUPPORTED (r = {r_best:.3f})") print(f" Distributional match does not predict steering effectiveness.") # Save results = { "sim_data": [{k: float(v) if isinstance(v, (float, np.floating)) else v for k, v in d.items()} for d in sim_data], } OUT = Path("/content/drive/MyDrive/topohd_dmp") OUT.mkdir(exist_ok=True, parents=True) with open(OUT / "dmp_results.json", "w") as f: json.dump(results, f, indent=2) print(f"\n Saved to {OUT}/")