empire-eval / scripts /verify.py
Lilambd's picture
Publish Lilambd Empire Eval
7f9a652 verified
Raw History Blame Contribute Delete
4.46 kB
"""Re-derive every answer from the dataset files and check the evidence rows.
usage: python verify.py --data-root ROOTS.json --qa DIR_OR_JSONL [--strict-sha]
For each question:
1. the files it cites must exist and (with --strict-sha) match manifest sha256
2. every evidence row_id must exist and its key columns must hold the stated values
3. the recipe is run again on freshly loaded files; the result must equal `answer`
4. for lookups, the cited row itself must hold the answer in the cited column
Exit code 0 only if every question passes.
"""
import argparse, glob, json, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from evallib import Store, plain, run, sha256
import importlib
from build import MODULES, load_module
from package import unflat
def same(a, b):
if isinstance(a, float) or isinstance(b, float):
try:
return abs(float(a) - float(b)) <= 1e-9 * max(1.0, abs(float(a)))
except (TypeError, ValueError):
return False
return a == b
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--data-root', required=True)
ap.add_argument('--qa', required=True)
ap.add_argument('--strict-sha', action='store_true')
ap.add_argument('--report', default=None, help='write {set: {questions, failed}} JSON here')
a = ap.parse_args()
roots = json.load(open(a.data_root))
paths = (sorted(glob.glob(os.path.join(a.qa, 'data', '*.jsonl'))) or sorted(glob.glob(os.path.join(a.qa, '*.jsonl')))) if os.path.isdir(a.qa) else [a.qa]
man = {}
mp = os.path.join(a.qa, 'manifest.json')
if os.path.isdir(a.qa) and os.path.exists(mp):
man = json.load(open(mp))['datasets']
total = bad = 0
report = {}
for p in paths:
name = os.path.basename(p)[:-6]
if name not in roots:
print(f'{name}: no data root, skipped')
continue
m = load_module(name)
if hasattr(m, 'setup'):
m.setup(roots[name])
store = Store(roots[name], getattr(m, 'STR', {}))
if a.strict_sha and name in man:
for f, meta in man[name]['files'].items():
h = sha256(os.path.join(roots[name], f))
if h != meta['sha256']:
print(f'{name}: {f} sha256 differs from manifest (dataset moved on); answers may be stale')
n = nb = 0
errs = []
for line in open(p, encoding='utf-8'):
it = unflat(json.loads(line))
if it.get('recipe') is None:
gen = report.setdefault('_generator_checked', 0)
report['_generator_checked'] = gen + 1
continue
n += 1
why = None
try:
for e in it['evidence']:
df = store[e['file']]
if not (1 <= e['row'] <= len(df)):
why = f"row {e['row_id']} missing"
break
row = df.iloc[e['row'] - 1]
for k, v in e['key'].items():
if not same(plain(row[k]), v):
why = f"{e['row_id']} key {k}: {plain(row[k])!r} != {v!r}"
break
if why:
break
if not why:
ans, _ = run(it['recipe'], store)
if not same(ans, it['answer']):
why = f'recipe gives {ans!r}, file says {it["answer"]!r}'
if not why and it['recipe']['op'] == 'lookup':
e = it['evidence'][0]
v = plain(store[e['file']].iloc[e['row'] - 1][it['recipe']['col']])
if not same(v, it['answer']):
why = f'cited cell holds {v!r}'
except Exception as ex: # noqa
why = f'{type(ex).__name__}: {ex}'
if why:
nb += 1
errs.append((it['id'], why))
total += n
bad += nb
report[name] = {'questions': n, 'failed': nb}
print(f'{name}: {n - nb}/{n} pass' + (f' e.g. {errs[:3]}' if errs else ''))
print(f'ALL: {total - bad}/{total} pass')
if a.report:
json.dump(report, open(a.report, 'w'), indent=1)
sys.exit(1 if bad else 0)
if __name__ == '__main__':
main()