File size: 10,427 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
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
import unittest
import torch
import torch.nn as nn
import random
import os
import numpy as np
from types import SimpleNamespace
from unittest.mock import MagicMock, call

# --- Mocking Dependencies ---
class MockModelType:
    VELOCITY = "velocity"
    NOISE = "noise"
    SCORE = "score"

class MockWeightType:
    VELOCITY = "velocity_weight"
    LIKELIHOOD = "likelihood_weight"
    NONE = "no_weight"
    UNKNOWN = "unknown_weight"  # to trigger NotImplementedError

def mock_mean_flat(tensor):
    """Averages a tensor across all dimensions except the first (batch)."""
    return tensor.mean(dim=list(range(1, len(tensor.shape))))

class MockPathModule:
    def __init__(self):
        self.expand_t_like_x = MagicMock(side_effect=lambda t, x: t)

# --- Importing Implementations ---
from canonical import training_losses as canonical_training_losses
from target_code import training_losses as generated_training_losses

def set_seed(seed=2025):
    """Sets the seed for reproducibility across all relevant 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.benchmark = False
    torch.backends.cudnn.deterministic = True


class TestTrainingLossesEquivalence(unittest.TestCase):
    """
    Expanded test suite to evaluate functional equivalence of the training_losses function
    across parameterizations, weights, and edge cases.
    """

    def setUp(self):
        set_seed()
        self.shape = (4, 3, 8, 8)  # (B, C, H, W)

        # Fixed tensors for deterministic behavior
        self.t_val = torch.rand(self.shape[0])
        self.xt_val = torch.randn(self.shape)
        self.ut_val = torch.randn(self.shape)
        self.model_pred_val = torch.randn(self.shape)
        self.x1_input = torch.randn(self.shape)

        # Mock model returning a predetermined prediction
        self.mock_model = MagicMock(spec=nn.Module, return_value=self.model_pred_val)

        # Mock path module
        self.mock_path = MockPathModule()

        # Mock 'trainer' object (self)
        self.mock_trainer = SimpleNamespace()
        self.mock_trainer.path_sampler = SimpleNamespace()
        self.mock_trainer.path_sampler.plan = MagicMock(return_value=(self.t_val, self.xt_val, self.ut_val))
        self.mock_trainer.sample = MagicMock(return_value=(self.t_val, torch.zeros_like(self.x1_input), self.x1_input))

        # Defaults commonly used
        self.mock_trainer.model_type = MockModelType.VELOCITY
        self.mock_trainer.use_cosine_loss = False
        self.mock_trainer.loss_type = MockWeightType.NONE

        # Functions used in non-VELOCITY branches
        # Return broadcastable "drift_var" and "sigma_t"
        self.mock_trainer.path_sampler.compute_drift = MagicMock(return_value=(None, torch.full((1,), 2.0)))
        self.mock_trainer.path_sampler.compute_sigma_t = MagicMock(return_value=(torch.full((1,), 0.5), None))

        # Patch the dependencies directly into the imported modules
        for mod in (canonical_training_losses, generated_training_losses):
            mod.__globals__['ModelType'] = MockModelType
            mod.__globals__['WeightType'] = MockWeightType
            mod.__globals__['mean_flat'] = mock_mean_flat
            mod.__globals__['path'] = self.mock_path

    # ---- Helpers -------------------------------------------------------------

    def run_both(self, **kwargs):
        """Run canonical and generated functions under identical seeds and kwargs."""
        set_seed()
        out_can = canonical_training_losses(self.mock_trainer, self.mock_model, self.x1_input, **kwargs)
        set_seed()
        out_gen = generated_training_losses(self.mock_trainer, self.mock_model, self.x1_input, **kwargs)
        return out_can, out_gen

    # ---- Core tests: VELOCITY ------------------------------------------------

    def test_velocity_loss_only_equivalence(self):
        self.mock_trainer.model_type = MockModelType.VELOCITY
        self.mock_trainer.use_cosine_loss = False

        out_can, out_gen = self.run_both()

        self.assertIn('loss', out_can)
        self.assertIn('loss', out_gen)
        self.assertNotIn('cos_loss', out_can)
        torch.testing.assert_close(out_can['loss'], out_gen['loss'])
        self.mock_model.assert_called_with(self.xt_val, self.t_val)

    def test_velocity_and_cosine_loss_equivalence(self):
        self.mock_trainer.model_type = MockModelType.VELOCITY
        self.mock_trainer.use_cosine_loss = True
        model_kwargs = {"guidance_scale": 7.5}

        out_can, out_gen = self.run_both(model_kwargs=model_kwargs)

        self.assertIn('loss', out_can)
        self.assertIn('cos_loss', out_can)
        self.assertIn('loss', out_gen)
        self.assertIn('cos_loss', out_gen)
        torch.testing.assert_close(out_can['loss'], out_gen['loss'])
        torch.testing.assert_close(out_can['cos_loss'], out_gen['cos_loss'])
        self.mock_model.assert_called_with(self.xt_val, self.t_val, **model_kwargs)

    def test_velocity_pred_key_present(self):
        self.mock_trainer.model_type = MockModelType.VELOCITY
        out_can, out_gen = self.run_both()
        self.assertIn('pred', out_can)
        self.assertIn('pred', out_gen)
        torch.testing.assert_close(out_can['pred'], out_gen['pred'])

    # ---- Non-velocity: NOISE -------------------------------------------------

    def _exercise_noise_with_weight(self, weight_type):
        self.mock_trainer.model_type = MockModelType.NOISE
        self.mock_trainer.loss_type = weight_type
        out_can, out_gen = self.run_both()
        self.assertIn('loss', out_can)
        self.assertIn('loss', out_gen)
        torch.testing.assert_close(out_can['loss'], out_gen['loss'])
        # path.expand_t_like_x should be called once per run
        self.assertGreaterEqual(self.mock_path.expand_t_like_x.call_count, 2)

    def test_noise_weight_none_equivalence(self):
        self._exercise_noise_with_weight(MockWeightType.NONE)

    def test_noise_weight_velocity_equivalence(self):
        self._exercise_noise_with_weight(MockWeightType.VELOCITY)

    def test_noise_weight_likelihood_equivalence(self):
        self._exercise_noise_with_weight(MockWeightType.LIKELIHOOD)

    # ---- Non-velocity: SCORE -------------------------------------------------

    def _exercise_score_with_weight(self, weight_type):
        self.mock_trainer.model_type = MockModelType.SCORE
        self.mock_trainer.loss_type = weight_type
        out_can, out_gen = self.run_both()
        self.assertIn('loss', out_can)
        self.assertIn('loss', out_gen)
        torch.testing.assert_close(out_can['loss'], out_gen['loss'])
        self.assertGreaterEqual(self.mock_path.expand_t_like_x.call_count, 2)

    def test_score_weight_none_equivalence(self):
        self._exercise_score_with_weight(MockWeightType.NONE)

    def test_score_weight_velocity_equivalence(self):
        self._exercise_score_with_weight(MockWeightType.VELOCITY)

    def test_score_weight_likelihood_equivalence(self):
        self._exercise_score_with_weight(MockWeightType.LIKELIHOOD)

    # ---- Error path: Unknown weight -> NotImplementedError -------------------

    def test_unknown_weight_raises_not_implemented(self):
        self.mock_trainer.model_type = MockModelType.SCORE
        self.mock_trainer.loss_type = MockWeightType.UNKNOWN
        with self.assertRaises(NotImplementedError):
            canonical_training_losses(self.mock_trainer, self.mock_model, self.x1_input)
        with self.assertRaises(NotImplementedError):
            generated_training_losses(self.mock_trainer, self.mock_model, self.x1_input)

    # ---- API plumbing & edge cases ------------------------------------------

    def test_model_kwargs_forwarded(self):
        self.mock_trainer.model_type = MockModelType.VELOCITY
        kw = {"foo": 1, "bar": True}
        self.run_both(model_kwargs=kw)
        self.mock_model.assert_called_with(self.xt_val, self.t_val, **kw)

    def test_sp_timesteps_and_shifted_mu_propagation(self):
        self.mock_trainer.model_type = MockModelType.VELOCITY
        sp = torch.tensor([0.1, 0.2, 0.7, 0.9])
        shifted = 3
        self.run_both(sp_timesteps=sp, shifted_mu=shifted)
        # Ensure sample got the exact args on both runs
        expected_calls = [call(self.x1_input, sp, shifted), call(self.x1_input, sp, shifted)]
        # sample is called once per run; since we run twice, verify at least twice with given args
        self.mock_trainer.sample.assert_has_calls(expected_calls, any_order=False)

    def test_model_output_shape_mismatch_raises(self):
        # Force wrong shape: drop the channel dimension
        bad_pred = torch.randn(self.shape[0], *self.shape[2:])  # (B, H, W) instead of (B, C, H, W)
        self.mock_model = MagicMock(spec=nn.Module, return_value=bad_pred)

        # Replace the model in both runs by calling functions directly
        self.mock_trainer.model_type = MockModelType.VELOCITY
        with self.assertRaises(AssertionError):
            canonical_training_losses(self.mock_trainer, self.mock_model, self.x1_input)
        with self.assertRaises(AssertionError):
            generated_training_losses(self.mock_trainer, self.mock_model, self.x1_input)

    def test_path_expand_called_with_expected_args(self):
        self.mock_trainer.model_type = MockModelType.SCORE
        _ = self.run_both()
        # We can't easily compare tensors for equality via call args,
        # but we can assert it was called with two args and call count >= 2.
        for args, kwargs in self.mock_path.expand_t_like_x.call_args_list:
            self.assertEqual(len(args), 2)  # (t, xt)
        self.assertGreaterEqual(self.mock_path.expand_t_like_x.call_count, 2)


if __name__ == '__main__':
    print("-" * 70)
    print("NOTE: If you see an `ImportError` below, it is likely because the")
    print("target code uses relative imports (e.g., `from . import path`).")
    print("This is expected when running a package file as a standalone script.")
    print("Please run this test within a proper package context (e.g., using pytest)")
    print("or temporarily modify the imports in the files being tested.")
    print("-" * 70)
    unittest.main(verbosity=2)