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

201 lines
9.3 KiB
Python

"""Capture Qwen sequences and train/evaluate the complete last-layer LiSA method."""
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
from crossqkv.forward_search import encode, problems, SEEDS
from crossqkv.lisa_pilot import DONOR, TARGET, Study
from functional.run import write_json
BATCH = 4
EPOCHS = 8
RANK = 40
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def capture(source, out):
from tokenizers import Tokenizer
model = Study(source / 'weights', json.loads((source / 'model_config.json').read_text()),
seconds=3600)
if TARGET != len(model.config['layer_types']) - 1:
raise ValueError('Exact cached training requires the final layer as the only recipient')
if any(model.config['layer_types'][i] != 'full_attention' for i in (DONOR, TARGET)):
raise ValueError('Both sites must be full attention layers')
model.capture_scores = True
tokenizer = Tokenizer.from_file(str(source / 'tokenizer.json'))
items = {split: problems(split) for split in SEEDS}
write_json(out / 'problems.json', items)
write_json(out / 'protocol.json', {
'source_sha256': {name: digest(source / name) for name in
('model_config.json', 'manifest.json', 'tokenizer.json')},
'donor': DONOR, 'target': TARGET, 'rank_per_head': RANK, 'epochs': EPOCHS,
'batch_size': BATCH, 'seed': 20261123, 'split_seeds': SEEDS,
'optimizer': 'AdamW', 'learning_rate': .0003, 'weight_decay': .1,
'objective': {'full_vocabulary_next_token_ce': .75, 'huber_delta_1': .25},
})
for split, rows in items.items():
for start in range(0, len(rows), BATCH):
batch = rows[start:start+BATCH]
prefixes, lengths, labels = encode(tokenizer, batch)
ids = np.pad(prefixes, ((0, 0), (0, 1)))
gold = np.array([r['gold'] - 1 for r in batch])
ids[np.arange(len(batch)), lengths] = np.asarray(labels)[gold]
native, saved = model.forward(ids, capture=[('attn', TARGET)])
rec = model.recipient
np.savez(out / f'{split}-{start:02}.npz', ids=ids, lengths=lengths + 1,
labels=labels, gold=gold, native=native, local=model.local,
inp=saved[f'attn_{TARGET}'], donor=model.donor, teacher=model.teacher,
values=rec['v'], gate=rec['gate'], residual=model.recipient_input)
print(split, 'captured', start + len(batch), '/', len(rows), flush=True)
def train(source, cache, out, linear_control):
import torch
from crossqkv.forward_search_fit import LastLayer
from crossqkv.lisa_train import (FrozenRecipient, LearnableSharingAttention, causal_attention,
language_model_loss, objective)
torch.set_num_threads(1)
torch.manual_seed(20261123)
protocol = json.loads((cache / 'protocol.json').read_text())
if any(digest(source / name) != sha for name, sha in protocol['source_sha256'].items()):
raise ValueError('The cache does not match the selected source checkpoint')
cfg = json.loads((source / 'model_config.json').read_text())['text_config']
heads, kv = cfg['num_attention_heads'], cfg['num_key_value_heads']
rp = cfg['rope_parameters']
frozen = LastLayer(source)
recipient = FrozenRecipient(frozen.weights, frozen.eps)
adapter = LearnableSharingAttention(cfg['hidden_size'], heads, kv, RANK,
rp['rope_theta'], rp['partial_rotary_factor'],
bias=cfg.get('attention_bias', False))
optimizer = torch.optim.AdamW(adapter.parameters(), lr=.0003, weight_decay=.1)
t = frozen.embedding
def vocabulary():
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):
for path in sorted(cache.glob(f'{split}-*.npz')):
with np.load(path, allow_pickle=False) as data:
yield {k: torch.from_numpy(data[k]) for k in data.files}
def adapter_scores(b):
return adapter(b['inp'], b['donor'], torch.arange(b['ids'].shape[1])[None, :])
def decode(b, s):
return recipient(causal_attention(s, b['values'], b['lengths']),
b['gate'], b['residual'])
def losses(b, s, h):
ce = language_model_loss(h, b['ids'], b['lengths'], vocabulary)
total, kd = objective(s, b['teacher'], b['lengths'], ce)
return total, ce, kd
def evaluate(split, modes, greedy=False):
totals = {mode: [] for mode in modes}
predictions = {mode: [] for mode in modes}
with torch.no_grad():
for b in batches(split):
answer_at = b['lengths'] - 2
valid = torch.arange(b['ids'].shape[1])[None, :] < b['lengths'][:, None]
states = []
for mode in modes:
if mode == 'native':
s = b['teacher']
elif mode == 'direct':
s = b['donor']
elif mode == 'linear_joint':
s = torch.einsum('bhts,hi->bits', torch.cat((b['donor'], b['local']), 1),
linear_matrix)
else:
s = adapter_scores(b)
h = decode(b, s)
if mode == 'native':
torch.testing.assert_close(h[valid], b['native'][valid], atol=4e-5, rtol=3e-5)
loss = losses(b, s, h)
totals[mode].append((int((b['lengths'] - 1).sum()),
sum(int(n)**2 for n in b['lengths']),
*map(float, loss)))
states.append(h[torch.arange(len(answer_at)), answer_at].numpy())
if greedy:
preds = np.split(frozen.greedy(np.concatenate(states)), len(modes))
labels = b['labels'][b['gold']].numpy()
for mode, pred in zip(modes, preds):
predictions[mode].extend((pred == labels).tolist())
results = {}
for mode, rows in totals.items():
if not rows:
raise ValueError(f'No complete capture batches for {split}')
n = sum(r[0] for r in rows)
pairs = sum(r[1] for r in rows)
ce = sum(r[0] * r[3] for r in rows) / n
kd = sum(r[1] * r[4] for r in rows) / pairs
results[mode] = {'ce': ce, 'huber': kd, 'objective': .75 * ce + .25 * kd,
'tokens': n, 'greedy_correct': sum(predictions[mode]),
'greedy_n': len(predictions[mode])}
return results
linear = json.loads(linear_control.read_text())['weights']['linear_joint']
linear_matrix = torch.tensor(linear, dtype=torch.float32)
trace = []
best = float('inf')
for epoch in range(EPOCHS):
step_losses = []
for batch in batches('fit'):
optimizer.zero_grad(set_to_none=True)
scores = adapter_scores(batch)
loss = losses(batch, scores, decode(batch, scores))
loss[0].backward()
if any(p.grad is None or not torch.isfinite(p.grad).all() for p in adapter.parameters()):
raise FloatingPointError('Invalid adapter gradient')
optimizer.step()
step_losses.append(list(map(lambda x: float(x.detach()), loss)))
validation = evaluate('validation', ('lisa',))['lisa']
trace.append({'epoch': epoch + 1, 'fit_batch_losses': step_losses, 'validation': validation})
if validation['objective'] < best:
best = validation['objective']
torch.save(adapter.state_dict(), out / 'best-adapter.pt')
write_json(out / 'trace.json', trace)
print('epoch', epoch + 1, 'validation', validation, flush=True)
adapter.load_state_dict(torch.load(out / 'best-adapter.pt', map_location='cpu', weights_only=True))
modes = ('native', 'direct', 'linear_joint', 'lisa')
result = {split: evaluate(split, modes, greedy=True) for split in ('validation', 'test')}
result['best_epoch'] = min(trace, key=lambda r: r['validation']['objective'])['epoch']
result['trainable_parameters'] = sum(p.numel() for p in adapter.parameters())
result['linear_control_sha256'] = digest(linear_control)
write_json(out / 'results.json', result)
print(result, flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('capture', 'train'))
parser.add_argument('--source', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
parser.add_argument('--cache', type=Path)
parser.add_argument('--linear-control', type=Path)
args = parser.parse_args()
if args.phase == 'train' and (args.cache is None or args.linear_control is None):
parser.error('train requires --cache and --linear-control')
args.out.mkdir()
if args.phase == 'capture':
capture(args.source, args.out)
else:
train(args.source, args.cache, args.out, args.linear_control)
if __name__ == '__main__':
main()