File size: 12,152 Bytes
e89a301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import unittest
import torch
import numpy as np

# Import the canonical and generated implementations
from canonical import ELCRecTrainer as CanonicalTrainer
from trainers import ELCRecTrainer as GeneratedTrainer

# ----------------- Dummies & Mocks ----------------- #

class DummyArgs:
    def __init__(self):
        self.no_cuda = True
        self.num_intent_clusters = "2"
        self.seq_representation_type = "mean"
        self.seq_representation_instancecl_type = "mean"
        self.prototype = "shift"     # will vary in tests
        self.seed = 42
        self.hidden_size = 4
        self.gpu_id = 0
        self.n_views = 2
        self.max_seq_length = 3
        self.adam_beta1 = 0.9
        self.adam_beta2 = 0.99
        self.lr = 0.001
        self.weight_decay = 0.0
        self.temperature = 1.0
        self.cf_weight = 1.0
        self.intent_cf_weight = 1.0
        self.rec_weight = 1.0
        self.trade_off = 1.0
        self.log_file = "test.log"
        self.contrast_type = "InstanceCL"  # will vary in tests
        self.de_noise = False              # will vary in tests
        self.warm_up_epoches = 0
        self.train_matrix = np.zeros((2, 20))  # not used in sampled eval

class DummyModel(torch.nn.Module):
    def __init__(self, hidden_size=4, num_clusters=2, vocab_size=20):
        super().__init__()
        self.hidden_size = hidden_size
        self.cluster_centers = torch.nn.Parameter(torch.randn(num_clusters, hidden_size))
        self.item_embeddings = torch.nn.Embedding(vocab_size, hidden_size)
        self.args = DummyArgs()

    def forward(self, x):
        return self.item_embeddings(x)

class DummyCriterion:
    def __call__(self, *args, **kwargs):
        return torch.tensor(0.5)

class DummyDataLoader:
    """Yields a single minimal batch for train/eval paths."""
    def __iter__(self):
        rec_batch = (
            torch.zeros(2, 3, dtype=torch.long),               # user ids
            torch.zeros(2, 3, dtype=torch.long),               # input_ids
            torch.tensor([[1, 2, 0], [0, 1, 2]], dtype=torch.long),  # target_pos (>=0)
            torch.zeros(2, 3, dtype=torch.long),               # target_neg
            torch.zeros(2, dtype=torch.long)                   # answers
        )
        cl_batches = [
            [torch.zeros(2, 3, dtype=torch.long), torch.ones(2, 3, dtype=torch.long)]
        ]
        seq_class_label_batches = [torch.zeros(2, dtype=torch.long)]
        yield rec_batch, cl_batches, seq_class_label_batches
    def __len__(self):
        return 1

class MockCluster:
    """Provides centroids and a no-op train() for KMeans init path."""
    def __init__(self, k=2, d=4):
        self._k = k
        self._d = d
        self.centroids = torch.zeros(k, d)  # deterministic
    def train(self, np_data):
        # set zeros deterministically; could also compute means if desired
        self.centroids = torch.zeros(self._k, self._d)

class MockOptim:
    def zero_grad(self): pass
    def step(self): pass

# ----------------- Test Suite ----------------- #
class DummyEvalSampledDataLoader:
    """

    Yields a single batch in the exact shape eval(sampled) expects:

    (user_ids, input_ids, target_pos, target_neg, answers, sample_negs)

    """
    def __iter__(self):
        user_ids = torch.zeros(2, 3, dtype=torch.long)          # shape matches train style but used only for .to()
        input_ids = torch.zeros(2, 3, dtype=torch.long)
        target_pos = torch.tensor([[1, 2, 0], [0, 1, 2]], dtype=torch.long)
        target_neg = torch.zeros(2, 3, dtype=torch.long)
        answers = torch.zeros(2, dtype=torch.long)
        sample_negs = torch.zeros(2, 10, dtype=torch.long)      # N sampled negatives per user; any N is fine
        yield (user_ids, input_ids, target_pos, target_neg, answers, sample_negs)

    def __len__(self):
        return 1

