File size: 6,413 Bytes
4318522
 
 
 
 
 
 
 
 
 
 
 
 
 
d96f432
4318522
 
 
 
 
43d7760
4318522
 
 
 
 
 
 
 
 
 
d96f432
43d7760
 
 
4318522
 
 
 
 
 
 
 
 
 
 
 
43d7760
 
 
ec86d11
 
4318522
 
43d7760
4318522
 
d96f432
 
4318522
 
 
43d7760
 
4318522
 
 
 
 
ec86d11
4318522
 
 
 
 
 
 
 
 
 
 
 
 
 
d96f432
 
 
 
 
 
4318522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d96f432
ec86d11
 
4318522
 
 
 
 
 
 
 
 
d96f432
 
 
43d7760
 
 
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
124
125
126
127
128
129
130
131
from collections import defaultdict
from dataclasses import dataclass
import gzip
import json
from pathlib import Path
import random

from omegaconf import OmegaConf
from rich import print
import torch
from tqdm import tqdm

from tiny_rl.sampling import load_model
from refined_v4.study import read, write
from .data import ROOT, small_final_calculation
from .envs import ENC, make_episode


@dataclass
class Config:
    root: str = str(ROOT / 'pilot-2m')
    model: str = '8m'
    per_band: int = 16
    batch: int = 4
    threads: int = 2
    device: str = 'cpu'
    shots: int = 2
    checkpoint: str = ''
    comparison: str = ''
    task: str = ''
    label: str = 'default'
    small_final_only: bool = False
    split: str = ''
    difficulty: str = ''
    output: str = ''


def rows(path: Path):
    with gzip.open(path, 'rt') as stream:
        return [json.loads(line) for line in stream]


@torch.inference_mode()
def probe(config: Config):
    torch.set_num_threads(config.threads)
    base = next(row['checkpoint'] for row in read(ROOT / 'pilot-2m/plan.json')['models'] if row['name'] == config.model)
    selections = []
    pilot = Path(config.root)
    if config.split not in ('', 'sft', 'dev'):
        raise ValueError('Answer probes use only SFT or development sources')
    tasks = (config.task,) if config.task else ('arithmetic', 'arithmetic_simple')
    for task in tasks:
        demonstrations = rows(pilot / 'data' / task / 'rl.jsonl.gz')[0]['demonstrations']
        demo_groups = {row['group'] for row in demonstrations}
        for split in ([config.split] if config.split else ('sft', 'dev')):
            bands = defaultdict(list)
            for row in rows(pilot / 'data' / task / (split + '.jsonl.gz')):
                if config.small_final_only and not small_final_calculation(dict(steps=row['provenance']['equations'])):
                    continue
                if row['group'] not in demo_groups:
                    bands[row['provenance']['difficulty']].append(row)
            for band, values in bands.items():
                if config.difficulty and band != config.difficulty:
                    continue
                selected = random.Random(f'probe/{task}/{split}/{band}').sample(values, min(config.per_band, len(values)))
                for row in selected:
                    row = dict(row, demonstrations=demonstrations[:config.shots])
                    selections.append((task, split, band, make_episode(row, 1)))
    checkpoints = [('base', None, base)]
    for task in tasks:
        p = pilot / 'runs' / config.model / task / 'sft.pt'
        if p.exists():
            checkpoints.append(('conditioned-relative', task, str(p)))
        for optimizer in ('adamw', 'relative'):
            p = ROOT / 'iterations/optim-v1/runs' / ('native-' + optimizer) / config.model / task / 'sft.pt'
            if p.exists():
                checkpoints.append(('native-' + optimizer, task, str(p)))
    if config.checkpoint:
        checkpoints = [(config.label, config.task or None, config.checkpoint)]
        if config.comparison:
            checkpoints.append(('matched-unweighted', config.task or None, config.comparison))
    records = []
    for recipe, selected_task, checkpoint in checkpoints:
        model, metadata = load_model(checkpoint, config.device)
        request = Path(checkpoint).parent / 'request.json'
        seen = None
        if request.exists():
            settings = read(request)['config']
            corpus = Path(settings['root']) / 'sft' / settings['task'] / 'train.jsonl.gz'
            seen = {example['group'] for document in rows(corpus) for example in document['examples']}
        selected = [row for row in selections if selected_task is None or row[0] == selected_task]
        for offset in tqdm(range(0, len(selected), config.batch), desc=f'{config.model}/{recipe}', colour='cyan', mininterval=10):
            group = selected[offset:offset + config.batch]
            width = max(len(row[3].prompt_ids) for row in group)
            inputs = torch.full((len(group), width), ENC.eot_token, device=config.device, dtype=torch.long)
            for index, row in enumerate(group):
                inputs[index, :len(row[3].prompt_ids)] = torch.tensor(row[3].prompt_ids, device=config.device)
            hidden = model._trunk(inputs)
            logits = model.lm_head(torch.stack([hidden[index, len(row[3].prompt_ids) - 1] for index, row in enumerate(group)]))[:, :ENC.n_vocab].float()
            logps = logits.log_softmax(-1)
            for index, (task, split, band, item) in enumerate(group):
                target = item.completion_ids[0]
                predicted = int(logits[index].argmax())
                top = logits[index].topk(5).indices.tolist()
                records.append(dict(recipe=recipe, model=config.model, task=task, split=split, difficulty=band,
                    source_id=item.source_id, p_gold=float(logps[index, target].exp()),
                    seen_in_checkpoint_sft=item.group in seen if seen is not None else None,
                    gold_rank=int((logits[index] > logits[index, target]).sum()) + 1,
                    context_tokens=len(item.prompt_ids),
                    greedy=predicted == target, gold=item.completion,
                    top5=[ENC.decode([token]) for token in top], prompt=item.prompt))
        del model
    groups = defaultdict(list)
    for record in records:
        groups[(record['recipe'], record['task'], record['split'], record['difficulty'])].append(record)
    summary = [dict(recipe=key[0], task=key[1], split=key[2], difficulty=key[3], queries=len(values),
        p_gold=sum(v['p_gold'] for v in values) / len(values),
        greedy=sum(v['greedy'] for v in values) / len(values)) for key, values in groups.items()]
    for row in summary:
        selected = groups[(row['recipe'], row['task'], row['split'], row['difficulty'])]
        row['seen_in_checkpoint_sft'] = sum(value['seen_in_checkpoint_sft'] is True for value in selected)
    output = (Path(config.output) if config.output else
              ROOT / f'report-cache/answer-probe-{config.model}-{config.label}-shots{config.shots}.json')
    write(output, dict(summary=summary, records=records))
    for row in summary:
        print(row)


if __name__ == '__main__':
    probe(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config), OmegaConf.from_cli())))