amlc-work / code /scripts /embed_f05.py
Arushhh's picture
e5 fine-tune: encode/eval job scripts, prep scripts, eval scripts with e5-ft
5f3280f verified
Raw History Blame Contribute Delete
11.2 kB
"""Judging-metric (macro F0.5) evaluation of zero-shot similarity models on the embed_eval pool.
For each model: cosine top-50 per query -> isotonic calibration (fit on fold A entities) -> expected-F0.5 decoding
+ one-parent rule -> macro F0.5 on fold B (swap, average). Real singleton S1 entities are added to the queries.
Runs on the L4 box: /opt/pytorch/bin/python embed_f05.py"""
import os, sys, time, json, re, unicodedata, gc
import numpy as np, pandas as pd, torch, duckdb
sys.path.insert(0, os.environ.get('AMLC_BASE','/opt/dlami/nvme/amlc')+'/code')
from src.decode import best_subset
from src.metric import f05_entity
from sklearn.isotonic import IsotonicRegression
BASE=os.environ.get('AMLC_BASE','/opt/dlami/nvme/amlc'); CACHE=f'{BASE}/embed_eval_cache'; SC=f'{BASE}/embed_f05_cache'; os.makedirs(SC, exist_ok=True)
N_SING=400; K=50; SEED=7; dev='cuda' if torch.cuda.is_available() else 'cpu'
def log(*a): print(f"[{time.strftime('%H:%M:%S')}]", *a, flush=True)
ev=pd.read_parquet(f'{BASE}/parquet/embed_eval_set.parquet')
MODELS={'bge-m3':dict(hf='BAAI/bge-m3',dtype=torch.float16,qp=None,dp=None),
'e5-large':dict(hf='intfloat/multilingual-e5-large',dtype=torch.float16,qp='query: ',dp='query: '),
'qwen3-0.6b':dict(hf='Qwen/Qwen3-Embedding-0.6B',dtype=torch.bfloat16,qp_name='query',dp=None,left=True),
'qwen3-4b':dict(hf='Qwen/Qwen3-Embedding-4B',dtype=torch.bfloat16,qp_name='query',dp=None,left=True),
'e5-ft':dict(hf=os.environ.get('FT_MODEL','Arushhh/amlc-e5-ft'),dtype=torch.float16,qp='query: ',dp='query: ')} # fine-tuned e5-large
avail=[k for k in MODELS if os.path.exists(f'{CACHE}/{k}__full.npy')]; log("cached models:", avail)
# ---- singleton queries (real S1 entities with no matches), per country
if os.environ.get('SING_PARQUET'): # same sample, pre-computed with the query below (e.g. for an HF job without amlc.duckdb)
sing=pd.read_parquet(os.environ['SING_PARQUET'])
else:
con=duckdb.connect(f'{BASE}/amlc.duckdb', read_only=True); con.execute("SET memory_limit='8GB'; SET threads=4")
sing=con.execute(f"""SELECT x.entity_id, x.business_name, x.business_address, x.country FROM gt g JOIN s1 x ON x.entity_id=g.source1_entity_id
WHERE g.matched_entity_ids='' AND x.country IN ('US','India') QUALIFY row_number() OVER (PARTITION BY x.country ORDER BY hash(x.entity_id||'sing{SEED}'))<={N_SING}""").df()
con.close()
sing['text_full']=np.where(sing.business_address.str.strip().str.len()>0, sing.business_name.str.strip()+' | '+sing.business_address.str.strip(), sing.business_name.str.strip())
log("singletons:", sing.country.value_counts().to_dict())
def encode_singletons(key):
cp=f'{SC}/{key}__sing.npy'
if os.path.exists(cp): return np.load(cp)
from sentence_transformers import SentenceTransformer
cfg=MODELS[key]; m=SentenceTransformer(cfg['hf'], model_kwargs={'torch_dtype':cfg['dtype']}, device=dev)
if cfg.get('left'): m.tokenizer.padding_side='left'
m.max_seq_length=64
qp=cfg.get('qp') if 'qp' in cfg else m.prompts.get(cfg['qp_name'])
e=m.encode(sing.text_full.tolist(), batch_size=64, prompt=qp, normalize_embeddings=True, convert_to_numpy=True).astype(np.float16)
np.save(cp,e); del m; gc.collect(); torch.cuda.empty_cache(); return e
def norm_txt(s):
s=unicodedata.normalize('NFKD',s); s=''.join(c for c in s if not unicodedata.combining(c)).lower(); return re.sub(r'[^a-z0-9]+',' ',s).strip()
def topk_dense(Q,P,k):
Qt=torch.from_numpy(np.asarray(Q,dtype=np.float32)).to(dev); Pt=torch.from_numpy(np.asarray(P,dtype=np.float32)).to(dev)
vals=[];idx=[]
for s in range(0,Qt.shape[0],512):
sim=Qt[s:s+512]@Pt.T; v,i=torch.topk(sim,k,dim=1); vals.append(v.cpu().numpy()); idx.append(i.cpu().numpy())
del Qt,Pt; torch.cuda.empty_cache(); return np.vstack(vals), np.vstack(idx)
def decide_and_score(qids, truth, cand_ids, cand_sim, cand_lab, tag):
"""qids: list of query ids; truth: dict qid->set; cand_*: arrays (nq,K). Two-fold isotonic + expected-F0.5 decode + one-parent."""
nq=len(qids); rng=np.random.default_rng(SEED); fold=rng.integers(0,2,nq); out={}
for f in (0,1):
tr=np.nonzero(fold!=f)[0]; te=np.nonzero(fold==f)[0]
iso=IsotonicRegression(out_of_bounds='clip', y_min=0.0, y_max=1.0).fit(cand_sim[tr].ravel(), cand_lab[tr].ravel())
# global threshold chosen on the training fold by macro F0.5
best_t,best_s=None,-1
lab_tr=cand_lab[tr]; sim_tr=cand_sim[tr]; ntrue=np.array([len(truth[qids[i]]) for i in tr],dtype=np.float32)
for t in np.linspace(0.5,0.99,50):
sel=sim_tr>=t; npred=sel.sum(1); tp=(sel*lab_tr).sum(1)
P=np.where(npred>0,tp/np.maximum(npred,1),0.0); Rc=np.where(ntrue>0,tp/np.maximum(ntrue,1),0.0)
fv=np.where(tp>0,1.25*P*Rc/np.maximum(0.25*P+Rc,1e-9),0.0); fv=np.where((ntrue==0)&(npred==0),1.0,fv)
s=float(fv.mean())
if s>best_s: best_s,best_t=s,t
prob=iso.predict(cand_sim[te].ravel()).reshape(len(te),K)
chosen={}; claims={}
for r,i in enumerate(te):
p=prob[r]; order=np.argsort(-p); k,_=best_subset(p[order]); sel=[(cand_ids[i][order[j]], p[order[j]]) for j in range(k)]
chosen[qids[i]]=sel
for cid,pp in sel: claims.setdefault(cid,[]).append((pp,qids[i]))
# one-parent rule: a pool record keeps only its highest-probability claimant
keep={cid:max(v)[1] for cid,v in claims.items()}
pred={q:{cid for cid,pp in sel if keep[cid]==q} for q,sel in chosen.items()}
pred_t={qids[i]:{cand_ids[i][j] for j in range(K) if cand_sim[i][j]>=best_t} for i in te}
sc=[f05_entity(pred[qids[i]], truth[qids[i]]) for i in te]; sct=[f05_entity(pred_t[qids[i]], truth[qids[i]]) for i in te]
is_s=np.array([len(truth[qids[i]])==0 for i in te]); sing_ok=np.mean([len(pred[qids[i]])==0 for i in te if len(truth[qids[i]])==0])
prec=np.mean([len(pred[qids[i]]&truth[qids[i]])/len(pred[qids[i]]) for i in te if pred[qids[i]]]) ; rec=np.mean([len(pred[qids[i]]&truth[qids[i]])/len(truth[qids[i]]) for i in te if truth[qids[i]]])
out[f]=dict(macro_f05_decoder=float(np.mean(sc)), macro_f05_threshold=float(np.mean(sct)), thr=float(best_t), f05_nonsingleton=float(np.mean(np.array(sc)[~is_s])), singleton_empty_rate=float(sing_ok), mean_precision=float(prec), mean_recall=float(rec), n=len(te))
agg={k:(out[0][k]+out[1][k])/2 for k in out[0] if k!='n'}; agg['n']=out[0]['n']+out[1]['n']; agg['tag']=tag; return agg
results=[]
for c in ['US','India']:
in_c=(ev.eval_country==c).to_numpy(); isq=(ev.role=='query').to_numpy()
qrows=np.nonzero(in_c&isq)[0]; prows=np.nonzero(in_c&~isq)[0]
qids=ev.entity_id.to_numpy()[qrows].tolist(); pool_ids=ev.entity_id.to_numpy()[prows]; pool_mo=ev.match_of.to_numpy()[prows]
srows=np.nonzero((sing.country==c).to_numpy())[0]; sids=sing.entity_id.to_numpy()[srows].tolist()
all_q=qids+sids; truth={q:set() for q in all_q}
for pid,mo in zip(pool_ids,pool_mo):
if mo is not None and mo in truth: truth[mo].add(pid)
npairs=sum(len(v) for v in truth.values()); log(f"{c}: {len(qids)} matched queries + {len(sids)} singletons, pool {len(prows)}, true pairs {npairs}")
sims={}
for key in avail:
E=np.load(f'{CACHE}/{key}__full.npy', mmap_mode='r'); Es=encode_singletons(key)[srows]
Q=np.vstack([np.asarray(E[qrows]), Es]); P=np.asarray(E[prows])
v,i=topk_dense(Q,P,K); sims[key]=(v,i)
r20=np.mean([len(set(pool_ids[i[r][:20]])&truth[all_q[r]])/len(truth[all_q[r]]) for r in range(len(qids)) if truth[all_q[r]]])
log(f" {key}: sanity recall@20 (pair-weighted) ~ {r20:.4f}")
# TF-IDF char 3-gram baseline on the same pool (CPU)
from sklearn.feature_extraction.text import TfidfVectorizer
txt_q=[norm_txt(t) for t in ev.text_full.to_numpy()[qrows]]+[norm_txt(t) for t in sing.text_full.to_numpy()[srows]]; txt_p=[norm_txt(t) for t in ev.text_full.to_numpy()[prows]]
vec=TfidfVectorizer(analyzer='char', ngram_range=(3,3), sublinear_tf=True, dtype=np.float32).fit(txt_p+txt_q)
Qs=vec.transform(txt_q); Ps=vec.transform(txt_p)
vals=[];idx=[]
for s in range(0,Qs.shape[0],1000):
S=(Qs[s:s+1000]@Ps.T).toarray(); i=np.argpartition(-S,K,axis=1)[:,:K]; v=np.take_along_axis(S,i,axis=1); o=np.argsort(-v,axis=1); vals.append(np.take_along_axis(v,o,axis=1)); idx.append(np.take_along_axis(i,o,axis=1))
sims['tfidf-char3']=(np.vstack(vals),np.vstack(idx)); log(" tfidf done")
# ensembles: union of top-50 lists with z-scored cosine average (missing entries get the model's min z)
def zs(v): mu,sd=v.mean(),v.std()+1e-9; return (v-mu)/sd
Z={kk:zs(sims[kk][0]) for kk in sims} # z-scored once per model
def ensemble(keys):
out_v=[];out_i=[]
for r in range(len(all_q)):
d={}
for kk in keys:
z=Z[kk][r]; ids=sims[kk][1][r]
for j in range(K): d.setdefault(ids[j],{})[kk]=z[j]
rows=[(sum(dd.get(kk, Z[kk][r].min()) for kk in keys)/len(keys), pid) for pid,dd in d.items()]
rows.sort(reverse=True); rows=rows[:K]
out_v.append([x for x,_ in rows]+[-9.0]*(K-len(rows))); out_i.append([p for _,p in rows]+[rows[-1][1]]*(K-len(rows)))
return np.array(out_v,dtype=np.float32), np.array(out_i)
ens={}
if 'e5-large' in sims and 'bge-m3' in sims: ens['ens:e5+bge']=ensemble(['e5-large','bge-m3'])
if 'e5-large' in sims: ens['ens:e5+tfidf']=ensemble(['e5-large','tfidf-char3'])
if 'e5-large' in sims and 'qwen3-4b' in sims: ens['ens:e5+qwen4b']=ensemble(['e5-large','qwen3-4b'])
if 'e5-large' in sims and 'bge-m3' in sims: ens['ens:e5+bge+tfidf']=ensemble(['e5-large','bge-m3','tfidf-char3'])
if 'e5-ft' in sims: ens['ens:e5ft+tfidf']=ensemble(['e5-ft','tfidf-char3'])
sims.update(ens)
for key,(v,i) in sims.items():
cand_ids=pool_ids[i]; cand_lab=np.array([[1.0 if cid in truth[all_q[r]] else 0.0 for cid in cand_ids[r]] for r in range(len(all_q))],dtype=np.float32)
res=decide_and_score(all_q, truth, cand_ids, v.astype(np.float32), cand_lab, f"{c}/{key}"); res['country']=c; res['model']=key; results.append(res)
log(f" {c:5s} {key:18s} macroF0.5(decoder)={res['macro_f05_decoder']:.4f} (threshold={res['macro_f05_threshold']:.4f} @{res['thr']:.2f}) non-singleton={res['f05_nonsingleton']:.4f} singleton_empty={res['singleton_empty_rate']:.3f} P={res['mean_precision']:.3f} R={res['mean_recall']:.3f}")
df=pd.DataFrame(results)[['country','model','macro_f05_decoder','macro_f05_threshold','thr','f05_nonsingleton','singleton_empty_rate','mean_precision','mean_recall','n']]
pd.set_option('display.width',250); print("\n=== MACRO F0.5 (judging metric) on the 142k-record pool, 2-fold calibrated, real singletons included (5.9% of queries) ===")
print(df.round(4).to_string(index=False))
df.to_csv(f'{BASE}/embed_f05_results.csv', index=False); json.dump(results, open(f'{BASE}/embed_f05_results.json','w'), indent=1)
os.system(f'aws s3 cp {BASE}/embed_f05_results.csv s3://amlc-2026-478982785786/ckpt/embed_eval/ >/dev/null 2>&1')
log("DONE")