160 lines
7.9 KiB
Python
160 lines
7.9 KiB
Python
"""Summarize paired score interventions, resampling entire tables."""
|
|
import argparse
|
|
import json
|
|
import math
|
|
import random
|
|
from pathlib import Path
|
|
from statistics import mean
|
|
|
|
|
|
def classify(question, row, mode):
|
|
records, query = question['question'].split('.\n')
|
|
table = dict(field.split('=') for field in records.removeprefix(
|
|
'Records in time order: ').split(', '))
|
|
target = query.removesuffix('?').split()[-1]
|
|
assert len(table) == len(set(table.values())) == 12
|
|
assert int(table[target]) == question['answer'] == row['gold']
|
|
assert question['id'] == row['id']
|
|
answer = row['arms'][mode]['answer']
|
|
correct = answer == row['gold']
|
|
assert correct == row['arms'][mode]['correct']
|
|
other_key = next((k for k, v in table.items() if int(v) == answer and k != target), None)
|
|
return dict(id=row['id'], answer=answer, correct=correct, target=target,
|
|
wrong_key=other_key, outside_table=answer is not None and not correct and other_key is None,
|
|
unparsable=answer is None)
|
|
|
|
|
|
def table_metrics(items, rows, mode):
|
|
assert len(items) == len(rows) and len(items) % 2 == 0
|
|
classified = [classify(item, row, mode) for item, row in zip(items, rows)]
|
|
metrics = []
|
|
for i in range(0, len(rows), 2):
|
|
pair = classified[i:i+2]
|
|
probabilities = [row['first_digit_probability'] for row in rows[i:i+2]]
|
|
assert all(math.isfinite(p) and 0 <= p <= 1 for p in probabilities)
|
|
metrics.append(dict(correct=mean(r['correct'] for r in pair),
|
|
both_correct=int(all(r['correct'] for r in pair)),
|
|
wrong_key=mean(r['wrong_key'] is not None for r in pair),
|
|
first_digit_probability=mean(probabilities)))
|
|
return metrics, classified
|
|
|
|
|
|
def interval(values, resamples):
|
|
estimates = sorted(sum(values[i] for i in indices)/len(values) for indices in resamples)
|
|
return dict(delta=mean(values), lower95=estimates[int(len(estimates)*.025)],
|
|
upper95=estimates[math.ceil(len(estimates)*.975)-1])
|
|
|
|
|
|
def summarize_arms(arms, contrasts, samples):
|
|
first = next(iter(arms.values()))
|
|
fields = first[0].keys()
|
|
count = len(first)
|
|
assert all(len(arm) == count for arm in arms.values())
|
|
means = {m: {k: mean(row[k] for row in arm) for k in fields}
|
|
for m, arm in arms.items()}
|
|
comparisons = {}
|
|
for name, coefficients in contrasts.items():
|
|
comparisons[name] = {}
|
|
for field in fields:
|
|
differences = [sum(c * arms[m][i][field] for m, c in coefficients.items())
|
|
for i in range(count)]
|
|
comparisons[name][field] = interval(differences, samples)
|
|
return dict(means=means, paired_contrasts=comparisons)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('directory', type=Path)
|
|
parser.add_argument('--tokenizer', required=True, type=Path)
|
|
parser.add_argument('--frozen', required=True, type=Path)
|
|
args = parser.parse_args()
|
|
from tokenizers import Tokenizer
|
|
from crossqkv.lisa_full_answer import fingerprint, prompt
|
|
from crossqkv.lisa_full_answer_verify import verify
|
|
from functional.run import write_json
|
|
protocol = json.loads(args.frozen.read_text())['protocol']
|
|
assert fingerprint(args.tokenizer) == protocol['weights']['tokenizer.json']
|
|
tokenizer = Tokenizer.from_file(str(args.tokenizer))
|
|
assert fingerprint(args.directory/'protocol.json') == 'c309f8721534b1f229a00ff556b48495c4e074be45c1905389aa57e9e3ddb048'
|
|
def read(name):
|
|
return json.loads((args.directory/name).read_text())
|
|
plan = read('protocol.json')
|
|
questions = plan['holdout']
|
|
modes = read('selection.json')['holdout_modes']
|
|
n = len(questions['swap']) // 2
|
|
assert n >= 32 and len(questions['query']) == 2*n
|
|
rng = random.Random(120204)
|
|
resamples = [rng.choices(range(n), k=n) for _ in range(10000)]
|
|
tables, detail, summary = {}, {}, {}
|
|
costs = {}
|
|
for kind, prompts in questions.items():
|
|
lengths = [len(tokenizer.encode(prompt(item['question']), add_special_tokens=False).ids)
|
|
for item in prompts]
|
|
costs[kind] = {}
|
|
tables[kind], detail[kind] = {}, {}
|
|
for mode in modes:
|
|
rows = read(f'holdout-19-{mode}-{kind}.json')
|
|
verify(tokenizer, protocol, prompts, rows, (mode,))
|
|
positions = edges = 0
|
|
for i in range(0, len(rows), 2):
|
|
width = max(lengths[i:i+2])
|
|
steps = max(len(r['arms'][mode]['tokens']) for r in rows[i:i+2]) - 1
|
|
positions += 2 * (width + steps)
|
|
edges += 2 * (width**2 + steps*width + steps*(steps+1)//2)
|
|
costs[kind][mode] = dict(processed_positions=positions, computed_score_positions=edges,
|
|
extra_native_projection_macs=0 if mode == 'baseline' else 9437184*positions,
|
|
extra_native_score_macs=0 if mode == 'baseline' else 2048*edges)
|
|
tables[kind][mode], detail[kind][mode] = table_metrics(prompts, rows, mode)
|
|
fields = tables['swap']['baseline'][0].keys()
|
|
tables['both_kinds'] = {
|
|
mode: [{k: (s[k]+q[k])/2 for k in fields}
|
|
for s, q in zip(tables['swap'][mode], tables['query'][mode])] for mode in modes}
|
|
for kind, arms in tables.items():
|
|
contrasts = {mode+'-baseline': {mode: 1, 'baseline': -1} for mode in modes if mode != 'baseline'}
|
|
contrasts['interaction'] = {'both': 1, 'baseline': 1, 'read': -1, 'send': -1}
|
|
if 'send-permuted' in modes:
|
|
contrasts['send-permuted-control'] = {'send': 1, 'send-permuted': -1}
|
|
if 'read-group-0' in modes:
|
|
selected = read('selection.json')['selected']
|
|
other = next(m for m in modes if m.startswith('read-group-') and m != selected)
|
|
contrasts['selected-other'] = {selected: 1, other: -1}
|
|
contrasts['selected-full-read'] = {selected: 1, 'read': -1}
|
|
summary[kind] = summarize_arms(arms, contrasts, resamples)
|
|
isolation = {}
|
|
layer_comparison = {}
|
|
for kind, prompts in plan['diagnostic'].items():
|
|
arms = {}
|
|
for mode in ('native', 'only-15', 'only-19', 'both-15-19'):
|
|
rows = read(f'diagnostic-isolation-{mode}-{kind}.json')
|
|
verify(tokenizer, protocol, prompts, rows, (mode,))
|
|
arms[mode], _ = table_metrics(prompts, rows, mode)
|
|
count = len(prompts)//2
|
|
diagnostic_rng = random.Random(120205)
|
|
samples = [diagnostic_rng.choices(range(count), k=count) for _ in range(10000)]
|
|
combinations = {
|
|
'only-15-minus-native': {'only-15': 1, 'native': -1},
|
|
'only-19-minus-native': {'only-19': 1, 'native': -1},
|
|
'joint-interaction': {'both-15-19': 1, 'only-19': -1, 'only-15': -1, 'native': 1}}
|
|
isolation[kind] = summarize_arms(arms, combinations, samples)
|
|
arms = {}
|
|
for site, mode in [(19, 'baseline')] + [(s, m) for s in (15, 19)
|
|
for m in ('both', 'read', 'send')]:
|
|
rows = read(f'diagnostic-{site}-{mode}-{kind}.json')
|
|
verify(tokenizer, protocol, prompts, rows, (mode,))
|
|
label = 'baseline' if mode == 'baseline' else f'{site}-{mode}'
|
|
arms[label], _ = table_metrics(prompts, rows, mode)
|
|
comparisons = {f'19-minus-15-{m}': {f'19-{m}': 1, f'15-{m}': -1}
|
|
for m in ('read', 'send', 'both')}
|
|
for site in (15, 19):
|
|
comparisons[f'{site}-interaction'] = {
|
|
f'{site}-both': 1, 'baseline': 1, f'{site}-read': -1, f'{site}-send': -1}
|
|
layer_comparison[kind] = summarize_arms(arms, comparisons, samples)
|
|
write_json(args.directory/'audit.json', dict(
|
|
tables=n, bootstrap_seed=120204, bootstrap_replicates=len(resamples),
|
|
summary=summary, answers=detail, costs=costs, diagnostic_isolation=isolation,
|
|
diagnostic_site_comparison=layer_comparison))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|