File size: 13,564 Bytes
2d13eb2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | 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()
|