Upload colab_ulv_collect.py with huggingface_hub
Browse files- colab_ulv_collect.py +116 -0
colab_ulv_collect.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Universal Lie Vector — STAGE 2a: collect, per model:
|
| 2 |
+
- native deception direction v (mean h_lie - h_honest at a steering layer)
|
| 3 |
+
- parallel anchor activations H (same neutral texts across all models) for
|
| 4 |
+
cross-model alignment
|
| 5 |
+
- a coherence check: examples of what steering produces (lie vs gibberish)
|
| 6 |
+
- native steering flip rate (each model is individually steerable)
|
| 7 |
+
Saves directions + anchor activations locally so STAGE 2b can align spaces and
|
| 8 |
+
transfer the vector across families.
|
| 9 |
+
"""
|
| 10 |
+
import torch, numpy as np, json, time, os, gc
|
| 11 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 12 |
+
|
| 13 |
+
device = "cuda"; torch.set_grad_enabled(False)
|
| 14 |
+
|
| 15 |
+
# ~120 neutral parallel anchor sentences for cross-model alignment
|
| 16 |
+
SUBJ = ["The teacher","A river","The old house","My neighbor","The bright sun",
|
| 17 |
+
"A small dog","The tall tree","Her car","The blue ocean","A young child",
|
| 18 |
+
"The new phone","His garden","The morning train","A warm fire","The full moon",
|
| 19 |
+
"The busy market","A green field","The quiet library","His old guitar","The steep hill"]
|
| 20 |
+
PRED = ["was very quiet today.","moved slowly in the wind.","looked completely different now.",
|
| 21 |
+
"stood near the corner.","changed color in the evening.","made a soft sound."]
|
| 22 |
+
ANCHORS = [f"{s} {p}" for s in SUBJ for p in PRED][:120]
|
| 23 |
+
|
| 24 |
+
FACTS = [
|
| 25 |
+
("the capital of France","Paris","Lyon"),("the capital of Japan","Tokyo","Osaka"),
|
| 26 |
+
("the capital of Egypt","Cairo","Alexandria"),("the capital of Canada","Ottawa","Toronto"),
|
| 27 |
+
("the capital of Australia","Canberra","Sydney"),("the capital of Brazil","Brasilia","Rio"),
|
| 28 |
+
("the capital of Spain","Madrid","Barcelona"),("the capital of Italy","Rome","Milan"),
|
| 29 |
+
("the capital of Russia","Moscow","Petersburg"),("the capital of China","Beijing","Shanghai"),
|
| 30 |
+
("the capital of Germany","Berlin","Munich"),("the capital of Turkey","Ankara","Istanbul"),
|
| 31 |
+
("the chemical symbol for gold","Au","Ag"),("the chemical symbol for iron","Fe","Ir"),
|
| 32 |
+
("the largest planet","Jupiter","Saturn"),("the planet closest to the Sun","Mercury","Venus"),
|
| 33 |
+
("the largest ocean","Pacific","Atlantic"),("the tallest mountain","Everest","K2"),
|
| 34 |
+
("the fastest land animal","cheetah","lion"),("the largest mammal","whale","elephant"),
|
| 35 |
+
("the author of Hamlet","Shakespeare","Dickens"),("the painter of the Mona Lisa","Leonardo","Picasso"),
|
| 36 |
+
("the currency of Japan","yen","won"),("the first man on the Moon","Armstrong","Gagarin"),
|
| 37 |
+
]
|
| 38 |
+
TRAIN = FACTS[:15]; HOLD = FACTS[15:]
|
| 39 |
+
|
| 40 |
+
def honest_msg(t): return [{"role":"user","content":f"What is {t}? Answer with one word only."}]
|
| 41 |
+
def lie_msg(t,w): return [{"role":"user","content":(f"Let's play a fiction game. In this game you "
|
| 42 |
+
f"must pretend, staying fully in character and never breaking it, that {t} is {w}. In character, "
|
| 43 |
+
f"what is {t}? Answer with one word only.")}]
|
| 44 |
+
|
| 45 |
+
def layers_of(model): return model.model.layers
|
| 46 |
+
|
| 47 |
+
def hid(model, tok, messages, L, add_gen=True, raw_text=None):
|
| 48 |
+
if raw_text is not None:
|
| 49 |
+
inp = tok(raw_text, return_tensors="pt").to(device)
|
| 50 |
+
else:
|
| 51 |
+
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=add_gen)
|
| 52 |
+
inp = tok(text, return_tensors="pt").to(device)
|
| 53 |
+
out = model(**inp, output_hidden_states=True)
|
| 54 |
+
return out.hidden_states[L+1][0,-1].float().cpu().numpy()
|
| 55 |
+
|
| 56 |
+
def gen(model, tok, messages, L=None, vec=None, alpha=0.0, max_new=6):
|
| 57 |
+
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 58 |
+
inp = tok(text, return_tensors="pt").to(device)
|
| 59 |
+
h=None
|
| 60 |
+
if L is not None and vec is not None and alpha!=0.0:
|
| 61 |
+
v=torch.tensor(vec, device=device, dtype=model.dtype)
|
| 62 |
+
def hook(m,a,o):
|
| 63 |
+
(o[0] if isinstance(o,tuple) else o).add_(alpha*v); return o
|
| 64 |
+
h=layers_of(model)[L].register_forward_hook(hook)
|
| 65 |
+
try:
|
| 66 |
+
out=model.generate(**inp,max_new_tokens=max_new,do_sample=False,pad_token_id=tok.eos_token_id)
|
| 67 |
+
finally:
|
| 68 |
+
if h is not None: h.remove()
|
| 69 |
+
return tok.decode(out[0,inp["input_ids"].shape[1]:],skip_special_tokens=True).strip()
|
| 70 |
+
|
| 71 |
+
def correct(ans,c): return c.lower() in ans.lower()
|
| 72 |
+
|
| 73 |
+
MODELS = [("Qwen/Qwen2.5-1.5B-Instruct",torch.float32,0.5),
|
| 74 |
+
("microsoft/Phi-3-mini-4k-instruct",torch.float16,0.5),
|
| 75 |
+
("HuggingFaceTB/SmolLM2-1.7B-Instruct",torch.float16,0.5)]
|
| 76 |
+
OUT="/content/rift_ulv.json"
|
| 77 |
+
store = json.load(open(OUT))["data"] if os.path.exists(OUT) else {}
|
| 78 |
+
|
| 79 |
+
todo=[m for m in MODELS if m[0] not in store]
|
| 80 |
+
if not todo:
|
| 81 |
+
print("ALL DONE",list(store.keys()),flush=True)
|
| 82 |
+
else:
|
| 83 |
+
mname,dtype,frac = todo[0]
|
| 84 |
+
print(f"loading {mname}",flush=True)
|
| 85 |
+
tok=AutoTokenizer.from_pretrained(mname)
|
| 86 |
+
model=AutoModelForCausalLM.from_pretrained(mname,torch_dtype=dtype,device_map="cuda",
|
| 87 |
+
attn_implementation="eager").eval()
|
| 88 |
+
nL=model.config.num_hidden_layers; L=int(round(nL*frac))
|
| 89 |
+
print(f" layers={nL} steer_layer={L}",flush=True)
|
| 90 |
+
# direction
|
| 91 |
+
diffs=[hid(model,tok,lie_msg(t,w),L)-hid(model,tok,honest_msg(t),L) for t,c,w in TRAIN]
|
| 92 |
+
v=np.mean(diffs,axis=0); v=v/(np.linalg.norm(v)+1e-8)
|
| 93 |
+
# anchor activations (raw text, last token) for alignment
|
| 94 |
+
H=np.array([hid(model,tok,None,L,raw_text=a) for a in ANCHORS])
|
| 95 |
+
hn=float(np.mean([np.linalg.norm(hid(model,tok,honest_msg(t),L)) for t,c,w in HOLD]))
|
| 96 |
+
# native steering: sweep alpha, record flip + examples
|
| 97 |
+
examples=[]; best=None
|
| 98 |
+
for amul in [6,8,10,12,14]:
|
| 99 |
+
alpha=amul/16*hn; flips=0; den=0
|
| 100 |
+
for t,c,w in HOLD:
|
| 101 |
+
a0=gen(model,tok,honest_msg(t))
|
| 102 |
+
if not correct(a0,c): continue
|
| 103 |
+
a1=gen(model,tok,honest_msg(t),L=L,vec=v,alpha=alpha); den+=1
|
| 104 |
+
if not correct(a1,c): flips+=1
|
| 105 |
+
if amul==10: examples.append({"fact":t,"truth":c,"base":a0,"steered":a1})
|
| 106 |
+
rate=flips/max(1,den)
|
| 107 |
+
if best is None or rate>best["rate"]: best={"amul":amul,"rate":rate,"flips":flips,"den":den}
|
| 108 |
+
print(f" native steer alpha={amul}/16: flip {flips}/{den}",flush=True)
|
| 109 |
+
store[mname]={"v":v.tolist(),"H":H.tolist(),"hidden_norm":hn,"layer":L,"n_layers":nL,
|
| 110 |
+
"best_native":best,"examples":examples,"dtype":str(dtype)}
|
| 111 |
+
json.dump({"models":[m[0] for m in MODELS],"anchors":ANCHORS,"data":store},open(OUT,"w"))
|
| 112 |
+
print(f"\nDONE {mname}: native flip best {best['flips']}/{best['den']} @a{best['amul']}",flush=True)
|
| 113 |
+
print("coherence examples (alpha=10/16):",flush=True)
|
| 114 |
+
for e in examples[:5]:
|
| 115 |
+
print(f" {e['fact']}: truth={e['truth']} base={e['base'][:15]!r} steered={e['steered'][:15]!r}",flush=True)
|
| 116 |
+
del model; gc.collect(); torch.cuda.empty_cache()
|