139 lines
7.4 KiB
Python
139 lines
7.4 KiB
Python
"""Check streamed frozen gradients and the Torch tail against the CPU reference."""
|
|
import unittest
|
|
|
|
import numpy as np
|
|
import torch
|
|
from torch.nn import functional as F
|
|
|
|
from crossqkv.lisa_decode import AttentionSiteCache
|
|
from crossqkv.lisa_decode_bench import ResidentSite, timed_site
|
|
from crossqkv.lisa_tail import FrozenLinear, TorchTail, gated_delta, rotate
|
|
from crossqkv.lisa_train import LearnableSharingAttention
|
|
from functional.model import PREFIX, delta_rule, rope
|
|
from functional.reference_check import ArrayLM
|
|
|
|
|
|
class Tensor:
|
|
def __init__(self, value):
|
|
self.value = value
|
|
self.shape = value.shape
|
|
|
|
def read(self, selection):
|
|
return self.value.ravel()[selection]
|
|
|
|
def evict(self):
|
|
pass
|
|
|
|
|
|
class TailTests(unittest.TestCase):
|
|
def test_frozen_rows_and_input_gradient(self):
|
|
torch.manual_seed(4)
|
|
x = torch.randn(2, 3, 5, requires_grad=True)
|
|
w = torch.randn(14, 5)
|
|
actual = FrozenLinear.apply(x, Tensor(w.numpy()), 2, 11)
|
|
dense = F.linear(x, w[2:11])
|
|
torch.testing.assert_close(actual, dense)
|
|
torch.testing.assert_close(torch.autograd.grad(actual.square().sum(), x)[0],
|
|
torch.autograd.grad(dense.square().sum(), x)[0])
|
|
|
|
def test_rotary_and_gated_delta(self):
|
|
rng = np.random.default_rng(8)
|
|
q, k, v = [rng.normal(size=(2, 5, 2, 8)).astype('f4') for _ in range(3)]
|
|
g = -np.abs(rng.normal(size=(2, 5, 2)).astype('f4'))
|
|
b = rng.uniform(size=(2, 5, 2)).astype('f4')
|
|
tx = torch.tensor(q)
|
|
torch.testing.assert_close(rotate(tx, 10000000., .5),
|
|
torch.tensor(rope(q, 10000000., .5)))
|
|
actual = gated_delta(*map(torch.tensor, (q, k, v, g, b)))
|
|
torch.testing.assert_close(actual, torch.tensor(delta_rule(q, k, v, g, b)[0]))
|
|
|
|
def test_two_recipient_forward_parity_and_both_get_gradients(self):
|
|
rng = np.random.default_rng(5)
|
|
cfg = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention', 'linear_attention',
|
|
'full_attention'], 'num_attention_heads': 2, 'num_key_value_heads': 1,
|
|
'head_dim': 8, 'linear_num_key_heads': 1, 'linear_num_value_heads': 2,
|
|
'linear_key_head_dim': 4, 'linear_value_head_dim': 4,
|
|
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
|
|
|
|
def rand(*shape):
|
|
return (rng.normal(size=shape) * .2).astype('f4')
|
|
|
|
a = {'norm.weight': rand(8), 'embed_tokens.weight': rand(10, 8)}
|
|
for i, kind in enumerate(cfg['layer_types']):
|
|
names = {'input_layernorm': (8,), 'post_attention_layernorm': (8,),
|
|
'mlp.gate_proj': (12, 8), 'mlp.up_proj': (12, 8), 'mlp.down_proj': (8, 12)}
|
|
if kind == 'full_attention':
|
|
names.update({'self_attn.q_proj': (32, 8), 'self_attn.k_proj': (8, 8),
|
|
'self_attn.v_proj': (8, 8), 'self_attn.o_proj': (8, 16),
|
|
'self_attn.q_norm': (8,), 'self_attn.k_norm': (8,)})
|
|
else:
|
|
names.update({'linear_attn.in_proj_qkv': (16, 8), 'linear_attn.in_proj_z': (8, 8),
|
|
'linear_attn.in_proj_b': (2, 8), 'linear_attn.in_proj_a': (2, 8),
|
|
'linear_attn.out_proj': (8, 8), 'linear_attn.norm': (4,),
|
|
'linear_attn.conv1d': (16, 1, 3)})
|
|
a[f'layers.{i}.linear_attn.A_log'] = rand(2)
|
|
a[f'layers.{i}.linear_attn.dt_bias'] = rand(2)
|
|
a.update({f'layers.{i}.{name}.weight': rand(*shape) for name, shape in names.items()})
|
|
original = ArrayLM(a, cfg)
|
|
original.tensors = {PREFIX+k: Tensor(v) for k,v in a.items()}
|
|
ids = rng.integers(0, 10, (2, 5))
|
|
h = torch.tensor(original.embedding(ids))
|
|
expected, _ = original.forward(ids)
|
|
adapters = {i: LearnableSharingAttention(8, 2, 1, 4, 10000., .5, 16)
|
|
for i in (0, 2)}
|
|
tail = TorchTail(original, 0, adapters)
|
|
lengths = torch.tensor([5, 5])
|
|
native, _ = tail(h, None, lengths, 'native', ())
|
|
torch.testing.assert_close(native, torch.tensor(expected), atol=2e-5, rtol=2e-5)
|
|
donor = torch.tensor(rand(2, 2, 5, 5))
|
|
run, _ = tail(h, donor, lengths, 'lisa', (0,2), keep_teacher=False)
|
|
ref, _ = tail(h, donor, lengths, 'lisa', (0,2), keep_teacher=True)
|
|
torch.testing.assert_close(run, ref)
|
|
run.square().sum().backward()
|
|
self.assertTrue(all(p.grad is not None and p.grad.abs().sum() > 0 for p in tail.parameters()))
|
|
|
|
|
|
def test_decode_uses_rotary_offsets_and_compact_key_cache(self):
|
|
rng = np.random.default_rng(252)
|
|
cfg = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention'],
|
|
'num_attention_heads': 2, 'num_key_value_heads': 1, 'head_dim': 16,
|
|
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
|
|
names = {'q_proj': (64, 8), 'k_proj': (16, 8), 'v_proj': (16, 8),
|
|
'o_proj': (8, 32), 'q_norm': (16,), 'k_norm': (16,)}
|
|
weights = {'layers.0.self_attn.' + k + '.weight':
|
|
rng.normal(0, .2, shape).astype('f4') for k, shape in names.items()}
|
|
source = ArrayLM(weights, cfg)
|
|
source.tensors = {PREFIX+k: Tensor(v) for k,v in weights.items()}
|
|
adapter = LearnableSharingAttention(8, 2, 1, 4, 10000., .5, width=12)
|
|
tail = TorchTail(source, 0, {0: adapter})
|
|
hidden = torch.tensor(rng.normal(0, .8, (2, 5, 8)).astype('f4'))
|
|
donor = torch.tensor(rng.normal(0, 1, (2, 2, 5, 5)).astype('f4'))
|
|
lengths = torch.tensor([5, 5])
|
|
native = AttentionSiteCache(tail, 0, 2, 5)
|
|
shared = AttentionSiteCache(tail, 0, 2, 5, adapter)
|
|
for mode, cache in [('native', native), ('lisa', shared)]:
|
|
out, raw, _ = tail.full(hidden, 0, donor, lengths, mode, (0,), False)
|
|
for pos in range(hidden.shape[1]):
|
|
row = donor[:, :, pos:pos+1, :pos+1] if mode == 'lisa' else None
|
|
actual, scores = cache.step(hidden[:, pos:pos+1], row)
|
|
torch.testing.assert_close(actual, out[:, pos:pos+1], atol=2e-6, rtol=2e-5)
|
|
torch.testing.assert_close(scores, raw[:, :, pos:pos+1, :pos+1],
|
|
atol=2e-6, rtol=2e-5)
|
|
cache.reset()
|
|
cache.prefill(hidden[:, :4])
|
|
row = donor[:, :, 4:5, :] if mode == 'lisa' else None
|
|
actual, scores = cache.step(hidden[:, 4:5], row)
|
|
torch.testing.assert_close(actual, out[:, 4:5], atol=2e-6, rtol=2e-5)
|
|
torch.testing.assert_close(scores, raw[:, :, 4:5, :], atol=2e-6, rtol=2e-5)
|
|
self.assertEqual(shared.allocated_bytes['v'], native.allocated_bytes['v'])
|
|
self.assertEqual(shared.allocated_bytes['k']*4, native.allocated_bytes['k'])
|
|
resident = ResidentSite(tail, 0)
|
|
_, original_states = timed_site({'native': native, 'lisa': shared}, hidden, donor, 5,
|
|
samples=2, rounds=2)
|
|
_, warm_states = timed_site({'native': AttentionSiteCache(resident, 0, 2, 5),
|
|
'lisa': AttentionSiteCache(resident, 0, 2, 5, adapter)},
|
|
hidden, donor, 5, samples=2, rounds=2)
|
|
for mode in ('native', 'lisa'):
|
|
for old, new in zip(original_states[mode], warm_states[mode]):
|
|
torch.testing.assert_close(old, new, atol=2e-6, rtol=2e-5)
|