Download code/refined_math/visible.py from davidheineman/tiny-rl-refined-math-v1: direct link, hf CLI and curl.
- Browser
- Download file 9.32 kB
-
https://huggingface.co/datasets/davidheineman/tiny-rl-refined-math-v1/resolve/main/code/refined_math/visible.py
- Command line
-
hf download hf://datasets/davidheineman/tiny-rl-refined-math-v1/code/refined_math/visible.py
-
curl -L -o visible.py https://huggingface.co/datasets/davidheineman/tiny-rl-refined-math-v1/resolve/main/code/refined_math/visible.py
9.32 kB
| import ast | |
| from collections import Counter | |
| from dataclasses import dataclass | |
| from fractions import Fraction | |
| import gzip | |
| import json | |
| from pathlib import Path | |
| from omegaconf import OmegaConf | |
| from rich import print | |
| from tqdm import tqdm | |
| from refined_v4.study import read, write | |
| from . import data, aligned, envs | |
| REVISION = 'gsm-visible-calculation-v2' | |
| WEIGHTS = dict(easy=70, standard=20, hard=10) | |
| original_sources = data.base_sources | |
| original_render = aligned.render_row | |
| class Config: | |
| root: str = str(data.ROOT / 'iterations/gsm-visible-v2') | |
| tokens: int = 2097152 | |
| auxiliary_fraction: float = .75 | |
| final_step_reference: bool = False | |
| def revision(style: dict) -> str: | |
| return 'gsm-final-step-reference-v3' if style.get('final_step_reference') else REVISION | |
| def instruction(expression: str) -> str: | |
| node = ast.parse(expression, mode='eval').body | |
| if isinstance(node, ast.BinOp) and not any(isinstance(part, ast.BinOp) | |
| for part in (node.left, node.right)): | |
| left, right = ast.unparse(node.left), ast.unparse(node.right) | |
| if isinstance(node.op, ast.Add): | |
| return f'Add {left} and {right} to find the total.' | |
| if isinstance(node.op, ast.Sub): | |
| return f'Subtract {right} from {left} to find what remains.' | |
| if isinstance(node.op, ast.Mult): | |
| return f'Multiply {left} by {right} to find the total.' | |
| if isinstance(node.op, ast.Div): | |
| return f'Divide {left} by {right} to find the quotient.' | |
| return 'Evaluate the supplied expression using the usual order of operations.' | |
| def band(source: dict) -> str: | |
| if data.small_final_calculation(source): | |
| return 'easy' | |
| tree = ast.parse(source['steps'][-1]['expression'], mode='eval') | |
| operations = [node for node in ast.walk(tree) if isinstance(node, ast.BinOp)] | |
| constants = [node.value for node in ast.walk(tree) if isinstance(node, ast.Constant)] | |
| if (1 <= len(operations) <= 2 and constants | |
| and all(type(value) is int and abs(value) <= 100 for value in constants) | |
| and Fraction(source['answer']).denominator == 1 and abs(Fraction(source['answer'])) <= 1000): | |
| return 'standard' | |
| return 'hard' | |
| def sources(config: data.Config): | |
| pools, audit = original_sources(config) | |
| excluded = [] | |
| for task in ('gsm8k', 'partial_gsm8k'): | |
| for split in data.SPLITS: | |
| selected = [] | |
| for source in pools[task][split]: | |
| tree = ast.parse(source['steps'][-1]['expression'], mode='eval') | |
| if not any(isinstance(node, ast.BinOp) for node in ast.walk(tree)): | |
| excluded.append(dict(task=task, split=split, source_id=source['source_id'], | |
| reason='Literal final expression would directly supply the answer')) | |
| continue | |
| selected.append(dict(source, original_difficulty=source['difficulty'], difficulty=band(source))) | |
| pools[task][split] = selected | |
| audit.update(context_revision=revision(data.DEFAULT_STYLE), context_exclusions=excluded, | |
| difficulty_definition=dict(easy='Add/subtract two integers in 0..20', | |
| standard='At most two operations with integer literals of magnitude <=100 and integer result of magnitude <=1000', | |
| hard='Remaining original GSM calculations'), training_problem_weights=WEIGHTS) | |
| return pools, audit | |
| def render(task: str, source: dict, style: dict, style_id: int, include_hints: bool = True): | |
| row = original_render(task, source, style, style_id, include_hints=False) | |
| if task in ('gsm8k', 'partial_gsm8k'): | |
| expression = ast.unparse(ast.parse(source['steps'][-1]['expression'], mode='eval').body) | |
| row['question'] += '\nThe final calculation is ' + expression + '.' | |
| if style.get('final_step_reference'): | |
| step = instruction(expression) | |
| row['reference'] = ('Reasoning: ' + step + ' The calculation is ' + expression + '.\nAnswer: ' + source['answer'] | |
| if task == 'gsm8k' else 'Answer: ' + step + '\nSo, the answer is ' + expression + ' = ' + source['answer']) | |
| difficulty = band(source) | |
| row['provenance'].update(context_revision=revision(style), | |
| original_problem_difficulty=source.get('original_difficulty', source['difficulty']), | |
| difficulty=difficulty, problem_sampling_weight=WEIGHTS[difficulty], | |
| provided_final_calculation=expression, | |
| rendered_question_sha256=data.digest(row['question'])) | |
| if include_hints: | |
| row['hint_levels'] = list(envs.available_hints(row)) | |
| return row | |
| def build(config: Config): | |
| root = Path(config.root) | |
| root.mkdir(parents=True, exist_ok=True) | |
| if config.final_step_reference: | |
| data.DEFAULT_STYLE = dict(data.DEFAULT_STYLE, final_step_reference=True) | |
| context_revision = revision(data.DEFAULT_STYLE) | |
| styles = dict(styles=[data.DEFAULT_STYLE], context_revision=context_revision, | |
| training_problem_weights=WEIGHTS, auxiliary_fraction=config.auxiliary_fraction) | |
| path = root / 'styles.json' | |
| if path.exists() and read(path) != styles: | |
| raise ValueError('Frozen calculation-context settings differ') | |
| write(path, styles) | |
| settings = data.Config(root=str(root), tokens=config.tokens, | |
| pilot_tokens=min(2097152, config.tokens), auxiliary_fraction=config.auxiliary_fraction) | |
| data.base_sources = sources | |
| data.make_row = render | |
| pools = data.build_environments(settings, styles['styles']) | |
| for task in ('gsm8k', 'partial_gsm8k'): | |
| path = root / 'data' / task / 'manifest.json' | |
| manifest = read(path) | |
| manifest.update(environment_revision=context_revision, final_calculation_protected=True, | |
| training_problem_weights=WEIGHTS) | |
| write(path, manifest) | |
| data.build_sft(settings, pools, styles['styles']) | |
| heldout = {source['group'] for task in data.TASKS for split in data.SPLITS if split != 'sft' | |
| for source in pools[task][split]} | |
| tasks = {} | |
| for task in data.TASKS: | |
| by_id = {source['source_id']: source for source in pools[task]['sft']} | |
| if task in ('gsm8k', 'partial_gsm8k'): | |
| by_id.update({source['source_id']: source for source in pools['arithmetic']['sft']}) | |
| total, examples, auxiliary = 0, 0, 0 | |
| with gzip.open(root / 'sft' / task / 'train.jsonl.gz', 'rt') as stream: | |
| for line in tqdm(stream, desc=task + ' context audit', colour='cyan', mininterval=10): | |
| document = json.loads(line) | |
| fragments = [] | |
| for example in document['examples']: | |
| source = by_id[example['source_id']] | |
| if source['group'] in heldout or source['group'] != example['group']: | |
| raise ValueError('SFT group identity or split differs') | |
| row = render(task, source, data.DEFAULT_STYLE, example['style_id'], include_hints=False) | |
| if data.digest(row['reference']) != example['reference_sha256']: | |
| raise ValueError('Context reference does not reconstruct') | |
| fragments.append(envs.render(row)) | |
| examples += 1 | |
| auxiliary += task in ('gsm8k', 'partial_gsm8k') and source['source'] == 'math-v1/small-arithmetic' | |
| if document['text'] != '\n\n'.join(fragments): | |
| raise ValueError('Context document does not reconstruct') | |
| total += document['budget_tokens'] | |
| if total != config.tokens: | |
| raise ValueError('Context SFT prediction budget differs') | |
| counts = {} | |
| if task in ('gsm8k', 'partial_gsm8k'): | |
| for split in data.SPLITS: | |
| with gzip.open(root / 'data' / task / (split + '.jsonl.gz'), 'rt') as stream: | |
| rows = [json.loads(line) for line in stream] | |
| counts[split] = dict(Counter(row['provenance']['difficulty'] for row in rows)) | |
| for row in rows: | |
| if row['hint_levels'] != list(range(1, 17)): | |
| raise ValueError('Every context GSM source must support all sixteen cuts') | |
| for level in (1, 16): | |
| item = envs.make_episode(row, level) | |
| if row['provenance']['provided_final_calculation'] not in item.prompt: | |
| raise ValueError('Final calculation was removed by the hint cut') | |
| tasks[task] = dict(prediction_tokens=total, examples=examples, | |
| auxiliary_fraction=auxiliary / examples, difficulty_counts=counts, | |
| sha256=data.signature(root / 'sft' / task / 'train.jsonl.gz')) | |
| write(root / 'context-audit.json', dict(context_revision=context_revision, tasks=tasks, | |
| source_groups_disjoint=True, protected_final_calculation=True, | |
| benchmark_change='Original questions retain a supplied final calculation at every cut; literal-answer expressions excluded. Separate from the full-GSM challenge.')) | |
| print('[green]Visible-calculation data and environments ready[/green]', tasks) | |
| if __name__ == '__main__': | |
| build(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config), OmegaConf.from_cli()))) | |