| import numpy as np |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
| import torchvision |
| import torchvision.transforms as transforms |
| from utils.carlini_wagner_l2 import carlini_wagner_l2 |
| import matplotlib.pyplot as plt |
| from tqdm import tqdm |
| import os |
|
|
| |
| def set_seed(seed): |
| torch.manual_seed(seed) |
| torch.cuda.manual_seed(seed) |
| torch.cuda.manual_seed_all(seed) |
| np.random.seed(seed) |
| torch.backends.cudnn.deterministic = True |
| torch.backends.cudnn.benchmark = False |
|
|
| set_seed(42) |
|
|
| |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| print(f"Using device: {device}") |
|
|
| |
| def load_cifar10(): |
| transform_test = transforms.Compose([ |
| transforms.ToTensor(), |
| ]) |
| testset = torchvision.datasets.CIFAR10(root='./data', train=False, |
| download=True, transform=transform_test) |
| testloader = torch.utils.data.DataLoader(testset, batch_size=1, |
| shuffle=False, num_workers=2) |
| return testloader |
|
|
| |
| def load_model(): |
| model = torchvision.models.resnet50(pretrained=True) |
| |
| |
| num_ftrs = model.fc.in_features |
| model.fc = nn.Linear(num_ftrs, 10) |
| |
| |
| try: |
| weight_path = "/share/pretrained_weights/cifar10_resnet50_cross_entropy.model" |
| if os.path.exists(weight_path): |
| state_dict = torch.load(weight_path) |
| model.load_state_dict(state_dict) |
| print(f"Loaded pretrained weights from {weight_path}") |
| else: |
| print(f"Warning: Pretrained weights not found at {weight_path}") |
| print("Using ImageNet pretrained weights with modified final layer") |
| except Exception as e: |
| print(f"Error loading pretrained weights: {e}") |
| |
| model = model.to(device) |
| model.eval() |
| return model |
|
|
| |
| def test_cw_attack_on_sample(model, inputs, labels): |
| model.eval() |
| inputs = inputs.to(device) |
| labels = labels.to(device) |
| |
| |
| with torch.no_grad(): |
| outputs = model(inputs) |
| _, predicted = torch.max(outputs, 1) |
| |
| print(f"Original prediction: {predicted.item()}, True label: {labels.item()}") |
| print(f"Model output shape: {outputs.shape}") |
| print(f"Confidence: {F.softmax(outputs, dim=1).max().item():.4f}") |
| |
| |
| def model_fn(x): |
| return model(x) |
| |
| |
| print("Running CW attack...") |
| try: |
| adv_inputs = carlini_wagner_l2( |
| model_fn=model_fn, |
| x=inputs, |
| n_classes=10, |
| y=predicted, |
| targeted=False, |
| lr=0.005, |
| binary_search_steps=5, |
| max_iterations=500, |
| confidence=0, |
| clip_min=0.0, |
| clip_max=1.0, |
| early_stop=True |
| ) |
| |
| |
| with torch.no_grad(): |
| adv_outputs = model(adv_inputs) |
| _, adv_predicted = torch.max(adv_outputs, 1) |
| |
| |
| perturbation = adv_inputs - inputs |
| l2_norm = torch.norm(perturbation.view(perturbation.shape[0], -1), p=2, dim=1) |
| |
| print(f"Adversarial prediction: {adv_predicted.item()}") |
| print(f"Attack success: {adv_predicted.item() != predicted.item()}") |
| print(f"L2 perturbation norm: {l2_norm.item():.4f}") |
| print(f"Adversarial confidence: {F.softmax(adv_outputs, dim=1).max().item():.4f}") |
| |
| |
| plt.figure(figsize=(12, 5)) |
| plt.subplot(1, 3, 1) |
| plt.title(f"Original: {predicted.item()}") |
| plt.imshow(inputs[0].cpu().permute(1, 2, 0).numpy()) |
| plt.axis('off') |
| |
| plt.subplot(1, 3, 2) |
| plt.title(f"Adversarial: {adv_predicted.item()}") |
| plt.imshow(adv_inputs[0].cpu().permute(1, 2, 0).numpy()) |
| plt.axis('off') |
| |
| plt.subplot(1, 3, 3) |
| plt.title(f"Difference (x10)") |
| diff = (adv_inputs - inputs)[0].cpu().permute(1, 2, 0).numpy() |
| |
| plt.imshow((diff * 10 + 0.5).clip(0, 1)) |
| plt.axis('off') |
| |
| plt.savefig(f"cw_attack_sample_{labels.item()}.png") |
| plt.close() |
| |
| return adv_predicted.item() != predicted.item(), l2_norm.item() |
| |
| except Exception as e: |
| print(f"Error in CW attack: {e}") |
| return False, 0.0 |
|
|
| |
| def test_cw_attack_multiple_samples(model, testloader, num_samples=10): |
| success_count = 0 |
| total_samples = 0 |
| l2_norms = [] |
| |
| for i, (inputs, labels) in enumerate(testloader): |
| if i >= num_samples: |
| break |
| |
| print(f"\n--- Sample {i+1}/{num_samples} ---") |
| success, l2_norm = test_cw_attack_on_sample(model, inputs, labels) |
| |
| if success: |
| success_count += 1 |
| l2_norms.append(l2_norm) |
| |
| total_samples += 1 |
| |
| success_rate = (success_count / total_samples) * 100 |
| avg_l2_norm = np.mean(l2_norms) if l2_norms else 0.0 |
| |
| print(f"\nResults on {total_samples} samples:") |
| print(f"Success rate: {success_rate:.2f}%") |
| print(f"Average L2 norm of successful perturbations: {avg_l2_norm:.4f}") |
| |
| return success_rate, avg_l2_norm |
|
|
| if __name__ == "__main__": |
| print("Loading CIFAR-10 dataset...") |
| testloader = load_cifar10() |
| |
| print("Loading model...") |
| model = load_model() |
| |
| print("Testing CW attack...") |
| success_rate, avg_l2_norm = test_cw_attack_multiple_samples(model, testloader, num_samples=5) |