MeningiomaBench / code /prepare_question_conditioned_development_readers.py
dfdu233's picture
Silver research draft; expert review pending
929ed75 verified
Raw History Blame Contribute Delete
6.13 kB
"""Further DEVELOPMENT diagnosis of question-aware grading on320cached answers.
The v2 control contract has NOT passed: this is not main-test clinical scoring.
"""
import hashlib,json
from pathlib import Path
import tiktoken
from prepare_question_conditioned_grader_ids import PROMPT,units,obj,enum,array
from prepare_openqa_dev161_equal_budget import freeze
ROOT=Path(__file__).resolve().parent;BASE=ROOT/'miriad_public';OUT=BASE/'question_conditioned_development_readers_v1'
def read(p):return [json.loads(x) for x in p.read_text().splitlines()]
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def response_format(catalog):
ids=lambda key:array(enum([r['id'] for r in catalog[key]]));claim=obj({'claim':{'type':'string'},'answer_ids':ids('answer_units'),'question_ids':ids('question_units'),'source_ids':ids('source_units'),'status':enum(['supported','contradicted','not_verifiable','uncertain'])})
schema=obj({'question_scope':enum(['source_bound','general','ambiguous']),'source_answerability':enum(['sufficient','partial','insufficient','ambiguous']),'core_status':enum(['adequate','partial','contradicted','not_verifiable','abstain','uncertain']),
'core_claims':array(claim),'additional_claims':array(claim),'missing_requirements':array(obj({'requirement':{'type':'string'},'question_ids':ids('question_units'),'source_ids':ids('source_units')})),
'source_boundary_flags':array({'type':'string'}),'extraction_complete':{'type':'boolean'},'reason':{'type':'string'}})
return {'type':'json_schema','json_schema':{'name':'source_bound_question_task','strict':True,'schema':schema}}
def main():
OUT.mkdir(exist_ok=True);items={r['id']:r for r in read(BASE/'openqa_development16/selected_items.jsonl')};mapping=read(BASE/'openqa_reference_coverage_batch_calibration_v1/mapping400_local_only.jsonl');mapping=[r for r in mapping if r['batch_id'].endswith(':primary')];assert len(mapping)==320
controls=json.loads((BASE/'question_conditioned_grader_ids_v2/control_audit.json').read_text());assert controls['passed']==19 and not controls['all_predeclared_sanity_checks_pass']
requests=[];records=[];enc=tiktoken.encoding_for_model('gpt-4o')
for r in sorted(mapping,key=lambda x:(x['id'],x['model'],x['method'])):
item=items[r['id']];assert item['split']=='development';answer=r['answer'];anon='DEV:'+hashlib.sha256((r['id']+'|'+r['model']).encode()).hexdigest()[:20]
# Full source/Q text first, answer last: cache optimization, recorded representation-order change.
catalog={'source_units':units(item['passage_text'],'S'),'question_units':units(item['question'],'Q'),'answer_units':units(answer,'A')};evidence=json.dumps(catalog,ensure_ascii=False)
request={'id':anon,'method':r['method'],'track':'development_source_bound_task_diagnostics_unvalidated','option_letters':[],'response_protocol':'question_conditioned_source_ids_v2',
'messages':[{'role':'system','content':PROMPT},{'role':'user','content':json.dumps({'evidence':evidence},ensure_ascii=False)}],
'context_sha256':hashlib.sha256(evidence.encode()).hexdigest(),'context_tokens_unified':len(enc.encode(evidence)),'response_format':response_format(catalog)}
requests.append(request);records.append({'request_id':anon,'qa_id':r['id'],'reader':r['model'],'method':r['method'],'source_family_id':item['source_family_id'],'catalog':catalog,
'candidate_answer_sha256':hashlib.sha256(answer.encode()).hexdigest(),'source_sha256':hashlib.sha256(item['passage_text'].encode()).hexdigest(),'old_luna_fact_coverage':r['old_fact_coverage'],'old_metrics':r['old_metrics'],'facts':r['facts']})
assert len({(r['id'],r['method']) for r in requests})==320
freeze(OUT/'requests320_local_only.jsonl',''.join(json.dumps(r)+'\n' for r in requests));freeze(OUT/'mapping320_local_only.jsonl',''.join(json.dumps(r)+'\n' for r in records))
protocol={'scope':'ALL16historicalDEVELOPMENTquestions/16sources×4cachedreaders×5methods=320source-bound gradingobservations. ZEROnewreaderanswers/QA. Notfull511clinicalaccuracyornewtest.',
'v2_control_sanity_failed_retained':True,'observed_control_failure':'Refusal metaclaim wascalledsupportedwithoutsourceIDs. Corestatuses20/20matched butfullcontract19/20,notpassed. No main-labelupgrade or clinicallyvalidatedgraderclaim.',
'purpose':'Measure taskstatus observations/contractvalidity/source-answerability variation onactualDEVELOPMENTanswers; retaininvalids/unknowns. Learnfailuremodesbeforeanytestaccuracyclaims; do nottuneoldcontrolsuntilpass.',
'candidate_contents':'EXACTcachedserialization-agnosticdeclaredanswer-or-wholefinaltext alreadyusedbyhistoricalgraders; no explanationcherrypicking/repair. Reader/method metadatahiddeninmessages; style mayrevealidentity.',
'source_view':'Samequestion+canonicalreferencepassageforall20answers/question, no canonicalanswer/fixedreferencefactsinthegrader. ThisisNOTactualprovided-contextfaithfulnessorcurrentclinicaltruth. Legitimatealternativesabsentfromonepassageareunverified,notmedicalfalse.',
'source_answerability':'PropertyofQ/sourcecanvaryspuriouslywithcandidate. Reportper-questionvariationandcommonall-armuncertainty,notcondition-specificfiltering; all16retained. Generalnonexhaustivequestionsrequiremulti-reference/taskscopeaudit.',
'representation_order_change':'Sourcecatalogfirst,Qsecond,A last forsharedprefixcache. Sameunderlyingtext/IDcontract; notidenticaltokenorderasv2controls,notanisolatedoutputformatcomparison.',
'requests_sha256':sha(OUT/'requests320_local_only.jsonl'),'input_mapping_sha256':sha(BASE/'openqa_reference_coverage_batch_calibration_v1/mapping400_local_only.jsonl'),'code_sha256':sha(Path(__file__)),
'expert_reviews':0,'new_accepted_labels':0,'main_test_questions':0,'independent_DeepSeek_pending':True}
freeze(OUT/'protocol_before_calls.json',json.dumps(protocol,indent=2)+'\n');freeze(OUT/'code_snapshot.py',Path(__file__).read_text());print('Frozen320furtherDEVELOPMENTgraderrequests; no calibrationpass/clinicalclaims')
if __name__=='__main__':main()