Add controlled two-layer LiSA reproduction on Qwen

This commit is contained in:
2026-11-24 00:00:42 +08:00
parent 115e440455
commit 1c8943a2e8
21 changed files with 4444 additions and 7 deletions
+30
View File
@@ -0,0 +1,30 @@
"""Check answer-only metrics and isolate recovery from newly lost items."""
import unittest
import numpy as np
import torch
from torch.nn import functional as F
from crossqkv.lisa_effect_answer_audit import vocabulary_scores
from crossqkv.lisa_effect_audit import paired
from tests.test_lisa_tail import Tensor
class EffectAuditTests(unittest.TestCase):
def test_paired_rescue_excludes_natively_wrong_items(self):
native, direct, candidate = (np.array(x, dtype=bool) for x in
[(1, 1, 1, 0), (0, 0, 1, 1), (1, 0, 0, 1)])
result = paired(native, direct, candidate)
self.assertEqual(result['native_correct_lost_by_direct'], 2)
self.assertEqual(result['rescued'], 1)
self.assertEqual(result['newly_lost_among_native_and_direct_correct'], 1)
self.assertEqual(result['accuracy_delta_vs_direct'], 0)
def test_streamed_answer_scores_match_full_reference(self):
g = torch.Generator().manual_seed(9)
h, w = torch.randn(4, 6, generator=g), torch.randn(1033, 6, generator=g)
target = torch.tensor([2, 1032, 22, 1024])
actual, loss = vocabulary_scores(h, target, Tensor(w.numpy()))
logits = F.linear(h, w)
torch.testing.assert_close(actual, logits.argmax(-1))
torch.testing.assert_close(loss, F.cross_entropy(logits, target, reduction='none'))
+62
View File
@@ -0,0 +1,62 @@
"""Check exact epoch resume through the actual LiSA training entry point."""
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
import numpy as np
import torch
from crossqkv.lisa_effect import train
from functional.model import PREFIX
from functional.reference_check import ArrayLM
from tests.test_lisa_tail import Tensor
class TrainingResumeTests(unittest.TestCase):
def test_checkpoint_resume_preserves_all_selected_outputs(self):
rng = np.random.default_rng(22)
def rand(shape):
return (.13*rng.standard_normal(shape)).astype('f4')
torch.set_num_threads(1)
c = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention'], 'hidden_size': 8,
'num_attention_heads': 2, 'num_key_value_heads': 1, 'head_dim': 8,
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
shapes = {'input_layernorm': (8,), 'post_attention_layernorm': (8,),
'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,),
'mlp.gate_proj': (13, 8), 'mlp.up_proj': (13, 8), 'mlp.down_proj': (8, 13)}
weights = {f'layers.0.{k}.weight': rand(v) for k, v in shapes.items()}
weights.update({'embed_tokens.weight': rand((12,8)), 'norm.weight': rand((8,))})
model = ArrayLM(weights, c)
model.tensors = {PREFIX+k: Tensor(v) for k,v in weights.items()}
with TemporaryDirectory() as directory:
p = Path(directory)
cache, out = p/'cache', p/'out'
cache.mkdir()
out.mkdir()
(p/'model_config.json').write_text(json.dumps(c))
(cache/'selection.json').write_text(json.dumps({'sites':[0], 'task':'fixture',
'source_sha256':{}}))
labels = np.arange(1, 5, dtype=np.int64)
for split, count in [('fit',12), ('validation',12), ('test',32)]:
for i in range(0, count, 4):
ids = rng.integers(1, 12, size=(4, 4))
gold = rng.integers(0, 4, size=4)
ids[:, -1] = labels[gold]
expected, _ = model.forward(ids)
np.savez(cache/f'{split}-{i:03}.npz', ids=ids, lengths=np.full(4,4),
labels=labels, gold=gold, residual=model.embedding(ids),
donor=rand((4,2,4,4)), expected=expected,
names=[f'{split}-{k}' for k in range(i,i+4)])
with patch('functional.model.StreamingLM', return_value=model), patch('builtins.print'):
train(p, cache, out, 1)
before = (out/'test-items.json').read_bytes()
lines = (out/'trace.json').read_bytes()
train(p, cache, out, 1, resume=True)
self.assertEqual(before, (out/'test-items.json').read_bytes())
self.assertEqual(lines, (out/'trace.json').read_bytes())
+53
View File
@@ -0,0 +1,53 @@
"""Prove shared-prefix replay matches the original replicated-batch screen."""
import unittest
import numpy as np
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from tokenizers.pre_tokenizers import Whitespace
from crossqkv.lisa_effect_screen import MODES, ScreeningModel, evaluate, problems
from functional.model import PREFIX
from functional.reference_check import ArrayLM
class ArrayTensor:
def __init__(self, values):
self.raw = values
self.shape = values.shape
self.dtype = 'F32'
def evict(self):
pass
class TinyScreen(ScreeningModel, ArrayLM):
pass
class ScreenTests(unittest.TestCase):
def test_replay_preserves_all_three_arms(self):
rng = np.random.default_rng(11)
cfg = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention']*24,
'num_attention_heads': 2, 'num_key_value_heads': 1, 'head_dim': 8,
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
rand = lambda shape: (.12*rng.standard_normal(shape)).astype('f4')
weights = {'norm.weight': rand((8,)), 'embed_tokens.weight': rand((15, 8))}
shapes = {'input_layernorm': (8,), 'post_attention_layernorm': (8,),
'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,),
'mlp.gate_proj': (13, 8), 'mlp.up_proj': (13, 8), 'mlp.down_proj': (8, 13)}
weights.update({f'layers.{i}.{k}.weight': rand(v) for i in range(24) for k,v in shapes.items()})
model = TinyScreen(weights, cfg)
model.tensors = {PREFIX+k: ArrayTensor(v) for k,v in weights.items()}
tok = Tokenizer(WordLevel({'[UNK]': 0, **{str(i): i for i in range(1, 10)}}, unk_token='[UNK]'))
tok.pre_tokenizer = Whitespace()
examples = problems('screen', 2)
originals = evaluate(model, tok, examples)
model.reuse_prefix = True
replay = evaluate(model, tok, examples)
for orig, new in zip(originals, replay):
for key in MODES:
np.testing.assert_allclose(orig['scores'][key]['logits'],
new['scores'][key]['logits'], atol=1e-6)
+138
View File
@@ -0,0 +1,138 @@
"""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)
+16
View File
@@ -27,6 +27,22 @@ class LiSATrainingTests(unittest.TestCase):
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)