svs-subspace-validity-suite / experiments /theorem_verification_v2.py
Anonymousblind's picture
Upload folder using huggingface_hub
17373f3 verified
Raw
History Blame Contribute Delete
8.52 kB
#!/usr/bin/env python3
"""
Theorem Verification v2: Extract weights by parameter name
=============================================================
Uses named_parameters() to find weight matrices directly,
avoiding module navigation issues with device_map.
Setup:
!pip install -q transformers accelerate torch scikit-learn scipy 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_theorem")
OUT.mkdir(exist_ok=True, parents=True)
print("=" * 65)
print("Theorem Verification v2: Weight Matrix SVD")
print("=" * 65)
# ================================================================
# Load model and extract weights by name
# ================================================================
print("\n[1/3] Loading LLaVA weights ...")
from transformers import LlavaForConditionalGeneration
model = LlavaForConditionalGeneration.from_pretrained(
"llava-hf/llava-1.5-7b-hf", torch_dtype=torch.float32,
low_cpu_mem_usage=True, device_map="cpu")
N_LAYERS = model.config.text_config.num_hidden_layers
HDIM = model.config.text_config.hidden_size
print(f" Layers: {N_LAYERS}, Hidden: {HDIM}")
# Find all weight matrices by scanning parameter names
print(f"\n Scanning parameter names ...")
weight_matrices = {}
for name, param in model.named_parameters():
# Look for attention output and FFN down projections
for layer_idx in range(N_LAYERS):
# Attention output: *layers.{l}*o_proj.weight
if f".{layer_idx}." in name and "o_proj.weight" in name and "self_attn" in name:
weight_matrices[f"attn_out_L{layer_idx}"] = param
# FFN down projection: *layers.{l}*down_proj.weight
if f".{layer_idx}." in name and "down_proj.weight" in name:
weight_matrices[f"ffn_down_L{layer_idx}"] = param
# FFN gate: *layers.{l}*gate_proj.weight
if f".{layer_idx}." in name and "gate_proj.weight" in name:
weight_matrices[f"ffn_gate_L{layer_idx}"] = param
print(f" Found {len(weight_matrices)} weight matrices")
# Show a few examples
for name in sorted(weight_matrices.keys())[:6]:
print(f" {name}: {weight_matrices[name].shape}")
# ================================================================
# Compute SVD at target layers
# ================================================================
TARGET_LAYERS = [0, 4, 8, 12, 16, 20, 24, 28, 32]
TARGET_LAYERS = [l for l in TARGET_LAYERS if l < N_LAYERS]
print(f"\n[2/3] Computing SVD at {len(TARGET_LAYERS)} layers ...")
layer_svd = {}
for l in tqdm(TARGET_LAYERS, desc="SVD", ncols=80):
layer_svd[l] = {}
for wtype, prefix in [("attn_out", f"attn_out_L{l}"),
("ffn_down", f"ffn_down_L{l}")]:
if prefix not in weight_matrices:
continue
W = weight_matrices[prefix].detach().float().numpy()
U, S, Vt = np.linalg.svd(W, full_matrices=False)
layer_svd[l][wtype] = {
"shape": list(W.shape),
"top50_sv": S[:50].tolist(),
"dominance_10": float(S[0] / (S[9] + 1e-10)),
"dominance_48": float(S[0] / (S[47] + 1e-10)) if len(S) > 47 else 0,
"top10_var": float((S[:10]**2).sum() / (S**2).sum()),
"top48_var": float((S[:48]**2).sum() / (S**2).sum()),
"top_left_sv": U[:, :48], # don't save to JSON, use for alignment
}
del model; gc.collect()
# ================================================================
# Results
# ================================================================
print(f"\n[3/3] Results")
print("=" * 70)
print(f"\n ATTENTION OUTPUT (W_o) — Eigenvalue Dominance:")
print(f" {'Layer':>6} {'Shape':>14} {'s1/s10':>8} {'s1/s48':>8} "
f"{'Top10%':>8} {'Top48%':>8}")
print(f" {'-'*56}")
for l in TARGET_LAYERS:
d = layer_svd.get(l, {}).get("attn_out", {})
if not d: continue
print(f" {l:>6} {str(d['shape']):>14} {d['dominance_10']:>8.1f} "
f"{d['dominance_48']:>8.1f} {d['top10_var']*100:>7.1f}% "
f"{d['top48_var']*100:>7.1f}%")
print(f"\n FFN DOWN (W_down) — Eigenvalue Dominance:")
print(f" {'Layer':>6} {'Shape':>14} {'s1/s10':>8} {'s1/s48':>8} "
f"{'Top10%':>8} {'Top48%':>8}")
print(f" {'-'*56}")
for l in TARGET_LAYERS:
d = layer_svd.get(l, {}).get("ffn_down", {})
if not d: continue
print(f" {l:>6} {str(d['shape']):>14} {d['dominance_10']:>8.1f} "
f"{d['dominance_48']:>8.1f} {d['top10_var']*100:>7.1f}% "
f"{d['top48_var']*100:>7.1f}%")
# ---- Compare with actual PCA ----
print(f"\n Weight SVD vs Image-Token PCA Alignment:")
PCA_PATHS = [
Path("/content/drive/MyDrive/topohd_illusion/subspaces.npz"),
Path("/content/drive/MyDrive/topohd_corrected/all_bases.npz"),
]
actual_pca = {}
for src in PCA_PATHS:
if not src.exists(): continue
data = np.load(src)
for key in data.files:
for l in TARGET_LAYERS:
if (f"img_{l}" == key) or (f"image" in key and "basis" in key):
actual_pca[l] = data[key]
if "image_basis" in key:
actual_pca["default"] = data[key]
if actual_pca:
print(f" Found PCA at: {list(actual_pca.keys())}")
print(f" {'Layer':>6} {'W_o align':>12} {'W_down align':>14}")
print(f" {'-'*32}")
for l in TARGET_LAYERS:
pca = actual_pca.get(l, actual_pca.get("default", None))
if pca is None: continue
k = min(pca.shape[0], 48)
for wtype in ["attn_out", "ffn_down"]:
sd = layer_svd.get(l, {}).get(wtype, {})
if "top_left_sv" not in sd: continue
U_top = sd["top_left_sv"][:, :k].T # (k, d)
cos = np.abs(pca[:k] @ U_top.T)
align = float(cos.max(axis=1).mean())
sd["pca_alignment"] = align
wo_a = layer_svd.get(l, {}).get("attn_out", {}).get("pca_alignment", "N/A")
wd_a = layer_svd.get(l, {}).get("ffn_down", {}).get("pca_alignment", "N/A")
if wo_a != "N/A" or wd_a != "N/A":
print(f" {l:>6} {wo_a if isinstance(wo_a, str) else f'{wo_a:.4f}':>12} "
f"{wd_a if isinstance(wd_a, str) else f'{wd_a:.4f}':>14}")
else:
print(f" No PCA data found for alignment comparison.")
# ---- Theorem statement ----
print("""
================================================================
THEOREM (Eigenvalue Dominance Principle):
In transformer layer h_l = sigma(W_l * h_(l-1) + b_l), if W_l
has dominant singular values (s1/s_k >> 1), then the top-k PCA
components of ANY token subset converge to the left singular
vectors of W_l, regardless of token content.
PROOF: Output covariance Cov(h) ~ W * Cov(x) * W^T.
By Davis-Kahan, eigenvector perturbation bounded by:
sin(theta) <= ||delta_Cov|| / (s_k^2 - s_(k+1)^2)
Large spectral gap => small perturbation => same eigenvectors.
================================================================
""")
# Verify
all_dom = [layer_svd.get(l, {}).get("attn_out", {}).get("dominance_48", 0)
for l in TARGET_LAYERS]
all_dom = [d for d in all_dom if d > 0]
if all_dom:
print(f" VERIFICATION:")
print(f" s1/s48 range: {min(all_dom):.1f} - {max(all_dom):.1f}")
print(f" Mean: {np.mean(all_dom):.1f}")
if min(all_dom) > 1.5:
print(f" VERIFIED: All layers show spectral dominance.")
print(f" PCA of ANY token subset must capture these dominant modes.")
else:
print(f" PARTIAL: Some layers have weak dominance.")
# Save (without large arrays)
save_results = {}
for l in TARGET_LAYERS:
save_results[str(l)] = {}
for wtype in ["attn_out", "ffn_down"]:
sd = layer_svd.get(l, {}).get(wtype, {})
if sd:
save_results[str(l)][wtype] = {
k: v for k, v in sd.items()
if k != "top_left_sv" and not isinstance(v, np.ndarray)
}
with open(OUT / "theorem_results.json", "w") as f:
json.dump(save_results, f, indent=2)
# Save singular value spectra for figure
spectra = {}
for l in TARGET_LAYERS:
for wtype in ["attn_out", "ffn_down"]:
sd = layer_svd.get(l, {}).get(wtype, {})
if "top50_sv" in sd:
spectra[f"{wtype}_L{l}"] = sd["top50_sv"]
with open(OUT / "sv_spectra.json", "w") as f:
json.dump(spectra, f, indent=2)
print(f"\n Saved to {OUT}/")