Anonymousblind's picture
Upload folder using huggingface_hub
17373f3 verified
Raw
History Blame Contribute Delete
21 kB
#!/usr/bin/env python3
"""
PCAS: Pixel-Critical Arbitration Steering
============================================
Step 1: Mine pixel-critical COCO examples (text priors wrong)
Step 2: Learn steering vector v_L per layer (max image-text divergence)
Step 3: PCAS decoding + ablation + amplification
Step 4: Layer sweep + evaluation
Setup:
!pip install -q transformers accelerate bitsandbytes torch torchvision \
scikit-learn scipy Pillow requests tqdm
"""
import os, json, gc, re, warnings
from pathlib import Path
from io import BytesIO
from collections import defaultdict
import numpy as np
import requests
import torch
import torch.nn.functional as F
from PIL import Image
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_pcas")
OUT.mkdir(exist_ok=True, parents=True)
print("=" * 65)
print("PCAS: Pixel-Critical Arbitration Steering")
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)
cat_id2name = {c["id"]: c["name"] for c in coco_data["categories"]}
img2cats = defaultdict(set)
for a in coco_data["annotations"]:
img2cats[a["image_id"]].add(cat_id2name[a["category_id"]])
img2file = {i["id"]: i["file_name"] for i in coco_data["images"]}
SYNS={"person":["person","man","woman","boy","girl","child","people","men","women","lady","kid","children","guy","player","rider"],"bicycle":["bicycle","bike"],"car":["car","automobile","vehicle"],"motorcycle":["motorcycle","motorbike"],"airplane":["airplane","plane","aircraft","jet"],"bus":["bus"],"train":["train"],"truck":["truck"],"boat":["boat","ship","sailboat"],"traffic light":["traffic light","stoplight"],"fire hydrant":["fire hydrant","hydrant"],"stop sign":["stop sign"],"bench":["bench"],"bird":["bird"],"cat":["cat","kitten"],"dog":["dog","puppy"],"horse":["horse","pony"],"sheep":["sheep","lamb"],"cow":["cow","cattle","bull"],"elephant":["elephant"],"bear":["bear"],"zebra":["zebra"],"giraffe":["giraffe"],"backpack":["backpack","bag","rucksack"],"umbrella":["umbrella"],"handbag":["handbag","purse"],"tie":["tie","necktie"],"suitcase":["suitcase","luggage"],"frisbee":["frisbee"],"skis":["skis","ski"],"snowboard":["snowboard"],"sports ball":["ball","baseball","football","soccer ball","tennis ball","basketball"],"kite":["kite"],"baseball bat":["baseball bat","bat"],"baseball glove":["baseball glove","glove","mitt"],"skateboard":["skateboard"],"surfboard":["surfboard"],"tennis racket":["tennis racket","racket"],"bottle":["bottle"],"wine glass":["wine glass","glass","goblet"],"cup":["cup","mug"],"fork":["fork"],"knife":["knife"],"spoon":["spoon"],"bowl":["bowl"],"banana":["banana"],"apple":["apple"],"sandwich":["sandwich"],"orange":["orange"],"broccoli":["broccoli"],"carrot":["carrot"],"hot dog":["hot dog","hotdog"],"pizza":["pizza"],"donut":["donut","doughnut"],"cake":["cake"],"chair":["chair","seat"],"couch":["couch","sofa"],"potted plant":["potted plant","plant","flower","flowers"],"bed":["bed"],"dining table":["dining table","table","desk"],"toilet":["toilet"],"tv":["tv","television","monitor","screen"],"laptop":["laptop","computer"],"mouse":["mouse"],"remote":["remote"],"keyboard":["keyboard"],"cell phone":["cell phone","phone","cellphone","smartphone"],"microwave":["microwave"],"oven":["oven","stove"],"toaster":["toaster"],"sink":["sink"],"refrigerator":["refrigerator","fridge"],"book":["book","books"],"clock":["clock"],"vase":["vase"],"scissors":["scissors"],"teddy bear":["teddy bear","stuffed animal"],"hair drier":["hair drier","hair dryer"],"toothbrush":["toothbrush"]}
S2C={}
for c,ss in SYNS.items():
for s in ss: S2C[s.lower()]=c
def chair_eval(cap, gt):
cl = cap.lower(); mentioned = set()
for s in sorted(S2C, key=len, reverse=True):
if re.search(r'\b'+re.escape(s)+r'\b', cl): mentioned.add(S2C[s])
if not mentioned:
return dict(halluc=False, chair_i=0.0, n_mentioned=0, n_halluc=0)
h = mentioned - gt
return dict(halluc=len(h)>0, chair_i=len(h)/len(mentioned),
n_mentioned=len(mentioned), n_halluc=len(h))
COCO_URL = "http://images.cocodataset.org/val2014/{}"
_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) < 400: _ic[iid] = im
return im
CHECKPOINT = OUT / "pcas_checkpoint.json"
results = {}
if CHECKPOINT.exists():
with open(CHECKPOINT) as f:
results = json.load(f)
# ================================================================
# STEP 1: Mine pixel-critical examples
# ================================================================
print("\n[1/5] Mining pixel-critical examples ...")
# Scene-object priors: common objects expected in scenes
SCENE_PRIORS = {
"street": {"car", "truck", "bus", "traffic light", "person"},
"kitchen": {"person", "dining table", "chair", "oven", "refrigerator"},
"park": {"person", "dog", "bench", "bird"},
"beach": {"person", "surfboard", "umbrella"},
"living room": {"couch", "tv", "person", "chair"},
"bedroom": {"bed", "person", "lamp"},
"restaurant": {"person", "dining table", "chair", "bottle", "cup"},
}
# Find images where expected objects are MISSING
# These are pixel-critical: text says "kitchen" → expect person, table
# but image only has unusual objects
np.random.seed(42)
all_ids = list(img2cats.keys())
np.random.shuffle(all_ids)
pixel_critical = [] # images where common priors are wrong
normal_images = [] # typical images for comparison
for iid in all_ids:
gt = img2cats[iid]
# Check if image is "surprising" - has fewer than expected common objects
common_objects = {"person", "car", "dog", "cat", "chair", "dining table",
"cup", "bottle", "tv", "couch", "bed", "truck", "bus"}
n_common = len(gt & common_objects)
n_total = len(gt)
if n_total >= 2 and n_common == 0:
# Image has objects but NONE of the common ones → text priors will be wrong
pixel_critical.append(iid)
elif n_total >= 3 and n_common >= 2:
normal_images.append(iid)
if len(pixel_critical) >= 150 and len(normal_images) >= 200:
break
print(f" Pixel-critical images (no common objects): {len(pixel_critical)}")
print(f" Normal images (common objects present): {len(normal_images)}")
# ================================================================
# STEP 2: Learn steering vectors v_L
# ================================================================
TARGET_LAYERS = [8, 16, 24, 32]
N_TRAIN = 100 # pixel-critical images for learning v_L
if "vectors_built" not in results:
print(f"\n[2/5] Learning steering vectors from {N_TRAIN} pixel-critical examples ...")
from transformers import LlavaForConditionalGeneration, AutoProcessor
model = LlavaForConditionalGeneration.from_pretrained(
"llava-hf/llava-1.5-7b-hf", torch_dtype=torch.float16,
low_cpu_mem_usage=True, device_map="auto",
attn_implementation="eager")
proc = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
model.eval()
HDIM = model.config.text_config.hidden_size
PROMPT = "USER: <image>\nDescribe this image in detail.\nASSISTANT:"
blank_image = Image.new("RGB", (336, 336), (128, 128, 128))
diffs = {l: [] for l in TARGET_LAYERS}
delta_scores = [] # KL divergence per example
# Find lm_head for KL computation
lm_head = None
for name, mod in model.named_modules():
if name.endswith("lm_head"):
lm_head = mod; break
for iid in tqdm(pixel_critical[:N_TRAIN], desc="Learning v_L", ncols=80):
try:
image = load_img(iid)
# With image
inp_img = proc(text=PROMPT, images=image, return_tensors="pt")
inp_img = {k: v.to(model.device) for k, v in inp_img.items()}
with torch.no_grad():
out_img = model(**inp_img, output_hidden_states=True)
# Without image (blank)
inp_txt = proc(text=PROMPT, images=blank_image, return_tensors="pt")
inp_txt = {k: v.to(model.device) for k, v in inp_txt.items()}
with torch.no_grad():
out_txt = model(**inp_txt, output_hidden_states=True)
# Collect diffs at last token position per layer
for l in TARGET_LAYERS:
if l >= len(out_img.hidden_states) or l >= len(out_txt.hidden_states):
continue
h_i = out_img.hidden_states[l][0, -1, :].cpu().float().numpy()
h_t = out_txt.hidden_states[l][0, -1, :].cpu().float().numpy()
if np.isnan(h_i).any() or np.isnan(h_t).any(): continue
d = h_i - h_t
if np.linalg.norm(d) > 1e-8:
diffs[l].append(d)
# Compute KL divergence (arbitration score)
logits_img = out_img.logits[0, -1, :].float()
logits_txt = out_txt.logits[0, -1, :].float()
p = F.softmax(logits_img, dim=-1)
q = F.softmax(logits_txt, dim=-1)
kl = F.kl_div(q.log(), p, reduction='sum').item()
delta_scores.append(kl)
del out_img, out_txt; torch.cuda.empty_cache()
except:
torch.cuda.empty_cache()
# Learn v_L: top singular vector of diffs
steering_vectors = {}
for l in TARGET_LAYERS:
if len(diffs[l]) < 20: continue
D = np.array(diffs[l])
valid = ~np.isnan(D).any(axis=1) & ~np.isinf(D).any(axis=1)
D = D[valid]
U, S, Vt = np.linalg.svd(D, full_matrices=False)
v_L = Vt[0] # top singular vector
v_L = v_L / (np.linalg.norm(v_L) + 1e-8)
steering_vectors[l] = v_L
var_exp = S[0]**2 / (S**2).sum()
print(f" Layer {l}: v_L from {D.shape[0]} diffs, "
f"top SV explains {var_exp:.1%} variance")
print(f" Mean Δ (KL) on pixel-critical: {np.mean(delta_scores):.4f}")
np.savez_compressed(OUT / "steering_vectors.npz",
**{f"v_{l}": v for l, v in steering_vectors.items()})
results["vectors_built"] = True
results["HDIM"] = HDIM
results["mean_delta"] = float(np.mean(delta_scores))
results["n_train"] = len(diffs[TARGET_LAYERS[0]])
with open(CHECKPOINT, "w") as f:
json.dump(results, f, indent=2)
# Keep model loaded for evaluation
print(" Keeping LLaVA loaded for evaluation ...")
else:
print("\n[2/5] Loading pre-built steering vectors ...")
sv_data = np.load(OUT / "steering_vectors.npz")
steering_vectors = {int(k.split("_")[1]): sv_data[k] for k in sv_data.files}
HDIM = results["HDIM"]
from transformers import LlavaForConditionalGeneration, AutoProcessor
model = LlavaForConditionalGeneration.from_pretrained(
"llava-hf/llava-1.5-7b-hf", torch_dtype=torch.float16,
low_cpu_mem_usage=True, device_map="auto",
attn_implementation="eager")
proc = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
model.eval()
lm_head = None
for name, mod in model.named_modules():
if name.endswith("lm_head"):
lm_head = mod; break
# ================================================================
# STEP 3: PCAS decoding (amplification + ablation)
# ================================================================
print(f"\n[3/5] PCAS decoding evaluation ...")
N_EVAL = 200
eval_ids = normal_images[:N_EVAL] # evaluate on normal images (not training set)
PROMPT_CAP = ("USER: <image>\nDescribe this image in detail. "
"Mention all objects you can see.\nASSISTANT:")
class PCASSteering:
"""Amplify or ablate the steering vector component at generation time."""
def __init__(self, lm_head_mod, v_L_tensor, mode="amplify", beta=0.5):
self.lm_head = lm_head_mod
self.v = v_L_tensor # (d,)
self.mode = mode # "amplify", "ablate", or "none"
self.beta = beta
self.last_h = None
def capture(self, module, args):
try: self.last_h = args[0][:, -1:, :].detach()
except: pass
return args
def steer(self, module, args):
if self.mode == "none" or self.last_h is None:
return args
try:
h_full = args[0].clone()
h = h_full[:, -1:, :].float()
v = self.v.to(h.device).unsqueeze(0).unsqueeze(0) # (1,1,d)
# Scalar projection
s = (h * v).sum(dim=-1, keepdim=True) # (B,1,1)
if self.mode == "amplify":
# Boost the arbitration component
h_new = h + self.beta * s * v
elif self.mode == "ablate":
# Remove the arbitration component
h_new = h - s * v
else:
h_new = h
h_full[:, -1:, :] = h_new.half()
return (h_full,) + args[1:] if len(args) > 1 else (h_full,)
except:
return args
# Evaluate at the best layer (16) plus layer sweep
CONDITIONS = [
("baseline", 16, "none", 0),
("pcas_L16_b0.3", 16, "amplify", 0.3),
("pcas_L16_b0.5", 16, "amplify", 0.5),
("pcas_L16_b1.0", 16, "amplify", 1.0),
("ablate_L16", 16, "ablate", 0),
("pcas_L8", 8, "amplify", 0.5),
("pcas_L24", 24, "amplify", 0.5),
("pcas_L32", 32, "amplify", 0.5),
]
eval_results = {}
for cond_name, layer, mode, beta in CONDITIONS:
if cond_name in results.get("eval_results", {}):
print(f" {cond_name}: already done. Skipping.")
eval_results[cond_name] = results["eval_results"][cond_name]
continue
if layer not in steering_vectors and mode != "none":
print(f" {cond_name}: no vector for layer {layer}. Skipping.")
continue
v_L = torch.tensor(steering_vectors.get(layer, np.zeros(HDIM)),
dtype=torch.float32)
pcas = PCASSteering(lm_head, v_L, mode=mode, beta=beta)
h1 = lm_head.register_forward_pre_hook(pcas.capture)
h2 = lm_head.register_forward_pre_hook(pcas.steer)
records = []
for iid in tqdm(eval_ids, desc=cond_name[:20], ncols=80):
try:
image = load_img(iid)
gt = img2cats[iid]
inp = proc(text=PROMPT_CAP, images=image, return_tensors="pt")
inp = {k: v.to(model.device) for k, v in inp.items()}
n_prompt = inp["input_ids"].shape[1]
with torch.no_grad():
gen = model.generate(**inp, max_new_tokens=200, do_sample=False)
cap = proc.decode(gen[0, n_prompt:], skip_special_tokens=True).strip()
ch = chair_eval(cap, gt)
ch["n_tokens"] = int(gen.shape[1] - n_prompt)
records.append(ch)
del gen; torch.cuda.empty_cache()
except:
torch.cuda.empty_cache()
h1.remove(); h2.remove()
hr = sum(r["halluc"] for r in records) / len(records) if records else 0
ci = np.mean([r["chair_i"] for r in records]) if records else 0
mt = np.mean([r["n_tokens"] for r in records]) if records else 0
mo = np.mean([r["n_mentioned"] for r in records]) if records else 0
eval_results[cond_name] = dict(halluc=float(hr), chair_i=float(ci),
tokens=float(mt), objects=float(mo),
n=len(records))
# Checkpoint
results["eval_results"] = eval_results
with open(CHECKPOINT, "w") as f:
json.dump(results, f, indent=2, default=float)
print(f" {cond_name}: halluc={hr*100:.1f}% CHAIR_I={ci:.4f} "
f"tok={mt:.0f} obj={mo:.1f}")
# ================================================================
# STEP 4: Gibberish test on PCAS vectors
# ================================================================
print(f"\n[4/5] Gibberish test on PCAS steering vectors ...")
del model, proc; gc.collect(); torch.cuda.empty_cache()
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")
tok = AutoTokenizer.from_pretrained("lmsys/vicuna-7b-v1.5")
vicuna.eval()
GIB_PROMPTS = {
"visual": [
"A kitchen with a table, chairs, and a refrigerator.",
"A beach with surfers and umbrellas.", "A park with dogs and trees.",
"A street with cars and traffic lights.", "A farm with cows and a barn.",
"A zoo with elephants.", "A restaurant with wine glasses.",
"A bedroom with a bed and lamp.", "A classroom with desks.",
"A grocery store with produce.",
],
"gibberish": [
"Xkq plm wvt zzz brrn.", "Qwzyx nkl jjj hhh ttttt.",
"Aaaa bbbb cccc dddd.", "Mlkj hgfd sapo iuyt.",
"Fghjkl zxcvbnm qwerty.", "Jjjjj kkkkk lllll.",
"Bnmz xkwq plrv.", "Wwww xxxx yyyy zzzz.",
"Vcxz nmbl kpoj.", "Rrrr ssss tttt uuuu.",
],
}
rng = np.random.RandomState(42)
random_vec = rng.randn(HDIM).astype(np.float32)
random_vec /= np.linalg.norm(random_vec)
gib_test = {}
for pt, prompts in GIB_PROMPTS.items():
for l in steering_vectors:
for vname, vec in [("pcas", steering_vectors[l]), ("random", random_vec)]:
key = f"{pt}|{vname}|{l}"
gib_test[key] = []
for prompt in prompts:
inp = tok(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)
if l < len(out.hidden_states):
h = out.hidden_states[l][0, -1, :].cpu().float().numpy()
if not np.isnan(h).any():
proj = abs(float(np.dot(h, vec))) / (np.linalg.norm(h) + 1e-8)
gib_test[key].append(proj)
del out; torch.cuda.empty_cache()
del vicuna, tok; gc.collect(); torch.cuda.empty_cache()
print(f"\n PCAS Gibberish Test (single vector projection):")
print(f" {'Layer':>6} {'Vis|PCAS':>10} {'Gib|PCAS':>10} {'Gib/Vis':>8} "
f"{'Vis|Rnd':>10} {'Gib|Rnd':>10}")
print(f" {'-'*55}")
for l in sorted(steering_vectors.keys()):
vp = np.mean(gib_test.get(f"visual|pcas|{l}", [0]))
gp = np.mean(gib_test.get(f"gibberish|pcas|{l}", [0]))
vr = np.mean(gib_test.get(f"visual|random|{l}", [0]))
gr = np.mean(gib_test.get(f"gibberish|random|{l}", [0]))
gv = gp / (vp + 1e-8)
print(f" {l:>6} {vp:>10.4f} {gp:>10.4f} {gv:>7.2f} {vr:>10.4f} {gr:>10.4f}")
# ================================================================
# RESULTS SUMMARY
# ================================================================
print(f"\n[5/5] Results Summary")
print("=" * 70)
baseline_hr = eval_results.get("baseline", {}).get("halluc", 0)
print(f"\n {'Condition':<22} {'Halluc%':>8} {'Delta':>8} {'CHAIR_I':>8} "
f"{'Tokens':>7} {'Objects':>8}")
print(f" {'-'*62}")
for cname in ["baseline", "pcas_L16_b0.3", "pcas_L16_b0.5", "pcas_L16_b1.0",
"ablate_L16", "pcas_L8", "pcas_L24", "pcas_L32"]:
d = eval_results.get(cname, {})
if not d: continue
hr = d["halluc"]
delta = f"({(hr-baseline_hr)*100:+.1f}pp)" if cname != "baseline" else "(base)"
print(f" {cname:<22} {hr*100:>7.1f}% {delta:>8} {d['chair_i']:>8.4f} "
f"{d['tokens']:>7.0f} {d['objects']:>8.1f}")
# Verdict
best_cond = min((c for c in eval_results if c != "baseline"),
key=lambda c: eval_results[c]["halluc"], default=None)
if best_cond:
best = eval_results[best_cond]
print(f"\n Best: {best_cond}{best['halluc']*100:.1f}% "
f"({(best['halluc']-baseline_hr)*100:+.1f}pp)")
if best["halluc"] < baseline_hr - 0.02:
print(f"\n >>> PCAS REDUCES HALLUCINATION <<<")
print(f" Pixel-critical arbitration steering works.")
print(f" This is a constructive contribution grounded in")
print(f" arbitration theory, not PCA-based visual subspaces.")
else:
print(f"\n >>> PCAS EFFECT IS SMALL OR ABSENT <<<")
results["eval_results"] = eval_results
results["gib_test"] = {k: [float(x) for x in v] for k, v in gib_test.items()}
with open(CHECKPOINT, "w") as f:
json.dump(results, f, indent=2, default=float)
print(f"\n Saved to {OUT}/")