MeningiomaBench / code /audit_minicheck_development.py
dfdu233's picture
Silver research draft; expert review pending
3627825 verified
Raw History Blame Contribute Delete
4.5 kB
"""Control detection and agreement with two automatic silver source judges."""
import argparse,collections,json
from pathlib import Path
ROOT=Path(__file__).resolve().parent/'miriad_public/minicheck_development_calibration_v1'
def read(p):return [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else []
def stats(pairs):
cells=collections.Counter((int(y),int(p)) for y,p,s in pairs);positives=sum(y==1 for y,p,s in pairs);negatives=sum(y==0 for y,p,s in pairs)
sensitivity=cells[1,1]/positives if positives else None;specificity=cells[0,0]/negatives if negatives else None
# Rank-based AUROC with tie averaging; against SILVER labels, not medical truth.
rank_sum=0.;ordered=sorted(pairs,key=lambda x:x[2]);offset=0
while offset<len(ordered):
end=offset+1
while end<len(ordered) and ordered[end][2]==ordered[offset][2]:end+=1
rank=(offset+1+end)/2;rank_sum+=rank*sum(x[0]==1 for x in ordered[offset:end]);offset=end
return {'unique_pairs':len(pairs),'supported_labels':positives,'unsupported_labels':negatives,'confusion_reference_rows_metric_columns':{f'{a}:{b}':cells[a,b] for a in [0,1] for b in [0,1]},
'binary_label_agreement':(cells[0,0]+cells[1,1])/len(pairs) if pairs else None,'supported_recall_against_silver':sensitivity,'unsupported_recall_against_silver':specificity,
'balanced_label_agreement':(sensitivity+specificity)/2 if sensitivity is not None and specificity is not None else None,
'auroc_against_silver':(rank_sum-positives*(positives+1)/2)/(positives*negatives) if positives and negatives else None}
def main():
p=argparse.ArgumentParser();p.add_argument('--partial',action='store_true');args=p.parse_args();inputs=read(ROOT/'source_claim_pairs_local_only.jsonl');preds={}
for r in read(ROOT/'minicheck_predictions_local_only.jsonl'):assert r['id'] not in preds;preds[r['id']]=r
if not args.partial:assert len(preds)==len(inputs),'Need completed metric; no replacement of missing rows'
byjudge=collections.defaultdict(list);consensus=[];controls=[];disagree=0;missing=0;internally_inconsistent=collections.Counter()
for row in inputs:
if row['id'] not in preds:continue
pred=preds[row['id']];label=pred['label'];score=pred['support_probability'];valid={}
for judge,labels in row['old_judge_labels'].items():
binary={int(x=='supported') for x in labels}
if len(binary)==1:
value=next(iter(binary));valid[judge]=value;byjudge[judge].append((value,label,score))
else:internally_inconsistent[judge]+=1
if len(valid)==2:
if len(set(valid.values()))==1:consensus.append((next(iter(valid.values())),label,score))
else:disagree+=1
else:missing+=1
if row['control_labels']:
assert len(set(row['control_labels']))==1;controls.append((int(row['control_labels'][0]),label,score))
report={'scope':'Historical16development-source claim calibration; not medical accuracy, expert ground truth, untouchedtest or clinical calibration.',
'complete':len(preds)==len(inputs),'unique_document_claim_pairs':len(inputs),'metric_outputs':len(preds),'logical_claim_records':len(read(ROOT/'claim_logical_mapping_local_only.jsonl')),
'control_unique_pairs':stats(controls),'agreement_against_each_automatic_judge':{k:stats(v) for k,v in byjudge.items()},'agreement_against_unanimous_two_judge_silver_only':stats(consensus),
'between_judge_disagreements_retained':disagree,'missing_or_internally_inconsistent_judge_labels':missing,'within_judge_binary_inconsistency':dict(internally_inconsistent),
'truncated_document_claim_chunks':sum(r['truncated_chunk_count'] for r in preds.values()),'total_model_seconds':sum(r['seconds'] for r in preds.values()),'expert_reviews':0,'new_reader_generations':0,'new_cloud_api_calls':0,
'limits':'All existing extracted claims retained independent of current metric. Source passages can merge different document sections/cases; literal passage support is not study-role entailment. Max-over-chunks can over-support. Missing source support is not medical falsehood. Scores are not calibrated clinical probabilities. Repeated logical claims are not independent validation examples. No automatic acceptance upgrade or solved-negative-RAG claim.'}
(ROOT/'calibration_audit.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
if __name__=='__main__':main()