207 lines
9.9 KiB
Python
207 lines
9.9 KiB
Python
"""Fit LiSA on a development-selected schedule, then evaluate fresh continuations."""
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import torch
|
|
from tokenizers import Tokenizer
|
|
|
|
from crossqkv.lisa_effect_audit import paired
|
|
from crossqkv.lisa_full_answer import (PROCESS_SWAP_LIMIT_KIB, SCHEDULES, STOP_TEXT, choose, evaluate, fingerprint,
|
|
prompt, summarize)
|
|
from crossqkv.lisa_tail import TorchTail, weight_chunks
|
|
from crossqkv.lisa_train import LearnableSharingAttention, huber_distillation, language_model_loss
|
|
from functional.model import PREFIX, StreamingLM
|
|
from functional.run import write_json
|
|
|
|
|
|
class FitCapture(TorchTail):
|
|
def norm(self, x, name, centered=True):
|
|
if name == f'layers.{self.sites[0]}.input_layernorm':
|
|
self.residual = x
|
|
return super().norm(x, name, centered)
|
|
|
|
|
|
def load_locked(source, screen):
|
|
fixed = screen/'frozen.json'
|
|
rows = screen/'screen-rows.json'
|
|
chosen = json.loads((screen/'selection.json').read_text())
|
|
if (chosen['frozen_sha256'] != fingerprint(fixed)
|
|
or chosen['screen_sha256'] != fingerprint(rows)):
|
|
raise ValueError('Locked screening hashes do not match')
|
|
manifest = json.loads(fixed.read_text())
|
|
screen_rows = json.loads(rows.read_text())
|
|
expected = [(x['id'], x['task'], x['answer']) for x in manifest['problems']['screen']]
|
|
if [(x['id'], x['task'], x['gold']) for x in screen_rows] != expected:
|
|
raise ValueError('Screening did not evaluate the frozen development set')
|
|
expected_selection = choose(summarize(screen_rows))
|
|
if expected_selection is None or chosen['chosen'] != expected_selection:
|
|
raise ValueError('Development screen did not produce a qualifying schedule')
|
|
for name, digest in manifest['protocol']['weights'].items():
|
|
if fingerprint(source/name) != digest:
|
|
raise ValueError(f'Model input {name} changed')
|
|
return chosen, manifest
|
|
|
|
|
|
@torch.no_grad()
|
|
def capture(model, tokenizer, fit_examples, directory):
|
|
directory.mkdir(exist_ok=True)
|
|
teacher = FitCapture(model, 0)
|
|
teacher.sites = model.sites
|
|
for i, row in enumerate(fit_examples):
|
|
path = directory/f'{i:03}.npz'
|
|
if path.exists():
|
|
continue
|
|
text = prompt(row['question'])
|
|
base = tokenizer.encode(text, add_special_tokens=False).ids
|
|
complete = tokenizer.encode(text + str(row['answer']) + STOP_TEXT[0],
|
|
add_special_tokens=False).ids
|
|
if complete[:len(base)] != base or len(complete) <= len(base):
|
|
raise ValueError('Answer did not tokenize as an extension of the frozen prompt')
|
|
ids = np.array([complete])
|
|
model.guard()
|
|
hidden = torch.from_numpy(model.embedding(ids))
|
|
_, side = teacher(hidden, None, torch.tensor([len(complete)]), 'native', ())
|
|
pending = path.with_suffix('.tmp.npz')
|
|
np.savez(pending, ids=ids, start=[len(base)], residual=teacher.residual.numpy(),
|
|
donor=side[model.sites[0]-4][0].numpy(),
|
|
teacher=np.stack([side[i][0].numpy() for i in model.sites]))
|
|
pending.replace(path)
|
|
print('fit capture', i+1, '/', len(fit_examples), flush=True)
|
|
|
|
|
|
def checkpoint(path, obj):
|
|
pending = path.with_suffix('.tmp')
|
|
torch.save(obj, pending)
|
|
pending.replace(path)
|
|
|
|
|
|
def train(model, tokenizer, out, split, epochs, rank):
|
|
c = model.config
|
|
rope = c['rope_parameters']
|
|
adapters = {i: LearnableSharingAttention(c['hidden_size'], c['num_attention_heads'],
|
|
c['num_key_value_heads'], rank, rope['rope_theta'], rope['partial_rotary_factor'],
|
|
bias=c.get('attention_bias', False)) for i in model.sites}
|
|
tail = TorchTail(model, model.sites[0], adapters)
|
|
optim = torch.optim.AdamW(tail.parameters(), lr=.0003, weight_decay=.1)
|
|
last = out/'resume.pt'
|
|
selected = out/'lisa.pt'
|
|
state = {'epoch': 0, 'steps': [], 'trace': [], 'best_correct': -1}
|
|
if last.exists():
|
|
state = torch.load(last, weights_only=True, map_location='cpu')
|
|
tail.adapters.load_state_dict(state['parameters'])
|
|
optim.load_state_dict(state['optimizer'])
|
|
|
|
embedding = model.tensors[PREFIX+'embed_tokens.weight']
|
|
|
|
def vocab():
|
|
start = 0
|
|
for w in weight_chunks(embedding, 0, embedding.shape[0], rows=1024):
|
|
yield start, w
|
|
start += len(w)
|
|
|
|
paths = sorted((out/'fit-capture').glob('*.npz'))
|
|
for epoch in range(state['epoch'], epochs):
|
|
for path in paths[len(state['steps']):]:
|
|
with np.load(path, allow_pickle=False) as entry:
|
|
b = {key: torch.from_numpy(entry[key]) for key in entry.files}
|
|
lengths = torch.tensor([b['ids'].shape[1]])
|
|
optim.zero_grad(set_to_none=True)
|
|
h, side = tail(b['residual'], b['donor'], lengths, 'lisa', model.sites)
|
|
kd = torch.stack([huber_distillation(side[i][0], t, lengths)
|
|
for i, t in zip(model.sites, b['teacher'])]).mean()
|
|
ce = language_model_loss(h, b['ids'], lengths, vocab, completion_starts=b['start'])
|
|
loss = .25*kd + .75*ce
|
|
loss.backward()
|
|
if any(p.grad is None or not torch.isfinite(p.grad).all() for p in tail.parameters()):
|
|
raise FloatingPointError('Nonfinite LiSA gradient')
|
|
optim.step()
|
|
state['steps'].append({'capture': path.name, 'huber': float(kd.detach()),
|
|
'completion_ce': float(ce.detach())})
|
|
checkpoint(last, {**state, 'parameters': tail.adapters.state_dict(),
|
|
'optimizer': optim.state_dict()})
|
|
print('fit epoch', epoch+1, 'step', len(state['steps']), '/', len(paths), flush=True)
|
|
val = []
|
|
for start in range(0, len(split['validation']), 2):
|
|
val.extend(evaluate(model, tokenizer, split['validation'][start:start+2],
|
|
{'lisa': model.sites}, adapters))
|
|
correct = sum(x['arms']['lisa']['correct'] for x in val)
|
|
if correct > state['best_correct']:
|
|
state['best_correct'] = correct
|
|
state['best_epoch'] = epoch+1
|
|
state['best_parameters'] = {
|
|
name: param.detach().clone() for name, param in tail.adapters.state_dict().items()
|
|
}
|
|
state['trace'].append({'epoch': epoch+1, 'steps': state['steps'], 'validation': val})
|
|
state['steps'] = []
|
|
state['epoch'] = epoch+1
|
|
checkpoint(last, {**state, 'parameters': tail.adapters.state_dict(),
|
|
'optimizer': optim.state_dict()})
|
|
write_json(out/'trace.json', {'selected_epoch': state['best_epoch'], 'epochs': state['trace']})
|
|
checkpoint(selected, state['best_parameters'])
|
|
tail.adapters.load_state_dict(state['best_parameters'])
|
|
return adapters
|
|
|
|
|
|
def audit(rows):
|
|
correct = {name: np.array([r['arms'][name]['correct'] for r in rows])
|
|
for name in ('native', 'direct', 'lisa')}
|
|
bad_value = [r for r in rows if r['arms']['native']['correct']
|
|
and r['arms']['direct']['answer'] is not None and not r['arms']['direct']['correct']]
|
|
return {'n': len(rows), 'correct': {name: int(x.sum()) for name, x in correct.items()},
|
|
'substantive_loss_ids': [r['id'] for r in bad_value],
|
|
'substantive_rescued_ids': [r['id'] for r in bad_value if r['arms']['lisa']['correct']],
|
|
'unscored': {name: sum(r['arms'][name]['answer'] is None for r in rows) for name in correct},
|
|
**paired(correct['native'], correct['direct'], correct['lisa'])}
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
for path in ('source', 'screen', 'out'):
|
|
p.add_argument('--'+path, type=Path, required=True)
|
|
p.add_argument('--epochs', type=int, default=2)
|
|
args = p.parse_args()
|
|
if args.epochs < 1:
|
|
p.error('--epochs must be positive')
|
|
torch.set_num_threads(1)
|
|
torch.manual_seed(621011)
|
|
locked, manifest = load_locked(args.source, args.screen)
|
|
selection = locked['chosen']
|
|
sites = tuple(selection['recipients'])
|
|
if sites != SCHEDULES[selection['arm']]:
|
|
raise ValueError('Unexpected selected schedule')
|
|
spec = {'screen': locked, 'epochs': args.epochs, 'rank': 40, 'seed': 621011,
|
|
'objective': '0.25 teacher attention Huber + 0.75 full-vocabulary completion CE'}
|
|
args.out.mkdir(exist_ok=True)
|
|
run = args.out/'train-spec.json'
|
|
if run.exists() and json.loads(run.read_text()) != spec:
|
|
raise ValueError('Cannot resume with a different experiment definition')
|
|
write_json(run, spec)
|
|
tasks = {name: [r for r in rows if r['task'] == selection['task']]
|
|
for name, rows in manifest['problems'].items()}
|
|
model = StreamingLM(args.source/'weights', json.loads((args.source/'model_config.json').read_text()),
|
|
seconds=86400, process_swap_limit_kib=PROCESS_SWAP_LIMIT_KIB)
|
|
model.sites = sites
|
|
tokenizer = Tokenizer.from_file(str(args.source/'tokenizer.json'))
|
|
capture(model, tokenizer, tasks['fit'], args.out/'fit-capture')
|
|
adapters = train(model, tokenizer, args.out, tasks, args.epochs, spec['rank'])
|
|
output = args.out/'test-items.json'
|
|
rows = json.loads(output.read_text()) if output.exists() else []
|
|
if [r['id'] for r in rows] != [x['id'] for x in tasks['test'][:len(rows)]]:
|
|
raise ValueError('Test continuation does not match the frozen rows')
|
|
for start in range(len(rows), len(tasks['test']), 2):
|
|
batch = tasks['test'][start:start+2]
|
|
base = evaluate(model, tokenizer, batch, {'native': (), 'direct': sites})
|
|
lisa = evaluate(model, tokenizer, batch, {'lisa': sites}, adapters)
|
|
for x, y in zip(base, lisa):
|
|
x['arms'].update(y['arms'])
|
|
rows.extend(base)
|
|
write_json(output, rows)
|
|
print('test complete', len(rows), '/', len(tasks['test']), flush=True)
|
|
write_json(args.out/'test-audit.json', audit(rows))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|