class TestELCRecTrainerEquivalence(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # ... keep your existing seeding, model, args, and loaders ...
        cls.model1 = DummyModel()
        cls.model2 = DummyModel()
        cls.model2.load_state_dict(cls.model1.state_dict())
        cls.args = DummyArgs()

        cls.dataloader = DummyDataLoader()
        cls.cluster_dataloader = DummyDataLoader()
        cls.eval_dataloader = DummyEvalSampledDataLoader()  # <-- use the new loader here
        cls.test_dataloader = DummyDataLoader()

        cls.canonical = CanonicalTrainer(
            cls.model1, cls.dataloader, cls.cluster_dataloader, cls.eval_dataloader, cls.test_dataloader, cls.args
        )
        cls.generated = GeneratedTrainer(
            cls.model2, cls.dataloader, cls.cluster_dataloader, cls.eval_dataloader, cls.test_dataloader, cls.args
        )

        # Patches unchanged...
        for tr in (cls.canonical, cls.generated):
            tr.device = torch.device("cpu")
            tr.cf_criterion = DummyCriterion()
            tr.pcl_criterion = DummyCriterion()
            tr.clusters = [MockCluster(k=2, d=cls.args.hidden_size)]
            tr.optim = MockOptim()
            tr.predict_full = lambda x: torch.zeros((x.shape[0], 20))
            tr.predict_sample = (
                lambda rep, items: torch.zeros((items.shape[0], items.shape[1]))  # (bsz, 1+neg) or (bsz, M)
            )
            tr.get_full_sort_score = lambda epoch, answers, preds: {"dummy": 1.0}
            tr.get_sample_scores = lambda epoch, logits: {"sample@10": 1.0}

    # ... keep the rest of the tests unchanged ...

    
        
    def test_distance_equivalence(self):
        x = torch.randn(5, 4)
        c = torch.randn(3, 4)
        dis_canon = CanonicalTrainer.distance(x, c)
        dis_gen = GeneratedTrainer.distance(x, c)
        self.assertTrue(torch.allclose(dis_canon, dis_gen, atol=1e-6), "distance() mismatch")

    def test_cross_entropy_equivalence(self):
        seq_out = torch.ones((2, 3, 4))
        pos_ids = torch.tensor([[1, 2, 0], [0, 1, 2]], dtype=torch.long)
        neg_ids = torch.ones((2, 3), dtype=torch.long)

        loss_canon = self.canonical.cross_entropy(seq_out, pos_ids, neg_ids)
        loss_gen = self.generated.cross_entropy(seq_out, pos_ids, neg_ids)
        self.assertAlmostEqual(float(loss_canon), float(loss_gen), places=6, msg="cross_entropy loss mismatch")

    # ---------- InstanceCL variants ---------- #

    def test_instance_cl_shift_mean_equivalence(self):
        self.canonical.args.prototype = "shift"
        self.generated.args.prototype = "shift"
        self.canonical.args.seq_representation_instancecl_type = "mean"
        self.generated.args.seq_representation_instancecl_type = "mean"

        inputs = [torch.zeros(2, 3, dtype=torch.long), torch.ones(2, 3, dtype=torch.long)]
        loss_canon = self.canonical._instance_cl_one_pair_contrastive_learning(inputs)
        loss_gen = self.generated._instance_cl_one_pair_contrastive_learning(inputs)
        self.assertAlmostEqual(float(loss_canon), float(loss_gen), places=6, msg="InstanceCL shift/mean mismatch")

    def test_instance_cl_concat_equivalence(self):
        self.canonical.args.prototype = "concat"
        self.generated.args.prototype = "concat"
        # mean pooling still active
        inputs = [torch.zeros(2, 3, dtype=torch.long), torch.ones(2, 3, dtype=torch.long)]
        loss_canon = self.canonical._instance_cl_one_pair_contrastive_learning(inputs)
        loss_gen = self.generated._instance_cl_one_pair_contrastive_learning(inputs)
        self.assertAlmostEqual(float(loss_canon), float(loss_gen), places=6, msg="InstanceCL concat mismatch")

    def test_instance_cl_with_denoise_flag_equivalence(self):
        self.canonical.args.prototype = "shift"
        self.generated.args.prototype = "shift"
        self.canonical.args.de_noise = True
        self.generated.args.de_noise = True

        inputs = [torch.zeros(2, 3, dtype=torch.long), torch.ones(2, 3, dtype=torch.long)]
        intent_ids = torch.zeros(2, dtype=torch.long)
        loss_canon = self.canonical._instance_cl_one_pair_contrastive_learning(inputs, intent_ids=intent_ids)
        loss_gen = self.generated._instance_cl_one_pair_contrastive_learning(inputs, intent_ids=intent_ids)
        self.assertAlmostEqual(float(loss_canon), float(loss_gen), places=6, msg="InstanceCL de_noise mismatch")
        # reset
        self.canonical.args.de_noise = False
        self.generated.args.de_noise = False

    # ---------- PCL path ---------- #

    def test_pcl_equivalence(self):
        self.canonical.args.seq_representation_type = "mean"
        self.generated.args.seq_representation_type = "mean"
        inputs = [torch.zeros(2, 3, dtype=torch.long), torch.ones(2, 3, dtype=torch.long)]
        intents = [torch.ones(2, 4), torch.ones(2, 4)]
        intent_ids = [torch.zeros(2, dtype=torch.long), torch.ones(2, dtype=torch.long)]

        loss_canon = self.canonical._pcl_one_pair_contrastive_learning(inputs, intents, intent_ids)
        loss_gen = self.generated._pcl_one_pair_contrastive_learning(inputs, intents, intent_ids)
        self.assertAlmostEqual(float(loss_canon), float(loss_gen), places=6, msg="PCL loss mismatch")

    def test_pcl_with_denoise_flag_equivalence(self):
        self.canonical.args.de_noise = True
        self.generated.args.de_noise = True
        inputs = [torch.zeros(2, 3, dtype=torch.long), torch.ones(2, 3, dtype=torch.long)]
        intents = [torch.ones(2, 4), torch.ones(2, 4)]
        intent_ids = [torch.zeros(2, dtype=torch.long), torch.ones(2, dtype=torch.long)]

        loss_canon = self.canonical._pcl_one_pair_contrastive_learning(inputs, intents, intent_ids)
        loss_gen = self.generated._pcl_one_pair_contrastive_learning(inputs, intents, intent_ids)
        self.assertAlmostEqual(float(loss_canon), float(loss_gen), places=6, msg="PCL de_noise mismatch")
        # reset
        self.canonical.args.de_noise = False
        self.generated.args.de_noise = False

    # ---------- Iteration: training branches ---------- #

    def _run_train_iteration_and_compare(self, contrast_type):
        self.canonical.args.contrast_type = contrast_type
        self.generated.args.contrast_type = contrast_type
        # Ensure warmup allows IntentCL/Hybrid KMeans path at epoch 0
        self.canonical.args.warm_up_epoches = 0
        self.generated.args.warm_up_epoches = 0

        rec_avg_loss_canon, joint_avg_loss_canon = self.canonical.iteration(
            epoch=0, dataloader=self.dataloader, cluster_dataloader=self.cluster_dataloader, full_sort=True, train=True
        )
        rec_avg_loss_gen, joint_avg_loss_gen = self.generated.iteration(
            epoch=0, dataloader=self.dataloader, cluster_dataloader=self.cluster_dataloader, full_sort=True, train=True
        )
        self.assertAlmostEqual(rec_avg_loss_canon, rec_avg_loss_gen, places=6, msg=f"{contrast_type} rec_avg mismatch")
        self.assertAlmostEqual(joint_avg_loss_canon, joint_avg_loss_gen, places=6, msg=f"{contrast_type} joint_avg mismatch")

    def test_iteration_train_instancecl(self):
        self._run_train_iteration_and_compare("InstanceCL")

    def test_iteration_train_intentcl(self):
        self._run_train_iteration_and_compare("IntentCL")

    def test_iteration_train_hybrid(self):
        self._run_train_iteration_and_compare("Hybrid")

    # ---------- Iteration: eval (sampled) branch ---------- #

    def test_iteration_eval_sampled_equivalence(self):
        result_canon = self.canonical.iteration(
            epoch=0, dataloader=self.eval_dataloader, full_sort=False, train=False
        )
        result_gen = self.generated.iteration(
            epoch=0, dataloader=self.eval_dataloader, full_sort=False, train=False
        )
        self.assertEqual(result_canon, result_gen, "Eval (sampled) results mismatch")

if __name__ == '__main__':
    unittest.main(verbosity=2)