import json, math, random, torch, sys sys.path.insert(0,"/root/alea") from alea.eval import load_model, predict_all from transformers import AutoTokenizer ckpt=sys.argv[1]; data=sys.argv[2]; out=sys.argv[3]; n=int(sys.argv[4]) if len(sys.argv)>4 else 4000 dev=torch.device("cuda") tok=AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B") model=load_model(ckpt,"Qwen/Qwen3-0.6B",dev) rows=[json.loads(l) for l in open(data)] random.seed(0); random.shuffle(rows); rows=rows[:n] preds=predict_all(model,tok,rows,dev,max_len=4096) # collect (probs, target) per type ch=[]; sc=[]; nu=[] for r in rows: pr=preds.get(r["id"],{}) for qid,spec in r["questions"].items(): t=r["targets"].get(qid); a=pr.get(qid) if t is None or a is None: continue if spec["type"]=="choice" and a.get("type")=="choice": ch.append((torch.tensor(a["probs"],dtype=torch.float64),torch.tensor(t,dtype=torch.float64))) elif spec["type"]=="score" and a.get("type")=="choice" : sc.append((torch.tensor(a["probs"],dtype=torch.float64),torch.tensor(t,dtype=torch.float64))) elif spec["type"]=="noul" and a.get("type")=="noul": nu.append((a["p"],float(t))) def scale_probs(p,tau): q=torch.log(p.clamp_min(1e-12))/tau return torch.softmax(q,-1) def brier_list(items,tau): s=0 for p,y in items: q=scale_probs(p,tau); s+=((q-y)**2).sum().item() return s/len(items) def noul_brier(items,tau): s=0 for p,y in items: lp=math.log(max(p,1e-9)/(1-max(p,1e-9)))/tau q=1/(1+math.exp(-lp)); s+=(q-y)**2 return s/len(items) best={} for name,items,fn in [("choice",ch,brier_list),("score",sc,brier_list),("noul",nu,noul_brier)]: if not items: best[name]=(1.0,0.0); continue cands=[x/20 for x in range(10,81)] scores=[(t,fn(items,t)) for t in cands] best[name]=min(scores,key=lambda z:z[1]) base=fn(items,1.0) print(f"{name}: n={len(items)} base_brier={base:.4f} tau={best[name][0]:.2f} brier={best[name][1]:.4f}") # bake c=torch.load(ckpt,map_location="cpu") tc=best["choice"][0]; ts=best["score"][0]; tn=best["noul"][0] for k in ["out.weight","out.bias"]: c["heads"]["choice"][k]=c["heads"]["choice"][k]/tc c["heads"]["score"][k]=c["heads"]["score"][k]/ts for k in ["net.3.weight","net.3.bias"]: c["heads"]["noul"][k]=c["heads"]["noul"][k]/tn c["temp_cal"]={"choice":tc,"score":ts,"noul":tn,"fit_data":data,"n":n} torch.save(c,out); print("saved",out)