File size: 4,185 Bytes
87ab2b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deterministic task checks only. Reference smoke tests are not model baselines."""
import argparse,json,math,re,sys
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
from common import *

def parse_strict(s):
    def invalid(x):raise ValueError('nonfinite JSON '+x)
    def unique(pairs):
        d={}
        for k,v in pairs:
            if k in d:raise ValueError('duplicate JSON key')
            d[k]=v
        return d
    o=json.loads(s,parse_constant=invalid,object_pairs_hook=unique)
    if not isinstance(o,dict):raise ValueError('JSON object required')
    return o

def check_one(check,prediction):
    typ=check['type'];expected=check['expected']
    try:
        if typ.startswith('json_'):
            value=parse_strict(prediction)
            for key in check['target'].split('.'):value=value[key]
            expected=json.loads(expected)
            if typ=='json_number':return type(value) in [int,float] and math.isfinite(value) and abs(value-expected)<=check['tolerance']
            return type(value)==type(expected) and value==expected
        if typ=='contains':return norm(expected) in norm(prediction)
        if typ=='citation_set':return set(re.findall(r'\[([^\[\]]+)\]',prediction))==set(json.loads(expected))
    except (ValueError,KeyError,TypeError,OverflowError):return False
    raise ValueError('Unknown check type '+typ)

def score_record(record,prediction):
    checks=record['checks'];out=[]
    for c in checks:out.append({'type':c['type'],'target':c['target'],'metric':c['metric'],'weight':c['weight'],'passed':bool(check_one(c,prediction))})
    metrics={}
    for metric in ['instruction_following','methodological_correctness','groundedness','citation_correctness','abstention_accuracy','task_completion','format_compliance']:
        applicable=[r for r in out if r['metric']==metric]
        metrics[metric]=sum(r['weight']*r['passed'] for r in applicable)/sum(r['weight'] for r in applicable) if applicable else None
    if any(c['type'].startswith('json_') for c in checks):
        try:parse_strict(prediction);metrics['format_compliance']=1.
        except Exception:metrics['format_compliance']=0.
    return {'id':record['id'],'metrics':metrics,'checks':out,'qualitative_rubric_status':'pending_independent_review','note':'Keyword, label and citation-set checks do not verify full methodological correctness or entailment.'}

def evaluate(config,predictions,reference_smoke=False):
    rows=[r for c,_,r in all_data() if c==config]
    expected={r['id'] for r in rows}
    if set(predictions)!=expected:raise ValueError('Prediction IDs must match configuration exactly; missing/extra IDs are not silently skipped')
    scores=[score_record(r,predictions[r['id']]) for r in rows];aggregate={}
    for k in scores[0]['metrics']:
        v=[s['metrics'][k] for s in scores if s['metrics'][k] is not None]
        aggregate[k]={'mean':sum(v)/len(v) if v else None,'applicable_records':len(v)}
    return {'config':config,'records':len(scores),'run_type':'reference_consistency_smoke_NOT_MODEL_BASELINE' if reference_smoke else 'external_predictions','aggregate':aggregate,'scores':scores,'baselines_claimed':False if reference_smoke else 'only supplied predictions; model identity must be recorded separately'}
if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--config',choices=['benchmark','rag'],required=True);p.add_argument('--predictions',type=Path);p.add_argument('--reference-smoke',action='store_true');p.add_argument('--output',type=Path,required=True);a=p.parse_args()
    if bool(a.predictions)==a.reference_smoke:p.error('Choose predictions OR reference-smoke')
    if a.reference_smoke:preds={r['id']:r['reference_answer'] for c,_,r in all_data() if c==a.config}
    else:
        lines=[json.loads(l) for l in a.predictions.read_text().splitlines()];preds={r['id']:r['prediction'] for r in lines}
        if len(preds)!=len(lines):raise ValueError('Duplicate prediction IDs')
    result=evaluate(a.config,preds,a.reference_smoke);dump(a.output,result);print({'run_type':result['run_type'],'records':result['records'],'aggregate':result['aggregate']})