File size: 6,474 Bytes
6aba0e6 | 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 | import unittest
import torch
import numpy as np
# Assume the canonical code is in a file named 'canonical_code.py'
# and the generated code is in 'generated_code.py'
# Make sure both files are in the same directory or accessible via PYTHONPATH
# Canonical Implementation
from canonical import DDPMDeletionLoss as CanonicalDDPMDeletionLoss
# Generated Implementation (to be replaced with the actual import)
from ddpm_deletion_loss import DDPMDeletionLoss as GeneratedDDPMDeletionLoss
class MockUNet(torch.nn.Module):
"""A mock U-Net that returns a tensor of zeros with the same shape as the input."""
def forward(self, sample, timestep, **kwargs):
return (torch.zeros_like(sample),)
class TestDDPMDeletionLoss(unittest.TestCase):
def setUp(self):
"""Set up common inputs for the tests."""
self.batch_size = 2
self.num_channels = 3
self.height = 8
self.width = 8
self.num_timesteps = 1000
# Create mock schedules
self.gamma = torch.linspace(0.9999, 0.02, self.num_timesteps)
self.sigma = torch.sqrt(1 - self.gamma**2)
# Create a mock U-Net
self.unet = MockUNet()
# Create sample data
self.timesteps = torch.randint(0, self.num_timesteps, (self.batch_size,))
self.noise = torch.randn(self.batch_size, self.num_channels, self.height, self.width)
self.conditioning = {}
self.all_samples_dict = {
'og_latents': torch.randn(self.batch_size, self.num_channels, self.height, self.width),
'noisy_latents': torch.randn(self.batch_size, self.num_channels, self.height, self.width)
}
self.deletion_samples_dict = {
'og_latents': torch.randn(self.batch_size, self.num_channels, self.height, self.width),
'noisy_latents': torch.randn(self.batch_size, self.num_channels, self.height, self.width)
}
# Set a seed for reproducibility of torch.rand in the mixture function
torch.manual_seed(42)
def test_init_equivalence(self):
"""Test Instruction 1: Verify the __init__ method equivalence."""
canonical_loss = CanonicalDDPMDeletionLoss(gamma=self.gamma, sigma=self.sigma)
generated_loss = GeneratedDDPMDeletionLoss(gamma=self.gamma, sigma=self.sigma)
# Check if the schedules are stored correctly
self.assertTrue(torch.equal(canonical_loss.all_gamma, generated_loss.all_gamma),
"Gamma schedules do not match after initialization.")
self.assertTrue(torch.equal(canonical_loss.all_sigma, generated_loss.all_sigma),
"Sigma schedules do not match after initialization.")
def test_importance_sampling_with_mixture_equivalence(self):
"""Test Instruction 2: Verify functional equivalence of importance_sampling_with_mixture."""
lambd = 0.5
# Reset seed before each call to ensure torch.rand produces the same values
torch.manual_seed(42)
canonical_loss_obj = CanonicalDDPMDeletionLoss(gamma=self.gamma, sigma=self.sigma)
_, can_loss_x, can_loss_a, can_imp_x, can_imp_a, can_w_loss_x, can_w_loss_a = \
canonical_loss_obj.importance_sampling_with_mixture(
self.unet, self.timesteps, self.noise, self.conditioning,
self.all_samples_dict, self.deletion_samples_dict, lambd
)
torch.manual_seed(42)
generated_loss_obj = GeneratedDDPMDeletionLoss(gamma=self.gamma, sigma=self.sigma)
_, gen_loss_x, gen_loss_a, gen_imp_x, gen_imp_a, gen_w_loss_x, gen_w_loss_a = \
generated_loss_obj.importance_sampling_with_mixture(
self.unet, self.timesteps, self.noise, self.conditioning,
self.all_samples_dict, self.deletion_samples_dict, lambd
)
# Compare the key outputs
# Using numpy.testing.assert_allclose for float tensor comparison
np.testing.assert_allclose(can_w_loss_x.detach().numpy(), gen_w_loss_x.detach().numpy(),
rtol=1e-5, err_msg="Mismatch in weighted_loss_x")
np.testing.assert_allclose(can_w_loss_a.detach().numpy(), gen_w_loss_a.detach().numpy(),
rtol=1e-5, err_msg="Mismatch in weighted_loss_a")
# Optional: Compare other intermediate outputs for more detailed debugging
np.testing.assert_allclose(can_loss_x.detach().numpy(), gen_loss_x.detach().numpy(),
rtol=1e-5, err_msg="Mismatch in loss_x")
np.testing.assert_allclose(can_loss_a.detach().numpy(), gen_loss_a.detach().numpy(),
rtol=1e-5, err_msg="Mismatch in loss_a")
np.testing.assert_allclose(can_imp_x.detach().numpy(), gen_imp_x.detach().numpy(),
rtol=1e-5, err_msg="Mismatch in importance_weight_x")
np.testing.assert_allclose(can_imp_a.detach().numpy(), gen_imp_a.detach().numpy(),
rtol=1e-5, err_msg="Mismatch in importance_weight_a")
def test_double_forward_with_neg_del_equivalence(self):
"""Test Instruction 3: Verify functional equivalence of double_forward_with_neg_del."""
canonical_loss_obj = CanonicalDDPMDeletionLoss(gamma=self.gamma, sigma=self.sigma)
_, can_loss_x, can_loss_a, _, _, _, _ = \
canonical_loss_obj.double_forward_with_neg_del(
self.unet, self.timesteps, self.noise, self.conditioning,
self.all_samples_dict, self.deletion_samples_dict
)
generated_loss_obj = GeneratedDDPMDeletionLoss(gamma=self.gamma, sigma=self.sigma)
_, gen_loss_x, gen_loss_a, _, _, _, _ = \
generated_loss_obj.double_forward_with_neg_del(
self.unet, self.timesteps, self.noise, self.conditioning,
self.all_samples_dict, self.deletion_samples_dict
)
# Compare the key outputs
np.testing.assert_allclose(can_loss_x.detach().numpy(), gen_loss_x.detach().numpy(),
rtol=1e-5, err_msg="Mismatch in loss_x for double_forward")
np.testing.assert_allclose(can_loss_a.detach().numpy(), gen_loss_a.detach().numpy(),
rtol=1e-5, err_msg="Mismatch in loss_a for double_forward")
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)
|