import unittest import torch import torch.nn as nn import numpy as np import sys import os # --- Dummy to_one_hot function (from previous fix) --- def to_one_hot(indices, num_classes): if indices.dim() > 1: indices_flat = indices.reshape(-1) else: indices_flat = indices size = list(indices_flat.size()) + [num_classes] one_hot = torch.zeros(*size, device=indices.device) return one_hot.scatter_(-1, indices_flat.unsqueeze(-1), 1) mock_utils_module = type('module', (object,), {'to_one_hot': to_one_hot}) sys.modules['utils'] = mock_utils_module # --- Import Canonical and Generated Implementations --- try: from canonical import ( batch_gradient_w_loss as canonical_batch_gradient_w_loss, fast_find_matrix_around_image as canonical_fast_find_matrix_around_image, get_class_rank as canonical_get_class_rank, get_k_best_target_classes as canonical_get_k_best_classes ) class CanonicalModel(nn.Module): def __init__(self, num_classes=10): super(CanonicalModel, self).__init__() self.fc = nn.Linear(784, num_classes) self.device = torch.device("cpu") # Updated in setUp def forward(self, x): return self.fc(x.view(x.size(0), -1)) except ImportError as e: print(f"ERROR: Could not import MALT functions from canonical.py. Details: {e}") sys.exit(1) try: # IMPORTANT: Import from 'targeting' as specified from targeting import ( batch_gradient_w_loss as generated_batch_gradient_w_loss, fast_find_matrix_around_image as generated_fast_find_matrix_around_image, get_class_rank as generated_get_class_rank, get_k_best_target_classes as generated_get_k_best_classes ) class GeneratedModel(nn.Module): def __init__(self, num_classes=10): super(GeneratedModel, self).__init__() self.fc = nn.Linear(784, num_classes) self.device = torch.device("cpu") # Updated in setUp def forward(self, x): return self.fc(x.view(x.size(0), -1)) except ImportError as e: print(f"ERROR: Could not import MALT functions from targeting.py. Details: {e}") sys.exit(1) # --- Unit Test Suite --- class TestMALTFunctions(unittest.TestCase): @classmethod def setUpClass(cls): """ Setup for all tests. Checks CUDA availability and initializes models. """ if not torch.cuda.is_available(): print("WARNING: CUDA not available. Running tests on CPU. This might be slower.") cls.device = torch.device("cpu") else: cls.device = torch.device("cuda") print(f"Running tests on GPU: {torch.cuda.get_device_name(0)}") # Set a consistent random seed for reproducibility across runs and implementations # Essential for numerical stability and reproducibility, especially with GPU operations. torch.manual_seed(42) np.random.seed(42) if torch.cuda.is_available(): torch.cuda.manual_seed_all(42) # Enable deterministic algorithms for maximum reproducibility on CUDA # Note: This might make some operations slower or not supported. torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # Disable auto-tuner for deterministic behavior def setUp(self): """ Setup for each individual test method. Initializes fresh models and input data. """ self.num_images = 4 self.img_channels = 1 self.img_height = 28 self.img_width = 28 self.num_classes = 10 self.batch_size = 2 # Initialize canonical and generated models, moving them to the test device # Crucially, ensure models are in evaluation mode if gradients are computed for Jacobian # without updating model parameters. This prevents issues with dropout/batchnorm. self.canonical_model = CanonicalModel(num_classes=self.num_classes).to(self.device).eval() self.canonical_model.device = self.device # Set device attribute self.generated_model = GeneratedModel(num_classes=self.num_classes).to(self.device).eval() self.generated_model.device = self.device # Set device attribute # Ensure models have identical initial weights for direct comparison # This is critical if the models themselves are part of the comparison. # Copy canonical model's state_dict to generated model. self.generated_model.load_state_dict(self.canonical_model.state_dict()) # Create dummy input data, ensuring it's on the correct device and detached # .clone().detach() provides a fresh tensor for each test method self.input_data = torch.randn(self.num_images, self.img_channels, self.img_height, self.img_width).to(self.device).clone().detach() self.target_labels = torch.randint(0, self.num_classes, (self.num_images,)).to(self.device).clone().detach() self.candidate_indices = torch.randint(0, self.num_classes, (self.num_images, 5)).to(self.device).clone().detach() def tearDown(self): """ Clean up after each test method. """ if torch.cuda.is_available(): torch.cuda.empty_cache() # --- Test Cases for each MALT function --- def test_batch_gradient_w_loss(self): """ Tests the batch_gradient_w_loss function for functional equivalence. """ print("\n--- Testing batch_gradient_w_loss ---") backward_var = torch.zeros(self.input_data.shape[0], self.num_classes, device=self.device) backward_var[0, 0] = 1.0 backward_var[1, 5] = 1.0 backward_var[2, 3] = 1.0 backward_var[3, 8] = 1.0 canonical_grads = canonical_batch_gradient_w_loss( self.canonical_model, self.input_data, backward_var, self.batch_size ) generated_grads = generated_batch_gradient_w_loss( self.generated_model, self.input_data, backward_var, self.batch_size ) self.assertEqual(canonical_grads.shape, generated_grads.shape, f"Shape mismatch: Canonical={canonical_grads.shape}, Generated={generated_grads.shape}") self.assertEqual(canonical_grads.dtype, generated_grads.dtype, f"Dtype mismatch: Canonical={canonical_grads.dtype}, Generated={generated_grads.dtype}") # Use a slightly higher tolerance if tiny floating point differences are acceptable torch.testing.assert_close(canonical_grads, generated_grads, rtol=1e-3, atol=1e-5, # Increased tolerance msg="Mismatch in batch_gradient_w_loss outputs.") print("batch_gradient_w_loss test passed.") def test_fast_find_matrix_around_image(self): """ Tests the fast_find_matrix_around_image function for functional equivalence. """ print("\n--- Testing fast_find_matrix_around_image ---") canonical_jacobian_with_targets = canonical_fast_find_matrix_around_image( self.input_data, self.target_labels, self.candidate_indices, self.canonical_model, num_classes=self.num_classes, batch_size=self.batch_size ) generated_jacobian_with_targets = generated_fast_find_matrix_around_image( self.input_data, self.target_labels, self.candidate_indices, self.generated_model, num_classes=self.num_classes, batch_size=self.batch_size ) self.assertEqual(canonical_jacobian_with_targets.shape, generated_jacobian_with_targets.shape, f"Shape mismatch (with targets): Canonical={canonical_jacobian_with_targets.shape}, Generated={generated_jacobian_with_targets.shape}") self.assertEqual(canonical_jacobian_with_targets.dtype, generated_jacobian_with_targets.dtype, f"Dtype mismatch (with targets): Canonical={canonical_jacobian_with_targets.dtype}, Generated={generated_jacobian_with_targets.dtype}") torch.testing.assert_close(canonical_jacobian_with_targets, generated_jacobian_with_targets, rtol=1e-3, atol=1e-5, # Increased tolerance msg="Mismatch in fast_find_matrix_around_image (with targets) outputs.") print("fast_find_matrix_around_image (with targets) test passed.") # Test Case 2: Without explicit target labels canonical_jacobian_no_targets = canonical_fast_find_matrix_around_image( self.input_data, None, self.candidate_indices, self.canonical_model, num_classes=self.num_classes, batch_size=self.batch_size ) generated_jacobian_no_targets = generated_fast_find_matrix_around_image( self.input_data, None, self.candidate_indices, self.generated_model, num_classes=self.num_classes, batch_size=self.batch_size ) torch.testing.assert_close(canonical_jacobian_no_targets, generated_jacobian_no_targets, rtol=1e-3, atol=1e-5, # Increased tolerance msg="Mismatch in fast_find_matrix_around_image (no targets) outputs.") print("fast_find_matrix_around_image (no targets) test passed.") def test_get_class_rank(self): """ Tests the get_class_rank (MALT score calculation) function. """ print("\n--- Testing get_class_rank ---") with torch.no_grad(): canonical_srcoutput = self.canonical_model(self.input_data) generated_srcoutput = self.generated_model(self.input_data) _, canonical_srcclass = torch.max(canonical_srcoutput, dim=1) _, generated_srcclass = torch.max(generated_srcoutput, dim=1) canonical_linmatrix = canonical_fast_find_matrix_around_image( self.input_data, self.target_labels, self.candidate_indices, self.canonical_model, num_classes=self.num_classes, batch_size=self.batch_size ) generated_linmatrix = generated_fast_find_matrix_around_image( self.input_data, self.target_labels, self.candidate_indices, self.generated_model, num_classes=self.num_classes, batch_size=self.batch_size ) # Test Case 1: L2 norm canonical_malt_scores_l2 = canonical_get_class_rank( self.input_data, self.candidate_indices, 2, canonical_linmatrix, canonical_srcoutput, canonical_srcclass, type=torch.float # Explicitly pass type ) generated_malt_scores_l2 = generated_get_class_rank( self.input_data, self.candidate_indices, 2, generated_linmatrix, generated_srcoutput, generated_srcclass, type=torch.float ) self.assertEqual(canonical_malt_scores_l2.shape, generated_malt_scores_l2.shape, f"Shape mismatch (L2): Canonical={canonical_malt_scores_l2.shape}, Generated={generated_malt_scores_l2.shape}") self.assertEqual(canonical_malt_scores_l2.dtype, generated_malt_scores_l2.dtype, f"Dtype mismatch (L2): Canonical={canonical_malt_scores_l2.dtype}, Generated={generated_malt_scores_l2.dtype}") torch.testing.assert_close(canonical_malt_scores_l2, generated_malt_scores_l2, rtol=1e-3, atol=1e-5, # Increased tolerance msg="Mismatch in get_class_rank (L2 norm) outputs.") print("get_class_rank (L2 norm) test passed.") # Test Case 2: L1 (np.inf) norm canonical_malt_scores_l1 = canonical_get_class_rank( self.input_data, self.candidate_indices, np.inf, canonical_linmatrix, canonical_srcoutput, canonical_srcclass, type=torch.float ) generated_malt_scores_l1 = generated_get_class_rank( self.input_data, self.candidate_indices, np.inf, generated_linmatrix, generated_srcoutput, generated_srcclass, type=torch.float ) torch.testing.assert_close(canonical_malt_scores_l1, generated_malt_scores_l1, rtol=1e-3, atol=1e-5, # Increased tolerance msg="Mismatch in get_class_rank (L1 norm) outputs.") print("get_class_rank (L1 norm) test passed.") # Test Case 3: Zero gradient norms (adjust expectation based on canonical code's behavior) zero_linmatrix = torch.zeros_like(canonical_linmatrix).to(self.device) canonical_malt_scores_zero_grad = canonical_get_class_rank( self.input_data, self.candidate_indices, 2, zero_linmatrix, canonical_srcoutput, canonical_srcclass, type=torch.float ) generated_malt_scores_zero_grad = generated_get_class_rank( self.input_data, self.candidate_indices, 2, zero_linmatrix, generated_srcoutput, generated_srcclass, type=torch.float ) # Based on canonical code, if all norms are zero, epsilon_matrix remains zeros, # and those zeros are then placed into `all_classes_matrix`. # So, the expectation is that the scores for 'next_topk_inxs' should be 0.0, # while other scores might still be inf. # Verify that the scores for the candidate indices are indeed zero for canonical # First, ensure canonical_malt_scores_zero_grad has the correct shape self.assertEqual(canonical_malt_scores_zero_grad.shape, (self.num_images, self.num_classes), "Canonical zero grad output shape mismatch.") # Check if the relevant parts of canonical output are zero (not inf) # We need to specifically check the elements corresponding to `next_topk_inxs` # as the rest of the `all_classes_matrix` might still be `inf`. cpu_arange_indices = torch.arange(self.num_images).unsqueeze(-1).cpu().detach() cpu_candidate_indices = self.candidate_indices.cpu().detach() canonical_candidate_scores = canonical_malt_scores_zero_grad[ cpu_arange_indices, cpu_candidate_indices ] # Assert that these candidate scores are effectively zero (or very close to it) # For floating point zero, direct equality might fail, so use assert_close torch.testing.assert_close(canonical_candidate_scores, torch.zeros_like(canonical_candidate_scores), rtol=1e-6, atol=1e-8, # Using strict tolerance for checking zero msg="Canonical candidate scores for zero gradient norm should be zero.") # Assert that the *generated* output also matches this behavior. # This is where the functional equivalence check happens. # --- FIX: Use CPU indices --- generated_candidate_scores = generated_malt_scores_zero_grad[ cpu_arange_indices, cpu_candidate_indices ] # --- End FIX --- torch.testing.assert_close(canonical_candidate_scores, generated_candidate_scores, rtol=1e-3, atol=1e-5, # Back to normal tolerance for comparison msg="Mismatch in generated output for zero gradient norm case.") print("get_class_rank (zero gradient norm) test passed.") def test_get_k_best_target_classes(self): """ Tests the main get_k_best_target_classes (Algorithm 1) function. """ print("\n--- Testing get_k_best_target_classes ---") topk = 3 testk = 5 canonical_topk_classes = canonical_get_k_best_classes( self.canonical_model, self.input_data, self.target_labels, 2, topk, testk, self.batch_size ) generated_topk_classes = generated_get_k_best_classes( self.generated_model, self.input_data, self.target_labels, 2, topk, testk, self.batch_size ) self.assertEqual(canonical_topk_classes.shape, generated_topk_classes.shape, f"Shape mismatch: Canonical={canonical_topk_classes.shape}, Generated={generated_topk_classes.shape}") self.assertEqual(canonical_topk_classes.dtype, generated_topk_classes.dtype, f"Dtype mismatch: Canonical={canonical_topk_classes.dtype}, Generated={generated_topk_classes.dtype}") torch.testing.assert_close(canonical_topk_classes, generated_topk_classes, msg="Mismatch in get_k_best_target_classes outputs (standard).") print("get_k_best_target_classes (standard) test passed.") # Test Case 2: `testk` is None canonical_topk_classes_all_candidates = canonical_get_k_best_classes( self.canonical_model, self.input_data, self.target_labels, 2, topk, testk=None, batch_size=self.batch_size ) generated_topk_classes_all_candidates = generated_get_k_best_classes( self.generated_model, self.input_data, self.target_labels, 2, topk, testk=None, batch_size=self.batch_size ) self.assertEqual(canonical_topk_classes_all_candidates.shape, generated_topk_classes_all_candidates.shape, f"Shape mismatch (all candidates): Canonical={canonical_topk_classes_all_candidates.shape}, Generated={generated_topk_classes_all_candidates.shape}") torch.testing.assert_close(canonical_topk_classes_all_candidates, generated_topk_classes_all_candidates, msg="Mismatch in get_k_best_target_classes outputs (all candidates).") print("get_k_best_target_classes (all candidates) test passed.") # Test Case 3: `topk` is greater than available classes large_topk = self.num_classes + 5 expected_clipped_k = self.num_classes - 1 canonical_topk_classes_large_k = canonical_get_k_best_classes( self.canonical_model, self.input_data, self.target_labels, 2, large_topk, testk=None, batch_size=self.batch_size ) generated_topk_classes_large_k = generated_get_k_best_classes( self.generated_model, self.input_data, self.target_labels, 2, large_topk, testk=None, batch_size=self.batch_size ) self.assertEqual(canonical_topk_classes_large_k.shape, (self.num_images, expected_clipped_k), f"Canonical output shape mismatch for large topk: Expected ({self.num_images}, {expected_clipped_k}), Got {canonical_topk_classes_large_k.shape}") self.assertEqual(generated_topk_classes_large_k.shape, (self.num_images, expected_clipped_k), f"Generated output shape mismatch for large topk: Expected ({self.num_images}, {expected_clipped_k}), Got {generated_topk_classes_large_k.shape}") torch.testing.assert_close(canonical_topk_classes_large_k, generated_topk_classes_large_k, msg="Mismatch in get_k_best_target_classes outputs (large topk).") print("get_k_best_target_classes (large topk) test passed.") if __name__ == '__main__': unittest.main(verbosity=2)