File size: 6,495 Bytes
d370082 f88e8d1 d370082 f88e8d1 d370082 f88e8d1 d370082 2375585 | 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 | from dataclasses import replace
import hashlib
import math
import random
from functional_rl import v2
from . import REVISION
TASKS = ('gsm8k', 'partial_gsm8k', 'arithmetic', 'arithmetic_simple')
ENC = v2.ENC
WEIGHTS = dict(tiny_addsub=40, small_addsub=30, multiplication=15, two_step=15,
easy=40, standard=45, hard=15)
def header(row: dict) -> str:
return 'Question: ' + row['question'] + '\n'
def render(row: dict) -> str:
return header(row) + row['reference']
def construct(row: dict, level: int, demonstrations: tuple[dict, ...]):
if type(level) is not int or not 1 <= level <= 16:
raise ValueError('Hint length must be an integer in [1, 16]')
if row['task'] not in TASKS:
raise ValueError('Unknown math task')
groups = {row['group']}
for demo in demonstrations:
if demo['task'] != row['task'] or demo['group'] in groups:
raise ValueError('Demonstrations must use distinct same-task source groups')
groups.add(demo['group'])
context = ''.join(render(demo).rstrip() + '\n\n' for demo in demonstrations)
document_header = context + header(row)
document = document_header + row['reference']
ids = ENC.encode_ordinary(document)
if len(ids) > 1024:
raise ValueError('Math episode exceeds the model context')
prompt_ids, completion_ids = ids[:-level], ids[-level:]
prompt, completion = ENC.decode(prompt_ids), ENC.decode(completion_ids)
protected = 'Reasoning:' if row['task'] in ('gsm8k', 'arithmetic') else 'Answer:'
if (len(completion_ids) != level or not prompt.startswith(document_header + protected)
or prompt + completion != document or '\ufffd' in prompt + completion):
raise ValueError('Requested hint removes protected task context')
return v2.Episode(row['task'], row['source_id'], row['group'], level,
prompt, completion, tuple(prompt_ids), tuple(completion_ids),
prompt[len(document_header):], row['reference'], row['answer'], (), '',
version=REVISION, question=row['question'], provenance=row.get('provenance', {}),
demonstrations=tuple(dict(task=d['task'], source_id=d['source_id'], group=d['group'],
text=render(d), split='sft') for d in demonstrations))
def available_hints(row: dict) -> tuple[int, ...]:
if 'hint_levels' in row:
return tuple(row['hint_levels'])
result = []
for level in range(1, 17):
try:
construct(row, level, ())
result.append(level)
except ValueError:
pass
return tuple(result)
def make_episode(row: dict, level: int):
return construct(row, level, tuple(row.get('demonstrations', ())))
def reward(item, completion: str, judge=None) -> float:
return v2.reward(item, completion, judge)
class Pool:
def __init__(self, rows: list[dict]):
self.rows = rows
self.weights = dict(WEIGHTS)
declared = {}
for row in rows:
band = row['provenance']['difficulty']
weight = row['provenance'].get('problem_sampling_weight')
if weight is not None:
if not math.isfinite(weight) or weight <= 0:
raise ValueError('Problem sampling weights must be positive and finite')
if band in declared and declared[band] != weight:
raise ValueError('Inconsistent sampling weights within a difficulty band')
declared[band] = weight
self.weights.update(declared)
self.by_hint = {level: [row for row in rows if level in available_hints(row)]
for level in range(1, 17)}
if any(not rows for rows in self.by_hint.values()):
raise ValueError('Every hint length needs eligible questions')
self.by_band = {level: {} for level in range(1, 17)}
for level, selected in self.by_hint.items():
for row in selected:
self.by_band[level].setdefault(row['provenance']['difficulty'], []).append(row)
def sample(self, rng: random.Random):
level = rng.randint(1, 16)
bands = list(self.by_band[level])
band = rng.choices(bands, [self.weights[name] for name in bands])[0]
return make_episode(rng.choice(self.by_band[level][band]), level)
def fixed_panel(rows: list[dict], queries: int, seed: int):
if queries < 16 or queries % 16:
raise ValueError('Evaluation size must be a positive multiple of 16')
pool = Pool(rows)
result, used, pairs = [], set(), set()
for index in range(queries):
level = index % 16 + 1
candidates = sorted(pool.by_hint[level], key=lambda row: hashlib.sha256(
f'{seed}/{level}/{row["group"]}'.encode()).hexdigest())
bands = sorted(pool.by_band[level])
band = bands[(index // 16) % len(bands)]
preferred = [row for row in candidates if row['provenance']['difficulty'] == band]
candidates = preferred + [row for row in candidates if row['provenance']['difficulty'] != band]
fresh = [row for row in candidates if row['group'] not in used]
eligible = [row for row in candidates if (row['group'], level) not in pairs]
if not eligible:
raise ValueError('Insufficient unique source/hint evaluation pairs')
row = (fresh or eligible)[0]
used.add(row['group'])
pairs.add((row['group'], level))
result.append((row, level))
return result
def stratified_panel(rows: list[dict], queries: int, seed: int):
if queries < 16 or queries % 16:
raise ValueError('Evaluation size must be a positive multiple of 16')
pool = Pool(rows)
result, used, pairs = [], set(), set()
for index in range(queries):
level = index % 16 + 1
bands = sorted(pool.by_band[level])
band = bands[(index // 16) % len(bands)]
candidates = sorted(pool.by_band[level][band], key=lambda row: hashlib.sha256(
f'{seed}/{level}/{row["group"]}'.encode()).hexdigest())
eligible = [row for row in candidates if (row['group'], level) not in pairs]
if not eligible:
raise ValueError(f'Insufficient unique {band}/hint-{level} evaluation pairs')
fresh = [row for row in eligible if row['group'] not in used]
row = (fresh or eligible)[0]
used.add(row['group'])
pairs.add((row['group'], level))
result.append((row, level))
return result
|