123 lines
6.1 KiB
Python
123 lines
6.1 KiB
Python
"""Evaluate all predeclared models on fresh counterfactual pairs."""
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
from time import monotonic
|
|
|
|
import numpy as np
|
|
import torch
|
|
from tokenizers import Tokenizer
|
|
|
|
from crossqkv.lisa_combination_screen import ADAPTER_SHA, SITES
|
|
from crossqkv.lisa_full_answer import evaluate, fingerprint
|
|
from crossqkv.lisa_full_answer_verify import verify
|
|
from crossqkv.lisa_rank_compare import make_adapters
|
|
from functional.model import StreamingLM
|
|
from functional.run import write_json
|
|
|
|
|
|
def changed_answers(questions, comparisons, local_uniform):
|
|
"""Identify net gains that hide different sets of corrected and lost answers."""
|
|
ids = np.array([item['id'] for item in questions]).reshape(local_uniform.shape)
|
|
pairwise = {}
|
|
for name, delta in comparisons.items():
|
|
if name != 'rank-interaction':
|
|
pairwise[name] = {'corrected': ids[delta > 0].tolist(),
|
|
'lost': ids[delta < 0].tolist()}
|
|
|
|
versus_share = comparisons['rank-vs-uniform']
|
|
versus_allocation = comparisons['rank-vs-local']
|
|
both = {}
|
|
for name, sign in [('corrected_against_both', 1), ('lost_against_both', -1)]:
|
|
mask = (versus_share == sign) & (versus_allocation == sign)
|
|
both[name] = [{'id': item_id, 'local_uniform_correct': bool(correct)}
|
|
for item_id, correct in zip(ids[mask].tolist(), local_uniform[mask])]
|
|
return {'pairwise': pairwise, 'rank_combination': both}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
for name in ('source','prior','out'):
|
|
parser.add_argument('--'+name, type=Path, required=True)
|
|
args = parser.parse_args()
|
|
torch.set_num_threads(1)
|
|
path = args.out/'protocol.json'
|
|
if fingerprint(path) != '6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef':
|
|
raise ValueError('Frozen protocol mismatch')
|
|
questions = json.loads(path.read_text())['splits']['test']
|
|
prior_protocol = json.loads((args.prior/'frozen.json').read_text())['protocol']
|
|
config = json.loads((args.source/'model_config.json').read_text())
|
|
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
|
|
out = args.out/'holdout'
|
|
out.mkdir(exist_ok=True)
|
|
scores = {}
|
|
generation = {}
|
|
for arm in ('native','direct','prior-lisa','trajectory-student','trajectory-reference',
|
|
'shared-uniform','shared-allocated','shared-reversed','local-uniform','local-allocated'):
|
|
model = StreamingLM(args.source/'weights', config, seconds=172800,process_swap_limit_kib=None)
|
|
sites = () if arm=='native' else SITES
|
|
adapters = None
|
|
if arm not in ('native','direct'):
|
|
ranks = dict.fromkeys(SITES,40)
|
|
shared = True
|
|
if arm=='prior-lisa':
|
|
weights = args.prior/'final/lisa.pt'
|
|
if fingerprint(weights) != ADAPTER_SHA:
|
|
raise ValueError('Incorrect starting checkpoint')
|
|
elif arm.startswith('trajectory-'):
|
|
weights = args.out/arm/'adapter.pt'
|
|
else:
|
|
spec = json.loads((args.out/arm/'config.json').read_text())
|
|
ranks = {int(k):v for k,v in spec['ranks'].items()}
|
|
shared = spec['shared']
|
|
weights = args.out/arm/'lisa.pt'
|
|
adapters = make_adapters(model.config,ranks,shared)
|
|
torch.nn.ModuleDict({str(i):v for i,v in adapters.items()}).load_state_dict(
|
|
torch.load(weights,weights_only=True,map_location='cpu'))
|
|
digest = fingerprint(weights)
|
|
else:
|
|
digest = prior_protocol['weights']['manifest.json']
|
|
lock = out/(arm+'-source.json')
|
|
if lock.exists() and json.loads(lock.read_text()) != digest:
|
|
raise ValueError('Cannot resume with changed weights')
|
|
write_json(lock,digest)
|
|
path = out/(arm+'.json')
|
|
rows = json.loads(path.read_text()) if path.exists() else []
|
|
if rows:
|
|
verify(tok,prior_protocol,questions,rows,(arm,),allow_prefix=True)
|
|
for start in range(len(rows),len(questions),2):
|
|
batch = questions[start:start+2]
|
|
before = monotonic()
|
|
generated = evaluate(model,tok,batch,{arm:sites},adapters)
|
|
seconds = monotonic() - before
|
|
verify(tok,prior_protocol,batch,generated,(arm,))
|
|
generated[0]['batch_seconds'] = seconds
|
|
rows.extend(generated)
|
|
write_json(path,rows)
|
|
print(arm,len(rows),'/',len(questions),flush=True)
|
|
scores[arm] = np.array([x['arms'][arm]['correct'] for x in rows],dtype=int).reshape(-1,2)
|
|
generation[arm] = {'generated_tokens':sum(len(row['arms'][arm]['tokens']) for row in rows),
|
|
'seconds':sum(row['batch_seconds'] for row in rows[::2])}
|
|
comparisons = {'rank-vs-uniform':scores['shared-allocated']-scores['shared-uniform'],
|
|
'rank-vs-reversed':scores['shared-allocated']-scores['shared-reversed'],
|
|
'rank-vs-local':scores['shared-allocated']-scores['local-allocated'],
|
|
'rank-interaction':scores['shared-allocated']-scores['shared-uniform']
|
|
-scores['local-allocated']+scores['local-uniform'],
|
|
'student-vs-prior':scores['trajectory-student']-scores['prior-lisa'],
|
|
'student-vs-reference':scores['trajectory-student']-scores['trajectory-reference']}
|
|
rng = np.random.default_rng(72505)
|
|
sample = rng.integers(0,len(questions)//2,size=(10000,len(questions)//2))
|
|
audit = {'questions':len(questions),
|
|
'generation':generation,
|
|
'changed_answers':changed_answers(questions,comparisons,scores['local-uniform']),
|
|
'correct':{k:int(v.sum()) for k,v in scores.items()},
|
|
'pairs_both_correct':{k:int(v.all(1).sum()) for k,v in scores.items()},
|
|
'paired_differences':{k:{'delta':float(v.mean()),
|
|
'interval_95':np.quantile(v.mean(1)[sample].mean(1),[.025,.975]).tolist()}
|
|
for k,v in comparisons.items()}}
|
|
write_json(out/'audit.json',audit)
|
|
|
|
|
|
if __name__=='__main__':
|
|
main()
|