Download code/refined_math/iteration_report.py from davidheineman/tiny-rl-refined-math-v1: direct link, hf CLI and curl.
- Browser
- Download file 9.61 kB
-
https://huggingface.co/datasets/davidheineman/tiny-rl-refined-math-v1/resolve/main/code/refined_math/iteration_report.py
- Command line
-
hf download hf://datasets/davidheineman/tiny-rl-refined-math-v1/code/refined_math/iteration_report.py
-
curl -L -o iteration_report.py https://huggingface.co/datasets/davidheineman/tiny-rl-refined-math-v1/resolve/main/code/refined_math/iteration_report.py
9.61 kB
| import csv | |
| from dataclasses import dataclass | |
| import html | |
| from pathlib import Path | |
| import runpy | |
| import time | |
| from refined_v4.study import digest, read, write | |
| from .data import ROOT | |
| def summarize(case: dict): | |
| folder = Path(case['output']) | |
| points = [read(path) for path in (folder / 'eval').glob('*.json') if not path.name.startswith('test-')] | |
| budget = case.get('sft_tokens', 2097152) | |
| sft = [v for v in points if v['phase'] == 'sft' and v['counter'] == budget] | |
| if not sft and (folder / 'reused-sft.json').exists(): | |
| local = folder / 'eval/rl-0.json' | |
| source = Path(read(folder / 'reused-sft.json')['source_evaluation']) | |
| sft = [read(local if local.exists() else source)] | |
| rl = sorted([v for v in points if v['phase'] == 'rl'], key=lambda v: v['counter']) | |
| tracker = read(folder / 'wandb.json') if (folder / 'wandb.json').exists() else {} | |
| return dict(model=case['model'], task=case['task'], sft_tokens=budget, recipe=case.get('recipe', 'conditioned-relative'), | |
| sft=sft[0] if sft else None, rl=rl[-1] if rl else None, | |
| stopped=read(folder / 'stopped.json') if (folder / 'stopped.json').exists() else None, | |
| complete=(folder / 'complete.json').exists(), wandb=tracker.get('url', '')) | |
| def saved_test_comparisons(root: Path, plan: dict) -> str: | |
| from .verify import paired | |
| table = [] | |
| for case in plan['cases']: | |
| folder = Path(case['output']) | |
| if not (folder / 'complete.json').exists(): | |
| continue | |
| output = ROOT / 'verification' / f'{root.name}-{case["model"]}-{case["task"]}-native' | |
| if not (output / 'result.json').exists(): | |
| before = read(folder / 'eval' / f'test-sft-{plan["sft_tokens"]}.json') | |
| after = read(folder / 'eval' / f'test-rl-{plan["rl_rollouts"]}.json') | |
| write(output / 'protocol.json', dict(run=str(folder), | |
| selection='All prespecified sizes and both GSM variants; reuse exact terminal policies and their original held-out evaluations. No additional inference.', | |
| queries=before['metric']['queries'], samples=plan['eval_samples'], | |
| sft_sha256=digest(folder / 'sft.pt'), rl_sha256=digest(folder / 'rl.pt'), | |
| panel_sampling='Uniform hints and equal eligible difficulty bands; original frozen test panel.', | |
| panel=[dict(source_id=q['source_id'], group=q['group'], hint_level=q['hint_level']) for q in before['questions']])) | |
| evaluations = output / 'eval' | |
| if evaluations.exists() or evaluations.is_symlink(): | |
| if evaluations.resolve() != (folder / 'eval').resolve(): | |
| raise ValueError('Saved verification points to a different evaluation folder') | |
| else: | |
| evaluations.symlink_to(folder / 'eval', target_is_directory=True) | |
| write(output / 'result.json', paired(before, after)) | |
| value = read(output / 'result.json') | |
| low, high = value['uplift_ci95'] | |
| table.append(f'<tr><td>{case["model"].upper()}</td><td>{case["task"]}</td>' | |
| f'<td>{value["sft_pass1"]:.1%}</td><td>{value["rl_pass1"]:.1%}</td>' | |
| f'<td>[{100 * low:+.1f}, {100 * high:+.1f}] pp</td></tr>') | |
| return ('<h2>Original held-out panels</h2><p>Matched terminal SFT/RL evaluations; ' | |
| 'paired 95% gain intervals cluster source groups. The larger 32M verification is separate.</p>' | |
| '<table><tr><th>Size</th><th>Task</th><th>SFT</th><th>RL</th><th>95% gain interval</th></tr>' | |
| + ''.join(table) + '</table>') if table else '' | |
| def update(root: Path, results: Path): | |
| plan = read(root / 'plan.json') | |
| baseline = read(ROOT / 'pilot-2m/plan.json') | |
| revised_gsm = plan['revision'] in ('gsm-visible-calculation-v2', 'gsm-final-step-reference-v3') | |
| records = ([] if revised_gsm else | |
| [summarize(case) for case in baseline['cases'] if case['model'] in ('8m', '32m')]) | |
| records += [summarize(case) for case in plan['cases']] | |
| figures = '' | |
| if revised_gsm: | |
| plot = runpy.run_path(str(Path(__file__).parent / '.plotting/visible.py'))['plot'] | |
| plot(root, results) | |
| figures = '<p><img style="max-width:100%" src="sft_and_rl.png"></p><p>Fixed 32M diagnostic by missing length and final-calculation difficulty:</p><p><img style="max-width:100%" src="difficulty_32m.png"></p>' | |
| if plan['revision'] == 'gsm-final-step-reference-v3': | |
| figures += saved_test_comparisons(root, plan) | |
| write(results / '.cache/comparison.json', records) | |
| fields = ['task', 'model', 'sft_tokens', 'recipe', 'sft_pass1', 'sft_hint1', 'rl_rollouts', 'rl_pass1', 'rl_hint1', 'complete', 'stopped', 'wandb'] | |
| rows = [] | |
| for record in records: | |
| sft, rl = record['sft'], record['rl'] | |
| rows.append(dict(task=record['task'], model=record['model'], sft_tokens=record['sft_tokens'], recipe=record['recipe'], | |
| sft_pass1=sft['metric']['pass1'] if sft else None, | |
| sft_hint1=sft['by_hint']['1']['pass1'] if sft else None, | |
| rl_rollouts=rl['counter'] if rl else 0, rl_pass1=rl['metric']['pass1'] if rl else None, | |
| rl_hint1=rl['by_hint']['1']['pass1'] if rl else None, complete=record['complete'], | |
| stopped=bool(record['stopped']), wandb=record['wandb'])) | |
| with (results / 'comparison.csv').open('w', newline='') as stream: | |
| writer = csv.DictWriter(stream, fieldnames=fields) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| table = [] | |
| for row in rows: | |
| cells = [] | |
| for key in fields[:-1]: | |
| value = row[key] | |
| if key in ('sft_pass1', 'sft_hint1', 'rl_pass1', 'rl_hint1'): | |
| value = '—' if value is None else f'{value:.1%}' | |
| cells.append('<td>' + html.escape(str(value)) + '</td>') | |
| table.append('<tr>' + ''.join(cells) + '<td><a href="' + html.escape(row['wandb']) + '">W&B</a></td></tr>') | |
| (results / 'index.html').write_text('''<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="30"> | |
| <title>Math optimizer controls</title><style>body{font:14px system-ui;margin:30px}td,th{padding:7px;text-align:left}tr{border-bottom:1px solid #ddd}table{border-collapse:collapse}</style> | |
| <h1>Math · SFT and RL controls</h1><p>''' + html.escape(plan['controlled_comparison']) + '''</p><p>Scores use fixed development panels; each hint has ''' + str(plan.get('eval_queries', 64) // 16) + ''' questions. Stopped diagnostics are incomplete benchmarks.</p> | |
| <p><a href="comparison.csv">CSV</a></p>''' + figures + '<table><tr>' + ''.join('<th>' + key + '</th>' for key in fields) + '</tr>' + ''.join(table) + '</table>') | |
| class ReportConfig: | |
| watch: bool = False | |
| interval: int = 60 | |
| publish: bool = False | |
| def refresh(config: ReportConfig): | |
| from rich import print | |
| while True: | |
| runpy.run_path(str(Path(__file__).parent / '.plotting/iterative.py'), run_name='__main__') | |
| if not config.watch: | |
| return | |
| validation = ROOT / 'verification/arithmetic-balanced-job.json' | |
| plan = ROOT / 'iterations/projection-only-v1/plan.json' | |
| ready = validation.exists() and plan.exists() | |
| if ready: | |
| ready = all((Path(case['output']) / 'result.json').exists() | |
| for case in read(validation)['cases']) | |
| ready = ready and all(any((Path(case['output']) / marker).exists() | |
| for marker in ['complete.json', 'stopped.json']) | |
| for case in read(plan)['cases']) | |
| auxiliary = ROOT / 'iterations/aux-smallmath-v1/plan.json' | |
| if auxiliary.exists(): | |
| ready = ready and all(any((Path(case['output']) / marker).exists() | |
| for marker in ['complete.json', 'stopped.json']) | |
| for case in read(auxiliary)['cases']) | |
| curriculum = ROOT / 'iterations/rl-smallcalc-v1/plan.json' | |
| if curriculum.exists(): | |
| ready = ready and all(any((Path(case['output']) / marker).exists() | |
| for marker in ['complete.json', 'stopped.json']) | |
| for case in read(curriculum)['cases']) | |
| for suite in ('gsm-visible-v2', 'gsm-final-step-v3'): | |
| experiment = ROOT / 'iterations' / suite / 'plan.json' | |
| if experiment.exists(): | |
| update(experiment.parent, Path(read(experiment)['results'])) | |
| ready = ready and all(any((Path(case['output']) / marker).exists() | |
| for marker in ['complete.json', 'stopped.json']) | |
| for case in read(experiment)['cases']) | |
| expanded = ROOT / 'verification/full-arithmetic-balanced-job.json' | |
| if expanded.exists(): | |
| ready = ready and all((Path(case['output']) / 'result.json').exists() | |
| for case in read(expanded)['cases']) | |
| print('[cyan]Math overview refreshed[/cyan]', 'complete' if ready else 'experiments running', flush=True) | |
| if ready: | |
| if config.publish: | |
| from .publish import Config as PublishConfig, run | |
| run(PublishConfig()) | |
| return | |
| time.sleep(min(60, max(1, config.interval))) | |
| if __name__ == '__main__': | |
| from omegaconf import OmegaConf | |
| refresh(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(ReportConfig), OmegaConf.from_cli()))) | |