Files
exp-model-parameter-similarity/crossqkv/lisa_effect.py
T

297 lines
13 KiB
Python

"""Train matched multi-recipient sharing adapters and evaluate the frozen test set."""
import argparse
import hashlib
import json
import time
from pathlib import Path
import numpy as np
from crossqkv.core import QKVModel
from crossqkv.lisa_effect_screen import TASKS
from crossqkv.lisa_pilot import batch, scores
from functional.model import PREFIX
from functional.run import write_json
CANDIDATES = ('linear', 'lisa', 'lisa_answer_weighted')
def selection(screen):
eligible = []
for task, modes in screen.items():
base = modes['native']
if base['correct'] < 5:
continue
for name, sites in [('direct_23', [23]), ('direct_19_23', [19, 23])]:
row = modes[name]
if row['native_wins_lost']:
eligible.append((row['native_wins_lost'], len(sites),
base['correct']-row['correct'], task, sites))
if not eligible:
raise ValueError('No task/schedule met the prespecified development eligibility rule')
_, _, _, task, sites = max(eligible)
return {'task': task, 'sites': sites}
class Capture(QKVModel):
def normalization(self, x, name):
if name == f'layers.{self.first}.input_layernorm':
self.residual = x
return super().normalization(x, name)
def full_attention(self, h, layer, shared_p=None):
if layer != self.first - 4:
return super().full_attention(h, layer, shared_p)
part = self.parts(h, layer, heads=False)
self.donor = scores(part['q'], part['k'])
return part['output'], part['p']
def capture(source, screen_dir, out, schedule):
from tokenizers import Tokenizer
fixed_path = screen_dir/'fixed-problems.json'
fixed = json.loads(fixed_path.read_text())
chosen = selection(json.loads((screen_dir/'screen-summary.json').read_text()))
if schedule == 'chain':
modes = json.loads((screen_dir/'screen-summary.json').read_text())[chosen['task']]
if not modes['direct_19_23']['native_wins_lost']:
raise ValueError('The development-selected task has no recorded losses under the chain')
chosen['sites'] = [19, 23]
model = Capture(source/'weights', json.loads((source/'model_config.json').read_text()),
seconds=7200)
model.first = chosen['sites'][0]
tok = Tokenizer.from_file(str(source/'tokenizer.json'))
sha = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
write_json(out/'selection.json', {**chosen, 'fixed_problems_sha256': sha(fixed_path),
'source_sha256': {n: sha(source/n) for n in
('manifest.json', 'model_config.json', 'tokenizer.json')}})
for split in ('fit', 'validation', 'test'):
selected = [ex for ex in fixed[split] if ex['task'] == chosen['task']]
for start in range(0, len(selected), 4):
group = selected[start:start+4]
ids, lengths, labels = batch(tok, group)
gold = np.array([r['answer_index'] for r in group])
ids = np.pad(ids, ((0, 0), (0, 1)))
ids[np.arange(len(group)), lengths] = np.asarray(labels)[gold]
h, _ = model.forward(ids)
pending = out/f'{split}-{start:03}.tmp.npz'
np.savez(pending, ids=ids, lengths=np.asarray(lengths)+1, labels=labels, gold=gold,
residual=model.residual, donor=model.donor, expected=h,
names=[x['id'] for x in group])
pending.replace(out/f'{split}-{start:03}.npz')
print('capture', split, start+len(group), '/', len(selected), flush=True)
def train(source, cache, out, epochs, resume=False):
import torch
from torch import nn
from crossqkv.lisa_tail import TorchTail
from crossqkv.lisa_train import LearnableSharingAttention, huber_distillation, language_model_loss
from functional.model import StreamingLM
torch.set_num_threads(1)
torch.manual_seed(415005)
spec = json.loads((cache/'selection.json').read_text())
if any(hashlib.sha256((source/n).read_bytes()).hexdigest() != s
for n, s in spec['source_sha256'].items()):
raise ValueError('Checkpoint provenance mismatch')
expected_batches = {'fit':12, 'validation':12, 'test':32}
for split, count in expected_batches.items():
actual = 0
for p in cache.glob(f'{split}-*.npz'):
with np.load(p, allow_pickle=False) as b:
actual += len(b['names'])
if actual != count:
raise ValueError(f'Expected {count} {split} examples, found {actual}')
run_config = {'epochs': epochs, 'selection': spec, 'optimizer': 'AdamW',
'lr': .0003, 'weight_decay': .1, 'answer_weight': 16., 'seed': 415005}
config_path = out/'train-protocol.json'
if resume:
if json.loads(config_path.read_text()) != run_config:
raise ValueError('Training configuration differs from the original run')
else:
write_json(config_path, run_config)
model = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
sites = tuple(spec['sites'])
cfg = model.config
heads = cfg['num_attention_heads']
rope = cfg['rope_parameters']
t = model.tensors[PREFIX+'embed_tokens.weight']
def vocab():
for start in range(0, t.shape[0], 1024):
end = min(start+1024, t.shape[0])
yield start, torch.from_numpy(t.read(slice(start*t.shape[1], end*t.shape[1]))
.reshape(end-start, t.shape[1]))
t.evict()
def batches(split, micro=False):
for path in sorted(cache.glob(f'{split}-*.npz')):
with np.load(path, allow_pickle=False) as f:
b = {k: torch.from_numpy(f[k]) for k in f.files if k != 'names'}
names = f['names'].tolist()
if not micro:
yield b, names
else:
for j, name in enumerate(names):
yield {k: v if k == 'labels' else v[j:j+1] for k, v in b.items()}, [name]
def make(candidate):
torch.manual_seed(415005)
if candidate == 'linear':
blocks = {i: nn.Linear(heads, heads, bias=False) for i in sites}
for value in blocks.values():
with torch.no_grad():
value.weight.copy_(torch.eye(heads))
else:
blocks = {i: LearnableSharingAttention(cfg['hidden_size'], heads,
cfg['num_key_value_heads'], 40, rope['rope_theta'],
rope['partial_rotary_factor'], bias=cfg.get('attention_bias', False))
for i in sites}
return TorchTail(model, sites[0], blocks)
def run(tail, b, mode, teacher=False):
return tail(b['residual'], b['donor'], b['lengths'], mode, sites, teacher)
def score(h, b):
index = b['lengths'] - 2
f = h[torch.arange(len(index)), index]
labels = b['labels'].tolist()
weights = np.stack([t.read(slice(i*t.shape[1], (i+1)*t.shape[1])) for i in labels])
t.evict()
logits = f @ torch.from_numpy(weights).T
nll = torch.logsumexp(logits, -1) - logits[torch.arange(len(index)), b['gold']]
return logits, nll
def evaluate(tail, split, mode):
rows = []
with torch.no_grad():
for b, names in batches(split):
h, _ = run(tail, b, mode)
if mode == 'native':
valid = torch.arange(h.shape[1])[None] < b['lengths'][:, None]
torch.testing.assert_close(h[valid], b['expected'][valid], rtol=7e-5, atol=8e-5)
logits, nll = score(h, b)
rows.extend({'id': name, 'gold': int(g), 'logits': x.tolist(),
'pred': int(x.argmax()), 'answer_nll': float(v)}
for name, g, x, v in zip(names, b['gold'], logits, nll))
if not rows:
raise ValueError(f'No cached rows for {split}')
return rows
def mean_nll(rows):
return sum(r['answer_nll'] for r in rows) / len(rows)
trace = {}
for candidate in CANDIDATES:
tail = make(candidate)
mode = 'linear' if candidate == 'linear' else 'lisa'
optim = torch.optim.AdamW(tail.parameters(), lr=.0003, weight_decay=.1)
ans_weight = 16.0 if candidate == 'lisa_answer_weighted' else 1.0
best = float('inf')
best_weights = None
trace[candidate] = []
last = out/f'{candidate}-resume.pt'
if resume and 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'])
trace[candidate] = state['trace']
best = state['best']
best_weights = state['best_parameters']
for epoch in range(len(trace[candidate]), epochs):
loss_total = 0.
count = 0
for b, _ in batches('fit', micro=True):
optim.zero_grad(set_to_none=True)
h, layer = run(tail, b, mode, teacher=True)
kd = torch.stack([huber_distillation(*layer[i], b['lengths']) for i in sites]).mean()
ce = None if mode == 'linear' else language_model_loss(
h, b['ids'], b['lengths'], vocab, answer_weight=ans_weight)
loss = kd if ce is None else .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('Invalid adapter gradients')
optim.step()
loss_total += float(loss.detach())
count += 1
rows = evaluate(tail, 'validation', mode)
val = mean_nll(rows)
trace[candidate].append({'epoch': epoch+1, 'fit_loss': loss_total/count,
'validation_answer_nll': val})
if val < best:
best = val
best_weights = {k: v.detach().clone() for k, v in tail.adapters.state_dict().items()}
pending = last.with_suffix('.tmp')
torch.save({'parameters': tail.adapters.state_dict(), 'optimizer': optim.state_dict(),
'trace': trace[candidate], 'best': best, 'best_parameters': best_weights},
pending)
pending.replace(last)
write_json(out/'trace.json', trace)
print(candidate, epoch+1, 'validation answer NLL', val, flush=True)
selected = out/f'{candidate}.pt'
pending = selected.with_suffix('.tmp')
torch.save(best_weights, pending)
pending.replace(selected)
# All checkpoints are frozen before evaluating holdout. Native and direct
# go through the same path, including numerical parity with NumPy.
results = {}
empty = TorchTail(model, sites[0])
for mode in ('native', 'direct'):
results[mode] = evaluate(empty, 'test', mode)
for name in CANDIDATES:
tail = make(name)
tail.adapters.load_state_dict(torch.load(out/f'{name}.pt', map_location='cpu', weights_only=True))
results[name] = evaluate(tail, 'test', 'linear' if name == 'linear' else 'lisa')
write_json(out/'test-items.json', results)
b, _ = next(batches('validation'))
b = {k: v if k == 'labels' else v[:1] for k, v in b.items()}
trained = make('lisa')
trained.adapters.load_state_dict(torch.load(out/'lisa.pt', weights_only=True))
timing = {'native': [], 'direct': [], 'lisa': []}
with torch.no_grad():
for turn in range(4):
modes = list(timing)
for mode in modes[turn % 3:] + modes[:turn % 3]:
t0 = time.perf_counter()
_, _ = run(trained if mode == 'lisa' else empty, b, mode)
if turn:
timing[mode].append(time.perf_counter()-t0)
tokens = int(b['lengths'][0])
kv, d = cfg['num_key_value_heads'], cfg['head_dim']
cache_bytes = {'scope': 'formula for one sequence, BF16 keys and score buffers',
'native_recipient_key_bytes': len(sites)*tokens*kv*d*2,
'lisa_recipient_key_bytes': len(sites)*tokens*kv*40*2,
'one_shared_decode_score_row_bytes': heads*tokens*2,
'one_full_prefill_score_matrix_bytes': heads*tokens*tokens*2}
write_json(out/'performance.json', {'scope': 'cached-prefix last layers, prefill',
'seconds': timing, 'real_tokens': tokens, 'cache_estimate': cache_bytes})
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('phase', choices=('capture', 'train'))
p.add_argument('--source', required=True, type=Path)
p.add_argument('--input', required=True, type=Path)
p.add_argument('--out', required=True, type=Path)
p.add_argument('--schedule', choices=('best','chain'), default='best')
p.add_argument('--epochs', type=int, default=2)
p.add_argument('--resume', action='store_true')
a = p.parse_args()
if a.epochs < 1:
p.error('--epochs must be positive')
if a.resume and a.phase != 'train':
p.error('--resume is for training with saved epoch checkpoints')
a.out.mkdir(exist_ok=a.resume)
if a.phase == 'capture':
capture(a.source, a.input, a.out, a.schedule)
else:
train(a.source, a.input, a.out, a.epochs, a.resume)
if __name__ == '__main__':
main()