davidheineman's picture
Publish coherent math-v1 datasets
d96f432 verified
Raw History Blame Contribute Delete
23.2 kB
import ast
from collections import Counter
from dataclasses import dataclass
from fractions import Fraction
from functools import lru_cache
import fcntl
import gzip
import hashlib
import json
from pathlib import Path
import random
import re
from omegaconf import OmegaConf
import pyarrow.parquet as pq
from rich import print
from tqdm import tqdm
from functional_rl.v2_format import calculate, number, arithmetic_trace
from refined_v4.data import atomic_json, signature, write_rows
from . import REVISION
from . import envs
ROOT = Path('/nlp/scr/dhei/tiny-rl/experiments/refined-math-v1')
TASKS = envs.TASKS
SPLITS = ('sft', 'rl', 'calibration', 'dev', 'test')
GSM_CACHE = Path('/nlp/scr/dhei/tiny-rl/experiments/hinted-v1/hf-cache/datasets--openai--gsm8k/snapshots')
GSM_REVISION = '740312add88f781978c0658806c59bc2815b9866'
@dataclass
class Config:
root: str = str(ROOT)
action: str = 'build'
tokens: int = 16777216
pilot_tokens: int = 2097152
seed: int = 2718
max_arithmetic_problems: int = 18000
small_final_fraction: float = 0.
auxiliary_fraction: float = 0.
def digest(text: str) -> str:
return hashlib.sha256(text.encode()).hexdigest()
def split_for(group: str) -> str:
value = int(digest(REVISION + '/' + group)[:8], 16) % 100
for threshold, split in ((60, 'sft'), (85, 'rl'), (89, 'calibration'), (94, 'dev'), (100, 'test')):
if value < threshold:
return split
raise ValueError('Invalid split')
def arithmetic_problems():
problems = {}
for a in range(21):
for b in range(21):
for op in ('+', '-'):
if op == '-' and a < b:
continue
expression = f'({a} {op} {b})'
band = 'tiny_addsub' if a <= 9 and b <= 9 else 'small_addsub'
problems[expression] = (band, 1)
for a in range(10):
for b in range(10):
problems[f'({a} * {b})'] = ('multiplication', 1)
for a in range(10):
for b in range(10):
for c in range(10):
for left in ('+', '-'):
for right in ('+', '-'):
problems[f'(({a} {left} {b}) {right} {c})'] = ('two_step', 2)
return problems
def canonical_steps(expression: str) -> list[dict]:
tree = ast.parse(expression, mode='eval')
result = []
def visit(node):
if isinstance(node, ast.BinOp):
left, right = visit(node.left), visit(node.right)
operator = '+' if isinstance(node.op, ast.Add) else '-' if isinstance(node.op, ast.Sub) else '*'
text = f'{number(left)} {operator} {number(right)}'
value = calculate(ast.parse(text, mode='eval'))
result.append(dict(expression=text, value=number(value)))
return value
return calculate(node)
visit(tree.body)
return result
def checked_gsm(raw: dict, identity: str) -> dict:
question = raw['question'].strip()
working, answer = raw['answer'].rsplit('####', 1)
answer = number(Fraction(answer.strip().replace(',', '')))
steps = []
for expression, value in re.findall(r'<<([^<>]+)=([^<>]+)>>', working):
expression = expression.replace(',', '').strip()
expected = number(Fraction(value.strip().replace(',', '')))
actual = number(calculate(ast.parse(expression, mode='eval')))
if actual != expected:
raise ValueError('Canonical GSM equation is inconsistent')
steps.append(dict(expression=expression, value=expected))
if not steps or steps[-1]['value'] != answer:
raise ValueError('GSM requires a verified final calculation')
largest = max([abs(Fraction(x)) for x in re.findall(r'(?<![\w.])\d+(?:\.\d+)?', steps[-1]['expression'])] or [0])
band = 'easy' if len(steps) <= 2 and largest <= 20 else 'standard' if largest <= 1000 else 'hard'
return dict(source_id=identity, group='gsm8k/' + digest(question), question=question, answer=answer,
steps=steps, difficulty=band, operation_count=len(steps), question_sha256=digest(question),
equations_sha256=digest(json.dumps(steps, sort_keys=True)), source='openai/gsm8k', source_revision=GSM_REVISION)
def base_sources(config: Config) -> tuple[dict, dict]:
pools = {task: {split: [] for split in SPLITS} for task in TASKS}
excluded = []
for expression, (band, operations) in arithmetic_problems().items():
steps = canonical_steps(expression)
group = 'arithmetic/' + digest(ast.dump(ast.parse(expression, mode='eval')))
source = dict(source_id='math-v1/' + group, group=group,
question='Evaluate ' + expression + '.', answer=steps[-1]['value'], steps=steps,
difficulty=band, operation_count=operations, expression=expression,
question_sha256=digest('Evaluate ' + expression + '.'),
equations_sha256=digest(json.dumps(steps, sort_keys=True)), source='math-v1/small-arithmetic')
for task in ('arithmetic', 'arithmetic_simple'):
pools[task][split_for(group)].append(source)
raw = {split: pq.read_table(GSM_CACHE / GSM_REVISION / 'main' / f'{split}-00000-of-00001.parquet').to_pylist()
for split in ('train', 'test')}
test_groups = {'gsm8k/' + digest(row['question'].strip()) for row in raw['test']}
seen_groups = set()
for split, values in raw.items():
for index, row in enumerate(tqdm(values, desc='Verify canonical GSM equations', colour='cyan')):
identity = f'gsm8k-{split}-{index}'
try:
source = checked_gsm(row, identity)
if split == 'train' and source['group'] in test_groups:
raise ValueError('Question also appears in official test split')
if source['group'] in seen_groups:
raise ValueError('Duplicate canonical question')
seen_groups.add(source['group'])
except (ValueError, SyntaxError, ZeroDivisionError, OverflowError) as error:
excluded.append(dict(source_id=identity, reason=str(error)))
continue
fold = 'test' if split == 'test' else split_for(source['group'])
# Official test stays held out; hashed train-test fold is merged into development.
if split == 'train' and fold == 'test':
fold = 'dev'
for task in ('gsm8k', 'partial_gsm8k'):
pools[task][fold].append(source)
return pools, dict(exclusions=excluded, source_revision=GSM_REVISION,
source_inputs={split: dict(path=str(GSM_CACHE / GSM_REVISION / 'main' / f'{split}-00000-of-00001.parquet'),
sha256=signature(GSM_CACHE / GSM_REVISION / 'main' / f'{split}-00000-of-00001.parquet'), rows=len(values))
for split, values in raw.items()})
DEFAULT_STYLE = dict(opening='Work through the given quantities in order.',
transition='Use this intermediate value in the next step.',
final='The remaining calculation is', question='Evaluate {expression}.')
@lru_cache(maxsize=12000)
def trace(question: str, answer: str) -> str:
return arithmetic_trace(question, answer)
def make_row(task: str, source: dict, style: dict, style_id: int, include_hints: bool = True) -> dict:
steps = source['steps']
expression = steps[-1]['expression']
if task == 'arithmetic_simple':
reference = 'Answer: ' + trace(source['question'], source['answer'])
else:
parts = [style['opening']]
for step in steps[:-1]:
parts.append(step['expression'] + ' = ' + step['value'] + '.')
parts.append(style['transition'])
if task == 'partial_gsm8k':
reference = 'Answer: ' + ' '.join(parts) + '\nSo, the answer is ' + expression + ' = ' + source['answer']
else:
parts.append(style['final'] + ' ' + expression + '.')
reference = 'Reasoning: ' + ' '.join(parts) + '\nAnswer: ' + source['answer']
question = source['question']
if task.startswith('arithmetic'):
question = style['question'].replace('{expression}', source['expression'])
provenance = dict(revision=REVISION, source=source['source'], original_source_id=source['source_id'],
source_revision=source.get('source_revision', REVISION),
original_question=source['question'], question_sha256=source['question_sha256'],
equations_sha256=source['equations_sha256'], equations=steps, style_id=style_id,
difficulty=source['difficulty'], operation_count=source['operation_count'],
answer_digits=len(source['answer'].lstrip('-')), validation_scope='locked_source_verified_arithmetic',
teacher_controls='Generic wording only; question facts, equations and answer are immutable')
row = dict(task=task, revision=REVISION, source_id=source['source_id'], group=source['group'],
question=question, reference=reference, answer=source['answer'], tests=[], setup='', provenance=provenance)
if include_hints:
row['hint_levels'] = list(envs.available_hints(row))
if not row['hint_levels']:
raise ValueError('Source cannot support any valid suffix hint')
return row
def build_environments(config: Config, styles: list[dict]):
root = Path(config.root)
pools, audit = base_sources(config)
atomic_json(root / 'source-audit.json', audit)
for task in TASKS:
folder = root / 'data' / task
if (folder / 'manifest.json').exists():
continue
candidates = sorted(pools[task]['sft'], key=lambda source: digest(source['group']))
selected = []
for operations in (1, 2):
suitable = [source for source in candidates if source['operation_count'] == operations
and 2 <= Fraction(source['answer']) <= 20]
if suitable:
selected.append(suitable[0])
if len(selected) < 2:
selected = candidates[:2]
demos = [make_row(task, source, DEFAULT_STYLE, -1) for source in selected]
if len(demos) != 2 or demos[0]['group'] == demos[1]['group']:
raise ValueError('Need two independent SFT demonstrations')
manifests = {}
for split in SPLITS:
rows = []
excluded = []
for source in tqdm(pools[task][split], desc=f'{task}/{split} gold checks', colour='blue', mininterval=10):
row = make_row(task, source, DEFAULT_STYLE, -1)
row['demonstrations'] = [] if split == 'sft' else demos
try:
for level in row['hint_levels']:
item = envs.make_episode(row, level)
if envs.reward(item, item.completion) != 1.:
raise ValueError('Gold suffix failed its exact numeric oracle')
except ValueError as error:
excluded.append(dict(source_id=source['source_id'], reason=str(error)))
continue
rows.append(row)
path = folder / f'{split}.jsonl.gz'
write_rows(path, rows)
manifests[split] = dict(path=str(path.relative_to(root)), rows=len(rows),
source_groups=len({row['group'] for row in rows}), sha256=signature(path),
difficulty_counts=dict(Counter(row['provenance']['difficulty'] for row in rows)),
excluded=excluded,
available_by_hint={str(level): sum(level in row['hint_levels'] for row in rows) for level in range(1, 17)})
atomic_json(folder / 'manifest.json', dict(task=task, revision=REVISION, status='data_ready',
splits=manifests, shots=2, environment_revision=REVISION,
hint_policy='Choose length uniformly in1..16, then choose an eligible source; short rows remain in low-hint pools.',
gold_verification='Every exported eligible source/hint pair passes the exact numeric oracle',
source_policy='Original GSM questions and verified calculator annotations; small arithmetic with one or two operations.'))
return pools
def weighted_source(pools: dict, task: str, rng: random.Random) -> dict:
bands = {}
for source in pools[task]['sft']:
bands.setdefault(source['difficulty'], []).append(source)
if task.startswith('arithmetic'):
weights = dict(tiny_addsub=40, small_addsub=30, multiplication=15, two_step=15)
else:
weights = dict(easy=40, standard=45, hard=15)
names = [name for name in weights if bands.get(name)]
chosen = rng.choices(names, [weights[name] for name in names])[0]
return rng.choice(bands[chosen])
def small_final_calculation(source: dict) -> bool:
expression = ast.parse(source['steps'][-1]['expression'], mode='eval').body
return (isinstance(expression, ast.BinOp)
and isinstance(expression.op, (ast.Add, ast.Sub))
and all(isinstance(value, ast.Constant) and type(value.value) is int
and 0 <= value.value <= 20 for value in (expression.left, expression.right)))
def close_corpus(root: Path, target: Path, task: str, budget: int, count: dict, path: Path, handle):
handle.close()
path.with_suffix('.gz.tmp').replace(path)
manifest = dict(task=task, status='sft_ready', fresh_sft=True, revision=REVISION,
generation_revision=REVISION, generation_scope='verified_math', native_format=True,
training_token_budget=budget, available_tokens=count['available'], documents=count['documents'],
examples=count['examples'], unique_source_examples=len(count['sources']), unique_source_groups=len(count['groups']),
unique_reference_variants=len(count['variants']), reference_repetitions=count['examples'] - len(count['variants']),
difficulty_counts=dict(count['difficulties']), repeated_small_problems_intentional=True,
frozen_demonstration_examples=2,
path=str(path.relative_to(target)), sha256=signature(path), tokenizer='gpt2',
format='Two to four native examples per document; no system prompt or chat markers.',
locked_math='Teacher provides generic wording only; canonical equations, facts and labels are immutable.',
small_final_fraction=count.get('small_final_fraction', 0.),
auxiliary_fraction=count.get('auxiliary_fraction', 0.),
styles_sha256=signature(root / 'styles.json'), source_manifest=str(root / 'data' / task / 'manifest.json'))
atomic_json(target / 'sft' / task / 'manifest.json', manifest)
def build_sft(config: Config, pools: dict, styles: list[dict]):
root = Path(config.root)
if not 0 <= config.small_final_fraction <= 1:
raise ValueError('Small-calculation sampling fraction must be in [0, 1]')
if not 0 <= config.auxiliary_fraction <= 1:
raise ValueError('Arithmetic auxiliary fraction must be in [0, 1]')
# Build band indexes once; repeated small problems are intentional and audited.
indexes = {task: {} for task in TASKS}
for task in TASKS:
for source in pools[task]['sft']:
indexes[task].setdefault(source['difficulty'], []).append(source)
for task in TASKS:
folder = root / 'sft' / task
if (folder / 'manifest.json').exists():
existing = json.loads((folder / 'manifest.json').read_text())
if existing['training_token_budget'] != config.tokens or signature(root / existing['path']) != existing['sha256']:
raise ValueError('Existing immutable corpus has a different budget or checksum')
if existing.get('small_final_fraction', 0.) != config.small_final_fraction:
raise ValueError('Existing immutable corpus has a different sampling curriculum')
if existing.get('auxiliary_fraction', 0.) != config.auxiliary_fraction:
raise ValueError('Existing immutable corpus has a different auxiliary curriculum')
continue
folder.mkdir(parents=True, exist_ok=True)
pilot = root / 'pilot-2m'
(pilot / 'sft' / task).mkdir(parents=True, exist_ok=True)
rng = random.Random(f'{config.seed}/{task}')
full_path = folder / 'train.jsonl.gz'
pilot_path = pilot / 'sft' / task / 'train.jsonl.gz'
pilot_manifest = pilot / 'sft' / task / 'manifest.json'
pilot_ready = pilot_manifest.exists()
if pilot_ready:
existing_pilot = json.loads(pilot_manifest.read_text())
if (existing_pilot['training_token_budget'] != min(config.pilot_tokens, config.tokens)
or signature(pilot_path) != existing_pilot['sha256']
or existing_pilot.get('small_final_fraction', 0.) != config.small_final_fraction):
raise ValueError('Existing immutable pilot has a different budget or checksum')
if existing_pilot.get('auxiliary_fraction', 0.) != config.auxiliary_fraction:
raise ValueError('Existing immutable pilot has a different auxiliary curriculum')
handles = [gzip.open(full_path.with_suffix('.gz.tmp'), 'wt', compresslevel=3),
None if pilot_ready else gzip.open(pilot_path.with_suffix('.gz.tmp'), 'wt', compresslevel=3)]
budgets = [config.tokens, min(config.pilot_tokens, config.tokens)]
counts = [dict(tokens=0, available=0, documents=0, examples=0, groups=set(), sources=set(), variants=set(), difficulties=Counter()) for _ in budgets]
for count in counts:
count['small_final_fraction'] = config.small_final_fraction
count['auxiliary_fraction'] = config.auxiliary_fraction
if pilot_ready:
counts[1]['tokens'] = budgets[1]
bands = indexes[task]
weights = (dict(tiny_addsub=40, small_addsub=30, multiplication=15, two_step=15)
if task.startswith('arithmetic') else dict(easy=40, standard=45, hard=15))
names = [name for name in weights if bands.get(name)]
auxiliary = task in ('gsm8k', 'partial_gsm8k') and config.auxiliary_fraction > 0
auxiliary_weights = dict(tiny_addsub=40, small_addsub=30, multiplication=15, two_step=15)
auxiliary_names = ([name for name in auxiliary_weights if indexes.get('arithmetic', {}).get(name)]
if auxiliary else [])
if auxiliary and not auxiliary_names:
raise ValueError('Arithmetic auxiliary sampling requires bounded arithmetic SFT sources')
small_sources = ([source for source in pools[task]['sft'] if small_final_calculation(source)]
if task in ('gsm8k', 'partial_gsm8k') and config.small_final_fraction else [])
if task in ('gsm8k', 'partial_gsm8k') and config.small_final_fraction and len(small_sources) < 4:
raise ValueError('Small-calculation curriculum needs at least four distinct training sources')
with gzip.open(root / 'data' / task / 'rl.jsonl.gz', 'rt') as stream:
demonstrations = json.loads(next(stream))['demonstrations']
with tqdm(total=config.tokens, desc=task + ' SFT', unit='tok', unit_scale=True, colour='green', mininterval=10) as bar:
while counts[0]['tokens'] < config.tokens:
chosen = [dict(row) for row in demonstrations] if counts[0]['documents'] == 0 else []
used = {row['group'] for row in chosen}
while len(chosen) < 4:
if auxiliary and rng.random() < config.auxiliary_fraction:
band = rng.choices(auxiliary_names, [auxiliary_weights[name] for name in auxiliary_names])[0]
source = rng.choice(indexes['arithmetic'][band])
elif small_sources and rng.random() < config.small_final_fraction:
source = rng.choice(small_sources)
else:
band = rng.choices(names, [weights[name] for name in names])[0]
source = rng.choice(bands[band])
if source['group'] in used:
continue
style_id = rng.randrange(len(styles))
row = make_row(task, source, styles[style_id], style_id, include_hints=False)
if len(envs.ENC.encode_ordinary(envs.render(row))) > 480:
continue
candidate = '\n\n'.join(envs.render(value) for value in chosen + [row])
if len(envs.ENC.encode_ordinary(candidate)) > 1024:
if len(chosen) >= 2:
break
continue
chosen.append(row)
used.add(source['group'])
text = '\n\n'.join(envs.render(row) for row in chosen)
tokens = len(envs.ENC.encode_ordinary(text))
examples = [dict(source_id=row['source_id'], group=row['group'],
reference_sha256=digest(row['reference']), difficulty=row['provenance']['difficulty'],
style_id=row['provenance']['style_id']) for row in chosen]
for target, budget, count, path, handle in zip((root, pilot), budgets, counts, (full_path, pilot_path), handles, strict=True):
if count['tokens'] >= budget:
continue
usable = min(tokens, budget - count['tokens'])
handle.write(json.dumps(dict(text=text, tokens=tokens, budget_tokens=usable, examples=examples), ensure_ascii=False) + '\n')
count['tokens'] += usable
count['available'] += tokens
count['documents'] += 1
count['examples'] += len(chosen)
count['groups'].update(row['group'] for row in chosen)
count['sources'].update(row['source_id'] for row in chosen)
count['variants'].update((row['source_id'], digest(row['reference'])) for row in chosen)
count['difficulties'].update(row['provenance']['difficulty'] for row in chosen)
if count['tokens'] == budget:
close_corpus(root, target, task, budget, count, path, handle)
bar.update(min(tokens, config.tokens - bar.n))
print(f'[green]{task}: full and pilot SFT ready[/green]')
def run(config: Config):
root = Path(config.root)
root.mkdir(parents=True, exist_ok=True)
with (root / 'data-build.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
styles = json.loads((root / 'styles.json').read_text())['styles']
pools = build_environments(config, styles)
import shutil
for task in TASKS:
source = root / 'data' / task
target = root / 'pilot-2m/data' / task
if not target.exists():
shutil.copytree(source, target)
build_sft(config, pools, styles)
atomic_json(root / 'manifest.json', dict(revision=REVISION, tasks=list(TASKS), complete=True))
if __name__ == '__main__':
run(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config), OmegaConf.from_cli())))