File size: 12,837 Bytes
388fd6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
"""Tests for Gamma SSM Block."""

import torch
import pytest

from gamma_space_model import GammaSingleBlock


class TestGammaSingleBlockInitialization:
    """Test GammaSingleBlock initialization."""
    
    def test_direct_parameter_init(self):
        """Test GammaSingleBlock with direct parameters (no config)."""
        block = GammaSingleBlock(
            d_model=16,
            hidden_dim=32,
            delta_t=0.1,
            kernel_length=4,
            A_type="tridiagonal",
            prenorm=True,
            residual_scale=1.0,
            dropout=0.0,
        )
        
        assert block.d_model == 16
        assert block.prenorm is True
        assert block.residual_scale == 1.0
        assert block.dropout_p == 0.0
    
    def test_default_parameters(self):
        """Test that default parameters are set correctly."""
        block = GammaSingleBlock(d_model=16, hidden_dim=32)
        
        assert block.d_model == 16
        assert block.prenorm is True
        assert block.residual_scale == 1.0
        assert block.dropout_p == 0.0
        assert block.ssm.delta_t == 0.1
    
    def test_ssm_instantiation(self):
        """Test that SSM block is correctly instantiated."""
        block = GammaSingleBlock(
            d_model=16,
            hidden_dim=32,
            delta_t=0.2,
            A_type="tridiagonal",
        )
        
        assert block.ssm.state_dim == 16
        assert block.ssm.hidden_dim == 32
        assert block.ssm.delta_t == 0.2
        assert block.ssm.A_type == "tridiagonal"


class TestGammaSingleBlockForwardPass:
    """Test GammaSingleBlock forward pass."""
    
    def test_forward_output_shape(self):
        """Test that forward pass produces correct output shape."""
        batch_size, seq_len, d_model = 4, 32, 16
        hidden_dim = 32
        
        block = GammaSingleBlock(d_model=d_model, hidden_dim=hidden_dim)
        x = torch.randn(batch_size, seq_len, d_model)
        
        output, final_state = block(x)
        
        assert output.shape == (batch_size, seq_len, d_model)
        assert final_state.shape == (batch_size, hidden_dim)
    
    def test_forward_with_initial_state(self):
        """Test forward pass with provided initial state."""
        batch_size, seq_len, d_model, hidden_dim = 2, 16, 8, 16
        
        block = GammaSingleBlock(d_model=d_model, hidden_dim=hidden_dim)
        x = torch.randn(batch_size, seq_len, d_model)
        initial_state = torch.zeros(batch_size, hidden_dim)
        
        output1, final_state1 = block(x, state=initial_state)
        output2, final_state2 = block(x, state=None)
        
        # Should produce the same results since initial_state defaults to zeros
        assert torch.allclose(output1, output2, atol=1e-5)


class TestGammaSingleBlockNormalization:
    """Test GammaSingleBlock normalization (prenorm vs postnorm)."""
    
    def test_prenorm_configuration(self):
        """Test prenorm configuration."""
        block = GammaSingleBlock(d_model=16, hidden_dim=32, prenorm=True)
        
        x = torch.randn(2, 10, 16)
        output, _ = block(x)
        
        assert output.shape == (2, 10, 16)
    
    def test_postnorm_configuration(self):
        """Test postnorm configuration."""
        block = GammaSingleBlock(d_model=16, hidden_dim=32, prenorm=False)
        
        x = torch.randn(2, 10, 16)
        output, _ = block(x)
        
        assert output.shape == (2, 10, 16)
    
    def test_prenorm_vs_postnorm_outputs_differ(self):
        """Test that prenorm and postnorm produce different outputs."""
        x = torch.randn(2, 10, 16)
        
        prenorm_block = GammaSingleBlock(d_model=16, hidden_dim=32, prenorm=True)
        postnorm_block = GammaSingleBlock(d_model=16, hidden_dim=32, prenorm=False)
        
        output_pre, _ = prenorm_block(x)
        output_post, _ = postnorm_block(x)
        
        # Outputs should differ but have same shape
        assert output_pre.shape == output_post.shape
        assert not torch.allclose(output_pre, output_post)


