Monyzik's picture
Stage frozen training inputs privately for owner review
651b674 verified
Raw History Blame Contribute Delete
8.26 kB
"""Calibrate without val and select checkpoints by complete dev facts."""
from collections import Counter
import hashlib
import importlib.util
import json
import math
from pathlib import Path
import time
from compact_fact_extraction.calon_rag.backend import CalOnBackend, file_hash, attention_backend
from compact_fact_extraction.calon_rag.decoding import entity_events, decode_entities
from compact_fact_extraction.calon_rag.pipeline import CalOnRagPipeline
from compact_fact_extraction.training.supervision import attach_supervision, apply_candidate_masks
def read(path):
return [json.loads(s) for s in Path(path).open() if s.strip()]
def write(path, value):
path=Path(path); path.parent.mkdir(parents=True,exist_ok=True)
temporary=path.with_suffix(path.suffix+'.tmp')
temporary.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False)+'\n')
temporary.replace(path)
def metrics(tp,pred,gold):
return {'tp':int(tp),'pred':int(pred),'gold':int(gold),
'precision':tp/max(1,pred),'recall':tp/max(1,gold),'f1':2*tp/max(1,pred+gold)}
def entity_row(row):
"""Entity calibration must match CalOnBackend's relation-free first pass."""
return {k:v for k,v in row.items() if k not in {'rel_queries','relations'}}
def configuration(root,source,checkpoint):
cfg=json.loads((source/'configs/calon-rag.json').read_text())
cfg['graph']=str(source/'outputs/domain-graph.json'); cfg['index']=str(source/'outputs/domain-index.sqlite')
cfg['model'].update(release_dir=str(root/'assets/calon'),encoder_dir=str(root/'assets/tokenizer'),
checkpoint=str(checkpoint),device='cuda',entity_threshold=.5,relation_threshold=.5,
entity_temperature=1.,relation_temperature=1.,entity_logit_threshold=0.,
null_shift=math.log(1/.3),
span_overlap=.8,calibration_status='uncalibrated')
return cfg
def set_calibration(backend,config,calibration):
t=calibration['entity_logit_threshold']; r=calibration['relation_threshold']
backend.entity_logit_threshold=t; backend.api.cfg['relation_threshold']=r
backend.manifest['calibration'].update(entity_logit_threshold=t,relation_threshold=r)
backend.manifest['calibration_status']='dev_calib'
config['model'].update(entity_logit_threshold=t,relation_threshold=r,calibration_status='dev_calib')
def calibrate(backend,rows_dir,limit=128):
import numpy as np
import torch
from calon.data.collator import encode_row
from calon.eval.evaluate import predict,predict_re
from calon.model.pipeline import _shift_relations
# The same closed label set, utility decoder, overlap suppression and
# resource limits are used here and during real fact inference.
grid=np.array([-4.,-2.,0.,1.,2.,3.,4.,5.,6.,7.,8.,10.,12.,14.,16.,18.,20.,24.,28.,32.,40.])
regrid=np.array([.1,.3,.5,.7,.9,.95,.99,.999])
tp=np.zeros(len(grid),dtype=int); pred=tp.copy(); peak=tp.copy(); gold=0
rtp=np.zeros(len(regrid),dtype=int); rpred=rtp.copy(); rgold=0; rows=0; started=time.time()
with torch.inference_mode(), attention_backend(backend.device):
for source in ('official','synthetic'):
values=read(rows_dir/source/'dev_calib.jsonl')
values=sorted(values,key=lambda r:hashlib.sha256(r['id'].encode()).hexdigest())[:limit if source=='official' else limit//2]
for row in values:
enc=encode_row(entity_row(row),backend.api.tok,32)
out=predict(backend.api.model,[enc],backend.api.collate,backend.device,1)[0]
events=entity_events(enc,out['u'],backend.api.cfg['null_shift'])
gs=set(enc['gold_spans']); gold+=len(gs)
# Margin-priority greedy suppression is monotone in the decision
# threshold: candidates below it cannot suppress candidates above.
es=decode_entities(enc,row['text'],events,float(grid[0]),backend.span_overlap)
for i,threshold in enumerate(grid):
got={(e['start'],e['end'],e['label']) for e in es if e['decision_margin']>=threshold}
tp[i]+=len(got&gs); pred[i]+=len(got); peak[i]=max(peak[i],len(got))
renc=encode_row(row,backend.api.tok,32) if row.get('rel_queries') else {}
if renc.get('pairs'):
p=_shift_relations(predict_re(backend.api.model,[renc],backend.api.collate,backend.device,1),backend.api.cfg['null_shift'])[0]['p']
choices=p[1:].argmax(0); margins=1-p[0]
triples=[(h,t,renc['rel_labels'][int(c)]) for (h,t),c in zip(renc['pair_char'],choices)]
gt=set(renc.get('gold_triples',set())); rgold+=len(gt)
correct=np.array([t in gt for t in triples])
for i,threshold in enumerate(regrid):
keep=margins>=threshold; rpred[i]+=int(keep.sum()); rtp[i]+=int((keep&correct).sum())
rows+=1
entities=[dict(threshold=float(t),peak_entities=int(mx),**metrics(int(a),int(b),gold)) for t,a,b,mx in zip(grid,tp,pred,peak)]
eligible=[v for v in entities if v['peak_entities']<=128]
if not eligible: raise ValueError('No calibrated decoding configuration respects the resource budget')
selected=max(eligible,key=lambda m:(m['f1'],m['precision'],m['threshold']))
relations=[dict(threshold=float(t),**metrics(int(a),int(b),rgold)) for t,a,b in zip(regrid,rtp,rpred)]
rselected=max(relations,key=lambda m:(m['f1'],m['precision'],m['threshold']))
return {'split':'dev_calib','rows':rows,'scope':'partial literal spans, with runtime NMS; relations on reference endpoints',
'entity_logit_threshold':selected['threshold'],'relation_threshold':rselected['threshold'],
'entity':selected,'relation':rselected,'entity_grid':entities,'relation_grid':relations,
'span_overlap':backend.span_overlap,'elapsed_seconds':time.time()-started}
def scorer(path):
spec=importlib.util.spec_from_file_location('official_case_metrics',path)
module=importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
module.load_catalog(str(path)); return module
def evaluate_facts(backend,config,calls,official,output,full_metrics=False):
output=Path(output); output.mkdir(parents=True,exist_ok=False)
graph=json.loads(Path(config['graph']).read_text())
pipe=CalOnRagPipeline(graph,Path(config['index']),backend,windows=config['windows'],retrieval=config['retrieval'],limits=config['limits'])
predictions={}; matched=gold=0; elapsed=[]; errors=[]; reason=Counter()
started=time.time()
with (output/'pred.jsonl').open('x') as pf,(output/'trace.jsonl').open('x') as tf:
for i,c in enumerate(calls,1):
clean={k:c[k] for k in ('call_id','started_at','turns')}
t=time.time()
# A failure blocks selection/evaluation. No call becomes an implicit
# empty result and no difficult call is omitted from the denominator.
facts,trace=pipe.extract_call(clean)
p={'call_id':c['call_id'],'facts':facts}; predictions[c['call_id']]=p
matched+=len(official.match_facts(c['facts'],facts)); gold+=len(c['facts'])
elapsed.append(time.time()-t)
pf.write(json.dumps(p,ensure_ascii=False)+'\n'); pf.flush()
for r in trace:
tf.write(json.dumps(r,ensure_ascii=False)+'\n')
if r.get('reason'): reason[r['reason']]+=1
tf.flush()
if i%25==0 or i==len(calls):
write(output/'progress.json',{'completed':i,'total':len(calls),'elapsed_seconds':time.time()-started})
print('FACT_PROGRESS',output.name,i,len(calls),flush=True)
result=metrics(matched,sum(len(p['facts']) for p in predictions.values()),gold)
result.update(calls=len(calls),elapsed_seconds=time.time()-started,inference_seconds=sum(elapsed),pending_reasons=dict(reason))
if full_metrics:
result['official']=official.evaluate({c['call_id']:c for c in calls},predictions)
write(output/'metrics.json',result); write(output/'manifest.json',pipe.manifest)
return result