MeningiomaBench / code /audit_population_binding_challenge_development.py
dfdu233's picture
Silver research draft; expert review pending
a496c92 verified
Raw History Blame Contribute Delete
5.37 kB
"""Evaluate fixed development cohort controls and false abstentions separately."""
import json
import re
import sys
from collections import Counter
from pathlib import Path
from prepare_confirmation_source_cohort import OUT, read, digest
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'publication_candidate_20261120/code'))
from identified_numeric_scoring import parse_json_output, plain_numeric_content
DEST=OUT/'study_bound_numeric_binding_development_v2/population_binding_challenge_development_v1'
def main():
protocol=json.loads((DEST/'protocol.json').read_text())
request_path=DEST/'requests24_local_only.jsonl';assert digest(request_path)==protocol['requests_sha256']
requests={(r['id'],r['method']):r for r in read(request_path)};assert len(requests)==24
items={r['id']:r for r in read(DEST/'items12_local_only.jsonl')};assert digest(DEST/'items12_local_only.jsonl')==protocol['items_sha256']
literal={r['id']:r['decision'] for r in read(DEST/'literal_gate_decisions_before_readers.jsonl')}
models={}
for model in ['luna','qwen3_4b','qwen25_7b']:
path=DEST/('luna_predictions.jsonl' if model=='luna' else model+'/predictions.jsonl')
gen=json.loads((path.with_suffix('.protocol.json') if model=='luna' else DEST/model/'protocol.json').read_text())
assert gen.get('request_sha256',gen.get('input_sha256'))==digest(request_path)
if model!='luna':assert json.loads((DEST/model/'complete.json').read_text())['complete']
outputs=read(path);assert len(outputs)==24 and {(r['id'],r['method']) for r in outputs}==requests.keys()
counts={m:{s:Counter() for s in ['positive','absent_count','present_other_role_count']} for m in protocol['methods']};cases=[]
for row in outputs:
key=row['id'],row['method'];req=requests[key];item=items[row['id']]
assert not row.get('error') and row['model_requested']==row['model_returned']==gen['model']
assert all(row[k]==req[k] for k in ['context_sha256','context_tokens_unified','response_protocol'])
parsed=parse_json_output(row['output'])
try:strict=json.loads(row['output'])==parsed
except (ValueError,TypeError):strict=False
valid=bool(isinstance(parsed,dict) and set(parsed)=={'answer','citations'} and isinstance(parsed['answer'],str) and isinstance(parsed['citations'],list) and all(isinstance(x,str) for x in parsed['citations']))
evidence=json.loads(req['messages'][1]['content'])['evidence'];ids=set(re.findall(r'(?m)^\[(E\d+)\] SourceID:',evidence))
pointers=bool(valid and all(x in ids for x in parsed['citations']))
numeric=plain_numeric_content(item['target'],parsed);unanswerable=numeric['content_unanswerable'];positive=item['condition']=='positive'
protocol_ok=bool(strict and valid and pointers and row.get('finish_reason')=='stop')
passed=bool(protocol_ok and (numeric['numeric_content_complete'] if positive else unanswerable))
gate=literal[row['id']]['abstain'];gate_pass=bool(protocol_ok and ((numeric['numeric_content_complete'] and not gate) if positive else (unanswerable or gate)))
counts[row['method']][item['condition']].update(cases=1,protocol_valid=int(protocol_ok),strict_success=int(passed),
abstentions=int(unanswerable),literal_gate_hypothetical_success=int(gate_pass),literal_gate_rejects=int(gate))
cases.append({'id':row['id'],'pmid':item['pmid'],'method':row['method'],'condition':item['condition'],
'answer':parsed.get('answer') if isinstance(parsed,dict) else None,'numeric_contract':numeric['numeric_contract'],
'numeric_content_complete':numeric['numeric_content_complete'],'content_unanswerable':unanswerable,
'strict_success':passed,'protocol_valid':protocol_ok,'literal_gate_abstain':gate,'clinical_gold':False})
matrix={(r['id'],r['method']):r for r in cases};paired={}
for condition in ['positive','absent_count','present_other_role_count']:
pairs=[(matrix[i,'plain_reader']['strict_success'],matrix[i,'explicit_population_check']['strict_success']) for i,item in items.items() if item['condition']==condition]
paired[condition]={'gains':sum(not a and b for a,b in pairs),'losses':sum(a and not b for a,b in pairs)}
models[model]={'generation_protocol':gen,'predictions_sha256':digest(path),'counts':counts,'paired':paired,'cases':cases,
'new_provider_logged_tokens':sum((r.get('usage') or {}).get('total_tokens',0) for r in outputs) if model=='luna' else 0}
report={'scope':'Evidence-controlled DEVELOPMENT mechanism stress test on4sources/12syntheticcases. Not a heldout clinical benchmark or deployable retrieval experiment.',
'protocol':protocol,'models':models,'new_model_responses':72,'expert_reviews':0,'new_accepted_benchmark_questions':0,
'limits':'Same-paper counts in different roles are not equivalent cohorts. Controls are source-bound unsupported premises, not clinical-falsehood judgments. Literal gate is offline hypothetical and incurs no demonstrated token savings.'}
(DEST/'reader_audit.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({m:v['counts'] for m,v in models.items()},indent=2))
if __name__=='__main__':main()