138 lines
7.0 KiB
Python
138 lines
7.0 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 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():
|
|
estimates = {mode: {k: mean(row[k] for row in arms[mode]) for k in fields} for mode in modes}
|
|
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}
|
|
comparisons = {}
|
|
for name, coefficients in contrasts.items():
|
|
comparisons[name] = {k: interval([
|
|
sum(c*arms[m][i][k] for m, c in coefficients.items()) for i in range(n)
|
|
], resamples) for k in fields}
|
|
summary[kind] = dict(means=estimates, paired_contrasts=comparisons)
|
|
isolation = {}
|
|
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] = {
|
|
'means': {m: {k: mean(row[k] for row in arm) for k in fields} for m, arm in arms.items()},
|
|
'contrasts': {name: {k: interval([
|
|
sum(c*arms[m][i][k] for m,c in coefficients.items()) for i in range(count)
|
|
], samples) for k in fields} for name, coefficients in combinations.items()}}
|
|
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))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|