Datasets:
Download code/evaluation-code/v0.2-0c2690ae/tools/evaluation/receipts.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 7.95 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/tools/evaluation/receipts.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/v0.2-0c2690ae/tools/evaluation/receipts.py
-
curl -L -o receipts.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/tools/evaluation/receipts.py
7.95 kB
| """Per-item release receipts and the blind-answer check of whitepaper 3.5. | |
| Input: an np_export directory (items.jsonl, truth.jsonl, export.json) and, optionally, a runner run directory scored | |
| with ``runner.py score`` (the text-only preset gives the LLM blind baseline). Output, in a fresh ``--out``: | |
| - ``receipts.jsonl`` one row per exported item: source line, subtask, scaffold group, text hash, truth, | |
| constant-baseline answer and hit, LLM blind status and hit | |
| - ``table.json`` hit rates per subtask x group, reasons, verdict | |
| Subtask = the version id before '/'. Groups: no scaffold / scaffold (``tags.scaffold``). The constant baseline answers | |
| the median truth of the subtask over both groups (continuous answers; per component for points, vectors and time pairs, | |
| around the circle for angles), or, per cell, the fixed option with the most hits (choices). Both baselines must stay at or under 35% in every cell; a cell under 20 items is too few to judge. | |
| Exit: 0 pass, 1 a cell over the limit, 75 cannot judge (missing or failed blind runs, | |
| too few items, a missing group, unrecorded scaffold, a version without tolerance, list answers that have no constant, | |
| or an export whose denominator does not add up). | |
| """ | |
| import argparse | |
| import collections | |
| import hashlib | |
| import json | |
| import statistics | |
| import sys | |
| from pathlib import Path | |
| import np_answers | |
| LIMIT, MIN_CELL = 0.35, 20 | |
| NOT_JUDGED = ('NOT_RUN', 'ERROR', 'TRUNCATED') | |
| def read_jsonl(path): | |
| return [json.loads(line) for line in open(path, encoding='utf-8') if line.strip()] | |
| def hit(item, truth, value): | |
| """True / False, or None when the version has no tolerance (NO_TOLERANCE).""" | |
| return np_answers.score(item['scoring'], truth, {'status': 'PARSED', 'value': value})['passed'] | |
| def center(truths, kind): | |
| """Median truth: per component for pairs, and for angles after cutting the circle at its widest empty arc.""" | |
| if kind == 'list': | |
| return None # answers of varying length have no single constant | |
| if isinstance(truths[0], (list, tuple)): | |
| return [statistics.median(c) for c in zip(*truths)] | |
| if kind == 'angle': | |
| a = sorted(t % 360 for t in truths) | |
| gaps = [y - x for x, y in zip(a, a[1:])] + [a[0] + 360 - a[-1]] | |
| cut = a[(gaps.index(max(gaps)) + 1) % len(a)] | |
| return statistics.median(t if t >= cut else t + 360 for t in a) % 360 | |
| return statistics.median(truths) | |
| def group_of(item): | |
| scaffold = item['tags'].get('scaffold', 'unrecorded') | |
| return None if scaffold == 'unrecorded' else 'no_scaffold' if scaffold == 'none' else 'scaffold' | |
| def build(export_dir, run_dir=None): | |
| export_dir = Path(export_dir) | |
| items = read_jsonl(export_dir / 'items.jsonl') | |
| truth = {t['item_id']: t['truth'] for t in read_jsonl(export_dir / 'truth.jsonl')} | |
| den = json.loads((export_dir / 'export.json').read_text())['denominator'] | |
| reasons = [] | |
| if den['pass_rows'] != den['items'] + den['skipped_pass'] or den['items'] != len(items): | |
| reasons.append(f'denominator: {den}, items.jsonl {len(items)}') | |
| llm = {r['item_id']: r for r in read_jsonl(Path(run_dir) / 'scores.jsonl')} if run_dir else {} | |
| cells = collections.defaultdict(list) | |
| for item in items: | |
| cells[item['version_id'].split('/')[0], group_of(item)].append(item) | |
| pools = collections.defaultdict(list) # a subtask can mix answer kinds (sector and angle): one constant per kind | |
| for (subtask, _), its in cells.items(): | |
| for i in its: | |
| pools[subtask, i['tags']['answer_kind']].append(truth[i['item_id']]) | |
| rows, table = [], {} | |
| for (subtask, group), its in sorted(cells.items(), key=lambda kv: (kv[0][0], str(kv[0][1]))): | |
| consts = {} | |
| for kind in sorted({i['tags']['answer_kind'] for i in its}): | |
| same = [i for i in its if i['tags']['answer_kind'] == kind] | |
| if kind in np_answers.CONTINUOUS: | |
| consts[kind] = center(pools[subtask, kind], kind) | |
| else: # every fixed option in turn; the best one stands for "always the same option" | |
| options = [o['id'] for o in same[0]['answer'].get('options', [])] or \ | |
| [json.loads(s) for s in sorted({json.dumps(truth[i['item_id']]) for i in same})] | |
| consts[kind] = max(options, key=lambda o: sum(bool(hit(i, truth[i['item_id']], o)) for i in same)) | |
| n_hit, llm_hit, unscored, llm_status = 0, 0, 0, collections.Counter() | |
| for item in its: | |
| t, r = truth[item['item_id']], llm.get(item['item_id'], {'status': 'NOT_RUN'}) | |
| const = consts[item['tags']['answer_kind']] | |
| c = None if const is None else hit(item, t, const) | |
| n_hit += bool(c) | |
| unscored += c is None | |
| llm_status[r['status']] += 1 | |
| llm_hit += bool(r.get('passed')) | |
| rows.append({'item_id': item['item_id'], 'src': item.get('src'), 'version_id': item['version_id'], | |
| 'subtask': subtask, 'group': group, 'scaffold': item['tags'].get('scaffold'), | |
| 'answer_kind': item['tags']['answer_kind'], 'scoring': item['scoring'], | |
| 'text_sha256': hashlib.sha256(item['question']['zh'].encode()).hexdigest(), 'truth': t, | |
| 'blind_const': {'answer': const, 'hit': c}, | |
| 'blind_llm': {'status': r['status'], 'answer': r.get('answer'), 'hit': bool(r.get('passed'))}, | |
| 'review': 'NOT_REVIEWED'}) | |
| n = len(its) | |
| cell = {'n': n, 'const_answer': consts, 'const_rate': n_hit / n, 'llm_rate': llm_hit / n, | |
| 'llm_status': dict(llm_status)} | |
| cell['verdict'] = ('cannot judge: scaffold unrecorded' if group is None else | |
| f'cannot judge: {unscored} items without a constant or a tolerance' if unscored else | |
| f'too few (<{MIN_CELL})' if n < MIN_CELL else | |
| 'cannot judge: blind LLM ' + ','.join(s for s in llm_status if s in NOT_JUDGED) | |
| if any(s in NOT_JUDGED for s in llm_status) else | |
| 'over' if max(cell['const_rate'], cell['llm_rate']) > LIMIT else 'pass') | |
| table[f'{subtask} | {group}'] = cell | |
| for subtask in sorted({s for s, _ in cells}): | |
| if {g for s, g in cells if s == subtask} != {'no_scaffold', 'scaffold'}: | |
| reasons.append(f'{subtask}: missing group') | |
| verdicts = [c['verdict'] for c in table.values()] | |
| code = 75 if reasons or any(v != 'pass' and v != 'over' for v in verdicts) else 1 if 'over' in verdicts else 0 | |
| return rows, {'schema': 'release-receipts/1', 'items': len(rows), 'denominator': den, 'limit': LIMIT, | |
| 'min_cell': MIN_CELL, 'cells': table, 'reasons': reasons, 'exit_code': code} | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]) | |
| ap.add_argument('--export', required=True, help='np_export output directory') | |
| ap.add_argument('--run', help='runner run directory with scores.jsonl (text-only preset)') | |
| ap.add_argument('--out', required=True) | |
| args = ap.parse_args(argv) | |
| out = Path(args.out) | |
| if out.exists() and any(out.iterdir()): | |
| raise SystemExit(f'{out} is not empty') | |
| out.mkdir(parents=True, exist_ok=True) | |
| rows, table = build(args.export, args.run) | |
| with open(out / 'receipts.jsonl', 'w', encoding='utf-8') as fh: | |
| fh.writelines(json.dumps(r, ensure_ascii=False) + '\n' for r in rows) | |
| (out / 'table.json').write_text(json.dumps(table, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') | |
| for key, cell in table['cells'].items(): | |
| print(f"{key}: n={cell['n']} const={cell['const_rate']:.2f} llm={cell['llm_rate']:.2f} {cell['verdict']}") | |
| print('reasons:', '; '.join(table['reasons']) or '-', f"rc={table['exit_code']}") | |
| return table['exit_code'] | |
| if __name__ == '__main__': | |
| sys.exit(main()) | |