MeningiomaBench / code /population_frame_choice_development.py
dfdu233's picture
Silver research draft; expert review pending
a496c92 verified
Raw History Blame Contribute Delete
10.9 kB
"""Compare free quotation with source-frame IDs under identical DEV evidence."""
import argparse
from collections import Counter
import json
import re
import sys
from pathlib import Path
import tiktoken
from prepare_confirmation_source_cohort import OUT, read, digest
from prepare_openqa_dev161_equal_budget import freeze, sha
from study_population_witness_gate import counts, HEAD
from quoted_population_count_resolution import resolve
from population_count_selector_development import PROMPT
OLD=OUT/'study_bound_numeric_binding_development_v2/population_count_selector_development_v1'
DEST=OLD.parent/'population_frame_choice_development_v1'
MARKER='\n\n-----Population frames-----\n'
METHODS=['free_quote_with_catalog','frame_id_with_catalog']
def prepare():
DEST.mkdir(exist_ok=True)
selectors=[r for r in read(OLD/'selectors32_before_readers.jsonl') if r['arm']=='masked'];unique=list(dict.fromkeys(r['request_id'] for r in selectors));assert len(unique)==8
inputs={r['id']:r for r in read(OLD/'requests24_local_only.jsonl')};encoder=tiktoken.encoding_for_model('gpt-4o');requests=[];catalogs=[];mapping=[]
for oldid in unique:
payload=json.loads(inputs[oldid]['messages'][1]['content']);original=payload['evidence'];assert MARKER not in original
heads=list(HEAD.finditer(original));frames=[]
for i,h in enumerate(heads):
body=original[h.end():heads[i+1].start() if i+1<len(heads) else len(original)];seen=set()
for c in counts(body):
for m in re.finditer(re.escape(c['surface']),body):
if (m.start(),m.end()) in seen:continue
seen.add((m.start(),m.end()));start=max(0,m.start()-160);end=min(len(body),m.end()+240)
frames.append({'frame_id':'F'+str(len(frames)+1),'source_id':h[2],'count':c['value'],'entity_family':c['family'],
'source_body_span':[start,end],'quote':body[start:end]})
assert frames and all(any(x['value']==f['count'] and x['family']==f['entity_family'] for x in counts(f['quote'])) for f in frames)
augmented=original+MARKER+json.dumps(frames,ensure_ascii=False);assert len(encoder.encode(augmented))<=6000
ident='FRAMECHOICE:'+oldid.split(':')[1];payload={**payload,'evidence':augmented}
for method in METHODS:
system=PROMPT if method==METHODS[0] else PROMPT[:PROMPT.index('Return only JSON')]+'''A deterministic frame catalog follows the original evidence. Select the frame whose count and quoted source context establish the cohort or subgroup named by the question for the requested analysis. Return only JSON with exactly one string field, frame_id, copied from the catalog. If no frame establishes it, return an empty string. Do not answer the clinical numerical question.'''
if method==METHODS[0]:system+=' A deterministic source-only frame catalog follows the original evidence; use it to locate an exact count-bearing quote.'
requests.append({'id':ident,'method':method,'track':'population_frame_choice_development','option_letters':[],
'context_sha256':sha(augmented.encode()),'context_tokens_unified':len(encoder.encode(augmented)),
'response_protocol':'source_cohort_free_quote_or_frame_choice_v1',
'messages':[{'role':'system','content':system},{'role':'user','content':json.dumps(payload,ensure_ascii=False)}]})
catalogs.append({'id':ident,'original_evidence':original,'frames':frames,'original_evidence_tokens':len(encoder.encode(original)),
'augmented_evidence_tokens':len(encoder.encode(augmented))})
mapping.extend({'case_id':s['case_id'],'request_id':ident} for s in selectors if s['request_id']==oldid)
freeze(DEST/'catalogs8_source_only_local.jsonl',''.join(json.dumps(r)+'\n' for r in catalogs))
freeze(DEST/'selectors16_before_readers.jsonl',''.join(json.dumps(r)+'\n' for r in mapping))
freeze(DEST/'requests16_local_only.jsonl',''.join(json.dumps(r)+'\n' for r in requests))
freeze(DEST/'protocol.json',json.dumps({'scope':'DEVELOPMENT-only output-representation control on4previously usedarticles,8maskedquestioninputs representing16controlledcases. No independent test or clinical gold.',
'questions':8,'methods':METHODS,'requests_sha256':digest(DEST/'requests16_local_only.jsonl'),'catalogs_sha256':digest(DEST/'catalogs8_source_only_local.jsonl'),
'same_evidence_and_user_bytes_between_arms':True,'frames_generated_without_question_or_target_labels':True,
'frame_policy':'All literal-count occurrences in suppliedsourcebody; deterministicsourceorder;160charsbefore/240aftercount; no answer-based frame pruning or role assignment.',
'evidence_max_tokens':6000,'catalog_changes_actual_evidence_from_prior_free_extractor':True,
'comparison':'Free quote vs frame-ID choice BOTH receive same originalsource+catalog. Prior catalog-free extractor not an output-format-only control.',
'source_body_unchanged':True,'luna_reasoning_effort':'low','luna_temperature':'provider_default','local_temperature':0,
'max_completion_tokens_or_local_max_tokens':1000,'expert_reviews':0,'new_accepted_main_benchmark_questions':0,
'limits':'Frame ID proves literal count/source binding only. Correct analysis/subgroup role still requires independent evaluation. Model disagreement and unknowns are retained; no clinical safety or novelty claim.'},indent=2)+'\n')
print('Frozen16requests/model; identical catalog evidence in botharms;0modelcalls')
def audit(project_syntax=False):
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'publication_candidate_20261120/code'))
from identified_numeric_scoring import parse_json_output
protocol=json.loads((DEST/'protocol.json').read_text());rp=DEST/'requests16_local_only.jsonl';assert digest(rp)==protocol['requests_sha256']
req={(r['id'],r['method']):r for r in read(rp)};catalogs={r['id']:r for r in read(DEST/'catalogs8_source_only_local.jsonl')}
assert digest(DEST/'catalogs8_source_only_local.jsonl')==protocol['catalogs_sha256']
items={r['id']:r for r in read(OLD/'cases16_local_only.jsonl')};mapping=read(DEST/'selectors16_before_readers.jsonl');models={}
for model in ['luna','qwen3_4b','qwen25_7b']:
op=DEST/('luna_predictions.jsonl' if model=='luna' else model+'/predictions.jsonl');gen=json.loads((op.with_suffix('.protocol.json') if model=='luna' else DEST/model/'protocol.json').read_text())
assert gen.get('request_sha256',gen.get('input_sha256'))==digest(rp)
if model!='luna':assert json.loads((DEST/model/'complete.json').read_text())['complete']
rows=read(op);assert len(rows)==16 and {(r['id'],r['method']) for r in rows}==req.keys()
extracted={};states={m:Counter() for m in METHODS}
for row in rows:
key=row['id'],row['method'];r=req[key];cat=catalogs[row['id']];assert not row.get('error') and row['model_requested']==row['model_returned']==gen['model']
assert all(row[k]==r[k] for k in ['context_sha256','context_tokens_unified','response_protocol'])
parsed=parse_json_output(row['output'])
if row['method']==METHODS[0]:result=resolve(cat['original_evidence'],parsed,counts)
else:
valid_shape=isinstance(parsed,dict) and set(parsed)=={'frame_id'} and isinstance(parsed['frame_id'],str)
frame=next((f for f in cat['frames'] if f['frame_id']==parsed['frame_id']),None) if valid_shape else None
if project_syntax:
from frame_choice_syntax_projection import project
projection=project(row['output'],{f['frame_id'] for f in cat['frames']})
frame=next((f for f in cat['frames'] if f['frame_id']==projection['frame_id']),None)
result={'valid':frame is not None,'count':frame['count'] if frame else None,'family':frame['entity_family'] if frame else None,
'state':'valid_frame_id' if frame else 'unknown_or_invalid_frame_id'}
if project_syntax:result['state']=projection['state']
if row.get('finish_reason')!='stop':result={**result,'valid':False,'state':'truncated_output'}
extracted[key]=result;states[row['method']][result['state']]+=1
counters={m:{s:Counter() for s in ['positive','absent_count','present_other_role_count','valid_subgroup']} for m in METHODS};details=[]
for select in mapping:
item=items[select['case_id']]
for method in METHODS:
e=extracted[select['request_id'],method];known=bool(e['valid'] and e['family']==item['expected_family']);reject=bool(known and e['count']!=item['requested_count'])
right=bool(known and e['count']==item['expected_source_count'])
counters[method][item['stratum']].update(cases=1,literal_valid=int(known),exact_role_count=int(right),rejects=int(reject),
positive_false_abstain=int(reject and not item['expected_reject']),unknown=int(not known))
details.append({**select,'method':method,'stratum':item['stratum'],'requested_count':item['requested_count'],'expected_source_count':item['expected_source_count'],
'extracted_count':e['count'],'literal_valid':known,'exact_role_count':right,'hypothetical_reject':reject,'clinical_gold':False})
models[model]={'generation_protocol':gen,'predictions_sha256':digest(op),'counts':counters,'unique_response_states':states,'cases':details,
'new_provider_logged_tokens':sum((r.get('usage') or {}).get('total_tokens',0) for r in rows) if model=='luna' else 0}
report={'scope':protocol['scope'],'protocol':protocol,'models':models,'new_model_responses':48,'expert_reviews':0,
'limits':'Known compatible count or valid ID is not whole-question entailment. Unknown does not override originalanswer. Source-controlled small development sample; no untouched-test or clinical performance claim.'}
if project_syntax:report.update(posthoc_frame_syntax_projection=True,primary_audit_sha256=digest(DEST/'reader_audit.json'),
changed_primary_scores=False,new_model_calls=0,projection_policy='Exactobject,JSONstring,singleframe_idfieldfragment,orbarevalidID only. No prose extraction, malformed escaping repair, ambiguous choices or target input.')
(DEST/('frame_syntax_projection_posthoc_audit.json' if project_syntax else '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__':
ap=argparse.ArgumentParser();ap.add_argument('--audit',action='store_true');ap.add_argument('--posthoc-frame-syntax',action='store_true');args=ap.parse_args()
audit(project_syntax=args.posthoc_frame_syntax) if args.audit else prepare()