STER / code /ster_flow_v2.py
eduzrh's picture
4B Flow zero-shot v2 (direction-cosine) confirmed to fail -> insight: transfer identity-invariance (WM), not transformation (flow)
cdff63d verified
Raw
History Blame Contribute Delete
4.14 kB
"""
STER — Flow-Matching zero-shot v2 (4B, fixed).
v1 failed (F1 0.006): used raw residual MAGNITUDE for the score, whose scale shifts
across domains -> threshold calibrated on multi-LoD was meaningless on Hague.
v2 fix: use a SCALE-INVARIANT flow-DIRECTION score. Train Conditional Flow Matching
v_theta transporting LoD1.2 props -> LoD2.2 props. A true pair (a,b) should have the
learned velocity field pointing along (b-a) at every t. Score = mean_t cos(v_theta(x_t,t), b-a),
which is domain-robust. Also test a bidirectional variant (fit both directions).
Threshold calibrated ONLY on held-out multi-LoD. Zero Hague labels.
"""
import os, json, numpy as np, torch, torch.nn as nn, torch.nn.functional as F
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import f1_score, precision_score, recall_score
NPZ="/root/ster/data/ster_wm_vectors.npz"; OUT="/root/ster/exp/ster_flow_v2_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=z["lod12_X"],z["lod22_X"]
candX,indexX=z["cand_X"],z["index_X"]; teP,teY=z["test_pairs"],z["test_y"]
DIM=lod12.shape[1]; N=lod12.shape[0]
sc=StandardScaler().fit(np.vstack([lod12,lod22,candX,indexX]))
L12,L22=sc.transform(lod12),sc.transform(lod22); CAND,INDEX=sc.transform(candX),sc.transform(indexX)
idx=np.random.permutation(N); mtr,mcal=idx[:int(.8*N)],idx[int(.8*N):]
nbrs=NearestNeighbors(n_neighbors=6).fit(L22); _,knn=nbrs.kneighbors(L12)
class VNet(nn.Module):
def __init__(s,d):
super().__init__(); s.net=nn.Sequential(nn.Linear(d+1,128),nn.GELU(),nn.Linear(128,128),nn.GELU(),nn.Linear(128,d))
def forward(s,x,t): return s.net(torch.cat([x,t],-1))
def train_flow(x0,x1,epochs=800):
v=VNet(DIM).to(DEV); opt=torch.optim.Adam(v.parameters(),1e-3,weight_decay=1e-5)
X0=torch.tensor(x0,dtype=torch.float32,device=DEV); X1=torch.tensor(x1,dtype=torch.float32,device=DEV)
for ep in range(epochs):
p=torch.randperm(X0.size(0),device=DEV)
for i in range(0,X0.size(0),256):
b=p[i:i+256]
if b.numel()<8: continue
t=torch.rand(b.numel(),1,device=DEV); xt=(1-t)*X0[b]+t*X1[b]
loss=F.mse_loss(v(xt,t),X1[b]-X0[b]); opt.zero_grad(); loss.backward(); opt.step()
v.eval(); return v
vf=train_flow(L12[mtr],L22[mtr]) # LoD1.2 -> LoD2.2
vb=train_flow(L22[mtr],L12[mtr]) # reverse (for bidirectional)
@torch.no_grad()
def dir_cos(v,a,b,ts=(0.2,0.4,0.6,0.8)):
a=torch.tensor(a,dtype=torch.float32,device=DEV); b=torch.tensor(b,dtype=torch.float32,device=DEV)
if a.dim()==1: a=a[None]; b=b[None]
d=b-a; dn=F.normalize(d,dim=-1); acc=torch.zeros(a.size(0),device=DEV)
for t in ts:
tt=torch.full((a.size(0),1),t,device=DEV); xt=(1-t)*a+t*b
acc+=F.cosine_similarity(v(xt,tt),dn,dim=-1)
return (acc/len(ts)).cpu().numpy()
def score_fwd(a,b): return dir_cos(vf,a,b)
def score_bi(a,b): return 0.5*(dir_cos(vf,a,b)+dir_cos(vb,b,a))
def calib(scorefn):
pos=scorefn(L12[mcal],L22[mcal])
negs=[]
for i in mcal:
for j in knn[i][1:3]:
if j!=i: negs.append(scorefn(L12[[i]],L22[[j]])[0])
return pos,np.array(negs)
def evaluate(name,scorefn):
pos,neg=calib(scorefn); thr=float(np.median([np.quantile(pos,.2),np.quantile(neg,.8)]))
st=scorefn(CAND[teP[:,0]],INDEX[teP[:,1]]); pred=(st>=thr).astype(int)
return dict(thr=round(thr,3),f1=round(f1_score(teY,pred,zero_division=0),4),
precision=round(precision_score(teY,pred,zero_division=0),4),recall=round(recall_score(teY,pred,zero_division=0),4))
report={"flow_fwd_dircos":evaluate("fwd",score_fwd),"flow_bidir_dircos":evaluate("bi",score_bi)}
print("\n=== FLOW ZERO-SHOT v2 (direction cosine, 0 Hague labels) ===",flush=True)
for k,s in sorted(report.items(),key=lambda kv:-kv[1]['f1']): print(f" {k:22s} F1={s['f1']:.4f} P={s['precision']} R={s['recall']}",flush=True)
os.makedirs(os.path.dirname(OUT),exist_ok=True); json.dump(report,open(OUT,"w"),indent=2); print("Saved ->",OUT,flush=True)