Model: Xirui1208/selective-readtwice-7b-early-evaluated-20260928 Source: Original Platform
49 lines
3.8 KiB
Python
49 lines
3.8 KiB
Python
"""Evidence-supervised initialization; does not replace outcome-based RL."""
|
|
import argparse,json,random,time
|
|
import torch
|
|
import torch.nn.functional as F
|
|
from runtime import ROOT,CFG,read_jsonl,atomic_json
|
|
from gate import Gate,seed_everything,batch_pages,labels_for,predict
|
|
|
|
def main():
|
|
ap=argparse.ArgumentParser(); ap.add_argument('--epochs',type=int,default=CFG['sft_epochs']); ap.add_argument('--batch-size',type=int,default=4); ap.add_argument('--accumulation',type=int,default=2); a=ap.parse_args()
|
|
seed_everything(CFG['seed']); start=time.time()
|
|
examples={x['id']:x for x in read_jsonl(ROOT/'data/train.jsonl')}
|
|
prepared=read_jsonl(ROOT/'data/train.prepared.jsonl')
|
|
if set(x['id'] for x in prepared)!=set(examples): raise ValueError('Incomplete training preparation')
|
|
records=[(page,labels_for(examples[p['id']],page)) for p in prepared for page in p['pages']]
|
|
calex={x['id']:x for x in read_jsonl(ROOT/'data/calibration.jsonl')}
|
|
cal=read_jsonl(ROOT/'data/calibration.prepared.jsonl')
|
|
if set(x['id'] for x in cal)!=set(calex): raise ValueError('Incomplete calibration preparation')
|
|
gate=Gate(); opt=torch.optim.AdamW([p for p in gate.parameters() if p.requires_grad],lr=CFG['sft_lr'],weight_decay=.01)
|
|
print(json.dumps({'train_pages':len(records),'trainable_parameters':sum(p.numel() for p in gate.parameters() if p.requires_grad)}),flush=True)
|
|
best=float('inf'); step=0; history=[]
|
|
for epoch in range(a.epochs):
|
|
random.shuffle(records); gate.train(); opt.zero_grad(set_to_none=True)
|
|
batches=list(batch_pages(records,a.batch_size)); losses=[]
|
|
for bi,batch in enumerate(batches):
|
|
logits=torch.cat(gate([p for p,_ in batch])); targets=torch.tensor([y for _,ys in batch for y in ys],device='cuda:0',dtype=torch.float32)
|
|
loss=F.binary_cross_entropy_with_logits(logits,targets,pos_weight=torch.tensor(3.,device='cuda:0'))
|
|
# Correct scale for the final incomplete accumulation group.
|
|
group_size=min(a.accumulation,len(batches)-(bi//a.accumulation)*a.accumulation)
|
|
(loss/group_size).backward(); losses.append(loss.item())
|
|
if (bi+1)%a.accumulation==0 or bi+1==len(batches):
|
|
grad=torch.nn.utils.clip_grad_norm_([p for p in gate.parameters() if p.requires_grad],1.)
|
|
if not torch.isfinite(grad): raise RuntimeError('Non-finite SFT gradient')
|
|
opt.step(); opt.zero_grad(set_to_none=True); step+=1
|
|
if step%5==0: print(json.dumps({'phase':'sft','epoch':epoch+1,'step':step,'loss':sum(losses[-10:])/len(losses[-10:]),'seconds':round(time.time()-start)}),flush=True)
|
|
probs=predict(gate,cal); tp=fn=fp=tn=0; cal_loss=0; count=0
|
|
for uid,ps in probs.items():
|
|
ys=calex[uid]['gold_labels']; p=torch.tensor(ps).clamp(1e-6,1-1e-6); y=torch.tensor(ys,dtype=torch.float32)
|
|
cal_loss+=float((-3*y*p.log()-(1-y)*(1-p).log()).sum()); count+=len(ys)
|
|
for v,target in zip(ps,ys):
|
|
pred=v>=.2; tp+=int(pred and target); fn+=int(not pred and target); fp+=int(pred and not target); tn+=int(not pred and not target)
|
|
metrics={'epoch':epoch+1,'step':step,'cal_weighted_bce':cal_loss/count,'cal_gold_recall_at_02':tp/max(tp+fn,1),'cal_read_fraction_at_02':(tp+fp)/(tp+fp+tn+fn),'seconds':time.time()-start}
|
|
history.append(metrics); print(json.dumps(metrics),flush=True)
|
|
gate.save(ROOT/'checkpoints'/f'sft-epoch-{epoch+1}',{'training':'gold_evidence_sft','metrics':metrics})
|
|
if metrics['cal_weighted_bce']<best:
|
|
best=metrics['cal_weighted_bce']; gate.save(ROOT/'checkpoints/sft',{'training':'gold_evidence_sft','metrics':metrics})
|
|
atomic_json(ROOT/'logs/sft_metrics.json',history)
|
|
print('SFT_COMPLETE',flush=True)
|
|
if __name__=='__main__': main()
|