File size: 10,392 Bytes
d7ff85b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# test_cadirec_equivalence.py
import unittest
import torch
import numpy as np

# --- Import the two implementations ---
# Expectation: both modules expose a class CaDiRec(device, args)
from canonical import CaDiRec as CanonicalCaDiRec
from cadirec import CaDiRec as GeneratedCaDiRec


class _Args:
    """
    Minimal args container matching attributes accessed in CaDiRec.
    If your canonical code expects additional fields, add them here.
    """
    def __init__(self):
        # Model sizes kept tiny for speed
        self.item_size = 32
        self.train_batch_size = 2
        self.hidden_size = 8
        self.max_seq_length = 6
        self.n_layers = 1
        self.n_heads = 2
        self.inner_size = 16
        self.sasrec_dropout_prob = 0.1
        self.hidden_act = "gelu"
        self.layer_norm_eps = 1e-12
        self.initializer_range = 0.02
        self.temperature = 0.2

        # Some DeBERTa/HF encoders require additional fields in config-like objects.
        # If your canonical code expects more, add sane defaults here.
        # Common ones:
        self.attention_probs_dropout_prob = 0.1
        self.hidden_dropout_prob = 0.1
        self.intermediate_size = self.inner_size
        self.num_attention_heads = self.n_heads
        self.num_hidden_layers = self.n_layers
        self.max_position_embeddings = self.max_seq_length
        self.type_vocab_size = 2
        self.vocab_size = self.item_size  # not critical; DebertaEncoder ignores this weight here
        
        # DeBERTa specific attributes
        self.pos_att_type = ["p2c", "c2p"]  # Position attention type for DeBERTa


def _seed_all(seed: int = 1234):
    torch.manual_seed(seed)
    np.random.seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)


