Compare isolated layer sharing against the native lookup model

This commit is contained in:
2026-12-02 15:56:05 +08:00
parent 41895ae357
commit 80f79f7d15
4 changed files with 108 additions and 4 deletions
+67
View File
@@ -0,0 +1,67 @@
"""Check score routing against separate native and shared attention computations."""
import unittest
import numpy as np
import torch
from crossqkv.lisa_generate import GenerationDecoder
from crossqkv.lisa_score_paths import PathDecoder
from crossqkv.lisa_train import LearnableSharingAttention
from functional.model import PREFIX
from functional.reference_check import ArrayLM
from tests.test_lisa_tail import Tensor
class ScorePathTests(unittest.TestCase):
def test_route_native_and_shared_scores_independently_across_decode_steps(self):
rng = np.random.default_rng(129)
torch.manual_seed(129)
heads, kv, dim, width = 4, 2, 8, 16
config = dict(rms_norm_eps=1e-6, layer_types=['full_attention'] * 2,
num_attention_heads=heads, num_key_value_heads=kv, head_dim=dim,
rope_parameters=dict(rope_theta=10000., partial_rotary_factor=.5))
shapes = dict(q_proj=(2*heads*dim, width), k_proj=(kv*dim, width),
v_proj=(kv*dim, width), o_proj=(width, heads*dim),
q_norm=(dim,), k_norm=(dim,))
weights = {'layers.1.self_attn.'+k+'.weight': rng.normal(0, .2, shape).astype('f4')
for k, shape in shapes.items()}
source = ArrayLM(weights, config)
source.tensors = {PREFIX+k: Tensor(v) for k, v in weights.items()}
adapter = {1: LearnableSharingAttention(width, heads, kv, 4, 10000., .5, 12)}
native = GenerationDecoder(source, [()], [0])
shared = GenerationDecoder(source, [(1,)], [0], adapter)
routed = {}
for mode in ('read', 'send', 'both', 'send-permuted', 'read-group-0', 'read-group-1'):
decoder = PathDecoder(source, [(1,)], [0], adapter)
decoder.site, decoder.mode = 1, mode
routed[mode] = decoder
for start, stop in ((0, 3), (3, 4)):
positions = torch.arange(start, stop)[None, :]
causal = (torch.arange(stop) <= positions.T)[None, None]
hidden = torch.randn(1, stop-start, width)
donor = torch.randn(1, heads, stop-start, stop)
args = (hidden, 1, positions, causal, donor)
native_out, native_scores = native.attention_chunk(*args)
shared_out, shared_scores = shared.attention_chunk(*args)
self.assertFalse(torch.allclose(native_scores, shared_scores))
self.assertFalse(torch.allclose(native_out, shared_out))
outputs = {}
for mode, decoder in routed.items():
decoder.position = start
outputs[mode], outgoing = decoder.attention_chunk(*args)
expected = native_scores if mode in ('both', 'send') else shared_scores
if mode == 'send-permuted':
expected = native_scores.roll(heads//kv, dims=1)
torch.testing.assert_close(outgoing, expected)
for mode in ('read', 'both'):
torch.testing.assert_close(outputs[mode], native_out)
for mode in ('send', 'send-permuted'):
torch.testing.assert_close(outputs[mode], shared_out)
# Head contexts are concatenated before the common linear output projection.
# Restoring complementary groups must reconstruct the full output difference.
torch.testing.assert_close(outputs['read-group-0'] + outputs['read-group-1'],
native_out + shared_out)
for group in ('read-group-0', 'read-group-1'):
self.assertFalse(torch.allclose(outputs[group], shared_out))
self.assertFalse(torch.allclose(outputs[group], native_out))