jev-skills / code /bench_common.py
qmichalwarda's picture
Code: neutral wording
d25cd8a verified
Raw History Blame Contribute Delete
5.27 kB
"""Shared helpers for the public-dataset converters of the generators.
A converter module exposes `rows(limit, seed=0)` yielding decision rows:
{"id", "source": "hf:<short>:<task>", "state", "questions": {key: spec}, "targets": {key: {answer_id: prob}},
"label_kind": "gold" | "program" | "soft-votes", "license"}.
"""
import math
import random
from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator
def download(repo: str, filename: str, revision: str) -> str:
"""A pinned file of a Hugging Face dataset repo (cached by huggingface_hub)."""
from huggingface_hub import hf_hub_download
return hf_hub_download(repo, filename, repo_type="dataset", revision=revision)
def read_parquet(repo: str, filename: str, revision: str, columns=None):
import pandas as pd
return pd.read_parquet(download(repo, filename, revision), columns=columns)
def onehot(ids: Iterable[str], gold: str) -> dict[str, float]:
ids = list(ids)
if gold not in ids:
raise ValueError(f"gold {gold!r} not in {ids}")
return {k: float(k == gold) for k in ids}
def noul(instructions: str) -> dict:
return {"type": "noul", "instructions": instructions}
def noul_target(value: bool) -> dict[str, float]:
return {"false": float(not value), "true": float(bool(value))}
def choice(instructions: str, criteria: dict[str, str]) -> dict:
return {"type": "choice", "instructions": instructions, "criteria": dict(criteria)}
def score(instructions: str, levels: list[str]) -> dict:
return {"type": "score", "instructions": instructions, "criteria": list(levels)}
def normalize(dist: dict[str, float]) -> dict[str, float] | None:
total = sum(max(0.0, float(v)) for v in dist.values())
return {k: max(0.0, float(v)) / total for k, v in dist.items()} if total > 0 else None
def row(id: str, source: str, state: str, questions: dict, targets: dict, label_kind: str, license: str) -> dict:
return {"id": id, "source": source, "state": state, "questions": questions, "targets": targets,
"label_kind": label_kind, "license": license}
def caps(sizes: dict[str, int], limit: int) -> dict[str, int]:
"""Water-filled per-group caps: every group gets an equal share of `limit`, a group smaller than its share keeps
all of it and the rest is shared among the larger groups."""
out, left = {}, limit
order = sorted(sizes, key=lambda g: (sizes[g], g))
for i, g in enumerate(order):
share = -(-left // (len(order) - i))
out[g] = min(sizes[g], share)
left -= out[g]
return out
def balanced(groups: dict[str, list], limit: int, seed: int, convert: Callable[[str, object, random.Random], dict | None],
slack: float = 1.0) -> Iterator[dict]:
"""Rows from several groups (tasks/configs): items shuffled per group (deterministic in `seed`), each group capped
by water-filling so no group dominates, conversions that return None skipped, groups interleaved round-robin so
a prefix of the output is balanced too. `slack` > 1 raises the caps when many conversions are expected to fail."""
rng = random.Random(seed)
sizes = {g: len(v) for g, v in groups.items() if v}
cap = caps(sizes, math.ceil(limit * slack))
per: dict[str, list[dict]] = {}
for g in sorted(sizes):
grng = random.Random(f"{seed}:{g}")
order = list(range(sizes[g]))
grng.shuffle(order)
got: list[dict] = []
for i in order:
if len(got) >= cap[g]:
break
r = convert(g, groups[g][i], grng)
if r is not None:
got.append(r)
per[g] = got
names = sorted(per)
rng.shuffle(names)
n = 0
for k in range(max((len(v) for v in per.values()), default=0)):
for g in names:
if k < len(per[g]) and n < limit:
yield per[g][k]
n += 1
def letters(n: int) -> list[str]:
"""Option ids a, b, ..., z, aa, ab, ... for n options."""
out = []
for i in range(n):
s, k = "", i
while True:
s = chr(ord("a") + k % 26) + s
k = k // 26 - 1
if k < 0:
break
out.append(s)
return out
def _item(id, skill, source, state, questions, targets, license, key):
"""key: the distinctive text of the item (no page chrome or tool boilerplate) used to fingerprint the item."""
return {"id": id, "skill": skill, "source": source, "state": state, "questions": questions, "targets": targets,
"license": license, "key": key}
def _sample(items: list, n: int, rng: random.Random, by=None) -> list:
"""n items, spread evenly over the groups `by(item)` returns (water-filled)."""
if by is None:
return rng.sample(items, min(n, len(items)))
groups = defaultdict(list)
for x in items:
groups[by(x)].append(x)
for g in groups.values():
rng.shuffle(g)
out, keys = [], sorted(groups)
while len(out) < n and any(groups[k] for k in keys):
for k in keys:
if groups[k] and len(out) < n:
out.append(groups[k].pop())
return out
def screen_keys(items): # word-gram fingerprints are not shipped
return {}