class TestCaDiRecEquivalence(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        _seed_all(2025)

        cls.device = "cpu"
        cls.args = _Args()

        # Build both models
        cls.model_c = CanonicalCaDiRec(cls.device, cls.args)
        cls.model_g = GeneratedCaDiRec(cls.device, cls.args)

        # Ensure identical parameters: copy canonical weights into generated
        cls.model_g.load_state_dict(cls.model_c.state_dict(), strict=False)

        cls.model_c.eval()
        cls.model_g.eval()

        # Small, representative inputs (with padding zeros at left)
        B, L = cls.args.train_batch_size, cls.args.max_seq_length
        V = cls.args.item_size

        # Create padded sequences: zeros are padding id
        # Example sequences: [0, 0, 3, 4, 2, 7], [0, 5, 1, 9, 2, 8]
        seq = torch.zeros((B, L), dtype=torch.long)
        for b in range(B):
            non_pad = torch.randint(low=1, high=V, size=(L - (b + 1),))
            seq[b, (b + 1):] = non_pad  # increasing left padding across batch

        cls.item_seq = seq  # (B, L)

        # Positive targets: one next item per position, keep shape (B, L)
        cls.target_pos = torch.randint(1, V, (B, L), dtype=torch.long)

        # Negative samples: one negative per position (the canonical cross_entropy
        # expects the same shape as pos_ids)
        cls.target_neg = torch.randint(1, V, (B, L), dtype=torch.long)

        # For diffusion reverse: make a noisy embedding input of shape (B, L, H)
        H = cls.args.hidden_size
        cls.noisy_x = torch.randn(B, L, H, dtype=torch.float32)

        # Timesteps per batch (int tensor); small integers for simplicity
        cls.timesteps = torch.randint(low=0, high=10, size=(B,), dtype=torch.long)

        # Attention mask for diffusion encoder: (B, L) with 1 for real tokens
        # Build from item_seq (>0 = real token)
        cls.diff_attn_mask = (cls.item_seq > 0).long()

        # Two augmented sequences (same shape as item_seq)
        cls.aug_seq1 = torch.randint(1, V, (B, L), dtype=torch.long)
        cls.aug_seq2 = torch.randint(1, V, (B, L), dtype=torch.long)

    # --------------------------
    # Instruction 1: __init__
    # --------------------------
    def test_init_shapes_and_keys(self):
        """Check critical parameter presence and identical shapes/values after sync."""
        c_params = dict(self.model_c.named_parameters())
        g_params = dict(self.model_g.named_parameters())

        # Ensure both expose shared item & position embeddings with same shapes
        self.assertIn("item_embedding.weight", c_params)
        self.assertIn("item_embedding.weight", g_params)
        self.assertEqual(c_params["item_embedding.weight"].shape,
                         g_params["item_embedding.weight"].shape)

        self.assertIn("position_embedding.weight", c_params)
        self.assertIn("position_embedding.weight", g_params)
        self.assertEqual(c_params["position_embedding.weight"].shape,
                         g_params["position_embedding.weight"].shape)

        # After loading canonical weights into generated, values should match closely
        self.assertTrue(torch.allclose(
            c_params["item_embedding.weight"], g_params["item_embedding.weight"], atol=1e-6, rtol=1e-5
        ), "Item embedding weights mismatch after synchronization")

    # ---------------------------------
    # Instruction 2: diffusion_reverse
    # ---------------------------------
    def test_diffusion_reverse_equivalence(self):
        with torch.no_grad():
            out_c = self.model_c.diffusion_reverse(self.noisy_x, self.timesteps, self.diff_attn_mask)
            out_g = self.model_g.diffusion_reverse(self.noisy_x, self.timesteps, self.diff_attn_mask)

        # Primary check: exact numerical equivalence (tolerant)
        self.assertEqual(out_c.shape, out_g.shape, "Denoised outputs have different shapes")
        self.assertEqual(out_c.dtype, out_g.dtype, "Denoised outputs have different dtypes")
        self.assertTrue(torch.allclose(out_c, out_g, atol=1e-5, rtol=1e-4),
                        "Mismatch in diffusion_reverse outputs")

    # --------------------------------------
    # Instruction 3: calculate_rec_loss (BCE)
    # --------------------------------------
    def test_calculate_rec_loss_equivalence(self):
        with torch.no_grad():
            loss_c = self.model_c.calculate_rec_loss(self.item_seq, self.target_pos, self.target_neg)
            loss_g = self.model_g.calculate_rec_loss(self.item_seq, self.target_pos, self.target_neg)

        # Both should produce finite scalars and be close
        self.assertTrue(torch.isfinite(loss_c), "Canonical rec loss is not finite")
        self.assertTrue(torch.isfinite(loss_g), "Generated rec loss is not finite")
        self.assertTrue(torch.allclose(loss_c, loss_g, atol=1e-6, rtol=1e-5),
                        f"Recommendation loss mismatch: canonical={loss_c.item()}, generated={loss_g.item()}")

    # -----------------------------------------
    # Instruction 4: calculate_cl_loss (InfoNCE)
    # -----------------------------------------
    def test_calculate_cl_loss_equivalence(self):
        with torch.no_grad():
            cl_c = self.model_c.calculate_cl_loss(self.aug_seq1, self.aug_seq2)
            cl_g = self.model_g.calculate_cl_loss(self.aug_seq1, self.aug_seq2)

        self.assertTrue(torch.isfinite(cl_c), "Canonical CL loss is not finite")
        self.assertTrue(torch.isfinite(cl_g), "Generated CL loss is not finite")
        self.assertTrue(torch.allclose(cl_c, cl_g, atol=1e-6, rtol=1e-5),
                        f"Contrastive loss mismatch: canonical={cl_c.item()}, generated={cl_g.item()}")

    # ---------------------------------
    # Instruction 5: full_sort_predict
    # ---------------------------------
    def test_full_sort_predict_equivalence(self):
        with torch.no_grad():
            scores_c = self.model_c.full_sort_predict(self.item_seq)
            scores_g = self.model_g.full_sort_predict(self.item_seq)

        # Deterministic with shared weights; exact-ish equality
        self.assertEqual(scores_c.shape, scores_g.shape, "Prediction score shapes differ")
        self.assertTrue(torch.allclose(scores_c, scores_g, atol=1e-5, rtol=1e-4),
                        "Full-sort prediction scores mismatch")

    # ------------------------
    # Extra coverage & edges
    # ------------------------
    def test_structural_stability_with_all_padding_prefix(self):
        """Edge case: sequences with more padding should not crash and should align structurally."""
        B, L = self.args.train_batch_size, self.args.max_seq_length
        seq = torch.zeros((B, L), dtype=torch.long)
        # Only last two tokens are non-pad
        seq[:, -2:] = torch.randint(1, self.args.item_size, (B, 2))

        with torch.no_grad():
            scores_c = self.model_c.full_sort_predict(seq)
            scores_g = self.model_g.full_sort_predict(seq)

        self.assertEqual(scores_c.shape, (B, self.args.item_size))
        self.assertEqual(scores_g.shape, (B, self.args.item_size))
        self.assertTrue(torch.allclose(scores_c, scores_g, atol=1e-5, rtol=1e-4))

    def test_diffusion_reverse_mask_insensitivity_shape_and_dtype(self):
        """If diffusion uses attention masks internally, different masks with same shapes should retain structural equivalence."""
        B, L = self.args.train_batch_size, self.args.max_seq_length
        x = torch.randn(B, L, self.args.hidden_size)

        # Two masks: all ones vs derived from item_seq
        mask1 = torch.ones(B, L, dtype=torch.long)
        mask2 = (self.item_seq > 0).long()

        with torch.no_grad():
            out1_c = self.model_c.diffusion_reverse(x, self.timesteps, mask1)
            out1_g = self.model_g.diffusion_reverse(x, self.timesteps, mask1)
            out2_c = self.model_c.diffusion_reverse(x, self.timesteps, mask2)
            out2_g = self.model_g.diffusion_reverse(x, self.timesteps, mask2)

        # Pairwise equality for each mask
        self.assertTrue(torch.allclose(out1_c, out1_g, atol=1e-5, rtol=1e-4))
        self.assertTrue(torch.allclose(out2_c, out2_g, atol=1e-5, rtol=1e-4))

        # Stable characteristics across masks (not necessarily equal to each other)
        self.assertEqual(out1_c.shape, out2_c.shape)
        self.assertEqual(out1_g.shape, out2_g.shape)
        self.assertEqual(out1_c.dtype, out2_c.dtype)
        self.assertEqual(out1_g.dtype, out2_g.dtype)


if __name__ == "__main__":
    unittest.main()