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

116 lines
5.1 KiB
Python

"""Compare one vs two recipients on the same task using full-vocabulary answers."""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
from crossqkv.lisa_tail import TorchTail, weight_chunks
from crossqkv.lisa_train import LearnableSharingAttention
from functional.model import PREFIX, StreamingLM
from functional.run import write_json
def vocabulary_scores(hidden, targets, embedding):
n = len(hidden)
peak = hidden.new_full((n,), -torch.inf)
total = peak.clone()
top = torch.zeros(n, dtype=torch.int64)
true = torch.zeros_like(peak)
start = 0
for w in weight_chunks(embedding, 0, embedding.shape[0], rows=1024):
logits = F.linear(hidden, w)
total = torch.logaddexp(total, logits.logsumexp(dim=-1))
values, indices = logits.max(dim=-1)
top = torch.where(values > peak, indices + start, top)
peak = torch.maximum(values, peak)
local = (targets >= start) & (targets < start + len(w))
true[local] = logits[local, targets[local]-start]
start += len(w)
return top, total-true
def run(source, cache, trained, out):
torch.set_num_threads(1)
spec = json.loads((cache/'selection.json').read_text())
sites = tuple(spec['sites'])
stream = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
cfg = stream.config
rp = cfg['rope_parameters']
heads, kv = cfg['num_attention_heads'], cfg['num_key_value_heads']
def loaded(mode):
if mode == 'linear':
from torch import nn
modules = {site: nn.Linear(heads, heads, bias=False) for site in sites}
else:
modules = {site: LearnableSharingAttention(cfg['hidden_size'], heads, kv, 40,
rp['rope_theta'], rp['partial_rotary_factor'],
bias=cfg.get('attention_bias', False)) for site in sites}
tail = TorchTail(stream, sites[0], modules)
tail.adapters.load_state_dict(torch.load(trained/f'{mode}.pt', weights_only=True,
map_location='cpu'))
return tail
empty = TorchTail(stream, sites[0])
fitted = loaded('lisa')
arms = [('native', empty, 'native', ()),
('direct_23', empty, 'direct', (sites[-1],)),
('lisa_23_ablation', fitted, 'lisa', (sites[-1],))]
if len(sites) > 1:
arms.extend([('direct_chain', empty, 'direct', sites),
('lisa_chain', fitted, 'lisa', sites)])
arms.extend([('linear', loaded('linear'), 'linear', sites),
('lisa_answer_weighted', loaded('lisa_answer_weighted'), 'lisa', sites)])
answers = {name: [] for name, *_ in arms}
ids, labels, options = [], [], []
with torch.no_grad():
for path in sorted(cache.glob('test-*.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'}
ids.extend(f['names'].tolist())
labels.append(b['labels'][b['gold']])
options.append(b['labels'].expand(len(b['gold']), -1))
for name, tail, mode, chosen in arms:
h, _ = tail(b['residual'], b['donor'], b['lengths'], mode, chosen)
answers[name].append(h[torch.arange(len(h)), b['lengths']-2])
print('matched full-vocabulary audit', len(ids), flush=True)
if not ids:
raise ValueError('No captured holdout batches')
y = torch.cat(labels)
t = stream.tensors[PREFIX+'embed_tokens.weight']
hidden = torch.cat([torch.cat(answers[k]) for k in answers])
pred, nll = vocabulary_scores(hidden, y.repeat(len(answers)), t)
result = {}
opts = torch.cat(options)
for (name, h), p, v in zip(answers.items(), pred.split(len(y)), nll.split(len(y))):
option_w = torch.stack([torch.from_numpy(t.read(slice(i*t.shape[1], (i+1)*t.shape[1])))
for i in opts[0].tolist()])
if not torch.equal(opts, opts[0].expand_as(opts)):
raise ValueError('Option token IDs unexpectedly vary across items')
t.evict()
choice = opts[torch.arange(len(y)), F.linear(torch.cat(h), option_w).argmax(-1)]
result[name] = {'n': len(y), 'full_vocab_correct': int((p==y).sum()),
'four_choice_correct': int((choice==y).sum()),
'full_vocab_nll': float(v.mean()),
'rows': [{'id': key, 'gold_id': int(g), 'greedy_id': int(j),
'choice_id': int(c), 'nll': float(s)}
for key, g, j, c, s in zip(ids, y, p, choice, v)]}
write_json(out, {'single_lisa_is_ablation_of_joint_checkpoint': len(sites) > 1,
'candidate_sites': list(sites), 'arms': result})
def main():
p = argparse.ArgumentParser(description=__doc__)
for name in ('source', 'cache', 'trained', 'out'):
p.add_argument('--'+name, type=Path, required=True)
a = p.parse_args()
run(a.source, a.cache, a.trained, a.out)
if __name__ == '__main__':
main()