"""Anonymous batch reference-coverage silver diagnostic on cached answers. Calibrate against archived *automatic* individual grading on development first. Never equate reference coverage, batch agreement or exact spans with clinical truth. """ import argparse,hashlib,json,random from pathlib import Path from validate_openqa_grader import JUDGE,span from prepare_openqa_dev161_equal_budget import freeze ROOT=Path(__file__).resolve().parent MODELS=['deepseek','luna','qwen25_7b','llama31_8b'] METHODS=['no_rag','bm25','hybrid','oracle','hybrid_parent6000'] PROMPT=JUDGE.split('\nEvaluate EVERY supplied')[0]+'''\nThis is ONLY reference-fact coverage, not source support, medical truth, or overall task accuracy. Evaluate every anonymous candidate INDEPENDENTLY using its own answer only; do not compare/rank candidates or transfer content between them. All reference facts are automatic-silver diagnostics, not a minimum sufficient clinical answer; nonexhaustive examples can be valid without covering every listed reference fact. A true coverage label must convey the ENTIRE fact including qualifiers; a related partial span is insufficient. Do not repair quotes or use another candidate. No reader/model/method identities are supplied. Return ONLY JSON {"candidates":[{"candidate_id":"C...","fact_coverage":[{"index":0,"covered":true,"candidate_quote":"exact candidate span or null"}]}]}. covered is true,false,or"uncertain". Include EVERY supplied candidate and EVERY fact index exactly once. No reasons or extra fields.''' def read(p):return [json.loads(x) for x in p.read_text().splitlines()] def sha(b):return hashlib.sha256(b).hexdigest() def dump(x):return json.dumps(x,ensure_ascii=False) def prepare(): base=ROOT/'miriad_public/openqa_development16';out=ROOT/'miriad_public/openqa_reference_coverage_batch_calibration_v1';out.mkdir(exist_ok=True) items=read(base/'selected_items.jsonl');targets={x['id']:x for x in read(base/'fixed_reference_fact_targets.jsonl')};cases={};inputs={} for model in MODELS: # These are already normalized declared answer extractions. Their exact answer hashes are checked. predictions={ (x['id'],x['method']):x for x in read(base/(model+'_predictions.jsonl')) if not x.get('error')} if model in ['luna','deepseek'] else None # Canonical text-normalized answer-only extraction + source judgments supply the exact historical grader candidate. exts={(x['id'],x['method']):x for x in read(base/('grading_text_'+model)/'claim_extractions.jsonl')} old={(x['id'],x['method']):x for x in read(base/('grading_text_'+model)/'source_judgments.jsonl') if x['judge_requested']=='gpt-6-luna'} # Locate canonical candidate text in fixed source-grade judgments' extraction spans via original predictions. if model in ['luna','deepseek']: predpath=base/(model+'_predictions.jsonl') else: candidates=list((ROOT/'miriad_public').glob('openqa_development16*/'+model+'/predictions.jsonl')) predpath=None # Archived grading_text helpers retain the normalized declared-answer in its own frozen reader frame. inputs[model]={'extractions_sha256':sha((base/('grading_text_'+model)/'claim_extractions.jsonl').read_bytes()),'old_judgments_sha256':sha((base/('grading_text_'+model)/'source_judgments.jsonl').read_bytes())} import sys sys.path.insert(0,str(ROOT.parent/'MeningiomaBench-v1/code')) from response_parsing import normalize_prediction if predpath is None: # Matches the original v2 grading command provenance; locate via small known historical directories. found=[] for root in [base,ROOT/'miriad_public/openqa_development16_readers',ROOT/'miriad_public/openqa_development16_small']: if root.exists():found.extend(root.rglob('predictions.jsonl')) for path in found: rows=read(path) if rows and rows[0].get('model_returned')=={'qwen25_7b':'Qwen/Qwen2.5-7B-Instruct','llama31_8b':'meta-llama/Meta-Llama-3.1-8B-Instruct'}[model]: if {(r['id'],r['method']) for r in rows}==set(exts):predpath=path;break if predpath is None:raise RuntimeError('Locate exact historical small-reader predictions before preparing') preds={} for r in read(predpath): if r.get('error'):continue value=normalize_prediction(r) if not isinstance(value.get('answer'),str) or not value['answer'].strip():value['answer']=(r.get('output') or '').strip() preds[(r['id'],r['method'])]=value for key,ext in exts.items(): answer=preds[key].get('answer');assert isinstance(answer,str) and sha(answer.encode())==ext['answer_sha256'] cases[(key[0],model,key[1])]={'id':key[0],'model':model,'method':key[1],'answer':answer,'old_fact_coverage':old[key].get('judgment',{}).get('fact_coverage',[]),'old_metrics':old[key].get('metrics',{})} inputs[model]['predictions_path']=str(predpath);inputs[model]['predictions_sha256']=sha(predpath.read_bytes()) req=[];mapping=[];reverse_ids={x['id'] for x in sorted(items,key=lambda x:sha(x['id'].encode()))[:4]} for item in items: ident=item['id'];facts=targets[ident]['facts'];entries=[cases[(ident,m,a)] for m in MODELS for a in METHODS];random.Random('coverage-batch-v1:'+ident).shuffle(entries) for order in ['primary']+(['reverse'] if ident in reverse_ids else []): ordered=entries if order=='primary' else list(reversed(entries));cands=[] for e in ordered: cid='C'+sha((e['model']+'|'+e['method']+'|'+ident).encode())[:12];cands.append({'candidate_id':cid,'candidate_answer':e['answer']}) mapping.append({**e,'batch_id':ident+':'+order,'candidate_id':cid,'facts':facts,'reference_task_grade_valid':targets[ident]['reference_task_grade_valid']}) data={'question':item['question'],'fixed_reference_facts':[{'fact':f['fact']} for f in facts],'candidates':cands,'evidence':''} req.append({'id':ident+':'+order,'method':'anonymous_reference_coverage','track':'development_batch_calibration_not_clinical_truth','option_letters':[], 'response_protocol':'reference_coverage_batch_v1','messages':[{'role':'system','content':PROMPT},{'role':'user','content':dump(data)}],'context_sha256':sha(b''),'context_tokens_unified':0}) freeze(out/'requests20_local_only.jsonl',''.join(dump(x)+'\n' for x in req));freeze(out/'mapping400_local_only.jsonl',''.join(dump(x)+'\n' for x in mapping)) protocol={'split':'development','questions':16,'reader_answer_records':320,'reverse_order_questions':4,'new_judge_requests':20,'new_reader_generations':0,'expert_reviews':0,'clinical_truth_validated':False,'inputs':inputs,'request_sha256':sha((out/'requests20_local_only.jsonl').read_bytes()),'code_sha256':sha(Path(__file__).read_bytes()),'judge_prompt_sha256':sha(PROMPT.encode()),'batch_transport_sanity_rule_before_calls':{'minimum_comparable_label_agreement_with_archived_individual_luna':0.90,'maximum_primary_vs_reverse_coverage_disagreement':0.05,'require_all_candidate_and_fact_indices_and_exact_positive_anchors':True},'limits':'Thresholds test transport/conditioning stability only, not clinical correctness. Old automatic judges disagree and none is gold. Frozen targetsets unchanged; no new targetproposals used. Do not score full511 in this batch format unless sanity checks pass; failures retained, no threshold tuning.'} freeze(out/'protocol_before_calls.json',json.dumps(protocol,indent=2)+'\n');freeze(out/'code_snapshot.py',Path(__file__).read_text());print('Prepared20calibrationrequests/400logicalanswers;no new reader calls') if __name__=='__main__':prepare()