Files
exp-model-parameter-similarity/tests/test_lisa_combinations.py
T

143 lines
7.1 KiB
Python

"""Regression checks for rank allocation, donor controls and reverse KL."""
import json
import tempfile
import unittest
from pathlib import Path
import numpy as np
import torch
from crossqkv.lisa_combination_eval import changed_answers, score_differences
from crossqkv.lisa_combination_screen import SITES, paired_questions
from crossqkv.lisa_rank_compare import assignments, make_adapters, score_gold_answers
from crossqkv.lisa_trajectory_train import replay_teacher_inputs, reverse_kl
class CombinationTests(unittest.TestCase):
def test_reference_replay_uses_native_tail_only_on_matching_gold_tokens(self):
ids = torch.tensor([[13, 4, 7, 9]])
lengths = torch.tensor([4])
residual = torch.arange(12).reshape(1, 4, 3).float()
donor = torch.arange(16).reshape(1, 1, 4, 4).float()
def native_tail(h, scores, sizes, mode, recipients):
self.assertTrue(torch.equal(sizes, lengths))
self.assertEqual((mode, recipients), ('native', ()))
return h * 2, {}
with tempfile.TemporaryDirectory() as folder:
path = Path(folder)/'capture.npz'
np.savez(path, ids=ids.numpy(), start=[2], residual=residual.numpy(), donor=donor.numpy())
target, h, scores = replay_teacher_inputs(native_tail, path, ids, 2, lengths)
self.assertTrue(torch.equal(target, 2 * residual))
self.assertTrue(torch.equal(h, residual))
self.assertTrue(torch.equal(scores, donor))
for wrong_ids, start in [(ids + 1, 2), (ids, 1)]:
with self.assertRaises(ValueError):
replay_teacher_inputs(native_tail, path, wrong_ids, start, lengths)
def test_combinations_compare_to_the_original_and_matched_controls(self):
scores = {
'prior-lisa': np.array([[0, 1]]), 'shared-uniform': np.array([[1, 0]]),
'shared-allocated': np.array([[1, 1]]), 'shared-reversed': np.array([[0, 0]]),
'local-allocated': np.array([[1, 0]]), 'local-uniform': np.array([[0, 0]]),
'trajectory-student': np.array([[1, 0]]), 'trajectory-reference': np.array([[0, 0]]),
}
differences = score_differences(scores)
for name, expected in {
'rank-vs-prior': [[1, 0]], 'rank-vs-uniform': [[0, 1]],
'rank-vs-reversed': [[1, 1]], 'rank-vs-local': [[0, 1]],
'rank-interaction': [[-1, 1]], 'student-vs-prior': [[1, -1]],
'reference-vs-prior': [[0, -1]], 'student-vs-reference': [[1, 0]],
}.items():
np.testing.assert_array_equal(differences[name], expected, err_msg=name)
def test_joint_recoveries_require_beating_both_single_methods_on_one_item(self):
items = [{'id': name} for name in ['a', 'b', 'c', 'd']]
diffs = {'rank-vs-uniform': np.array([[1, -1], [1, 0]]),
'rank-vs-local': np.array([[1, -1], [0, 0]]),
'rank-interaction': np.array([[2, -2], [0, 0]])}
result = changed_answers(items, diffs, np.array([[0, 1], [0, 1]]))
self.assertEqual(result['pairwise']['rank-vs-uniform'],
{'corrected': ['a', 'c'], 'lost': ['b']})
self.assertNotIn('rank-interaction', result['pairwise'])
self.assertEqual(result['rank_combination'], {
'corrected_against_both': [{'id': 'a', 'local_uniform_correct': False}],
'lost_against_both': [{'id': 'b', 'local_uniform_correct': True}]})
def test_reverse_kl_gradient_matches_dense_unequal_vocab_chunks(self):
rng = torch.Generator().manual_seed(72504)
def normal(*shape):
return torch.randn(*shape, dtype=torch.float64, generator=rng)
student = normal(3, 4).requires_grad_()
teacher = normal(3, 4)
weight = normal(13, 4)
traversals = 0
def chunks():
nonlocal traversals
traversals += 1
yield from weight.split(5)
loss = reverse_kl(student, teacher, chunks)
self.assertEqual(traversals, 2)
logp = (student @ weight.T).log_softmax(-1)
logq = (teacher @ weight.T).log_softmax(-1)
dense = (logp.exp() * (logp - logq)).sum(-1).mean()
torch.testing.assert_close(loss, dense)
torch.testing.assert_close(torch.autograd.grad(loss, student)[0],
torch.autograd.grad(dense, student)[0])
def test_gold_scores_cover_only_answer_and_stop_at_the_correct_shift(self):
class Embedding:
def __init__(self, weights):
self.shape = weights.shape
self.flat = weights.numpy().ravel()
def read(self, span):
return self.flat[span]
def evict(self):
pass
rng = torch.Generator().manual_seed(72507)
weights = torch.randn(9, 4, generator=rng)
outputs = {label: torch.randn(2, 5, 4, generator=rng) for label in ('baseline', 'restore-15')}
ids = [[0, 1, 2, 3, 4, 8], [1, 0, 6, 8]]
gold, scores = score_gold_answers(outputs, ids, [3, 2], Embedding(weights))
self.assertEqual(gold, [[3, 4, 8], [6, 8]])
for label, hidden in outputs.items():
logp = (hidden @ weights.T).log_softmax(-1)
expected = ([logp[0, 2, 3], logp[0, 3, 4], logp[0, 4, 8]],
[logp[1, 1, 6], logp[1, 2, 8]])
for row, answer in zip(scores, expected):
torch.testing.assert_close(torch.tensor(row[label]), torch.stack(answer))
def test_diagnostic_tie_rule_and_wrong_assignment_control(self):
rows = paired_questions('diagnostic', 2, 72501)
protocol = {'splits': {'diagnostic': rows}, 'rank_budget': [32, 40, 48]}
with tempfile.TemporaryDirectory() as folder:
directory = Path(folder)
for label, correct in [('baseline', 0), ('restore-15', 1),
('restore-19', 3), ('restore-23', 1)]:
data = [{'id': x['id'], 'gold': x['answer'],
'arms': {label: {'correct': i < correct}}} for i, x in enumerate(rows)]
(directory/(label+'.json')).write_text(json.dumps(data))
_, ranks = assignments(protocol, directory)
self.assertEqual(ranks['allocated'], {19: 48, 15: 40, 23: 32})
self.assertEqual(ranks['reversed'], {19: 32, 15: 40, 23: 48})
def test_local_control_is_insensitive_to_donor_with_equal_parameter_count(self):
config = {'hidden_size': 8, 'num_attention_heads': 4, 'num_key_value_heads': 2,
'rope_parameters': {'rope_theta': 10000, 'partial_rotary_factor': 0.25}}
allocated = dict(zip(SITES, (32, 40, 48)))
local = make_adapters(config, allocated, False)
uniform = make_adapters(config, dict.fromkeys(SITES, 40), True)
def count(adapters):
return sum(p.numel() for a in adapters.values() for p in a.parameters())
self.assertEqual(count(local), count(uniform))
h = torch.randn(1, 3, 8)
donor = torch.randn(1, 4, 3, 3)
pos = torch.arange(3)[None, :]
a = local[15]
torch.testing.assert_close(a(h, donor, pos), a(h, donor * 5 + 2, pos))