davidheineman's picture
Publish coherent math-v1 datasets
f88e8d1 verified
Raw History Blame Contribute Delete
6.5 kB
from dataclasses import replace
import hashlib
import math
import random
from functional_rl import v2
from . import REVISION
TASKS = ('gsm8k', 'partial_gsm8k', 'arithmetic', 'arithmetic_simple')
ENC = v2.ENC
WEIGHTS = dict(tiny_addsub=40, small_addsub=30, multiplication=15, two_step=15,
easy=40, standard=45, hard=15)
def header(row: dict) -> str:
return 'Question: ' + row['question'] + '\n'
def render(row: dict) -> str:
return header(row) + row['reference']
def construct(row: dict, level: int, demonstrations: tuple[dict, ...]):
if type(level) is not int or not 1 <= level <= 16:
raise ValueError('Hint length must be an integer in [1, 16]')
if row['task'] not in TASKS:
raise ValueError('Unknown math task')
groups = {row['group']}
for demo in demonstrations:
if demo['task'] != row['task'] or demo['group'] in groups:
raise ValueError('Demonstrations must use distinct same-task source groups')
groups.add(demo['group'])
context = ''.join(render(demo).rstrip() + '\n\n' for demo in demonstrations)
document_header = context + header(row)
document = document_header + row['reference']
ids = ENC.encode_ordinary(document)
if len(ids) > 1024:
raise ValueError('Math episode exceeds the model context')
prompt_ids, completion_ids = ids[:-level], ids[-level:]
prompt, completion = ENC.decode(prompt_ids), ENC.decode(completion_ids)
protected = 'Reasoning:' if row['task'] in ('gsm8k', 'arithmetic') else 'Answer:'
if (len(completion_ids) != level or not prompt.startswith(document_header + protected)
or prompt + completion != document or '\ufffd' in prompt + completion):
raise ValueError('Requested hint removes protected task context')
return v2.Episode(row['task'], row['source_id'], row['group'], level,
prompt, completion, tuple(prompt_ids), tuple(completion_ids),
prompt[len(document_header):], row['reference'], row['answer'], (), '',
version=REVISION, question=row['question'], provenance=row.get('provenance', {}),
demonstrations=tuple(dict(task=d['task'], source_id=d['source_id'], group=d['group'],
text=render(d), split='sft') for d in demonstrations))
def available_hints(row: dict) -> tuple[int, ...]:
if 'hint_levels' in row:
return tuple(row['hint_levels'])
result = []
for level in range(1, 17):
try:
construct(row, level, ())
result.append(level)
except ValueError:
pass
return tuple(result)
def make_episode(row: dict, level: int):
return construct(row, level, tuple(row.get('demonstrations', ())))
def reward(item, completion: str, judge=None) -> float:
return v2.reward(item, completion, judge)
class Pool:
def __init__(self, rows: list[dict]):
self.rows = rows
self.weights = dict(WEIGHTS)
declared = {}
for row in rows:
band = row['provenance']['difficulty']
weight = row['provenance'].get('problem_sampling_weight')
if weight is not None:
if not math.isfinite(weight) or weight <= 0:
raise ValueError('Problem sampling weights must be positive and finite')
if band in declared and declared[band] != weight:
raise ValueError('Inconsistent sampling weights within a difficulty band')
declared[band] = weight
self.weights.update(declared)
self.by_hint = {level: [row for row in rows if level in available_hints(row)]
for level in range(1, 17)}
if any(not rows for rows in self.by_hint.values()):
raise ValueError('Every hint length needs eligible questions')
self.by_band = {level: {} for level in range(1, 17)}
for level, selected in self.by_hint.items():
for row in selected:
self.by_band[level].setdefault(row['provenance']['difficulty'], []).append(row)
def sample(self, rng: random.Random):
level = rng.randint(1, 16)
bands = list(self.by_band[level])
band = rng.choices(bands, [self.weights[name] for name in bands])[0]
return make_episode(rng.choice(self.by_band[level][band]), level)
def fixed_panel(rows: list[dict], queries: int, seed: int):
if queries < 16 or queries % 16:
raise ValueError('Evaluation size must be a positive multiple of 16')
pool = Pool(rows)
result, used, pairs = [], set(), set()
for index in range(queries):
level = index % 16 + 1
candidates = sorted(pool.by_hint[level], key=lambda row: hashlib.sha256(
f'{seed}/{level}/{row["group"]}'.encode()).hexdigest())
bands = sorted(pool.by_band[level])
band = bands[(index // 16) % len(bands)]
preferred = [row for row in candidates if row['provenance']['difficulty'] == band]
candidates = preferred + [row for row in candidates if row['provenance']['difficulty'] != band]
fresh = [row for row in candidates if row['group'] not in used]
eligible = [row for row in candidates if (row['group'], level) not in pairs]
if not eligible:
raise ValueError('Insufficient unique source/hint evaluation pairs')
row = (fresh or eligible)[0]
used.add(row['group'])
pairs.add((row['group'], level))
result.append((row, level))
return result
def stratified_panel(rows: list[dict], queries: int, seed: int):
if queries < 16 or queries % 16:
raise ValueError('Evaluation size must be a positive multiple of 16')
pool = Pool(rows)
result, used, pairs = [], set(), set()
for index in range(queries):
level = index % 16 + 1
bands = sorted(pool.by_band[level])
band = bands[(index // 16) % len(bands)]
candidates = sorted(pool.by_band[level][band], key=lambda row: hashlib.sha256(
f'{seed}/{level}/{row["group"]}'.encode()).hexdigest())
eligible = [row for row in candidates if (row['group'], level) not in pairs]
if not eligible:
raise ValueError(f'Insufficient unique {band}/hint-{level} evaluation pairs')
fresh = [row for row in eligible if row['group'] not in used]
row = (fresh or eligible)[0]
used.add(row['group'])
pairs.add((row['group'], level))
result.append((row, level))
return result