File size: 8,212 Bytes
811e55e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | """Portable answer scorer with source-cluster bootstrap and coverage accounting."""
import argparse,collections,json,pathlib,random,math
from response_parsing import normalize_prediction
p=argparse.ArgumentParser();p.add_argument('--track',required=True);p.add_argument('--predictions',nargs='+',required=True);p.add_argument('--methods',nargs='+',required=True);p.add_argument('--output',required=True);p.add_argument('--reference-method',default=None);a=p.parse_args()
reference=a.reference_method or ('no_rag' if 'no_rag' in a.methods else None)
if reference is not None and reference not in a.methods:p.error('--reference-method must be one of --methods')
items={x['id']:x for x in map(json.loads,pathlib.Path(a.track).open())}
eligible={i:x for i,x in items.items() if x.get('options') and x.get('gold') in x['options']}
if not eligible:p.error('No eligible MCQ rows. Open-answer QA requires a separate source-grounded evaluator; zero scored items is not a completed QA evaluation.')
pred={};errors=0
for filename in a.predictions:
for row in map(json.loads,pathlib.Path(filename).open()):
if row.get('error'):errors+=1;continue
if row['id'] in eligible:pred[(row['id'],row['method'])]=normalize_prediction(row,eligible[row['id']]['options'])
common=[i for i in eligible if all((i,m) in pred for m in a.methods)]
groups=collections.defaultdict(list)
for i in common:groups[eligible[i].get('source_family_id',i)].append(i)
expected_groups=collections.defaultdict(list)
for i in eligible:expected_groups[eligible[i].get('source_family_id',i)].append(i)
common_set=set(common)
complete_families=[f for f,ids in expected_groups.items() if all(i in common_set for i in ids)]
expected_pairs=collections.defaultdict(list)
for i,x in eligible.items():
if x.get('pair_id'):expected_pairs[x['pair_id']].append(i)
complete_pairs={pair:ids for pair,ids in expected_pairs.items() if len(ids)==2 and all(i in common_set for i in ids)}
families=sorted(groups);rng=random.Random(20261117);samples={m:[] for m in a.methods}
if common:
for _ in range(2000):
ids=[i for _ in families for i in groups[rng.choice(families)]]
for m in a.methods:samples[m].append(sum(pred[(i,m)].get('answer')==eligible[i]['gold'] for i in ids)/len(ids))
result={'track':pathlib.Path(a.track).stem,'eligible_mcq':len(eligible),'open_or_other_items':len(items)-len(eligible),'common_completed':len(common),'completion_fraction':len(common)/len(eligible) if eligible else None,'error_records':errors,'methods':{},'scoring':'Exact declared letter or explicitly versioned unique exact option-text mapping from first JSON object; explanations and gold never repair a prediction. Raw JSON compliance separate; missing predictions not mistaken for wrong answers.'}
for m in a.methods:
values=sorted(samples[m]);n=len(common);correct=sum(pred[(i,m)].get('answer')==eligible[i]['gold'] for i in common)
result['methods'][m]={'n':n,'correct':correct,'accuracy':correct/n if n else None,'source_cluster_95ci':[values[int(.025*(len(values)-1))],values[int(.975*(len(values)-1))]] if values else None,'strict_json_valid_n':sum(pred[(i,m)].get('strict_single_json_object') is True for i in common)}
result['methods'][m]['declared_valid_option_n']=sum(isinstance(pred[(i,m)].get('answer'),str) and pred[(i,m)]['answer'] in eligible[i]['options'] for i in common)
result['methods'][m]['response_protocol_counts']=dict(collections.Counter(pred[(i,m)].get('response_protocol','option_letter_v1') for i in common))
if any(pred[(i,m)].get('response_protocol')=='exact_option_text_v1' for i in common):
result['methods'][m]['option_text_exact_unique_match_n']=sum(pred[(i,m)].get('option_text_exact_unique_match') is True for i in common)
# A source-level reliability score has a non-degenerate interval even when
# every observed question is correct. It is a different estimand from micro
# question accuracy, not a replacement or relabeling of its bootstrap CI.
source_n=len(complete_families)
source_correct=sum(all(pred[(i,m)].get('answer')==eligible[i]['gold'] for i in expected_groups[f]) for f in complete_families)
result['methods'][m].update(expected_source_families=len(expected_groups),complete_source_families=source_n,source_complete_accuracy=None)
if source_n:
fraction=source_correct/source_n;z=1.959963984540054;denom=1+z*z/source_n
center=(fraction+z*z/(2*source_n))/denom
radius=z*math.sqrt(fraction*(1-fraction)/source_n+z*z/(4*source_n*source_n))/denom
result['methods'][m].update(source_families=source_n,all_questions_correct_source_families=source_correct,source_complete_accuracy=fraction,source_complete_wilson_95ci=[max(0,center-radius),min(1,center+radius)])
if expected_pairs:
pair_correct={pair:all(pred[(i,m)].get('answer')==eligible[i]['gold'] for i in ids) for pair,ids in complete_pairs.items()}
pair_groups=collections.defaultdict(list)
for pair,ids in complete_pairs.items():pair_groups[eligible[ids[0]].get('source_family_id',pair)].append(pair)
pair_families=sorted(pair_groups);pair_samples=[];pair_deltas=[];pair_rng=random.Random(20261118)
pair_reference={pair:all(pred[(i,reference)].get('answer')==eligible[i]['gold'] for i in ids) for pair,ids in complete_pairs.items()} if reference is not None else {}
if pair_families:
for _ in range(2000):
sample=[pair for _ in pair_families for pair in pair_groups[pair_rng.choice(pair_families)]]
pair_samples.append(sum(pair_correct[pair] for pair in sample)/len(sample))
if reference is not None:pair_deltas.append(sum(int(pair_correct[pair])-int(pair_reference[pair]) for pair in sample)/len(sample))
pair_samples.sort()
result['methods'][m]['contrast_pairs']={'expected':len(expected_pairs),'completed':len(complete_pairs),'both_correct':sum(pair_correct.values()),'pair_accuracy':sum(pair_correct.values())/len(complete_pairs) if complete_pairs else None,'source_cluster_95ci':[pair_samples[49],pair_samples[1949]] if pair_samples else None,'question_members_are_not_independent_pairs':True}
if reference is not None:
pair_deltas.sort()
result['methods'][m]['contrast_pairs'].update(reference_method=reference,gains=sum(pair_correct[pair] and not pair_reference[pair] for pair in complete_pairs),losses=sum(not pair_correct[pair] and pair_reference[pair] for pair in complete_pairs),paired_delta_source_cluster_95ci=[pair_deltas[49],pair_deltas[1949]] if pair_deltas else None)
if reference is not None:
delta=sorted(x-y for x,y in zip(samples[m],samples[reference]))
result['methods'][m].update(reference_method=reference,gains=sum(pred[(i,m)].get('answer')==eligible[i]['gold'] and pred[(i,reference)].get('answer')!=eligible[i]['gold'] for i in common),losses=sum(pred[(i,m)].get('answer')!=eligible[i]['gold'] and pred[(i,reference)].get('answer')==eligible[i]['gold'] for i in common),paired_delta_95ci=[delta[int(.025*(len(delta)-1))],delta[int(.975*(len(delta)-1))]] if delta else None)
result.update(expected_mcq=len(eligible),non_mcq_not_scored=len(items)-len(eligible),completed_mcq=len(common),evaluation_coverage=len(common)/len(eligible) if eligible else None,error_records=errors,complete=len(common)==len(eligible),diagnosis_classes_evaluated=dict(collections.Counter(str(eligible[i].get('diagnosis_target_positive','not_diagnostic')) for i in common)))
result['interval_note']='Percentile source bootstrap can degenerate on perfect or zero observed accuracy. Source-complete Wilson interval is for the separate event that all questions in an approximately independent source family are correct. Zero observed errors or differences does not establish universal accuracy or method equivalence.'
result['eligible_mcq']=len(eligible);result['coverage']=len(common)/len(eligible) if eligible else None;result['complete']=len(common)==len(eligible);result['expected_diagnosis_classes']=dict(collections.Counter(str(x.get('diagnosis_target_positive')) for x in eligible.values()));result['evaluated_diagnosis_classes']=dict(collections.Counter(str(eligible[i].get('diagnosis_target_positive')) for i in common))
out=pathlib.Path(a.output);out.parent.mkdir(parents=True,exist_ok=True);out.write_text(json.dumps(result,ensure_ascii=False,indent=2));print(json.dumps(result,ensure_ascii=False))
|