mcy98's picture
Upload folder using huggingface_hub
2d13eb2 verified
Raw History Blame Contribute Delete
13.6 kB
import unittest
import torch
import numpy as np
import math
from typing import Tuple, Optional
# Import functions from both implementations
# Assuming canonical implementation is in 'canonical.py'
# and generated implementation is in 'generation.py'
from canonical import repeat_kv as canonical_repeat_kv
from canonical import lambda_init_fn as canonical_lambda_init_fn
from canonical import MultiheadDiffAttn as CanonicalMultiheadDiffAttn
from multihead_diffattn import repeat_kv as generated_repeat_kv
from multihead_diffattn import lambda_init_fn as generated_lambda_init_fn
from multihead_diffattn import MultiheadDiffAttn as GeneratedMultiheadDiffAttn
class TestDifferentialAttentionFunctions(unittest.TestCase):
"""Test suite for Multi-head Differential Attention implementation"""
def setUp(self):
"""Set up test fixtures and sample data"""
# Set random seed for reproducibility
torch.manual_seed(42)
np.random.seed(42)
# Small representative test data
self.batch_size = 2
self.seq_len = 8
self.embed_dim = 64
self.num_heads = 4
self.num_kv_heads = 2
self.head_dim = self.embed_dim // self.num_heads // 2 # 8
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Sample input tensor for attention
self.input_tensor = torch.randn(self.batch_size, self.seq_len, self.embed_dim).to(self.device)
# Sample rel_pos for rotary embeddings (cos, sin tensors)
self.rel_pos = (
torch.randn(self.seq_len, self.head_dim // 2).to(self.device),
torch.randn(self.seq_len, self.head_dim // 2).to(self.device)
)
# Sample attention mask
self.attn_mask = torch.triu(
torch.zeros(self.seq_len, self.seq_len).fill_(float('-inf')),
diagonal=1
).to(self.device)
# Test data for repeat_kv function
self.kv_tensor = torch.randn(self.batch_size, self.num_kv_heads, self.seq_len, self.head_dim).to(self.device)
self.n_rep = self.num_heads // self.num_kv_heads
# Test depths for lambda_init_fn
self.test_depths = [0, 1, 2, 5, 10, 20]
def test_repeat_kv_functional_equivalence(self):
"""Test that repeat_kv functions produce identical outputs"""
if canonical_repeat_kv is None or generated_repeat_kv is None:
self.skipTest("Cannot import both implementations")
# Test with different repetition factors
for n_rep in [1, 2, 4]:
with self.subTest(n_rep=n_rep):
# Execute both functions with identical inputs
canonical_output = canonical_repeat_kv(self.kv_tensor, n_rep)
generated_output = generated_repeat_kv(self.kv_tensor, n_rep)
# Compare outputs
self.assertEqual(canonical_output.shape, generated_output.shape,
f"Shape mismatch for n_rep={n_rep}")
torch.testing.assert_close(canonical_output, generated_output,
rtol=1e-5, atol=1e-8,
msg=f"Value mismatch for n_rep={n_rep}")
# Verify expected output shape
expected_shape = (self.batch_size, self.kv_tensor.size(1) * n_rep,
self.seq_len, self.head_dim)
self.assertEqual(canonical_output.shape, expected_shape)
def test_lambda_init_fn_functional_equivalence(self):
"""Test that lambda_init_fn functions produce identical outputs"""
if canonical_lambda_init_fn is None or generated_lambda_init_fn is None:
self.skipTest("Cannot import both implementations")
for depth in self.test_depths:
with self.subTest(depth=depth):
# Execute both functions with identical inputs
canonical_output = canonical_lambda_init_fn(depth)
generated_output = generated_lambda_init_fn(depth)
# Compare outputs
self.assertIsInstance(canonical_output, float)
self.assertIsInstance(generated_output, float)
self.assertAlmostEqual(canonical_output, generated_output, places=10,
msg=f"Value mismatch for depth={depth}")
# Verify the mathematical formula: 0.8 - 0.6 * exp(-0.3 * depth)
expected_value = 0.8 - 0.6 * math.exp(-0.3 * depth)
self.assertAlmostEqual(canonical_output, expected_value, places=10)
def test_multihead_diff_attn_initialization(self):
"""Test MultiheadDiffAttn initialization equivalence"""
if CanonicalMultiheadDiffAttn is None or GeneratedMultiheadDiffAttn is None:
self.skipTest("Cannot import both implementations")
depth = 2
# Test with num_kv_heads specified (GQA)
canonical_module = CanonicalMultiheadDiffAttn(
embed_dim=self.embed_dim,
depth=depth,
num_heads=self.num_heads,
num_kv_heads=self.num_kv_heads
)
generated_module = GeneratedMultiheadDiffAttn(
embed_dim=self.embed_dim,
depth=depth,
num_heads=self.num_heads,
num_kv_heads=self.num_kv_heads
)
# Compare basic attributes
self.assertEqual(canonical_module.embed_dim, generated_module.embed_dim)
self.assertEqual(canonical_module.num_heads, generated_module.num_heads)
self.assertEqual(canonical_module.num_kv_heads, generated_module.num_kv_heads)
self.assertEqual(canonical_module.n_rep, generated_module.n_rep)
self.assertEqual(canonical_module.head_dim, generated_module.head_dim)
self.assertAlmostEqual(canonical_module.scaling, generated_module.scaling, places=10)
self.assertAlmostEqual(canonical_module.lambda_init, generated_module.lambda_init, places=10)
# Compare projection layer shapes
self.assertEqual(canonical_module.q_proj.weight.shape, generated_module.q_proj.weight.shape)
self.assertEqual(canonical_module.k_proj.weight.shape, generated_module.k_proj.weight.shape)
self.assertEqual(canonical_module.v_proj.weight.shape, generated_module.v_proj.weight.shape)
self.assertEqual(canonical_module.out_proj.weight.shape, generated_module.out_proj.weight.shape)
# Compare lambda parameter shapes
self.assertEqual(canonical_module.lambda_q1.shape, generated_module.lambda_q1.shape)
self.assertEqual(canonical_module.lambda_k1.shape, generated_module.lambda_k1.shape)
self.assertEqual(canonical_module.lambda_q2.shape, generated_module.lambda_q2.shape)
self.assertEqual(canonical_module.lambda_k2.shape, generated_module.lambda_k2.shape)
# Test with num_kv_heads=None (default MHA)
canonical_module_mha = CanonicalMultiheadDiffAttn(
embed_dim=self.embed_dim,
depth=depth,
num_heads=self.num_heads
)
generated_module_mha = GeneratedMultiheadDiffAttn(
embed_dim=self.embed_dim,
depth=depth,
num_heads=self.num_heads
)
self.assertEqual(canonical_module_mha.num_kv_heads, self.num_heads)
self.assertEqual(generated_module_mha.num_kv_heads, self.num_heads)
self.assertEqual(canonical_module_mha.n_rep, 1)
self.assertEqual(generated_module_mha.n_rep, 1)
def test_multihead_diff_attn_forward_functional_equivalence(self):
"""Test MultiheadDiffAttn forward pass functional equivalence"""
if CanonicalMultiheadDiffAttn is None or GeneratedMultiheadDiffAttn is None:
self.skipTest("Cannot import both implementations")
depth = 1
# Initialize both modules with identical parameters
torch.manual_seed(123)
canonical_module = CanonicalMultiheadDiffAttn(
embed_dim=self.embed_dim,
depth=depth,
num_heads=self.num_heads,
num_kv_heads=self.num_kv_heads
).to(self.device)
torch.manual_seed(123) # Same seed for identical initialization
generated_module = GeneratedMultiheadDiffAttn(
embed_dim=self.embed_dim,
depth=depth,
num_heads=self.num_heads,
num_kv_heads=self.num_kv_heads
).to(self.device)
# Ensure both modules have identical parameters
with torch.no_grad():
for (name1, param1), (name2, param2) in zip(
canonical_module.named_parameters(),
generated_module.named_parameters()
):
self.assertEqual(name1, name2)
param2.copy_(param1)
# Set both modules to evaluation mode
canonical_module.eval()
generated_module.eval()
# Test forward pass without attention mask
with torch.no_grad():
canonical_output = canonical_module.forward(
x=self.input_tensor,
rel_pos=self.rel_pos,
attn_mask=None
)
generated_output = generated_module.forward(
x=self.input_tensor,
rel_pos=self.rel_pos,
attn_mask=None
)
# Compare outputs
self.assertEqual(canonical_output.shape, generated_output.shape,
"Output shape mismatch")
expected_shape = (self.batch_size, self.seq_len, self.embed_dim)
self.assertEqual(canonical_output.shape, expected_shape)
torch.testing.assert_close(canonical_output, generated_output,
rtol=1e-4, atol=1e-6,
msg="Forward pass output mismatch without mask")
# Test forward pass with attention mask
with torch.no_grad():
canonical_output_masked = canonical_module.forward(
x=self.input_tensor,
rel_pos=self.rel_pos,
attn_mask=self.attn_mask
)
generated_output_masked = generated_module.forward(
x=self.input_tensor,
rel_pos=self.rel_pos,
attn_mask=self.attn_mask
)
torch.testing.assert_close(canonical_output_masked, generated_output_masked,
rtol=1e-4, atol=1e-6,
msg="Forward pass output mismatch with mask")
def test_edge_cases(self):
"""Test edge cases and boundary conditions"""
if any(x is None for x in [canonical_repeat_kv, generated_repeat_kv]):
self.skipTest("Cannot import repeat_kv implementations")
# Test repeat_kv with n_rep=1 (no repetition)
canonical_output_no_rep = canonical_repeat_kv(self.kv_tensor, 1)
generated_output_no_rep = generated_repeat_kv(self.kv_tensor, 1)
torch.testing.assert_close(canonical_output_no_rep, generated_output_no_rep,
msg="repeat_kv mismatch with n_rep=1")
# Verify no-repetition case returns identical tensor
torch.testing.assert_close(canonical_output_no_rep, self.kv_tensor,
msg="repeat_kv should return identical tensor when n_rep=1")
# Test lambda_init_fn with depth=0
if canonical_lambda_init_fn and generated_lambda_init_fn:
canonical_lambda_0 = canonical_lambda_init_fn(0)
generated_lambda_0 = generated_lambda_init_fn(0)
expected_lambda_0 = 0.8 - 0.6 * math.exp(0) # = 0.8 - 0.6 = 0.2
self.assertAlmostEqual(canonical_lambda_0, expected_lambda_0, places=10)
self.assertAlmostEqual(generated_lambda_0, expected_lambda_0, places=10)
self.assertAlmostEqual(canonical_lambda_0, generated_lambda_0, places=10)
def test_parameter_count_consistency(self):
"""Test that both implementations have consistent parameter counts"""
if CanonicalMultiheadDiffAttn is None or GeneratedMultiheadDiffAttn is None:
self.skipTest("Cannot import both implementations")
depth = 0
canonical_module = CanonicalMultiheadDiffAttn(
embed_dim=self.embed_dim,
depth=depth,
num_heads=self.num_heads,
num_kv_heads=self.num_kv_heads
).to(self.device)
generated_module = GeneratedMultiheadDiffAttn(
embed_dim=self.embed_dim,
depth=depth,
num_heads=self.num_heads,
num_kv_heads=self.num_kv_heads
).to(self.device)
canonical_params = sum(p.numel() for p in canonical_module.parameters())
generated_params = sum(p.numel() for p in generated_module.parameters())
self.assertEqual(canonical_params, generated_params,
"Parameter count mismatch between implementations")
def run_tests():
"""Run the test suite"""
unittest.main(verbosity=2)
if __name__ == '__main__':
run_tests()