Download code/evaluate_minicheck_development.py from dfdu233/MeningiomaBench: direct link, hf CLI and curl.
- Browser
- Download file 8.09 kB
-
https://huggingface.co/datasets/dfdu233/MeningiomaBench/resolve/main/code/evaluate_minicheck_development.py
- Command line
-
hf download hf://datasets/dfdu233/MeningiomaBench/code/evaluate_minicheck_development.py
-
curl -L -o evaluate_minicheck_development.py https://huggingface.co/datasets/dfdu233/MeningiomaBench/resolve/main/code/evaluate_minicheck_development.py
8.09 kB
| """Pinned official MiniCheck on existing development atomic claims and controls. | |
| No model-answer regeneration. Automatic consensus is not ground truth. | |
| """ | |
| import argparse,collections,hashlib,json,os | |
| from pathlib import Path | |
| ROOT=Path(__file__).resolve().parent | |
| BASE=ROOT/'miriad_public/openqa_development16' | |
| OUT=ROOT/'miriad_public/minicheck_development_calibration_v1' | |
| SOURCE=Path('/home/dbw/MedicalGraphRAG-deploy/third_party/MiniCheck') | |
| from prepare_openqa_dev161_equal_budget import freeze | |
| def read(p):return [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else [] | |
| def sha(b):return hashlib.sha256(b).hexdigest() | |
| def encode(x):return json.dumps(x,ensure_ascii=False) | |
| def prepare(): | |
| OUT.mkdir(exist_ok=True);items={x['id']:x for x in read(BASE/'selected_items.jsonl')};pool={};mapping=[];deps={} | |
| def add(source,claim,family,entry): | |
| key=sha((source+'\0'+claim).encode());pool.setdefault(key,{'id':key,'document':source,'claim':claim,'source_family_id':family,'old_judge_labels':{},'control_labels':[]}) | |
| for model,label in entry.get('old_judge_labels',{}).items(): | |
| if label is not None:pool[key]['old_judge_labels'].setdefault(model,[]).append(label) | |
| if 'expected_supported' in entry:pool[key]['control_labels'].append(entry['expected_supported']) | |
| mapping.append({'pair_id':key,**entry}) | |
| for reader in ['deepseek','luna','qwen25_7b','llama31_8b']: | |
| folder=BASE/('grading_text_'+reader);extracts=read(folder/'claim_extractions.jsonl');judges={(r['id'],r['method'],r['judge_requested']):r for r in read(folder/'source_judgments.jsonl')} | |
| deps[str((folder/'claim_extractions.jsonl').relative_to(ROOT))]=sha((folder/'claim_extractions.jsonl').read_bytes());deps[str((folder/'source_judgments.jsonl').relative_to(ROOT))]=sha((folder/'source_judgments.jsonl').read_bytes()) | |
| for ex in extracts: | |
| if not ex.get('extraction_valid'):continue | |
| item=items[ex['id']] | |
| for i,claim in enumerate(ex['claims']): | |
| old={} | |
| for judge in ['deepseek-v4.1-flash','gpt-6-luna']: | |
| row=judges.get((ex['id'],ex['method'],judge),{}) | |
| if not row.get('metrics',{}).get('atomic_claim_grade_valid'):continue | |
| assessments=row.get('judgment',{}).get('claim_assessments',[]);by={x['index']:x for x in assessments} | |
| if i in by:old[judge]=by[i]['status'] | |
| add(item['passage_text'],claim['claim'],item['source_family_id'],{'kind':'existing_development_claim','qa_id':ex['id'],'reader':reader,'method':ex['method'],'claim_index':i,'old_judge_labels':old}) | |
| controls=json.loads((ROOT/'miriad_public/openqa_judge_perturbations_dev/cases.json').read_text()) | |
| for case in controls: | |
| for i,claim in enumerate(case['atomic_candidate_claims']): | |
| add(case['source'],claim['claim'],'historical_control:'+case['group'],{'kind':'author_constructed_control','control_id':case['id'],'claim_index':i,'expected_supported':case['expected_status'][i]=='supported'}) | |
| # Stable source/claim order; this is not question-outcome selection. | |
| rows=[pool[k] for k in sorted(pool)] | |
| freeze(OUT/'source_claim_pairs_local_only.jsonl',''.join(encode(r)+'\n' for r in rows));freeze(OUT/'claim_logical_mapping_local_only.jsonl',''.join(encode(r)+'\n' for r in mapping)) | |
| receipt=json.loads((SOURCE/'source_receipt.json').read_text()) | |
| protocol={'scope':'All extracted atomic claims from historical16development questions across4readers/5methods, plus original5perturbationpairs/10answers/11claims. Reference passage only, NOT actual retrieved-context/citation support or medical accuracy.', | |
| 'unique_document_claim_pairs':len(rows),'logical_claim_records':len(mapping),'known_control_claim_records':sum(r['kind']=='author_constructed_control' for r in mapping), | |
| 'model':'lytang/MiniCheck-Flan-T5-Large','revision':'96eafd01cee2d16cf81aaa2fb226b14f422a37b3','official_source_receipt':receipt, | |
| 'max_model_len':2048,'chunk_size_words':500,'chunk_aggregation':'Official max over chunks, threshold >0.5, no posthoc threshold tuning. Preserve all chunk scores and record token truncation. Missing/cross-source attribution not solved.', | |
| 'calibration':'Compare original authored controls and both historical automatic judges. Consensus labels only when BOTH judges are internally unanimous and agree on supported-vs-not-supported; never expert gold. Contradicted/not_verifiable collapse to not-supported only for this binary document-grounding diagnostic, NOT medical falsehood.', | |
| 'software':'Official MiniCheck source files archived with hashes; git commit API unavailable. nltk3.9.1/accelerate0.34.2 installed without upgrading model runtime. No custom remote model code.', | |
| 'code_sha256':sha(Path(__file__).read_bytes()),'inputs_sha256':sha((OUT/'source_claim_pairs_local_only.jsonl').read_bytes()),'dependencies':deps,'expert_reviews':0,'new_reader_generations':0,'test_questions_used':0,'no_clinical_gold':True} | |
| freeze(OUT/'protocol_before_metric_calls.json',json.dumps(protocol,indent=2)+'\n');freeze(OUT/'code_snapshot.py',Path(__file__).read_text());print('FROZEN',len(rows),'unique document/claim pairs',len(mapping),'logical claims',flush=True) | |
| def run(): | |
| import sys,time,numpy as np,torch | |
| sys.path.insert(0,str(SOURCE));from minicheck.minicheck import MiniCheck | |
| protocol=json.loads((OUT/'protocol_before_metric_calls.json').read_text());verification=json.loads((OUT/'model_verification.json').read_text());assert verification['revision']==protocol['revision'] | |
| root=Path(verification['snapshot_path']);cache=root.parents[2];ref=root.parent.parent/'refs/main';ref.parent.mkdir(exist_ok=True) | |
| if ref.exists():assert ref.read_text().strip()==verification['revision'] | |
| else:ref.write_text(verification['revision']) | |
| assert os.environ.get('CUDA_VISIBLE_DEVICES')=='1' and torch.cuda.device_count()==1 | |
| # All model loads offline; the local default ref resolves only to this verified snapshot. | |
| torch.manual_seed(20261122);scorer=MiniCheck(model_name='flan-t5-large',max_model_len=2048,batch_size=8,cache_dir=str(cache)) | |
| assert scorer.model.model.device.type=='cuda' | |
| rows=read(OUT/'source_claim_pairs_local_only.jsonl');assert sha((OUT/'source_claim_pairs_local_only.jsonl').read_bytes())==protocol['inputs_sha256'] | |
| journal=OUT/'minicheck_predictions_local_only.jsonl';done={} | |
| for r in read(journal):assert r['id'] not in done;done[r['id']]=r | |
| with journal.open('a') as stream: | |
| for r in rows: | |
| if r['id'] in done:continue | |
| started=time.monotonic();labels,probs,chunks,chunk_probs=scorer.score(docs=[r['document']],claims=[r['claim']],chunk_size=500) | |
| parts=chunks[0];tokenlengths=[len(scorer.model.tokenizer('predict: '+scorer.model.tokenizer.eos_token.join([part,r['claim']]),add_special_tokens=True,truncation=False)['input_ids']) for part in parts] | |
| result={'id':r['id'],'label':int(labels[0]),'support_probability':float(probs[0]),'used_chunk_count':len(parts),'used_chunk_sha256':[sha(c.encode()) for c in parts], | |
| 'support_probability_per_chunk':np.asarray(chunk_probs[0]).tolist(),'untruncated_input_tokens_per_chunk':tokenlengths,'truncated_chunk_count':sum(x>2048 for x in tokenlengths),'seconds':round(time.monotonic()-started,4)} | |
| stream.write(encode(result)+'\n');stream.flush();done[r['id']]=result | |
| if len(done)%100==0:print('MINICHECK',len(done),'/',len(rows),flush=True) | |
| print('MINICHECK_COMPLETE',len(done),flush=True) | |
| if __name__=='__main__': | |
| p=argparse.ArgumentParser();p.add_argument('--run',action='store_true');p.add_argument('--run-directory',type=Path,help='Alternative frozen pair/protocol directory; only for --run');args=p.parse_args() | |
| if args.run_directory: | |
| assert args.run,'Alternative directory requires an already prepared --run experiment' | |
| OUT=args.run_directory.resolve() | |
| if args.run:run() | |
| else:prepare() | |