File size: 6,287 Bytes
4318522 2375585 4318522 ec86d11 d96f432 ec86d11 d96f432 ec86d11 f88e8d1 ec86d11 4318522 f88e8d1 2375585 4318522 f88e8d1 2375585 4318522 | 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 | from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
import numpy as np
from omegaconf import OmegaConf
from rich import print
import torch
from refined_v4 import data, train
from refined_v4.study import read, write
from refined_v4.train_metrics import Scoring, fixed_panel
from tiny_rl.sampling import load_model
from .data import ROOT
from .iterate import TrialConfig
@dataclass
class Config:
run: str = str(ROOT / 'iterations/rl-v2/runs/rl-rate0.333-kl0.1-queries4/32m/arithmetic_simple')
output: str = str(ROOT / 'verification/arithmetic-simple-32m')
queries: int = 256
samples: int = 8
device: str = 'auto'
stratified: bool = False
def paired(sft: dict, rl: dict):
def key(row):
return row['group'], row['hint_level']
before = {key(row): row for row in sft['questions']}
after = {key(row): row for row in rl['questions']}
if len(before) != len(sft['questions']) or len(after) != len(rl['questions']):
raise ValueError('Duplicate verification source/hint pairs')
if before.keys() != after.keys():
raise ValueError('Verification panels differ')
grouped = defaultdict(list)
for identity in before:
grouped[identity[0]].append(after[identity]['pass1'] - before[identity]['pass1'])
totals = np.array([sum(values) for values in grouped.values()])
counts = np.array([len(values) for values in grouped.values()])
rng = np.random.default_rng(2718)
indices = rng.integers(0, len(totals), (10000, len(totals)))
bootstraps = totals[indices].sum(1) / counts[indices].sum(1)
return dict(sft_pass1=sft['metric']['pass1'], rl_pass1=rl['metric']['pass1'],
uplift=float(totals.sum() / counts.sum()),
uplift_ci95=np.quantile(bootstraps, [.025, .975]).tolist(),
queries=len(before), source_groups=len(grouped),
method='Paired bootstrap over source groups; 10,000 resamples')
def publish_summary(folder: Path, output: Path):
import wandb
tracker = read(folder / 'wandb.json')
result = read(output / 'result.json')
run = wandb.Api().run(tracker['url'].removeprefix('https://wandb.ai/').replace('/runs/', '/'))
sampling = '_stratified' if 'panel_sampling' in read(output / 'protocol.json') else ''
prefix = f'verification_{result["queries"]}{sampling}/'
for name, value in result.items():
run.summary[prefix + name] = value
settings = read(folder / 'request.json')['config']
for phase, counter in [('sft', settings['sft_tokens']), ('rl', settings['rl_rollouts'])]:
evaluation = read(output / 'eval' / f'test-{phase}-{counter}.json')
for hint, metric in evaluation['by_hint'].items():
run.summary[prefix + phase + '/hint_' + hint + '/pass1'] = metric['pass1']
comparison = output / 'sampler-comparison.json'
if comparison.exists():
for name, value in read(comparison).items():
run.summary[prefix + 'sampler_comparison/' + name] = value
run.summary.update()
write(output / 'wandb-published.json', dict(run=tracker['url'], prefix=prefix,
protocol_sha256=train.file_hash(output / 'protocol.json')))
def main(config: Config):
folder, output = Path(config.run), Path(config.output)
output.mkdir(parents=True, exist_ok=True)
request = read(folder / 'request.json')
settings = OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(TrialConfig),
request['config'], dict(eval_queries=config.queries, eval_samples=config.samples,
wandb_mode='disabled')))
torch.set_num_threads(2)
device = ('cuda' if torch.cuda.is_available() else 'cpu') if config.device == 'auto' else config.device
rows = data.load_rows(Path(settings.root), settings.task, 'test')
if train.file_hash(Path(settings.root) / 'data' / settings.task / 'test.jsonl.gz') != request['split_sha256']['test']:
raise ValueError('Held-out data differs from the frozen training request')
stratified = config.stratified or settings.stratified_evaluation
if stratified:
from .envs import stratified_panel
panel = stratified_panel(rows, config.queries, settings.seed + 100000)
else:
panel = fixed_panel(rows, config.queries, settings.seed + 100000)
protocol = dict(run=str(folder), queries=config.queries, samples=config.samples,
selection='Selected from development results before expanding the held-out test panel.',
sft_sha256=train.file_hash(folder / 'sft.pt'), rl_sha256=train.file_hash(folder / 'rl.pt'),
panel=[dict(source_id=row['source_id'], group=row['group'], hint_level=level) for row, level in panel])
if stratified:
protocol['panel_sampling'] = 'Uniform hints; equal eligible difficulty-band counts per hint. Prefer fresh source groups within the scheduled band, then reuse across hints. Never repeat a source/hint pair. Bootstrap clusters repeated source groups.'
if (output / 'protocol.json').exists() and read(output / 'protocol.json') != protocol:
raise ValueError('Verification output belongs to different weights or questions; choose a new output')
write(output / 'protocol.json', protocol)
tracker = train.Tracker(settings, output)
scoring = Scoring(settings.task, device, 8, settings.judged_backend, settings.judge_cache)
try:
for phase, checkpoint, counter in [('test-sft', 'sft.pt', settings.sft_tokens),
('test-rl', 'rl.pt', settings.rl_rollouts)]:
model, metadata = load_model(str(folder / checkpoint), device)
train.evaluate(model, panel, settings, scoring, output, phase, counter, tracker)
del model
if device.startswith('cuda'):
torch.cuda.empty_cache()
result = paired(read(output / 'eval' / f'test-sft-{settings.sft_tokens}.json'),
read(output / 'eval' / f'test-rl-{settings.rl_rollouts}.json'))
write(output / 'result.json', result)
print('[green]Independent held-out verification[/green]', result)
finally:
scoring.close()
tracker.close(True)
if __name__ == '__main__':
main(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config), OmegaConf.from_cli())))
|