158 lines
7.7 KiB
Python
158 lines
7.7 KiB
Python
"""Independently validate frozen test outputs and report paired capability recovery."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
from statistics import median
|
|
|
|
import numpy as np
|
|
|
|
from functional.run import write_json
|
|
|
|
MODES = ('native', 'direct', 'linear', 'lisa', 'lisa_answer_weighted')
|
|
|
|
|
|
def paired_interval(delta):
|
|
rng = np.random.default_rng(415006)
|
|
draw = rng.integers(0, len(delta), size=(10000, len(delta)))
|
|
return np.quantile(delta[draw].mean(1), [.025, .975]).tolist()
|
|
|
|
|
|
def paired(native, direct, candidate):
|
|
damaged = native & ~direct
|
|
rescued = damaged & candidate
|
|
newly_lost = native & direct & ~candidate
|
|
candidate_only = ~direct & candidate
|
|
direct_only = direct & ~candidate
|
|
delta = candidate.astype(int) - direct.astype(int)
|
|
a, b = int(candidate_only.sum()), int(direct_only.sum())
|
|
k = a + b
|
|
p = min(1., 2. * sum(math.comb(k, i) for i in range(min(a, b)+1)) / 2**k)
|
|
return {'native_correct_lost_by_direct': int(damaged.sum()), 'rescued': int(rescued.sum()),
|
|
'newly_lost_among_native_and_direct_correct': int(newly_lost.sum()),
|
|
'candidate_correct_direct_wrong': a, 'direct_correct_candidate_wrong': b,
|
|
'accuracy_delta_vs_direct': float(delta.mean()),
|
|
'paired_prompt_bootstrap_95': paired_interval(delta), 'mcnemar_exact_p': p}
|
|
|
|
|
|
def loss_delta(losses, baseline):
|
|
delta = losses - baseline
|
|
return {'mean_delta': float(delta.mean()), 'paired_prompt_bootstrap_95': paired_interval(delta)}
|
|
|
|
|
|
def full_vocab_metrics(path, expected, sites, choices):
|
|
report = json.loads(path.read_text())
|
|
chain = len(sites) > 1
|
|
if (report['candidate_sites'] != sites
|
|
or report['single_lisa_is_ablation_of_joint_checkpoint'] != chain):
|
|
raise ValueError('Full-vocabulary layers differ from the locked schedule')
|
|
arms = report['arms']
|
|
mapped = {'native': 'native', 'linear': 'linear', 'lisa_answer_weighted': 'lisa_answer_weighted',
|
|
'direct_chain' if chain else 'direct_23': 'direct',
|
|
'lisa_chain' if chain else 'lisa_23_ablation': 'lisa'}
|
|
if set(arms) != set(mapped) | {'direct_23', 'lisa_23_ablation'}:
|
|
raise ValueError('Unexpected full-vocabulary arms')
|
|
expected_ids = [name for name, _ in expected]
|
|
correct, nll = {}, {}
|
|
gold_ids = [row['gold_id'] for row in arms['native']['rows']]
|
|
for mode, summary in arms.items():
|
|
rows = summary['rows']
|
|
if (summary['n'] != len(expected_ids) or [row['id'] for row in rows] != expected_ids
|
|
or [row['gold_id'] for row in rows] != gold_ids):
|
|
raise ValueError(f'{mode} vocabulary result does not match the locked rows')
|
|
correct[mode] = np.array([row['greedy_id'] == row['gold_id'] for row in rows])
|
|
nll[mode] = np.array([row['nll'] for row in rows])
|
|
choice_correct = np.array([row['choice_id'] == row['gold_id'] for row in rows])
|
|
if (not np.isfinite(nll[mode]).all() or (nll[mode] < 0).any()
|
|
or int(correct[mode].sum()) != summary['full_vocab_correct']
|
|
or int(choice_correct.sum()) != summary['four_choice_correct']
|
|
or not np.isclose(nll[mode].mean(), summary['full_vocab_nll'])):
|
|
raise ValueError(f'Invalid vocabulary metrics for {mode}')
|
|
if mode in mapped and not np.array_equal(choice_correct, choices[mapped[mode]]):
|
|
raise ValueError(f'{mode} choices differ across the two evaluations')
|
|
matches = {'lisa_23_ablation': 'direct_23',
|
|
'native': 'direct_chain' if chain else 'direct_23',
|
|
'linear': 'direct_chain' if chain else 'direct_23',
|
|
'lisa_answer_weighted': 'direct_chain' if chain else 'direct_23'}
|
|
if chain:
|
|
matches['lisa_chain'] = 'direct_chain'
|
|
return {
|
|
'arms': {mode: {'correct': int(correct[mode].sum()), 'answer_nll': float(nll[mode].mean())}
|
|
for mode in arms},
|
|
'matched_direct_comparisons': {
|
|
mode: {'baseline': direct, 'answer_nll_delta': loss_delta(nll[mode], nll[direct]),
|
|
**paired(correct['native'], correct[direct], correct[mode])}
|
|
for mode, direct in matches.items()},
|
|
}
|
|
|
|
|
|
def audit(fixed, selection, items, perf=None, decode=None, full_vocab=None):
|
|
spec = json.loads(selection.read_text())
|
|
if hashlib.sha256(fixed.read_bytes()).hexdigest() != spec['fixed_problems_sha256']:
|
|
raise ValueError('Fixed problems provenance mismatch')
|
|
problem = json.loads(fixed.read_text())
|
|
task = spec['task']
|
|
expected = [(r['id'], r['answer_index']) for r in problem['test'] if r['task'] == task]
|
|
data = json.loads(items.read_text())
|
|
if set(data) != set(MODES) or not expected:
|
|
raise ValueError('Unexpected test arms or empty selected split')
|
|
correct = {}
|
|
losses = {}
|
|
for mode, rows in data.items():
|
|
if [(r['id'], r['gold']) for r in rows] != expected:
|
|
raise ValueError(f'{mode} result does not match the locked challenge')
|
|
logits = np.array([r['logits'] for r in rows])
|
|
gold = np.array([r['gold'] for r in rows])
|
|
pred = np.array([r['pred'] for r in rows])
|
|
nll = np.logaddexp.reduce(logits, 1) - logits[np.arange(len(rows)), gold]
|
|
if (logits.shape != (len(rows), 4) or not np.isfinite(logits).all()
|
|
or not np.array_equal(logits.argmax(1), pred)):
|
|
raise ValueError(f'Invalid choice scores for {mode}')
|
|
np.testing.assert_allclose(nll, [row['answer_nll'] for row in rows], atol=3e-6, rtol=2e-6)
|
|
correct[mode], losses[mode] = pred == gold, nll
|
|
metrics = {'selected_task': task, 'sites': spec['sites'], 'n': len(expected),
|
|
'arms': {mode: {'correct': int(correct[mode].sum()),
|
|
'answer_nll_4': float(losses[mode].mean()),
|
|
'answer_nll_4_vs_direct': loss_delta(losses[mode], losses['direct']),
|
|
**paired(correct['native'], correct['direct'], correct[mode])}
|
|
for mode in MODES}}
|
|
if perf:
|
|
measured = json.loads(perf.read_text())
|
|
med = {k: median(v) for k,v in measured['seconds'].items()}
|
|
metrics['prefill'] = {'scope': measured['scope'], 'median_s': med,
|
|
'lisa_median_ratio_to_native': med['lisa']/med['native']}
|
|
if decode:
|
|
measured = json.loads(decode.read_text())
|
|
metrics['decode'] = {'scope': measured['scope'], 'sites': {}}
|
|
for layer, raw in measured['sites'].items():
|
|
times = {k: median(v) for k,v in raw['seconds_per_token'].items()}
|
|
mem = raw['allocated_bytes']
|
|
native = mem['native']['k'] + mem['native']['v']
|
|
lisa = mem['lisa']['k'] + mem['lisa']['v']
|
|
nn = raw['lisa_input_score_row_bytes']
|
|
assert mem['lisa']['v'] == mem['native']['v'] and mem['lisa']['k'] < mem['native']['k']
|
|
metrics['decode']['sites'][layer] = {
|
|
'median_s_per_token': times, 'measured_kv_bytes': {'native': native, 'lisa': lisa},
|
|
'lisa_upstream_score_row_bytes': nn, 'recipient_bytes_delta': lisa+nn-native,
|
|
}
|
|
if full_vocab:
|
|
metrics['full_vocab'] = full_vocab_metrics(full_vocab, expected, spec['sites'], correct)
|
|
return metrics
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
for name in ('fixed', 'selection', 'items', 'out'):
|
|
parser.add_argument('--'+name, type=Path, required=True)
|
|
parser.add_argument('--perf', type=Path)
|
|
parser.add_argument('--decode', type=Path)
|
|
parser.add_argument('--full-vocab', type=Path)
|
|
a = parser.parse_args()
|
|
report = audit(a.fixed, a.selection, a.items, a.perf, a.decode, a.full_vocab)
|
|
write_json(a.out, report)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|