"""Measure anonymous batch conditioning/order sensitivity against archived silver labels.""" import collections,hashlib,json from pathlib import Path from validate_openqa_grader import span ROOT=Path(__file__).resolve().parent/'miriad_public/openqa_reference_coverage_batch_calibration_v1' def read(p):return [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else [] def main(): mapping=read(ROOT/'mapping400_local_only.jsonl');requests=read(ROOT/'requests20_local_only.jsonl');protocol=json.loads((ROOT/'protocol_before_calls.json').read_text()) assert hashlib.sha256((ROOT/'requests20_local_only.jsonl').read_bytes()).hexdigest()==protocol['request_sha256'] predictions={r['id']:r for r in read(ROOT/'luna_predictions.jsonl') if not r.get('error')} assert len(predictions)==len(requests)==20,'Need all20transportresponses, preserve partials' source={r['id']:r for r in requests};expected=collections.defaultdict(dict) for r in mapping:expected[r['batch_id']][r['candidate_id']]=r records=[];failures=[];raw_by_case={};structural_batches=0 for ident,pred in predictions.items(): assert pred['model_returned']=='gpt-6-luna' and pred['context_sha256']==source[ident]['context_sha256'] try: assert pred.get('finish_reason')=='stop','not_completed' parsed=json.loads(pred['output']);candidates=parsed['candidates'];indices=[r['candidate_id'] for r in candidates] assert len(indices)==len(set(indices)) and set(indices)==set(expected[ident]),'candidate_ids_not_exact' for candidate in candidates: e=expected[ident][candidate['candidate_id']];cov=candidate['fact_coverage'];factids=[x['index'] for x in cov] assert all(type(i)is int for i in factids) and len(factids)==len(e['facts']) and set(factids)==set(range(len(e['facts']))),'fact_indices_not_exact' old={x['index']:x for x in e['old_fact_coverage']} raw_by_case[(e['id'],e['model'],e['method'],ident.rsplit(':',1)[1])]=cov for f in cov: assert type(f.get('covered'))is bool or f.get('covered')=='uncertain','invalid_label' idx=f['index'];anchor=span(e['answer'],f.get('candidate_quote'));valid=f['covered']is not True or anchor is not None prior=old.get(idx);oldvalid=prior is not None and (prior.get('covered')is not True or span(e['answer'],prior.get('candidate_quote'))is not None) records.append({'id':e['id'],'model':e['model'],'method':e['method'],'order':ident.rsplit(':',1)[1],'fact_index':idx, 'required':e['facts'][idx].get('requested_by_question'),'reference_task_grade_valid':e['reference_task_grade_valid'], 'batch_coverage':f['covered'],'batch_anchor_valid':valid,'prior_individual_coverage':prior.get('covered') if prior else None, 'prior_anchor_valid':oldvalid,'comparable':valid and oldvalid,'agree':f['covered']==prior.get('covered') if prior else False}) structural_batches+=1 except (AssertionError,ValueError,TypeError,KeyError) as exc:failures.append({'id':ident,'failure':str(exc)[:120]}) (ROOT/'per_fact_batch_individual_comparison_local_only.jsonl').write_text(''.join(json.dumps(x)+'\n' for x in records)) primary=[x for x in records if x['order']=='primary'];common=[x for x in primary if x['comparable']];agreement=sum(x['agree'] for x in common)/len(common) if common else None order=[] for key,cov in raw_by_case.items(): if key[-1]!='reverse':continue primarycov=raw_by_case.get((*key[:-1],'primary')) if primarycov is None:continue a={x['index']:x for x in primarycov};b={x['index']:x for x in cov} for i in a:order.append(a[i]['covered']!=b[i]['covered']) disagree=sum(order)/len(order) if order else None invalid=sum(not x['batch_anchor_valid'] for x in records) thresholds=protocol['batch_transport_sanity_rule_before_calls'] passes=structural_batches==20 and not failures and invalid==0 and agreement is not None and agreement>=thresholds['minimum_comparable_label_agreement_with_archived_individual_luna'] and disagree is not None and disagree<=thresholds['maximum_primary_vs_reverse_coverage_disagreement'] bymodel={} for model in sorted({x['model'] for x in primary}): rows=[x for x in common if x['model']==model];bymodel[model]={'comparable_labels':len(rows),'agreement':sum(x['agree'] for x in rows)/len(rows) if rows else None} result={'scope':'Development-only batch conditioning/order diagnostic against old automatic Luna, NOT expert/clinical calibration.', 'new_judge_calls':20,'new_reader_generations':0,'expert_reviews':0,'structurally_complete_batches':structural_batches,'batch_failures':failures,'primary_labels':len(primary),'comparable_primary_labels':len(common), 'batch_vs_individual_label_agreement':agreement,'by_reader':bymodel,'all_order_comparison_labels':len(order),'primary_vs_reverse_label_disagreement':disagree,'positive_coverage_missing_exact_candidate_anchor':invalid, 'predeclared_batch_transport_sanity_pass':passes,'frozen_thresholds':thresholds,'provider_logged_tokens':sum(r.get('usage',{}).get('total_tokens',0) for r in predictions.values()), 'limits':'Neither batch nor old individual labels are gold. Same-judge agreement cannot establish source necessity/clinical accuracy. Facts and answers unchanged; no new accepted QA. If sanity fails, do not scale this batching protocol to511 or tune thresholds on these outputs.'} (ROOT/'batch_conditioning_audit.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result),flush=True) if __name__=='__main__':main()