class TestGammaSingleBlockResidualConnection:
    """Test GammaSingleBlock residual connection."""
    
    def test_residual_with_scale_1(self):
        """Test residual connection with scale=1.0."""
        block = GammaSingleBlock(
            d_model=16,
            hidden_dim=32,
            residual_scale=1.0,
            prenorm=True,
        )
        
        x = torch.randn(2, 10, 16)
        output, _ = block(x)
        
        # Output should be x + SSM_output (approximately close to x)
        assert torch.allclose(output, x, atol=2.0)
    
    def test_residual_with_scale_0(self):
        """Test residual connection with scale=0.0 (no residual)."""
        block = GammaSingleBlock(
            d_model=16,
            hidden_dim=32,
            residual_scale=0.0,
            prenorm=True,
        )
        
        x = torch.randn(2, 10, 16)
        output, _ = block(x)
        
        # Output should be purely from norm + SSM (not affected by input)
        # It will still be different from x
        assert not torch.allclose(output, x)
    
    def test_residual_scale_effect(self):
        """Test that residual_scale parameter affects output."""
        x = torch.randn(2, 10, 16)
        
        block1 = GammaSingleBlock(
            d_model=16,
            hidden_dim=32,
            residual_scale=0.5,
            prenorm=True,
        )
        block2 = GammaSingleBlock(
            d_model=16,
            hidden_dim=32,
            residual_scale=2.0,
            prenorm=True,
        )
        
        output1, _ = block1(x)
        output2, _ = block2(x)
        
        # Different scales should produce different outputs
        assert not torch.allclose(output1, output2)


class TestGammaSingleBlockDropout:
    """Test GammaSingleBlock dropout."""
    
    def test_dropout_train_mode(self):
        """Test that dropout is applied during training."""
        block = GammaSingleBlock(
            d_model=16,
            hidden_dim=32,
            dropout=0.5,
        )
        block.train()
        
        x = torch.randn(2, 10, 16)
        
        # Multiple forward passes should give different results due to dropout
        output1, _ = block(x)
        output2, _ = block(x)
        
        assert not torch.allclose(output1, output2)
    
    def test_dropout_eval_mode(self):
        """Test that dropout is not applied during evaluation."""
        block = GammaSingleBlock(
            d_model=16,
            hidden_dim=32,
            dropout=0.5,
        )
        block.eval()
        
        x = torch.randn(2, 10, 16)
        
        # Multiple forward passes should give same results in eval mode
        output1, _ = block(x)
        output2, _ = block(x)
        
        assert torch.allclose(output1, output2)
    
    def test_no_dropout_with_zero_dropout_rate(self):
        """Test that no dropout is applied when dropout=0."""
        block = GammaSingleBlock(
            d_model=16,
            hidden_dim=32,
            dropout=0.0,
        )
        
        # Should not have dropout layer
        assert block.dropout is None


class TestGammaSingleBlockMasking:
    """Test GammaSingleBlock masking functionality."""
    
    def test_forward_with_mask(self):
        """Test forward pass with masking."""
        batch_size, seq_len, d_model = 2, 10, 16
        hidden_dim = 32
        
        block = GammaSingleBlock(d_model=d_model, hidden_dim=hidden_dim)
        x = torch.randn(batch_size, seq_len, d_model)
        mask = torch.ones(batch_size, seq_len, dtype=torch.bool)
        mask[1, 5:] = False
        
        output, _ = block(x, mask=mask)
        
        assert output.shape == (batch_size, seq_len, d_model)


