File size: 9,315 Bytes
f88e8d1 f0770ef f88e8d1 f0770ef f88e8d1 f0770ef f88e8d1 f0770ef f88e8d1 f0770ef f88e8d1 f0770ef f88e8d1 f0770ef f88e8d1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | 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
@dataclass
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())))
|