davidheineman's picture
Publish coherent math-v1 datasets
7c0f087 verified
Raw History Blame Contribute Delete
18 kB
from dataclasses import dataclass
import fcntl
import json
from pathlib import Path
import shutil
import time
from huggingface_hub import CommitOperationAdd, HfApi
from omegaconf import OmegaConf
from rich import print
from refined_v4 import publish as shared
from .data import ROOT, TASKS
REPO = 'davidheineman/tiny-rl-refined-math-v1'
STAGES = (
('full', '', 16777216, '', 'sft', 'rl_envs'),
('pilot-2m', 'pilot-2m', 2097152, 'pilot-2m/', 'sft_2m', 'rl_envs_2m'),
('aligned-2m', 'iterations/aligned-v1', 2097152, 'aligned-2m/', 'sft_aligned_2m', 'rl_envs_aligned_2m'),
('canonical-2m', 'iterations/canonical-v1', 2097152, 'canonical-2m/', 'sft_canonical_2m', 'rl_envs_canonical_2m'),
('bridge-2m', 'iterations/bridge-v1', 2097152, 'bridge-2m/', 'sft_bridge_2m', 'rl_envs_bridge_2m'),
('smallcalc-2m', 'iterations/smallcalc-v1', 2097152, 'smallcalc-2m/', 'sft_smallcalc_2m', 'rl_envs_smallcalc_2m'),
('auxiliary-2m', 'iterations/aux-smallmath-v1', 2097152, 'auxiliary-2m/', 'sft_auxiliary_2m', 'rl_envs_auxiliary_2m'),
('visible-2m', 'iterations/gsm-visible-v2', 2097152, 'visible-2m/', 'sft_visible_2m', 'rl_envs_visible_2m'),
('final-step-2m', 'iterations/gsm-final-step-v3', 2097152, 'final-step-2m/', 'sft_final_step_2m', 'rl_envs_final_step_2m'),
('auxiliary-full', 'curricula/auxiliary-full-v1', 16777216, 'auxiliary-full/', 'sft_auxiliary', 'rl_envs_auxiliary'),
('bridge-full', 'curricula/bridge-full-v1', 16777216, 'bridge-full/', 'sft_bridge', 'rl_envs_bridge'),
('visible-full', 'curricula/gsm-visible-full-v2', 16777216, 'visible-full/', 'sft_visible', 'rl_envs_visible'),
('final-step-full', 'curricula/gsm-final-step-full-v3', 16777216, 'final-step-full/', 'sft_final_step', 'rl_envs_final_step'))
@dataclass
class Config:
root: str = str(ROOT)
repo: str = REPO
action: str = 'upload'
interval: int = 60
def card(states: dict, repo: str, verification: dict) -> str:
lines = ['---', 'configs:']
for stage, source, budget, prefix, config, environment_config in STAGES:
if any(state.get('sft_fingerprint') for state in states.get(stage, {}).values()):
lines += [f'- config_name: {config}', ' data_files:', ' - split: train',
f' path: {prefix}data/sft/*/*.parquet']
if states.get(stage):
lines += [f'- config_name: {environment_config}', ' data_files:']
for split in ('train', 'validation', 'test'):
lines += [f' - split: {split}', f' path: {prefix}data/rl_envs/{split}/*/*.parquet']
lines += ['---', '', '# Tiny RL math-v1', '',
'Repaired GSM8k, Partial GSM8k, Arithmetic and Arithmetic Simple datasets. '
'The full SFT budget is 16,777,216 predictions per task; pilots contain 2,097,152. '
'SFT documents contain 2–4 native examples, without system prompts or chat control tokens.', '',
'GSM uses original questions and calculator annotations from openai/gsm8k at pinned revision '
'740312add88f781978c0658806c59bc2815b9866. Each equation is checked exactly. '
'The API supplies only short generic phrases from a closed vocabulary; it cannot change facts, equations, or answers. '
'Original GSM test questions stay held out. Source exclusions and duplicate handling are recorded in source-audit.json.', '',
'Arithmetic has one or two operations. Its SFT mixture is 40% tiny addition/subtraction with 0–9 inputs, '
'30% addition/subtraction with 0–20 inputs, 15% multiplication with 0–9 inputs, and 15% two-step small expressions. '
'Answers are bounded between -18 and 81. Repeated small problems are intentional; diversity is not obtained by increasing problem size.', '',
'Choose the missing-token count uniformly from 1 through 16, then choose a complexity band and an eligible source. '
'Renormalize mixture weights over the bands available at that length. '
'Short references support low hints and are retained. The environment configuration exports only eligible source/hint pairs; '
'not every source supports all 16 cuts. `provenance` records difficulty, operation count, answer width, and immutable equations.', '',
'All exported eligible gold suffixes pass the numeric oracle. Source groups are disjoint across '
'SFT/RL/calibration/development/test. Demonstrations use SFT groups. Native templates and source records are included '
'under raw/, provenance/, styles.json, and code/. Reconstruct a row from its source identity and style_id; '
'style_id=-1 selects DEFAULT_STYLE in code/refined_math/data.py. '
'the SFT text column is the actual training document.', '',
'Use sft / rl_envs for full-budget data and sft_2m / rl_envs_2m for pilot data. '
'RL train/validation/test correspond to RL/dev/test sources. JSON-valued columns are serialized JSON strings.', '',
'`sft_aligned_2m` is a later controlled revision: about half its examples use the exact frozen '
'environment wording, and half use the original API wording. It retains the same source folds and exact 2M budget. '
'Its matching environment config is rl_envs_aligned_2m; the environment assets are unchanged.', '',
'`sft_canonical_2m` uses only the frozen environment wording. `sft_bridge_2m` uses '
'approximately 75% computation subtasks and 25% original word problems for GSM. '
'A subtask asks for the final verified equation from an SFT-only source; it retains '
'the original source group, answer and question provenance. Arithmetic remains canonical. '
'No held-out equations are used to produce SFT. Matching `rl_envs_canonical_2m` and '
'`rl_envs_bridge_2m` retain the original word-problem environments byte-for-byte. '
'The styles and alignment audits record the exact mixtures. See code/refined_math/aligned.py.', '',
'`sft_auxiliary_2m` uses about 75% bounded arithmetic examples in each GSM variant’s '
'native layout and 25% original GSM word problems. Auxiliary arithmetic comes only '
'from the independent arithmetic SFT fold, disjoint from every held-out source fold. '
'Auxiliary identities and source domains remain explicit in provenance. Arithmetic tasks '
'remain canonical. `rl_envs_auxiliary_2m` retains the original GSM word problems and all '
'source/hint cuts; this curriculum changes SFT only.', '',
'`sft_visible_2m` / `rl_envs_visible_2m` define the separate visible-calculation GSM revision. '
'Original GSM questions retain the verified final calculation in the question context at every '
'1–16-token cut. Easy is addition/subtraction of integers in 0–20; standard has up to two '
'operations on integer literals of magnitude at most 100 with integer result at most 1,000; '
'hard retains the other original calculations. RL samples difficulty bands 70/20/10 after '
'choosing the hint uniformly; evaluation uses equal bands. Literal final expressions are '
'excluded because supplying them would directly give the answer. Source exclusions, exact '
'budgets and protected-context checks are recorded in context-audit.json and source-audit.json. '
'These scores describe a different hinted input from the original full-GSM challenge. '
'Native layouts and multiple examples per document are retained. The 16M counterparts '
'are sft_visible / rl_envs_visible; sft_auxiliary and sft_bridge provide the full earlier curricula.', '',
'`sft_final_step_2m` / `rl_envs_final_step_2m` retain the visible calculation and the same '
'GSM question folds and difficulty range, with a separate reference revision. References '
'explain the supplied final operation in one sentence followed by the equation and answer, '
'rather than a variable chain of intermediate steps. Operators use consistent spacing. '
'This makes the stopping point explicit at longer cuts. This is an experimental task '
'revision; matched learning results are listed below. Its full-budget counterparts '
'are sft_final_step / rl_envs_final_step when ready. Reconstruct visible/final-step rows '
'with code/refined_math/visible.py and the exported styles.json; rebuilding final-step '
'data requires final_step_reference=true. See its context-audit.json.', '',
'`sft_smallcalc_2m` is an isolated curriculum control using the original word problems '
'and canonical wording. Its GSM source sampler draws 80% of examples from training sources '
'whose final equation is a single addition/subtraction with integer operands 0..20, '
'and 20% from the original mixture. The realized small-calculation fraction is slightly '
'higher because the broad mixture also contains these problems. No questions or equations '
'are rewritten. Arithmetic uses the ordinary canonical corpus. '
'`rl_envs_smallcalc_2m` retains the same complete word-problem pools; there is no '
'easier evaluation subset. The training results are still being investigated.', '',
'The verified 32M Arithmetic Simple run uses the original sft_2m data, 512-token SFT batches, '
'Q/K RMS 0.1, undamped Q/K updates, one-third RL rates, KL 0.1, and 65,536 RL samples. '
'On 256 held-out source groups it scores 60.1% after SFT and 62.7% after RL. '
'The paired 95% interval for the gain is +0.5 to +4.8 percentage points. '
'Verification files are under verification/. GSM accuracy remains low and is still under investigation.', '',
'| Held-out comparison | SFT pass@1 | RL pass@1 | Gain (pp) | Paired 95% interval (pp) | Questions |',
'|---|---:|---:|---:|---:|---:|']
for name, result in sorted(verification.items()):
low, high = result['uplift_ci95']
lines.append(f'| {name} | {result["sft_pass1"]:.2%} | {result["rl_pass1"]:.2%} | '
f'{100 * result["uplift"]:+.2f} | [{100 * low:+.2f}, {100 * high:+.2f}] | {result["queries"]} |')
lines += ['',
'| Stage | Task | RL sources | Dev sources | Test sources | SFT tokens |', '|---|---|---:|---:|---:|---:|']
for stage, tasks in states.items():
for task, state in sorted(tasks.items()):
counts = state['environment_counts']
lines.append(f'| {stage} | {task} | {counts["train"]["source_rows"]} | '
f'{counts["validation"]["source_rows"]} | {counts["test"]["source_rows"]} | '
f'{state.get("sft_budget_tokens", "pending")} |')
return '\n'.join(lines) + '\n'
def materialize_ready_data(settings, task: str):
original = shared.source_state
def source_state(folder: Path, selected_task: str):
environments, supervised = original(folder, selected_task)
hold_path = folder / 'holds.json'
hold = shared.read_json(hold_path).get(selected_task, {}) if hold_path.exists() else {}
manifest_path = folder / 'sft' / selected_task / 'manifest.json'
training_hold = str(hold.get('reason', '')).startswith('2M iterative debugging:')
if supervised is None and training_hold and not hold.get('pending_revision') and manifest_path.exists():
candidate = shared.read_json(manifest_path)
if (candidate.get('status') == 'sft_ready' and candidate.get('fresh_sft') is True
and candidate.get('generation_scope') == 'verified_math'):
supervised = candidate
return environments, supervised
shared.source_state = source_state
try:
return shared.materialize_task(settings, task)
finally:
shared.source_state = original
def upload(config: Config):
root = Path(config.root)
stage = root / 'publication'
stage.mkdir(parents=True, exist_ok=True)
receipt = stage / 'published.json'
previous = shared.read_json(receipt) if receipt.exists() else dict(files={}, states={})
states, files = {}, {}
for label, relative, budget, prefix, sft_config, environment_config in STAGES:
source = root / relative
states[label] = {}
if relative.startswith('curricula/') and not any((source / name).exists()
for name in ('alignment-audit.json', 'context-audit.json')):
continue
settings = shared.Config(root=str(source), tasks=list(TASKS), tokens_per_task=budget)
for task in TASKS:
manifest = source / 'sft' / task / 'manifest.json'
if not manifest.exists():
continue
state = materialize_ready_data(settings, task)
if state is None:
continue
states[label][task] = state
for metadata in state['env_files'] + state.get('sft_files', []) + state.get('sft_provenance_files', []):
path = source / 'publish' / metadata['path']
files[prefix + metadata['path']] = path
files[prefix + 'manifests/' + task + '.json'] = source / 'publish/manifests' / (task + '.json')
files[prefix + 'raw_sft/' + task + '.jsonl.gz'] = source / 'sft' / task / 'train.jsonl.gz'
for name in ('styles.json', 'alignment-audit.json', 'context-audit.json', 'source-audit.json', 'pilot-prefix-audit.json'):
if (source / name).exists():
files[prefix + name] = source / name
for name in ('styles.json', 'source-audit.json'):
if (root / name).exists():
files[name] = root / name
failure_analysis = root / 'report-cache/failure-analysis.json'
if failure_analysis.exists():
files['audits/failure-analysis.json'] = failure_analysis
corpus_audit = root / 'report-cache/data-audit.json'
if corpus_audit.exists():
files['data-audit.json'] = corpus_audit
hint_probe = root / 'report-cache/final-step-hint1-easy-comparison.json'
if hint_probe.exists():
files['audits/final-step-hint1-easy-comparison.json'] = hint_probe
first_probe = root / 'iterations/gsm-final-step-v3/runs/single-final-calculation/8m/gsm8k/diagnostics'
for name in ('hint1-easy-sft-cpu.json', 'hint1-easy-sft-cpu-protocol.json',
'hint1-easy-rl-cpu.json', 'hint1-easy-rl-cpu-protocol.json'):
if (first_probe / name).exists():
files['audits/final-step-8m-' + name] = first_probe / name
verification = {}
for folder in sorted((root / 'verification').iterdir()):
if not (folder / 'result.json').exists():
continue
verification[folder.name] = shared.read_json(folder / 'result.json')
for name in ('protocol.json', 'result.json', 'sampler-comparison.json', 'comparison-reused-eval.json'):
if (folder / name).exists():
files['verification/' + folder.name + '/' + name] = folder / name
for suite in ('aux-smallmath-v1', 'rl-smallcalc-v1', 'full-arithmetic-v1', 'gsm-visible-v2',
'gsm-final-step-v3', 'gsm-final-step-full-v3'):
plan = root / 'iterations' / suite / 'plan.json'
if plan.exists():
files['protocols/' + suite + '/plan.json'] = plan
for case in shared.read_json(plan)['cases']:
for name in ('rl-curriculum.json', 'reused-sft.json'):
path = Path(case['output']) / name
if path.exists():
files['protocols/' + suite + '/' + case['task'] + '-' + name] = path
audit = root / 'report-cache/data-audit.json'
if audit.exists():
files['audits/data-audit.json'] = audit
if not any(states.values()):
return previous
for path in Path(__file__).parent.glob('*.py'):
files['code/refined_math/' + path.name] = path
readme = stage / 'README.md'
readme.write_text(card(states, config.repo, verification))
files['README.md'] = readme
changed = {name: path for name, path in files.items() if previous['files'].get(name) != shared.digest(path)}
if not changed:
return previous
api = HfApi()
api.create_repo(config.repo, repo_type='dataset', private=False, exist_ok=True)
repository = api.repo_info(config.repo, repo_type='dataset')
operations = [CommitOperationAdd(path_in_repo=name, path_or_fileobj=str(path)) for name, path in changed.items()]
commit = api.create_commit(config.repo, repo_type='dataset', operations=operations,
commit_message='Publish coherent math-v1 datasets', parent_commit=repository.sha, num_threads=4)
remote = api.get_paths_info(config.repo, list(changed), repo_type='dataset', revision=commit.oid)
by_path = {info.path: info for info in remote}
for name, path in changed.items():
if name not in by_path or not shared.remote_matches(by_path[name], path):
raise RuntimeError('Remote hash/size verification failed: ' + name)
result = dict(repo=config.repo, commit=commit.oid, states=states, updated=time.time(),
files={name: shared.digest(path) for name, path in files.items()})
shared.atomic_json(receipt, result)
print(f'[green]Public data uploaded and hash-verified: https://huggingface.co/datasets/{config.repo}[/green]')
return result
def run(config: Config):
root = Path(config.root)
(root / 'publication').mkdir(parents=True, exist_ok=True)
with (root / 'publication/publisher.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
while True:
result = upload(config)
complete = all(len(result.get('states', {}).get(stage, {})) == 4 for stage in ('full', 'pilot-2m'))
if config.action != 'watch' or complete:
return
time.sleep(config.interval)
if __name__ == '__main__':
run(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config), OmegaConf.from_cli())))