empire-eval / scripts /evallib.py
Lilambd's picture
Publish Lilambd Empire Eval
7f9a652 verified
Raw History Blame Contribute Delete
11.9 kB
"""Lilambd Empire Eval - core: table loading, recipe executor, item builder.
Every question carries a machine-readable `recipe`. The answer is never typed
by hand: it is what the recipe returns when run against the published files.
`verify.py` re-runs every recipe from the raw files and checks the answer and
the evidence rows again. Row ids are `<file>#<n>` where n is the 1-based data
row of the CSV (header excluded), i.e. physical line n+1.
"""
import hashlib, json, math, os, random, re
import numpy as np
import pandas as pd
NA_VALUES = [''] # keep "NA" (Namibia), "None", "null" as strings
def sha256(path, chunk=1 << 20):
h = hashlib.sha256()
with open(path, 'rb') as f:
while True:
b = f.read(chunk)
if not b:
break
h.update(b)
return h.hexdigest()
def read_table(path, str_cols=()):
dtype = {c: str for c in str_cols}
if path.endswith('.parquet'):
df = pd.read_parquet(path)
for c in str_cols:
df[c] = df[c].astype('string')
else:
df = pd.read_csv(path, keep_default_na=False, na_values=NA_VALUES, dtype=dtype, low_memory=False)
df['_row'] = np.arange(1, len(df) + 1)
return df
class Store:
"""rel_path -> DataFrame for one dataset, with lazily loaded tables."""
def __init__(self, root, str_cols=None):
self.root = root
self.str_cols = str_cols or {}
self._t = {}
def __getitem__(self, rel):
if rel not in self._t:
self._t[rel] = read_table(os.path.join(self.root, rel), self.str_cols.get(rel, ()))
return self._t[rel]
def files(self):
return list(self._t)
# ---------------------------------------------------------------- recipe
OPS = {
'==': lambda s, v: s == v,
'!=': lambda s, v: s != v,
'>': lambda s, v: s > v,
'>=': lambda s, v: s >= v,
'<': lambda s, v: s < v,
'<=': lambda s, v: s <= v,
'in': lambda s, v: s.isin(v),
'notna': lambda s, v: s.notna(),
'isna': lambda s, v: s.isna(),
'contains': lambda s, v: s.astype(str).str.contains(v, case=False, regex=False, na=False),
}
def _coerce(series, v):
if isinstance(v, (int, float)) and not isinstance(v, bool):
return pd.to_numeric(series, errors='coerce'), v
if isinstance(v, list):
return series.astype(str), [str(x) for x in v]
if v is None:
return series, v
return series.astype(str), str(v)
def select(df, where, env=None):
m = pd.Series(True, index=df.index)
for col, op, val in where:
if isinstance(val, str) and val.startswith('$') and env is not None:
val = env[val[1:]]
s, v = _coerce(df[col], val)
m &= OPS[op](s, v).fillna(False).astype(bool)
return df[m]
def num(x):
if x is None:
return None
try:
f = float(x)
except (TypeError, ValueError):
return x
if math.isnan(f):
return None
if f.is_integer() and abs(f) < 1e15:
return int(f)
return float(f'{f:.6g}')
def plain(x):
if x is pd.NA or x is pd.NaT:
return None
if isinstance(x, (np.integer,)):
return int(x)
if isinstance(x, (np.floating, float)):
return num(float(x))
if isinstance(x, (np.bool_,)):
return bool(x)
if x is None or (isinstance(x, float) and math.isnan(x)):
return None
return x
class RecipeError(Exception):
pass
def run(recipe, store, env=None):
"""Return (answer, evidence_rows) where evidence_rows = [(file, row_no)]."""
env = dict(env or {})
op = recipe['op']
if op == 'chain':
ev = []
ans = None
for i, step in enumerate(recipe['steps']):
ans, e = run(step, store, env)
env[step.get('as', f's{i}')] = ans
ev += e
return ans, ev
if op in ('diff', 'ratio', 'compare', 'same'):
parts = [run(p, store, env) for p in recipe['parts']]
vals = [p[0] for p in parts]
ev = sum((p[1] for p in parts), [])
if op == 'diff':
return num(vals[0] - vals[1]), ev
if op == 'ratio':
if not vals[1]:
raise RecipeError('ratio by zero')
return num(vals[0] / vals[1]), ev
if op == 'same':
return bool(vals[0] == vals[1]), ev
# compare: labels -> the label with the larger (or smaller) value
labels = recipe['labels']
if any(v is None or isinstance(v, str) for v in vals):
raise RecipeError('non-numeric compare')
if len(set(vals)) != len(vals):
raise RecipeError('tie')
k = int(np.argmax(vals)) if recipe.get('dir', 'max') == 'max' else int(np.argmin(vals))
return labels[k], ev
f = recipe['file']
df = store[f]
rows = select(df, recipe.get('where', []), env)
if op == 'absent':
if len(rows):
raise RecipeError('absent but found')
return None, []
if op == 'lookup':
if len(rows) != 1:
raise RecipeError(f'lookup matched {len(rows)}')
v = rows.iloc[0][recipe['col']]
v = plain(v)
if v is None or (isinstance(v, str) and not v.strip()):
raise RecipeError('lookup empty')
return v, [(f, int(rows.iloc[0]['_row']))]
if op == 'lookup_many': # sorted list of a column for all matching rows
if not len(rows):
raise RecipeError('empty')
vals = sorted({str(plain(v)) for v in rows[recipe['col']] if plain(v) is not None})
return vals, [(f, int(r)) for r in rows['_row']]
if op in ('argmax', 'argmin', 'topk', 'bottomk'):
col = recipe['col']
r2 = rows.assign(_v=pd.to_numeric(rows[col], errors='coerce')).dropna(subset=['_v'])
if len(r2) < recipe.get('min_rows', 2):
raise RecipeError('too few rows')
asc = op in ('argmin', 'bottomk')
r2 = r2.sort_values(['_v', '_row'], ascending=[asc, True])
k = recipe.get('k', 1)
if len(r2) > k and r2['_v'].iloc[k - 1] == r2['_v'].iloc[k]:
raise RecipeError('tie at cut')
top = r2.head(k)
ret = recipe['return']
vals = [plain(v) for v in top[ret]]
if len(set(map(str, vals))) != len(vals):
raise RecipeError('duplicate labels in top')
ev = [(f, int(r)) for r in top['_row']]
if op in ('argmax', 'argmin'):
return vals[0], ev
return vals, ev
if op == 'group_top': # group rows by `by`, size or sum(col), return the top group's key
r2 = rows[rows[recipe['by']].notna()]
g = r2.groupby(recipe['by']).size() if recipe.get('agg', 'count') == 'count' else pd.to_numeric(r2[recipe['col']], errors='coerce').groupby(r2[recipe['by']]).sum()
if len(g) < 2:
raise RecipeError('too few groups')
g = g.sort_values(ascending=False)
if g.iloc[0] == g.iloc[1]:
raise RecipeError('tie')
key = g.index[0]
win = r2[r2[recipe['by']] == key]
return plain(key), [(f, int(r)) for r in win['_row'][:recipe.get('ev_cap', 50)]]
if op == 'count':
return int(len(rows)), [(f, int(r)) for r in rows['_row'][:recipe.get('ev_cap', 50)]]
if op == 'nunique':
return int(rows[recipe['col']].nunique()), [(f, int(r)) for r in rows['_row'][:50]]
if op in ('sum', 'mean', 'max', 'min', 'median'):
v = pd.to_numeric(rows[recipe['col']], errors='coerce').dropna()
if not len(v):
raise RecipeError('empty agg')
out = getattr(v, op)()
return num(out), [(f, int(r)) for r in rows['_row'][:recipe.get('ev_cap', 50)]]
raise RecipeError(f'unknown op {op}')
def evidence_block(ev, store, keys, n_total=None):
out = []
seen = set()
for f, r in ev:
if (f, r) in seen:
continue
seen.add((f, r))
row = store[f].iloc[r - 1]
k = {c: plain(row[c]) for c in keys.get(f, []) if c in row.index}
out.append({'row_id': f'{f}#{r}', 'file': f, 'row': r, 'key': k})
return out
# ---------------------------------------------------------------- builder
class Builder:
def __init__(self, dataset, store, keys, revision, seed=20261103, prefix=None):
self.dataset = dataset
self.store = store
self.keys = keys # file -> key columns shown in evidence
self.revision = revision
self.items = []
self.rng = random.Random(seed)
self.prefix = prefix or dataset.split('/')[-1]
self.fail = {}
self._q = set()
def add(self, task, question, recipe, unit=None, tol=None, difficulty=1, skills=(), note=None, answer_format=None):
if question in self._q:
return False
try:
ans, ev = run(recipe, self.store)
except (RecipeError, KeyError, ValueError, IndexError, TypeError, ZeroDivisionError) as e:
self.fail[type(e).__name__ + ':' + str(e)[:30]] = self.fail.get(type(e).__name__ + ':' + str(e)[:30], 0) + 1
return False
if isinstance(ans, float) and (math.isnan(ans) or math.isinf(ans)):
return False
if ans is None and task != 'unanswerable':
return False
if isinstance(ans, bool):
atype = 'boolean'
elif isinstance(ans, (int, float)):
atype = 'number'
elif isinstance(ans, list):
atype = 'list_ordered' if recipe.get('op') in ('topk', 'bottomk') else 'list_set'
elif ans is None:
atype = 'none'
else:
atype = 'string'
if atype == 'number' and tol is None:
tol = {'abs': 0} if isinstance(ans, int) and recipe.get('op') in ('count', 'nunique') else {'rel': 0.01}
self._q.add(question)
item = {
'id': f'{self.prefix}-{len(self.items) + 1:04d}',
'dataset': self.dataset,
'revision': self.revision,
'task': task,
'difficulty': difficulty,
'skills': list(skills),
'question': question,
'answer': ans,
'answer_type': atype,
}
if tol is not None and atype == 'number':
item['tolerance'] = tol
if unit:
item['unit'] = unit
if answer_format:
item['answer_format'] = answer_format
item['evidence'] = evidence_block(ev, self.store, self.keys)
if recipe.get('op') in ('group_top', 'count', 'sum', 'mean', 'nunique', 'max', 'min', 'median', 'argmax', 'argmin', 'topk', 'bottomk', 'absent'):
item['evidence_scope'] = {'file': recipe['file'], 'filter': recipe.get('where', [])}
item['recipe'] = recipe
if note:
item['note'] = note
self.items.append(item)
return True
def sample(self, seq, k):
seq = list(seq)
if len(seq) <= k:
self.rng.shuffle(seq)
return seq
return self.rng.sample(seq, k)
def fmt(v, nd=None):
if isinstance(v, float):
if nd is not None:
return f'{v:,.{nd}f}'
return f'{v:,.6g}'
if isinstance(v, int):
return f'{v:,}'
return str(v)
def _jd(o):
if o is pd.NA:
return None
if isinstance(o, np.generic):
return o.item()
raise TypeError(type(o).__name__)
def write_jsonl(items, path):
with open(path, 'w', encoding='utf-8') as f:
for it in items:
f.write(json.dumps(it, ensure_ascii=False, default=_jd) + '\n')