81 lines
3.5 KiB
Python
81 lines
3.5 KiB
Python
"""Numerical checks for the exact CE and differentiable LiSA path."""
|
|
import unittest
|
|
|
|
import torch
|
|
from torch.nn import functional as F
|
|
|
|
from crossqkv.lisa_train import (FrozenRecipient, LearnableSharingAttention,
|
|
causal_attention, language_model_loss, objective)
|
|
|
|
|
|
class LiSATrainingTests(unittest.TestCase):
|
|
def test_streamed_ce_value_and_gradient_match_dense(self):
|
|
torch.manual_seed(8)
|
|
hidden = torch.randn(2, 5, 7, dtype=torch.float64, requires_grad=True)
|
|
head = torch.randn(11, 7, dtype=hidden.dtype)
|
|
ids = torch.randint(0, len(head), (2, 5))
|
|
lengths = torch.tensor([5, 3])
|
|
|
|
def vocab():
|
|
for start in range(0, len(head), 4):
|
|
yield start, head[start:start+4]
|
|
|
|
valid = torch.arange(1, 5) < lengths[:, None]
|
|
dense = F.cross_entropy(F.linear(hidden[:, :-1][valid], head), ids[:, 1:][valid])
|
|
streamed = language_model_loss(hidden, ids, lengths, vocab)
|
|
torch.testing.assert_close(streamed, dense)
|
|
torch.testing.assert_close(torch.autograd.grad(streamed, hidden)[0],
|
|
torch.autograd.grad(dense, hidden)[0])
|
|
|
|
def test_answer_weighted_ce_matches_dense(self):
|
|
torch.manual_seed(12)
|
|
h = torch.randn((2, 4, 3), dtype=torch.float64, requires_grad=True)
|
|
w = torch.randn((5, 3), dtype=h.dtype)
|
|
ids = torch.randint(0, 5, (2, 4))
|
|
lengths = torch.tensor([4, 3])
|
|
valid = torch.arange(1, 4) < lengths[:, None]
|
|
answer = torch.arange(2, 5) == lengths[:, None]
|
|
weights = torch.where(answer, 16., 1.)[valid]
|
|
ce = F.cross_entropy(F.linear(h[:, :-1][valid], w), ids[:, 1:][valid], reduction='none')
|
|
dense = (ce * weights).sum() / weights.sum()
|
|
streamed = language_model_loss(h, ids, lengths, lambda: iter([(0, w)]), answer_weight=16.)
|
|
torch.testing.assert_close(streamed, dense)
|
|
torch.testing.assert_close(torch.autograd.grad(streamed, h)[0],
|
|
torch.autograd.grad(dense, h)[0])
|
|
|
|
def test_causality_and_gradients_for_both_adapter_components(self):
|
|
torch.manual_seed(9)
|
|
a = LearnableSharingAttention(8, 2, 1, 8, 10000, .25, width=10)
|
|
hidden = torch.randn(2, 4, 8)
|
|
donor, teacher = torch.randn(2, 2, 4, 4), torch.randn(2, 2, 4, 4)
|
|
lengths = torch.tensor([4, 3])
|
|
values, gate = torch.randn(2, 4, 1, 4), torch.randn(2, 4, 2, 4)
|
|
recipient = FrozenRecipient({
|
|
'o': torch.randn(8, 8), 'post': torch.zeros(8), 'gate': torch.randn(12, 8),
|
|
'up': torch.randn(12, 8), 'down': torch.randn(8, 12), 'final': torch.zeros(8),
|
|
}, 1e-6)
|
|
scores = a(hidden, donor, torch.arange(4)[None, :])
|
|
context = causal_attention(scores, values, lengths)
|
|
altered = values.clone()
|
|
altered[:, -1] += 10.
|
|
torch.testing.assert_close(context[:, :-1], causal_attention(scores, altered, lengths)[:, :-1])
|
|
out = recipient(context, gate, hidden)
|
|
head = torch.randn(12, 8)
|
|
ids = torch.randint(0, len(head), (2, 4))
|
|
|
|
def vocab():
|
|
yield 0, head[:6]
|
|
yield 6, head[6:]
|
|
|
|
total, kd = objective(scores, teacher, lengths,
|
|
language_model_loss(out, ids, lengths, vocab))
|
|
total.backward()
|
|
self.assertTrue(kd.isfinite())
|
|
for p in a.parameters():
|
|
self.assertGreater(p.grad.abs().sum().item(), 0)
|
|
self.assertFalse(list(recipient.parameters()))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|