STER / code /ster_proto.py
eduzrh's picture
Few-shot optimization closeout: prototype+combo heads; WM gain confirmed K<=5; honest K>=10 tree recovery; docs+logs updated
44673a5 verified
Raw
History Blame Contribute Delete
4.7 kB
"""
STER — few-shot PROTOTYPE head in the WM embedding space (GPU).
Metric methods are the most sample-efficient at very low K (kNN was best at K=5).
We build a relation vector r(c,i) = [ |e_c - e_i| , e_c*e_i ] in the pretrained WM
identity space, then classify a test pair by cosine-distance to the POSITIVE vs
NEGATIVE prototype (mean relation vector of the K labelled pos/neg). Sample-efficient,
no tree overfitting.
Compares at K in {5,10,20,50}:
bar_raw_bagging, wm_cos, wm_proto (ours), wm_proto+raw_fusion
"""
import os, json, numpy as np, torch, torch.nn as nn, torch.nn.functional as F
from sklearn.ensemble import BaggingClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import f1_score
from scipy.stats import rankdata
NPZ="/root/ster/data/ster_wm_vectors.npz"; OUT="/root/ster/exp/ster_proto_results.json"
DEV="cuda" if torch.cuda.is_available() else "cpu"; torch.manual_seed(1); np.random.seed(1)
z=np.load(NPZ,allow_pickle=True); lod12,lod22,candX,indexX=z["lod12_X"],z["lod22_X"],z["cand_X"],z["index_X"]
trP,trY,teP,teY=z["train_pairs"],z["train_y"],z["test_pairs"],z["test_y"]; DIM=lod12.shape[1]
sc=StandardScaler().fit(np.vstack([lod12,lod22,candX,indexX]))
def T(x): return torch.tensor(sc.transform(x),dtype=torch.float32,device=DEV)
L12,L22,CAND,INDEX=T(lod12),T(lod22),T(candX),T(indexX)
class Enc(nn.Module):
def __init__(s,d):
super().__init__(); s.net=nn.Sequential(nn.Linear(d,64),nn.GELU(),nn.Linear(64,64),nn.GELU(),nn.Linear(64,32))
def forward(s,x): return F.normalize(s.net(x),dim=-1)
def info_nce(a,b,tau=0.1):
lg=a@b.t()/tau; lab=torch.arange(a.size(0),device=a.device); return .5*(F.cross_entropy(lg,lab)+F.cross_entropy(lg.t(),lab))
enc=Enc(DIM).to(DEV); opt=torch.optim.Adam(enc.parameters(),1e-3,weight_decay=1e-5)
for ep in range(400):
p=torch.randperm(L12.size(0),device=DEV)
for i in range(0,L12.size(0),256):
b=p[i:i+256]
if b.numel()<8: continue
loss=info_nce(enc(L12[b]),enc(L22[b])); opt.zero_grad(); loss.backward(); opt.step()
enc.eval()
with torch.no_grad(): ec=enc(CAND).cpu().numpy(); ei=enc(INDEX).cpu().numpy()
def relvec(P):
a,b=ec[P[:,0]],ei[P[:,1]]; return np.concatenate([np.abs(a-b),a*b],1)
def ratio(P):
a,b=candX[P[:,0]],indexX[P[:,1]]
with np.errstate(divide='ignore',invalid='ignore'): r=np.where(b!=0,a/b,1000.0)
return np.clip(np.round(r,3),None,1000.0)
R_tr,R_te=relvec(trP),relvec(teP); raw_tr,raw_te=ratio(trP),ratio(teP)
cos_tr=np.sum(ec[trP[:,0]]*ei[trP[:,1]],1); cos_te=np.sum(ec[teP[:,0]]*ei[teP[:,1]],1)
def unit(x): return x/(np.linalg.norm(x,axis=-1,keepdims=True)+1e-8)
Ru_te=unit(R_te)
def thr_from(s,y): return float(np.median([np.quantile(s[y==1],.2) if (y==1).any() else .5, np.quantile(s[y==0],.8) if (y==0).any() else .5]))
Ks,NDRAW=[5,10,20,50],15
pos=np.where(trY==1)[0]; neg=np.where(trY==0)[0]; report={}
for K in Ks:
acc={k:[] for k in ["bar_raw_bagging","wm_cos","wm_proto","wm_proto_raw_fusion"]}
for rep in range(NDRAW):
r=np.random.RandomState(300+rep)
pidx=r.choice(pos,K,replace=False); nidx=r.choice(neg,min(2*K,len(neg)),replace=False)
idx=np.concatenate([pidx,nidx]); y=trY[idx]
clf=BaggingClassifier(n_estimators=50,random_state=1).fit(raw_tr[idx],y)
pb_te=clf.predict_proba(raw_te)[:,1]
acc["bar_raw_bagging"].append(f1_score(teY,(pb_te>=0.5).astype(int),zero_division=0))
tc=thr_from(cos_tr[idx],y); acc["wm_cos"].append(f1_score(teY,(cos_te>=tc).astype(int),zero_division=0))
# prototype: mean relation vec of pos & neg in the K set
proto_p=unit(R_tr[idx][y==1].mean(0)[None])[0]; proto_n=unit(R_tr[idx][y==0].mean(0)[None])[0]
sp=Ru_te@proto_p - Ru_te@proto_n # >0 -> closer to positive prototype
acc["wm_proto"].append(f1_score(teY,(sp>=0).astype(int),zero_division=0))
# fusion of proto score + bagging prob (rank)
fr=0.5*rankdata(sp)/len(sp)+0.5*rankdata(pb_te)/len(pb_te)
sp_tr=(unit(R_tr[idx])@proto_p - unit(R_tr[idx])@proto_n)
fr_tr=0.5*np.array([(sp<v).mean() for v in sp_tr])+0.5*rankdata(clf.predict_proba(raw_tr[idx])[:,1])/len(idx)
acc["wm_proto_raw_fusion"].append(f1_score(teY,(fr>=thr_from(fr_tr,y)).astype(int),zero_division=0))
report[K]={k:dict(f1=round(float(np.mean(v)),4),std=round(float(np.std(v)),4)) for k,v in acc.items()}
print(f"\n=== K={K} ===",flush=True)
for k,s in sorted(report[K].items(),key=lambda kv:-kv[1]['f1']): print(f" {k:22s} F1={s['f1']:.4f} ±{s['std']:.4f}",flush=True)
os.makedirs(os.path.dirname(OUT),exist_ok=True); json.dump(report,open(OUT,"w"),indent=2); print("\nSaved ->",OUT,flush=True)