"""Select threshold ONLY on calibration, then run the frozen choice on test.""" import argparse,asyncio,json,math,time,gc from pathlib import Path import numpy as np from runtime import CFG,ROOT,Reader,tokenizer,read_jsonl,atomic_json from gate import Gate,predict def select_chunks(probs,threshold,forced): selected={i for i,p in enumerate(probs) if p>=threshold}|set(forced) if not selected: selected.add(max(range(len(probs)),key=lambda i:probs[i])) return sorted(selected) def aggregate(results,prepared): n=len(results); base=[prepared[r['id']]['baseline'] for r in results] def mean(key,rows): return float(np.mean([r[key] for r in rows])) tokens=sum(r['usage']['prompt_tokens']+r['usage']['completion_tokens'] for r in results) base_tokens=sum(r['usage']['prompt_tokens']+r['usage']['completion_tokens'] for r in base) skim=sum(sum(prepared[r['id']]['skim_usage'].values()) for r in results) gate=sum(sum(p['input_tokens'] for p in prepared[r['id']]['pages']) for r in results) regressions=[r['id'] for r,b in zip(results,base) if b['em'] and not r['em']] gains=[r['id'] for r,b in zip(results,base) if not b['em'] and r['em']] delta=np.array([r['em']-b['em'] for r,b in zip(results,base)]) rng=np.random.default_rng(20260921); boot=delta[rng.integers(0,n,size=(5000,n))].mean(1) return {'n':n,'em':mean('em',results),'f1':mean('f1',results),'baseline_em':mean('em',base),'baseline_f1':mean('f1',base), 'em_difference':float(delta.mean()),'em_difference_bootstrap_95ci':np.quantile(boot,[.025,.975]).tolist(), 'read_token_fraction':mean('read_token_fraction',results),'second_pass_tokens_saved':1-mean('read_token_fraction',results), 'read_chunk_fraction':sum(r['read_chunks'] for r in results)/sum(r['total_chunks'] for r in results), 'gold_complete_rate':mean('gold_complete',results),'gold_sentence_recall':mean('gold_recall',results), 'regression_count':len(regressions),'gain_count':len(gains),'regression_ids':regressions,'gain_ids':gains, 'all_stage_logical_token_savings':1-(skim+gate+tokens)/(skim+base_tokens), 'token_accounting_note':'Counts logical input + generated tokens including all first-pass SKIM and Gate prompts; not wall-time or FLOP savings.', 'first_pass_all_chunks':True,'max_page_prompt_tokens':max(p['input_tokens'] for r in results for p in prepared[r['id']]['pages']), 'capped_memory_updates':sum(r['capped_memory_updates'] for r in results)} async def evaluate_thresholds(reader,examples,prepared,probabilities,thresholds,outpath): sem=asyncio.Semaphore(48); all_results={} async def one(ex,threshold): async with sem: uid=ex['id']; p=prepared[uid] return await reader.rollout(ex,p,select_chunks(probabilities[uid],threshold,p['force_read_ids'])) for threshold in thresholds: results=await asyncio.gather(*(one(ex,threshold) for ex in examples)) all_results[str(threshold)]={'metrics':aggregate(results,prepared),'results':results} atomic_json(outpath,all_results) print(json.dumps({'threshold':threshold,**all_results[str(threshold)]['metrics']}),flush=True) return all_results async def main(args): adapter=Path(args.adapter).resolve(); tok=tokenizer() calibration=read_jsonl(ROOT/'data/calibration.jsonl'); calprep={p['id']:p for p in read_jsonl(ROOT/'data/calibration.prepared.jsonl')} gate=Gate(adapter,trainable=False) cal_probs=predict(gate,list(calprep.values())) atomic_json(adapter/'calibration_probabilities.json',cal_probs) if args.phase=='calibrate': # Once probabilities are materialized, QA rollouts need only the # frozen reader. Release the gate so shared GPUs retain headroom. del gate gc.collect() import torch torch.cuda.empty_cache() async with Reader(tok) as reader: if args.phase=='calibrate': outcomes=await evaluate_thresholds(reader,calibration,calprep,cal_probs,args.thresholds,adapter/'calibration_results.json') eligible=[(float(t),v) for t,v in outcomes.items() if v['metrics']['em']+1e-10>=v['metrics']['baseline_em'] and v['metrics']['f1']+1e-10>=v['metrics']['baseline_f1']] # A conservative threshold is always explicitly evaluated; no gold in inference. if not eligible: raise RuntimeError('No calibrated policy meets read-all EM and F1; do not promote this checkpoint') threshold,best=min(eligible,key=lambda tv:(tv[1]['metrics']['read_token_fraction'],tv[1]['metrics']['regression_count'])) selection={'adapter':str(adapter),'threshold':threshold,'minimum_read_chunks':1,'calibration_metrics':best['metrics'], 'criterion':'calibration EM >= read-all EM AND F1 >= read-all F1; minimize second-pass read tokens', 'test_not_used_for_selection':True,'config':CFG} atomic_json(adapter/'selection.json',selection); print('CALIBRATION_COMPLETE',flush=True) if adapter.name.startswith('rl-step-'): candidates=[] for file in (ROOT/'checkpoints').glob('rl-step-*/selection.json'): candidate=json.loads(file.read_text()) metrics=candidate['calibration_metrics'] if metrics['em']>=metrics['baseline_em'] and metrics['f1']>=metrics['baseline_f1']: candidates.append(candidate) chosen=min(candidates,key=lambda c:(c['calibration_metrics']['read_token_fraction'],c['calibration_metrics']['regression_count'])) atomic_json(ROOT/'selected_checkpoint.json',{'selected':chosen,'candidates':candidates,'selected_at_unix':time.time(),'selection_inputs':'calibration results only; no test results loaded'}) else: selection=json.loads((adapter/'selection.json').read_text()); threshold=selection['threshold'] test=read_jsonl(ROOT/'data/test.jsonl'); testprep={p['id']:p for p in read_jsonl(ROOT/'data/test.prepared.jsonl')} if set(testprep)!=set(x['id'] for x in test): raise ValueError('Incomplete test preparation') probs=predict(gate,list(testprep.values())); atomic_json(adapter/'test_probabilities.json',probs) outcome=await evaluate_thresholds(reader,test,testprep,probs,[threshold],adapter/'test_results.json') atomic_json(adapter/'evaluation.json',{'selection':selection,'test':outcome[str(threshold)]['metrics'], 'limitation':'128 examples held out from this gate training; base-model exposure unknown. Point estimates do not establish statistical non-inferiority.'}) print('TEST_COMPLETE',flush=True) if __name__=='__main__': ap=argparse.ArgumentParser(); ap.add_argument('--adapter',required=True); ap.add_argument('--phase',choices=['calibrate','test'],required=True) ap.add_argument('--thresholds',nargs='+',type=float,default=[.0,.005,.01,.02,.03,.06,.12,.2,.35,.5]); args=ap.parse_args() asyncio.run(main(args))