mcy98's picture
Upload folder using huggingface_hub
d7ff85b verified
Raw History Blame Contribute Delete
10.4 kB
# 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()