Evaluate matched half-size trajectory distillation updates
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
"""Test a single predeclared shrinkage of the two trained LiSA distillation updates."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
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 fingerprint
|
||||
from crossqkv.lisa_full_answer_train import checkpoint, load_locked
|
||||
from crossqkv.lisa_full_answer_verify import verify
|
||||
from crossqkv.lisa_rank_compare import make_adapters
|
||||
from crossqkv.lisa_trajectory_train import validate_checkpoint
|
||||
from functional.model import StreamingLM
|
||||
from functional.run import write_json
|
||||
|
||||
|
||||
PROTOCOL_SHA = '6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef'
|
||||
TRAINED_SHA = {
|
||||
'student': '7faacdffbc81d0c786ef0c7a5acaf1724d82af155fed7b834dabc73dcf91f3a4',
|
||||
'reference': '21ae007cb7343c1a0042655824bdc98ee2f03071d5f5dc43dbc8b441a262d84f',
|
||||
}
|
||||
VALIDATION_SHA = {
|
||||
'prior-lisa': '3a10cdd0a22e110b5468ba496c3440a8b510ab3595328df330e7ea02b0ccbb76',
|
||||
'trajectory-student': 'af213ef477e99780d48b995f8a1d07ada6409bd70011202fb73db56247199c5f',
|
||||
'trajectory-reference': '3b5557336570cbeb1f6a592013780dc3e00e7f29b4192d59c53c6b2493779b91',
|
||||
}
|
||||
|
||||
|
||||
def read(path):
|
||||
return json.loads(path.read_bytes())
|
||||
|
||||
|
||||
def midpoint(base, trained):
|
||||
if base.keys() != trained.keys():
|
||||
raise ValueError('Adapter parameter names differ')
|
||||
result = {}
|
||||
for name, old in base.items():
|
||||
new = trained[name]
|
||||
if new.shape != old.shape or new.dtype != old.dtype or not old.is_floating_point():
|
||||
raise ValueError(f'Incompatible parameters for {name}')
|
||||
value = ((old.double() + new.double()) * 0.5).to(old.dtype)
|
||||
if not torch.isfinite(value).all():
|
||||
raise ValueError(f'Nonfinite midpoint for {name}')
|
||||
result[name] = value
|
||||
return result
|
||||
|
||||
|
||||
def prepare(prior, out, directory):
|
||||
base_path = prior / 'final/lisa.pt'
|
||||
if fingerprint(base_path) != ADAPTER_SHA:
|
||||
raise ValueError('Wrong starting LiSA model')
|
||||
base = torch.load(base_path, weights_only=True, map_location='cpu')
|
||||
spec = {'protocol_sha256': PROTOCOL_SHA, 'base_sha256': ADAPTER_SHA, 'fraction': 0.5,
|
||||
'parameters': sum(t.numel() for t in base.values()), 'endpoints': {}}
|
||||
for prefix, digest in TRAINED_SHA.items():
|
||||
endpoint = out / ('trajectory-' + prefix) / 'adapter.pt'
|
||||
if fingerprint(endpoint) != digest:
|
||||
raise ValueError(f'Wrong {prefix} distillation checkpoint')
|
||||
value = midpoint(base, torch.load(endpoint, weights_only=True, map_location='cpu'))
|
||||
path = directory / (prefix + '.pt')
|
||||
if path.exists():
|
||||
saved = torch.load(path, weights_only=True, map_location='cpu')
|
||||
if saved.keys() != value.keys() or any(not torch.equal(t, saved[k]) for k, t in value.items()):
|
||||
raise ValueError(f'Stored {prefix} midpoint differs from its endpoints')
|
||||
else:
|
||||
checkpoint(path, value)
|
||||
spec['endpoints'][prefix] = {'trained_sha256': digest, 'midpoint_sha256': fingerprint(path)}
|
||||
path = directory / 'spec.json'
|
||||
if path.exists() and read(path) != spec:
|
||||
raise ValueError('Midpoint experiment specification changed')
|
||||
write_json(path, spec)
|
||||
return spec
|
||||
|
||||
|
||||
def summarize(questions, answers, *, intervals):
|
||||
ids = [q['id'] for q in questions]
|
||||
flags = {name: np.array([a['correct'] for a in rows], dtype=int).reshape(-1, 2)
|
||||
for name, rows in answers.items()}
|
||||
draws = np.random.default_rng(72505).integers(0, len(ids)//2, (10000, len(ids)//2)) if intervals else None
|
||||
comparisons = {}
|
||||
for prefix in TRAINED_SHA:
|
||||
name = 'half-' + prefix
|
||||
controls = ['prior-lisa', 'trajectory-' + prefix]
|
||||
if prefix == 'student':
|
||||
controls.append('half-reference')
|
||||
for control in controls:
|
||||
delta = flags[name] - flags[control]
|
||||
comparison = {'delta': float(delta.mean()),
|
||||
'corrected': [q for q, d in zip(ids, delta.flat) if d > 0],
|
||||
'lost': [q for q, d in zip(ids, delta.flat) if d < 0]}
|
||||
if intervals:
|
||||
comparison['interval_95'] = np.quantile(delta.mean(1)[draws].mean(1), [.025, .975]).tolist()
|
||||
comparisons[name + '-vs-' + control] = comparison
|
||||
return {'questions': len(ids), 'correct': {k: int(v.sum()) for k, v in flags.items()},
|
||||
'pairs_both_correct': {k: int(v.all(1).sum()) for k, v in flags.items()}, 'comparisons': comparisons}
|
||||
|
||||
|
||||
def score_split(args, directory, questions, split, protocol, model, tok, spec):
|
||||
folder = directory / split
|
||||
folder.mkdir(exist_ok=True)
|
||||
answers = {}
|
||||
for name, digest in VALIDATION_SHA.items():
|
||||
prefix = name.removeprefix('trajectory-')
|
||||
if split == 'validation':
|
||||
path = (args.out/'validation-prior-lisa.json' if name == 'prior-lisa'
|
||||
else args.out/name/('validation-' + prefix + '.json'))
|
||||
if fingerprint(path) != digest:
|
||||
raise ValueError(f'Validation control changed for {name}')
|
||||
else:
|
||||
path = args.out/'holdout'/(name + '.json')
|
||||
expected = ADAPTER_SHA if name == 'prior-lisa' else TRAINED_SHA[prefix]
|
||||
if read(path.with_name(name + '-source.json')) != expected:
|
||||
raise ValueError(f'Holdout control source changed for {name}')
|
||||
rows = read(path)
|
||||
verify(tok, protocol, questions, rows, (path.stem,))
|
||||
answers[name] = [r['arms'][path.stem] for r in rows]
|
||||
for prefix in TRAINED_SHA:
|
||||
name = 'half-' + prefix
|
||||
path = directory / (prefix + '.pt')
|
||||
if fingerprint(path) != spec['endpoints'][prefix]['midpoint_sha256']:
|
||||
raise ValueError(f'Midpoint changed for {prefix}')
|
||||
adapters = make_adapters(model.config, dict.fromkeys(SITES, 40), True)
|
||||
torch.nn.ModuleDict({str(i): v for i, v in adapters.items()}).load_state_dict(
|
||||
torch.load(path, weights_only=True, map_location='cpu'))
|
||||
answer_path = folder / (name + '.json')
|
||||
validate_checkpoint(model, tok, adapters, questions, protocol, answer_path, split_name=split)
|
||||
rows = read(answer_path)
|
||||
verify(tok, protocol, questions, rows, (name,))
|
||||
answers[name] = [r['arms'][name] for r in rows]
|
||||
summary = summarize(questions, answers, intervals=split == 'test')
|
||||
write_json(folder/'summary.json', summary)
|
||||
return summary
|
||||
|
||||
|
||||
def run(args):
|
||||
if fingerprint(args.out/'protocol.json') != PROTOCOL_SHA:
|
||||
raise ValueError('Wrong comparison protocol')
|
||||
directory = args.out/'trajectory-midpoint'
|
||||
directory.mkdir(exist_ok=True)
|
||||
with (directory/'.lock').open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
spec = prepare(args.prior, args.out, directory)
|
||||
if args.prepare_only:
|
||||
return
|
||||
_, prior = load_locked(args.source, args.prior)
|
||||
model = StreamingLM(args.source/'weights', read(args.source/'model_config.json'), seconds=172800,
|
||||
process_swap_limit_kib=None)
|
||||
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
|
||||
splits = read(args.out/'protocol.json')['splits']
|
||||
val = score_split(args, directory, splits['validation'], 'validation', prior['protocol'], model, tok, spec)
|
||||
counts = val['correct']
|
||||
qualified = [p for p in TRAINED_SHA if counts['half-' + p] > counts['prior-lisa']]
|
||||
if qualified:
|
||||
score_split(args, directory, splits['test'], 'test', prior['protocol'], model, tok, spec)
|
||||
write_json(directory/'decision.json', {'qualified_validation_prefixes': qualified,
|
||||
'test_evaluated': bool(qualified)})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for key in ('source', 'prior', 'out'):
|
||||
parser.add_argument('--' + key, required=True, type=Path)
|
||||
parser.add_argument('--prepare-only', action='store_true')
|
||||
torch.set_num_threads(1)
|
||||
run(parser.parse_args())
|
||||
Reference in New Issue
Block a user