Download code/refined_math/diagnose.py from davidheineman/tiny-rl-refined-math-v1: direct link, hf CLI and curl.
- Browser
- Download file 5.59 kB
-
https://huggingface.co/datasets/davidheineman/tiny-rl-refined-math-v1/resolve/main/code/refined_math/diagnose.py
- Command line
-
hf download hf://datasets/davidheineman/tiny-rl-refined-math-v1/code/refined_math/diagnose.py
-
curl -L -o diagnose.py https://huggingface.co/datasets/davidheineman/tiny-rl-refined-math-v1/resolve/main/code/refined_math/diagnose.py
5.59 kB
| import ast | |
| from collections import Counter, defaultdict | |
| from dataclasses import dataclass | |
| import json | |
| from pathlib import Path | |
| import re | |
| from omegaconf import OmegaConf | |
| from rich import print | |
| from tqdm import tqdm | |
| from functional_rl.envs import scalar | |
| from functional_rl.v2_format import calculate | |
| from refined_v4 import data as shared | |
| from refined_v4.study import read, write | |
| from .data import ROOT, small_final_calculation | |
| class Config: | |
| root: str = str(ROOT) | |
| run: str = '' | |
| phase: str = 'sft' | |
| counter: int = 0 | |
| def failure(task: str, text: str, expected: str) -> str: | |
| if task == 'partial_gsm8k': | |
| match = re.fullmatch(r'So, the answer is (.+) = ([^\n]+)', text.splitlines()[-1]) | |
| if not text.startswith('Answer: ') or match is None: | |
| return 'missing_equation_format' | |
| expression, answer = match.groups() | |
| elif task == 'arithmetic_simple': | |
| if not text.startswith('Answer: ') or ' = ' not in text: | |
| return 'missing_equation_format' | |
| pieces = text.removeprefix('Answer: ').split(' = ') | |
| expression, answer = pieces[:-1], pieces[-1] | |
| else: | |
| if '\nAnswer: ' not in text: | |
| return 'missing_answer_line' | |
| expression, answer = None, text.rsplit('\nAnswer: ', 1)[1] | |
| try: | |
| if scalar(answer) != scalar(expected): | |
| return 'wrong_number' | |
| except (ValueError, ZeroDivisionError): | |
| return 'non_numeric_answer' | |
| if expression is not None: | |
| try: | |
| expressions = expression if isinstance(expression, list) else [expression] | |
| if any(calculate(ast.parse(part, mode='eval')) != scalar(expected) for part in expressions): | |
| return 'wrong_expression' | |
| except (ValueError, SyntaxError, ZeroDivisionError, OverflowError): | |
| return 'invalid_expression' | |
| return 'correct' | |
| def main(config: Config): | |
| root = Path(config.root) | |
| results = {} | |
| if config.run: | |
| if config.phase not in ('sft', 'rl'): | |
| raise ValueError('Development diagnostic phase must be sft or rl') | |
| folders = [Path(config.run)] | |
| else: | |
| folders = [folder for folder in sorted((root / 'verification').iterdir()) | |
| if (folder / 'result.json').exists()] | |
| for folder in tqdm(folders, desc='Inspect saved math completions', colour='cyan'): | |
| source = folder if config.run else Path(read(folder / 'protocol.json')['run']) | |
| request = read(source / 'request.json')['config'] | |
| task = request['task'] | |
| split = 'dev' if config.run else 'test' | |
| rows = {row['source_id']: row for row in shared.load_rows(Path(request['root']), task, split)} | |
| phases = {} | |
| for phase in ([config.phase] if config.run else ['sft', 'rl']): | |
| counter = (config.counter if config.run and config.counter else | |
| request['sft_tokens' if phase == 'sft' else 'rl_rollouts']) | |
| filename = f'{phase if config.run else "test-" + phase}-{counter}.json' | |
| saved = read(folder / 'eval' / filename) | |
| by_hint = defaultdict(Counter) | |
| by_difficulty = defaultdict(Counter) | |
| examples = defaultdict(list) | |
| small = Counter() | |
| for question in saved['questions']: | |
| row = rows[question['source_id']] | |
| item = shared.make_episode(row, question['hint_level']) | |
| if item.prompt != question['prompt'] or item.prefix != question['prefix']: | |
| raise ValueError('Saved evaluation prompt differs from the frozen source') | |
| for completion, passed in zip(question['completions'], question['passed'], strict=True): | |
| verdict = shared.reward(item, completion) | |
| if verdict != passed: | |
| raise ValueError('Current numeric oracle differs from the saved verdict') | |
| status = failure(task, item.prefix + completion, row['answer']) | |
| if status == 'correct' and not verdict: | |
| status = 'invalid_completion_length' | |
| if status != 'correct' and verdict: | |
| raise ValueError('Failure classification rejects a successful completion') | |
| by_hint[str(item.hint_level)][status] += 1 | |
| by_difficulty[question['difficulty']][status] += 1 | |
| if small_final_calculation(dict(steps=row['provenance']['equations'])): | |
| small[status] += 1 | |
| if len(examples[status]) < 3: | |
| examples[status].append(dict(source_id=item.source_id, hint=item.hint_level, | |
| prefix=item.prefix, reference=item.completion, completion=completion, answer=row['answer'])) | |
| phases[phase] = dict(counter=counter, by_hint=dict(by_hint), | |
| by_difficulty=dict(by_difficulty), small_final=dict(small), examples=dict(examples)) | |
| bands = {name: sum((by_hint[str(n)] for n in levels), Counter()) | |
| for name, levels in [('1-2', range(1, 3)), ('3-8', range(3, 9)), ('9-16', range(9, 17))]} | |
| print(folder.name, phase, bands) | |
| if config.run: | |
| write(folder / 'diagnostics' / filename, phases[phase]) | |
| results[folder.name] = dict(task=task, phases=phases) | |
| if not config.run: | |
| write(root / 'report-cache/failure-analysis.json', results) | |
| if __name__ == '__main__': | |
| main(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config), OmegaConf.from_cli()))) | |