STER / code /ster_combo.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
5.15 kB
"""
STER — few-shot SAMPLE-EFFICIENT combined head (GPU).
The prototype/cosine heads win only at K=5; trees recover by K=10 but overfit at
very low K. The documented flagship "safety net" is: augment the raw-ratio vector
with the WM identity-relation vector and feed a SAMPLE-EFFICIENT linear model
(L2-regularised LogisticRegression) instead of a tree. LR needs far fewer labels
than Bagging, so it should hold the K<=10 regime while combined features add signal.
Compares at K in {5,10,20,50}:
raw_bagging (baseline) | raw_lr | wm_lr | combo_lr (ours) | combo_lr+wmcos_fusion
"""
import os, json, numpy as np, torch, torch.nn as nn, torch.nn.functional as F
from sklearn.ensemble import BaggingClassifier
from sklearn.linear_model import LogisticRegression
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_combo_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_te=np.sum(ec[teP[:,0]]*ei[teP[:,1]],1)
# standardise feature families for the linear model
rs=StandardScaler().fit(raw_tr); raw_tr_s,raw_te_s=rs.transform(raw_tr),rs.transform(raw_te)
Rs=StandardScaler().fit(R_tr); R_tr_s,R_te_s=Rs.transform(R_tr),Rs.transform(R_te)
combo_tr=np.concatenate([raw_tr_s,R_tr_s],1); combo_te=np.concatenate([raw_te_s,R_te_s],1)
def fit_pred(Xtr,ytr,Xte,kind):
if kind=="bag": m=BaggingClassifier(n_estimators=50,random_state=1)
else: m=LogisticRegression(C=0.5,max_iter=2000,class_weight="balanced")
m.fit(Xtr,ytr); return m.predict_proba(Xte)[:,1]
Ks,NDRAW=[5,10,20,50],15
pos=np.where(trY==1)[0]; neg=np.where(trY==0)[0]; report={}
for K in Ks:
keys=["raw_bagging","raw_lr","wm_lr","combo_lr","combo_lr_wmcos_fusion"]
acc={k:[] for k in keys}
for rep in range(NDRAW):
r=np.random.RandomState(400+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]
pb=fit_pred(raw_tr[idx],y,raw_te,"bag"); acc["raw_bagging"].append(f1_score(teY,(pb>=.5).astype(int),zero_division=0))
pr=fit_pred(raw_tr_s[idx],y,raw_te_s,"lr"); acc["raw_lr"].append(f1_score(teY,(pr>=.5).astype(int),zero_division=0))
pw=fit_pred(R_tr_s[idx],y,R_te_s,"lr"); acc["wm_lr"].append(f1_score(teY,(pw>=.5).astype(int),zero_division=0))
pc=fit_pred(combo_tr[idx],y,combo_te,"lr"); acc["combo_lr"].append(f1_score(teY,(pc>=.5).astype(int),zero_division=0))
# fusion: combo_lr prob (rank) + wm cosine (rank), threshold by median-cross on train draw
pc_tr=fit_pred(combo_tr[idx],y,combo_tr[idx],"lr")
cos_tr_idx=np.sum(ec[trP[idx][:,0]]*ei[trP[idx][:,1]],1)
fr=0.5*rankdata(pc)/len(pc)+0.5*rankdata(cos_te)/len(cos_te)
fr_tr=0.5*rankdata(pc_tr)/len(pc_tr)+0.5*rankdata(cos_tr_idx)/len(cos_tr_idx)
thr=float(np.median([np.quantile(fr_tr[y==1],.2) if (y==1).any() else .5,np.quantile(fr_tr[y==0],.8) if (y==0).any() else .5]))
acc["combo_lr_wmcos_fusion"].append(f1_score(teY,(fr>=thr).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:24s} 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)