class TestGammaSingleBlockGradients:
    """Test gradient flow through GammaSingleBlock."""
    
    def test_backward_pass(self):
        """Test that gradients flow correctly."""
        batch_size, seq_len, d_model = 2, 10, 16
        hidden_dim = 32
        
        block = GammaSingleBlock(d_model=d_model, hidden_dim=hidden_dim)
        x = torch.randn(batch_size, seq_len, d_model, requires_grad=True)
        
        output, _ = block(x)
        loss = output.sum()
        loss.backward()
        
        assert x.grad is not None
        assert x.grad.shape == x.shape
        
        # Check that block parameters have gradients
        for param in block.parameters():
            if param.requires_grad:
                assert param.grad is not None
    
    def test_gradient_flow_prenorm(self):
        """Test gradient flow with prenorm."""
        block = GammaSingleBlock(d_model=16, hidden_dim=32, prenorm=True)
        x = torch.randn(2, 10, 16, requires_grad=True)
        
        output, _ = block(x)
        loss = output.sum()
        loss.backward()
        
        assert x.grad is not None
    
    def test_gradient_flow_postnorm(self):
        """Test gradient flow with postnorm."""
        block = GammaSingleBlock(d_model=16, hidden_dim=32, prenorm=False)
        x = torch.randn(2, 10, 16, requires_grad=True)
        
        output, _ = block(x)
        loss = output.sum()
        loss.backward()
        
        assert x.grad is not None


class TestGammaSingleBlockIntegration:
    """Integration tests for GammaSingleBlock."""
    
    def test_stacked_blocks(self):
        """Test stacking multiple blocks together."""
        d_model, hidden_dim = 16, 32
        num_blocks = 3
        
        blocks = [
            GammaSingleBlock(d_model=d_model, hidden_dim=hidden_dim)
            for _ in range(num_blocks)
        ]
        
        x = torch.randn(2, 10, d_model)
        states = []
        
        # Forward through blocks
        for block in blocks:
            x, state = block(x)
            states.append(state)
        
        assert x.shape == (2, 10, d_model)
        assert len(states) == num_blocks
    
    def test_device_transfer(self):
        """Test that block can be transferred between devices."""
        block = GammaSingleBlock(d_model=16, hidden_dim=32)
        
        # Test on CPU
        x_cpu = torch.randn(2, 10, 16)
        output_cpu, _ = block(x_cpu)
        assert output_cpu.device.type == "cpu"
        
        if torch.cuda.is_available():
            # Transfer to GPU
            block = block.cuda()
            x_gpu = torch.randn(2, 10, 16).cuda()
            output_gpu, _ = block(x_gpu)
            assert output_gpu.device.type == "cuda"
            
            # Transfer back to CPU
            block = block.cpu()
            output_cpu2, _ = block(x_cpu)
            assert output_cpu2.device.type == "cpu"
    
    def test_state_dict_save_load(self):
        """Test saving and loading state dict."""
        block1 = GammaSingleBlock(d_model=16, hidden_dim=32)
        block2 = GammaSingleBlock(d_model=16, hidden_dim=32)
        
        # Save state dict from block1
        state_dict = block1.state_dict()
        
        # Load into block2
        block2.load_state_dict(state_dict)
        
        # They should produce same output
        x = torch.randn(2, 10, 16)
        
        with torch.no_grad():
            out1, _ = block1(x)
            out2, _ = block2(x)
        
        assert torch.allclose(out1, out2, atol=1e-6)
    
    def test_train_eval_mode_switching(self):
        """Test switching between train and eval modes."""
        block = GammaSingleBlock(d_model=16, hidden_dim=32, dropout=0.5)
        
        # Train mode
        block.train()
        assert block.training
        
        # Eval mode
        block.eval()
        assert not block.training
        
        # Train mode again
        block.train()
        assert block.training
    
    def test_different_d_models_and_hidden_dims(self):
        """Test blocks with various dimensions."""
        configs = [
            (8, 16),
            (16, 32),
            (64, 128),
            (256, 512),
        ]
        
        for d_model, hidden_dim in configs:
            block = GammaSingleBlock(d_model=d_model, hidden_dim=hidden_dim)
            x = torch.randn(2, 10, d_model)
            
            output, state = block(x)
            
            assert output.shape == (2, 10, d_model)
            assert state.shape == (2, hidden_dim)


if __name__ == "__main__":
    pytest.main([__file__, "-v"])