File size: 7,077 Bytes
22e9602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import unittest
import torch
import numpy as np
import os
import random

# Assume the canonical implementation is in 'canonical.py'
# and the generated implementation is in 'loss.py'
from canonical import SILoss as CanonicalSILoss
from loss import SILoss as GeneratedSILoss

def set_seed(seed=2025):
    """Sets random seeds for reproducibility across libraries."""
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

class MockDiffusionModel(torch.nn.Module):
    """
    A mock model that simulates the behavior of a diffusion model for testing purposes.
    """
    def __init__(self, feature_dim=16, num_encoders=2, num_patches=4, image_channels=3, image_size=8):
        super().__init__()
        self.feature_dim = feature_dim
        self.num_encoders = num_encoders
        self.num_patches = num_patches
        flat_image_size = image_channels * image_size * image_size
        
        self.denoising_layer = torch.nn.Linear(flat_image_size, flat_image_size)
        self.projection_layers = torch.nn.ModuleList([
            torch.nn.Linear(flat_image_size, num_patches * feature_dim) for _ in range(num_encoders)
        ])

    def forward(self, x, t, **kwargs):
        """
        Simulates a forward pass. zs_tilde is a list of tensors of shape (B, N_patches, F_dim).
        """
        batch_size = x.shape[0]
        x_flat = x.view(batch_size, -1)
        model_output = self.denoising_layer(x_flat).view(x.shape)
        
        zs_tilde = []
        for proj_layer in self.projection_layers:
            proj_output_reshaped = proj_layer(x_flat).view(
                batch_size, self.num_patches, self.feature_dim
            )
            zs_tilde.append(proj_output_reshaped)
            
        return model_output, zs_tilde


class TestSILossEquivalence(unittest.TestCase):
    """
    Test suite to verify the functional equivalence of a generated SILoss
    implementation against a canonical one.
    """

    def setUp(self):
        """Set up common test data."""
        self.batch_size = 2
        self.image_channels = 3
        self.image_size = 8
        self.feature_dim = 16
        self.num_encoders = 2
        self.num_patches = 4

        self.images = torch.randn(self.batch_size, self.image_channels, self.image_size, self.image_size)
        
        self.zs = [
            torch.randn(self.batch_size, self.num_patches, self.feature_dim) 
            for _ in range(self.num_encoders)
        ]

        self.mock_model = MockDiffusionModel(
            feature_dim=self.feature_dim,
            num_encoders=self.num_encoders,
            num_patches=self.num_patches
        )

    def test_initialization(self):
        """Instruction 1: Test that the SILoss class is initialized correctly."""
        params = {'prediction': 'v', 'path_type': 'cosine', 'weighting': 'lognormal'}
        canonical_loss = CanonicalSILoss(**params)
        generated_loss = GeneratedSILoss(**params)
        for key, value in params.items():
            self.assertEqual(getattr(canonical_loss, key), value)
            self.assertEqual(getattr(generated_loss, key), getattr(canonical_loss, key))

    def test_interpolant_method(self):
        """Instruction 2: Test the 'interpolant' method."""
        t = torch.tensor([0.0, 0.25, 0.5, 0.75, 1.0])
        for path in ["linear", "cosine"]:
            with self.subTest(path=path):
                canonical_loss_fn = CanonicalSILoss(path_type=path)
                generated_loss_fn = GeneratedSILoss(path_type=path)
                c_outputs = canonical_loss_fn.interpolant(t)
                g_outputs = generated_loss_fn.interpolant(t)
                # Compare all four return values for equivalence
                for c_out, g_out in zip(c_outputs, g_outputs):
                    if isinstance(c_out, torch.Tensor):
                        torch.testing.assert_close(c_out, g_out)
                    else:
                        self.assertEqual(c_out, g_out)

    def _run_call_comparison(self, path_type, weighting):
        """
        Helper function to run a full comparison of the __call__ method.
        This version uses the canonical output's shape as the ground truth.
        """
        canonical_loss_fn = CanonicalSILoss(path_type=path_type, weighting=weighting)
        generated_loss_fn = GeneratedSILoss(path_type=path_type, weighting=weighting)
        
        set_seed()
        c_denoising_loss, c_proj_loss = canonical_loss_fn(self.mock_model, self.images, zs=self.zs)

        set_seed()
        g_denoising_loss, g_proj_loss = generated_loss_fn(self.mock_model, self.images, zs=self.zs)

        # 1. Compare denoising loss (shape should be stable)
        self.assertEqual(c_denoising_loss.shape, (self.batch_size,), "Canonical denoising loss has unexpected shape.")
        self.assertEqual(g_denoising_loss.shape, c_denoising_loss.shape, "Denoising loss shape mismatch.")
        torch.testing.assert_close(c_denoising_loss, g_denoising_loss, msg="Denoising loss value mismatch.")

        # 2. Compare projection loss (shape may be unstable in canonical code)
        self.assertEqual(g_proj_loss.shape, c_proj_loss.shape,
                         f"Projection loss shape mismatch. Canonical is {c_proj_loss.shape}, Generated is {g_proj_loss.shape}.")
        torch.testing.assert_close(c_proj_loss, g_proj_loss, msg="Projection loss value mismatch.")
    
    def test_call_method_all_configs(self):
        """
        Instruction 3: Test the '__call__' method across all configurations.
        """
        for path_type in ["linear", "cosine"]:
            for weighting in ["uniform", "lognormal"]:
                with self.subTest(path=path_type, weight=weighting):
                    self._run_call_comparison(path_type=path_type, weighting=weighting)
    
    def test_call_invalid_prediction_type(self):
        """Instruction 3 Edge Case: Test __call__ for unsupported prediction types."""
        with self.assertRaises(NotImplementedError):
            loss_fn = CanonicalSILoss(prediction="unsupported")
            loss_fn(self.mock_model, self.images, zs=self.zs)
        with self.assertRaises(NotImplementedError):
            loss_fn = GeneratedSILoss(prediction="unsupported")
            loss_fn(self.mock_model, self.images, zs=self.zs)

    def test_call_with_zs_as_none(self):
        """Instruction 3 Edge Case: Test __call__ when zs is None."""
        canonical_loss_fn = CanonicalSILoss()
        generated_loss_fn = GeneratedSILoss()
        with self.assertRaises(Exception):
             canonical_loss_fn(self.mock_model, self.images, zs=None)
        with self.assertRaises(Exception):
             generated_loss_fn(self.mock_model, self.images, zs=None)

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)