"""Score predictions against Lilambd Empire Eval. usage: python score.py --qa data/ --pred predictions.jsonl [--out score.json] [--lenient] predictions.jsonl: one JSON object per line: {"id": "...", "answer": } - numbers may be given as strings with commas or a trailing unit ("1,234 km2") - lists may be a JSON list or a comma/semicolon separated string - to abstain, answer null, "" or a phrase like "not in the dataset" / "unknown" Metrics: accuracy share of all questions answered correctly (missing = wrong) answerable_accuracy accuracy on questions that have an answer abstention_accuracy share of unanswerable questions where the system abstained hallucination_rate share of unanswerable questions where it gave an answer anyway false_abstention share of answerable questions where it abstained Breakdowns by dataset, task, difficulty and skill. """ import argparse, collections, glob, json, math, os, re, sys, unicodedata sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from package import unflat ABSTAIN = re.compile(r"^(?:null|none|n/?a|unknown|not (in|available|found|present|recorded|listed)|no (data|record|row|answer|such)|cannot (be )?(determin\w*|answer\w*|find\w*)|can't|insufficient|unanswerable|the (dataset|data|ledger|table) (does not|doesn't|has no))(?:\b|$)", re.I) def norm_s(x): s = unicodedata.normalize('NFKD', str(x)) s = ''.join(c for c in s if not unicodedata.combining(c)).casefold() s = re.sub(r'[\s_]+', ' ', s) s = re.sub(r"[\"'`.,;:!?()\[\]{}]", '', s).strip() return s def parse_num(x): if isinstance(x, bool): return None if isinstance(x, (int, float)): return float(x) m = re.search(r'[-+−]?\d[\d,]*(?:\.\d+)?(?:[eE][-+]?\d+)?|[-+−]?\.\d+', str(x).replace(' ', '').replace(' ', '')) if not m: return None return float(m.group(0).replace(',', '').replace('−', '-')) def parse_list(x): if isinstance(x, list): return [norm_s(v) for v in x] s = str(x).strip() if s.startswith('['): try: return [norm_s(v) for v in json.loads(s)] except json.JSONDecodeError: pass return [norm_s(v) for v in re.split(r'[;,\n]|\s\|\s', s) if v.strip()] def is_abstain(x): if x is None: return True if isinstance(x, str) and (not x.strip() or ABSTAIN.match(x.strip())): return True return False def correct(item, pred, lenient=False): t = item['answer_type'] gold = item['answer'] if t == 'none': return is_abstain(pred) if is_abstain(pred): return False if t == 'number': p = parse_num(pred) if p is None or math.isnan(p): return False tol = item.get('tolerance', {'rel': 0.01}) if 'abs' in tol: return abs(p - gold) <= tol['abs'] + 1e-9 return abs(p - gold) <= tol['rel'] * max(abs(gold), 1e-12) if t == 'boolean': s = norm_s(pred) v = True if s in ('true', 'yes', 'y', '1') else False if s in ('false', 'no', 'n', '0') else None return v is not None and v == gold if t == 'list_ordered': return parse_list(pred) == [norm_s(v) for v in gold] if t == 'list_set': return set(parse_list(pred)) == {norm_s(v) for v in gold} g, p = norm_s(gold), norm_s(pred) if g == p: return True if isinstance(gold, (int, float)) or re.fullmatch(r'-?\d+(\.\d+)?', g): try: gn = float(gold) except (TypeError, ValueError): # e.g. a code like '111.242.222' that only looks numeric after normalising return False pn = parse_num(pred) return pn is not None and abs(pn - gn) < 1e-9 if lenient: return re.search(r'(^|\W)' + re.escape(g) + r'($|\W)', p) is not None return False def main(): ap = argparse.ArgumentParser() ap.add_argument('--qa', required=True, help='folder with *.jsonl or one jsonl file') ap.add_argument('--pred', required=True) ap.add_argument('--out', default=None) ap.add_argument('--lenient', action='store_true', help='string answers may be embedded in a longer reply') a = ap.parse_args() files = sorted(glob.glob(os.path.join(a.qa, '*.jsonl')) + glob.glob(os.path.join(a.qa, 'data', '*.jsonl'))) if os.path.isdir(a.qa) else [a.qa] items = [unflat(json.loads(l)) for f in files for l in open(f, encoding='utf-8')] items = [it for it in items if 'answer' in it] # question-only test rows are scored by the maintainer preds = {} for l in open(a.pred, encoding='utf-8'): if l.strip(): o = json.loads(l) preds[o['id']] = o.get('answer', o.get('prediction')) agg = collections.defaultdict(lambda: [0, 0]) unans = [0, 0, 0] # n, abstained, answered ansd = [0, 0] # n, abstained for it in items: has = it['id'] in preds p = preds.get(it['id'], '__missing__') ok = has and correct(it, p, a.lenient) keys = ['all', 'dataset:' + it['dataset'], 'task:' + it['task'], f"difficulty:{it['difficulty']}"] + ['skill:' + s for s in it.get('skills', [])] for k in keys: agg[k][0] += 1 agg[k][1] += ok if it['answer_type'] == 'none': unans[0] += 1 if has and is_abstain(p): unans[1] += 1 elif has: unans[2] += 1 else: ansd[0] += 1 if has and is_abstain(p): ansd[1] += 1 res = {k: {'n': v[0], 'correct': v[1], 'accuracy': round(v[1] / v[0], 4)} for k, v in sorted(agg.items())} summary = { 'questions': len(items), 'predicted': sum(1 for it in items if it['id'] in preds), 'accuracy': res['all']['accuracy'], 'answerable_accuracy': round(sum(1 for it in items if it['answer_type'] != 'none' and it['id'] in preds and correct(it, preds[it['id']], a.lenient)) / max(1, ansd[0]), 4), 'abstention_accuracy': round(unans[1] / max(1, unans[0]), 4), 'hallucination_rate': round(unans[2] / max(1, unans[0]), 4), 'false_abstention': round(ansd[1] / max(1, ansd[0]), 4), } out = {'summary': summary, 'breakdown': res} print(json.dumps(summary, indent=1)) print('\n| slice | n | accuracy |\n|---|---|---|') for k, v in res.items(): if k.startswith(('dataset:', 'task:', 'difficulty:')) or k == 'all': print(f"| {k} | {v['n']} | {v['accuracy']:.3f} |") if a.out: json.dump(out, open(a.out, 'w'), indent=1) if __name__ == '__main__': main()