| 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 |
| from tqdm import tqdm |
| import os |
| import json |
| import time |
| from sklearn.calibration import calibration_curve |
|
|
| |
| 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}") |
|
|
| |
| TEST_RESULTS_DIR = "test_results" |
| os.makedirs(TEST_RESULTS_DIR, exist_ok=True) |
|
|
| |
| def load_cifar10(batch_size=1): |
| 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=batch_size, |
| shuffle=False, num_workers=2) |
| return testloader, testset |
|
|
| |
| 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 get_feature_extractor(model): |
| class FeatureExtractor(nn.Module): |
| def __init__(self, model): |
| super().__init__() |
| self.model = model |
| self.features = None |
| |
| |
| def hook_fn(module, input, output): |
| self.features = output |
| |
| |
| model.avgpool.register_forward_hook(hook_fn) |
| |
| def forward(self, x): |
| logits = self.model(x) |
| return self.features, logits |
| |
| return FeatureExtractor(model).to(device) |
|
|
| |
| def compute_hardness_cw_logits(model, inputs, logits, debug=True): |
| """ |
| 通过在logits上使用CW L2攻击来计算样本的硬度 |
| |
| Args: |
| model: 模型 |
| inputs: 输入样本 |
| logits: 样本的logits |
| debug: 是否打印调试信息 |
| |
| Returns: |
| hardness: 样本硬度值 |
| success: 攻击是否成功 |
| """ |
| model.eval() |
| inputs = inputs.to(device) |
| |
| |
| with torch.no_grad(): |
| if logits is None: |
| outputs = model(inputs) |
| else: |
| outputs = logits |
| |
| original_pred = torch.argmax(outputs, 1) |
| probs = F.softmax(outputs, dim=1) |
| confidence = probs.max(dim=1)[0].item() |
| |
| if debug: |
| print(f"Original prediction: {original_pred.item()}, confidence: {confidence:.4f}") |
| |
| |
| class LogitsModel(nn.Module): |
| def __init__(self): |
| super().__init__() |
| |
| def forward(self, x): |
| return x |
| |
| logits_model = LogitsModel().to(device) |
| |
| |
| def model_fn(x): |
| return logits_model(x) |
| |
| |
| logits_input = outputs.detach().clone() |
| |
| |
| try: |
| if debug: |
| print("Running CW attack on logits with parameters:") |
| print(f"- Binary search steps: 5") |
| print(f"- Max iterations: 300") |
| print(f"- Learning rate: 0.01") |
| print(f"- Early stop: True") |
| |
| |
| logits_min = float(logits_input.min()) |
| logits_max = float(logits_input.max()) |
| |
| adv_logits, l2_norms, success_mask = carlini_wagner_l2( |
| model_fn=model_fn, |
| x=logits_input, |
| n_classes=logits_input.shape[1], |
| y=original_pred, |
| targeted=False, |
| lr=0.01, |
| binary_search_steps=5, |
| max_iterations=300, |
| confidence=0, |
| clip_min=logits_min, |
| clip_max=logits_max, |
| debug=debug, |
| early_stop=True |
| ) |
| |
| |
| adv_pred = torch.argmax(adv_logits, 1) |
| adv_probs = F.softmax(adv_logits, dim=1) |
| adv_confidence = adv_probs.max(dim=1)[0].item() |
| |
| |
| attack_success = success_mask.any().item() |
| |
| |
| l2_val = l2_norms[0].item() if l2_norms.numel() > 0 else 0.0 |
| |
| if debug: |
| print(f"Attack result: {'SUCCESS' if attack_success else 'FAILURE'}") |
| print(f"Adversarial prediction: {adv_pred.item()}, confidence: {adv_confidence:.4f}") |
| print(f"L2 perturbation norm in logits space: {l2_val:.4f}") |
| |
| if attack_success: |
| |
| |
| |
| logits_l2_max = 10.0 |
| mapped_hardness = 10.0 * min(l2_val, logits_l2_max) / logits_l2_max |
| if debug: |
| print(f"Mapped hardness (CW logits): {mapped_hardness:.4f}") |
| |
| return mapped_hardness, True |
| else: |
| |
| if debug: |
| print("Attack failed in logits space - using high hardness value 9.0") |
| return 9.0, False |
| |
| except Exception as e: |
| if debug: |
| print(f"Error in logits CW attack: {e}") |
| |
| logits_tensor = torch.tensor(outputs.cpu().numpy(), dtype=torch.float32) |
| original_pred = torch.argmax(logits_tensor).item() |
| |
| |
| sorted_logits, _ = torch.sort(logits_tensor, descending=True) |
| logit_gap = (sorted_logits[0][0] - sorted_logits[0][1]).item() |
| |
| |
| logit_gap_score = 5.0 + 5.0 * (logit_gap / (logit_gap + 1.0)) |
| if debug: |
| print(f"Using fallback logit gap hardness due to error: {logit_gap_score:.4f}") |
| return logit_gap_score, False |
|
|
| |
| def compute_hardness_gaussian_logits(model, inputs, num_trials=100, noise_std_range=(0.1, 5.0), debug=True): |
| """ |
| 通过在logits上添加高斯噪声来计算样本的硬度 |
| |
| Args: |
| model: 模型 |
| inputs: 输入样本 |
| num_trials: 每个噪声级别的试验次数 |
| noise_std_range: 噪声标准差范围 |
| debug: 是否打印调试信息 |
| |
| Returns: |
| hardness: 样本硬度值 |
| """ |
| model.eval() |
| inputs = inputs.to(device) |
| |
| |
| with torch.no_grad(): |
| logits = model(inputs) |
| original_pred = torch.argmax(logits, 1).item() |
| |
| |
| noise_stds = np.linspace(noise_std_range[0], noise_std_range[1], 10) |
| |
| |
| pred_changes = [] |
| |
| for noise_std in noise_stds: |
| changes = 0 |
| for _ in range(num_trials): |
| |
| noise = torch.randn_like(logits) * noise_std |
| noisy_logits = logits + noise |
| noisy_pred = torch.argmax(noisy_logits, 1).item() |
| |
| |
| if noisy_pred != original_pred: |
| changes += 1 |
| |
| |
| change_rate = changes / num_trials |
| pred_changes.append(change_rate) |
| |
| |
| if change_rate > 0.5: |
| break |
| |
| |
| threshold_idx = next((i for i, rate in enumerate(pred_changes) if rate >= 0.2), len(noise_stds) - 1) |
| threshold_std = noise_stds[threshold_idx] |
| |
| |
| |
| |
| max_std = noise_std_range[1] |
| mapped_hardness = 10.0 * min(threshold_std, max_std) / max_std |
| |
| if debug: |
| print(f"Original prediction: {original_pred}") |
| print(f"Threshold noise std: {threshold_std:.4f}") |
| print(f"Mapped hardness (gaussian logits): {mapped_hardness:.4f}") |
| |
| return mapped_hardness, True |
|
|
| |
| def compute_hardness_gaussian_features(model, inputs, feature_extractor, num_trials=100, noise_std_range=(0.1, 1.0), debug=True): |
| """ |
| 通过在特征上添加高斯噪声来计算样本的硬度 |
| |
| Args: |
| model: 模型 |
| inputs: 输入样本 |
| feature_extractor: 特征提取器 |
| num_trials: 每个噪声级别的试验次数 |
| noise_std_range: 噪声标准差范围 |
| debug: 是否打印调试信息 |
| |
| Returns: |
| hardness: 样本硬度值 |
| """ |
| model.eval() |
| feature_extractor.eval() |
| inputs = inputs.to(device) |
| |
| |
| with torch.no_grad(): |
| features, logits = feature_extractor(inputs) |
| original_pred = torch.argmax(logits, 1).item() |
| features = features.squeeze() |
| |
| |
| noise_stds = np.linspace(noise_std_range[0], noise_std_range[1], 10) |
| |
| |
| pred_changes = [] |
| |
| |
| def features_to_logits(feats): |
| |
| feats = feats.view(feats.size(0), -1) |
| return model.fc(feats) |
| |
| for noise_std in noise_stds: |
| changes = 0 |
| for _ in range(num_trials): |
| |
| noise = torch.randn_like(features) * noise_std |
| noisy_features = features + noise |
| |
| |
| noisy_logits = features_to_logits(noisy_features.unsqueeze(0)) |
| noisy_pred = torch.argmax(noisy_logits, 1).item() |
| |
| |
| if noisy_pred != original_pred: |
| changes += 1 |
| |
| |
| change_rate = changes / num_trials |
| pred_changes.append(change_rate) |
| |
| |
| if change_rate > 0.5: |
| break |
| |
| |
| threshold_idx = next((i for i, rate in enumerate(pred_changes) if rate >= 0.2), len(noise_stds) - 1) |
| threshold_std = noise_stds[threshold_idx] |
| |
| |
| |
| |
| max_std = noise_std_range[1] |
| mapped_hardness = 10.0 * min(threshold_std, max_std) / max_std |
| |
| if debug: |
| print(f"Original prediction: {original_pred}") |
| print(f"Threshold noise std: {threshold_std:.4f}") |
| print(f"Mapped hardness (gaussian features): {mapped_hardness:.4f}") |
| |
| return mapped_hardness, True |
|
|
| |
| def compute_hardness_cw_features(model, inputs, feature_extractor, debug=True): |
| """ |
| 通过在特征空间上使用CW攻击来计算样本的硬度 |
| |
| Args: |
| model: 模型 |
| inputs: 输入样本 |
| feature_extractor: 特征提取器 |
| debug: 是否打印调试信息 |
| |
| Returns: |
| hardness: 样本硬度值 |
| """ |
| model.eval() |
| feature_extractor.eval() |
| inputs = inputs.to(device) |
| |
| |
| with torch.no_grad(): |
| features, logits = feature_extractor(inputs) |
| original_pred = torch.argmax(logits, 1) |
| features = features.squeeze() |
| |
| |
| class FeatureWrapper(nn.Module): |
| def __init__(self, model): |
| super().__init__() |
| self.fc = model.fc |
| |
| def forward(self, x): |
| x = x.view(x.size(0), -1) |
| return self.fc(x) |
| |
| feature_model = FeatureWrapper(model).to(device) |
| |
| |
| def model_fn(x): |
| return feature_model(x) |
| |
| |
| try: |
| if debug: |
| print("Running CW attack on features with parameters:") |
| print(f"- Binary search steps: 5") |
| print(f"- Max iterations: 300") |
| print(f"- Learning rate: 0.01") |
| print(f"- Early stop: True") |
| |
| |
| feature_input = features.unsqueeze(0) |
| |
| |
| adv_features, l2_norms, success_mask = carlini_wagner_l2( |
| model_fn=model_fn, |
| x=feature_input, |
| n_classes=logits.shape[1], |
| y=original_pred, |
| targeted=False, |
| lr=0.01, |
| binary_search_steps=5, |
| max_iterations=300, |
| confidence=0, |
| clip_min=float(feature_input.min()), |
| clip_max=float(feature_input.max()), |
| debug=debug, |
| early_stop=True |
| ) |
| |
| |
| with torch.no_grad(): |
| adv_logits = feature_model(adv_features) |
| adv_pred = torch.argmax(adv_logits, 1) |
| |
| |
| attack_success = success_mask.any().item() |
| |
| |
| l2_val = l2_norms[0].item() if l2_norms.numel() > 0 else 0.0 |
| |
| if debug: |
| print(f"Attack result: {'SUCCESS' if attack_success else 'FAILURE'}") |
| print(f"Original prediction: {original_pred.item()}") |
| print(f"Adversarial prediction: {adv_pred.item()}") |
| print(f"L2 perturbation norm in feature space: {l2_val:.4f}") |
| |
| if attack_success: |
| |
| |
| |
| feature_l2_max = 2.0 |
| mapped_hardness = 10.0 * min(l2_val, feature_l2_max) / feature_l2_max |
| if debug: |
| print(f"Mapped hardness (CW features): {mapped_hardness:.4f}") |
| |
| return mapped_hardness, True |
| else: |
| |
| if debug: |
| print("Attack failed in feature space - using high hardness value 9.0") |
| return 9.0, False |
| |
| except Exception as e: |
| if debug: |
| print(f"Error in feature CW attack: {e}") |
| |
| logits_tensor = torch.tensor(logits.cpu().numpy(), dtype=torch.float32) |
| original_pred = torch.argmax(logits_tensor).item() |
| |
| |
| sorted_logits, _ = torch.sort(logits_tensor, descending=True) |
| logit_gap = (sorted_logits[0][0] - sorted_logits[0][1]).item() |
| |
| |
| logit_gap_score = 5.0 + 5.0 * (logit_gap / (logit_gap + 1.0)) |
| if debug: |
| print(f"Using fallback logit gap hardness due to error: {logit_gap_score:.4f}") |
| return logit_gap_score, False |
|
|
| |
| def compute_ece(probs, labels, n_bins=15): |
| """计算ECE (Expected Calibration Error)""" |
| bin_boundaries = np.linspace(0, 1, n_bins + 1) |
| bin_lowers = bin_boundaries[:-1] |
| bin_uppers = bin_boundaries[1:] |
| |
| confidences = np.max(probs, axis=1) |
| predictions = np.argmax(probs, axis=1) |
| accuracies = (predictions == labels) |
| |
| ece = 0.0 |
| for bin_lower, bin_upper in zip(bin_lowers, bin_uppers): |
| in_bin = np.logical_and(confidences > bin_lower, confidences <= bin_upper) |
| prop_in_bin = np.mean(in_bin) |
| if prop_in_bin > 0: |
| accuracy_in_bin = np.mean(accuracies[in_bin]) |
| avg_confidence_in_bin = np.mean(confidences[in_bin]) |
| ece += np.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin |
| |
| return ece |
|
|
| |
| class TemperatureScaling: |
| """标准温度缩放校准方法""" |
| def __init__(self, temp=1.0): |
| self.temp = temp |
| |
| def fit(self, logits, labels): |
| """通过最小化验证集上的NLL找到最优温度""" |
| from scipy.optimize import minimize |
| |
| def objective(temp, logits, labels): |
| scaled_logits = logits / temp |
| probs = F.softmax(torch.tensor(scaled_logits), dim=1).numpy() |
| nll = -np.mean(np.log(probs[np.arange(len(labels)), labels] + 1e-10)) |
| return nll |
| |
| |
| res = minimize(lambda t: objective(t, logits, labels), |
| x0=np.array([self.temp]), method='BFGS') |
| self.temp = res.x[0] |
| |
| def calibrate(self, logits): |
| """应用温度缩放到logits""" |
| scaled_logits = logits / self.temp |
| return F.softmax(torch.tensor(scaled_logits), dim=1).numpy() |
|
|
| |
| def compare_hardness_methods(model, testloader, num_samples=50, run_methods=None): |
| """ |
| 比较不同硬度计算方法的校准效果 |
| |
| Args: |
| model: 要评估的模型 |
| testloader: 测试数据加载器 |
| num_samples: 要评估的样本数量 |
| run_methods: 要运行的方法列表,可选值:['cw_logits', 'gaussian_logits', 'gaussian_features', 'cw_features'] |
| 如果为None,则运行所有方法 |
| """ |
| feature_extractor = get_feature_extractor(model) |
| |
| |
| all_methods = { |
| 'cw_logits': {'hardness_values': [], 'temps': [], 'func': compute_hardness_cw_logits}, |
| 'gaussian_logits': {'hardness_values': [], 'temps': [], 'func': compute_hardness_gaussian_logits}, |
| 'gaussian_features': {'hardness_values': [], 'temps': [], 'func': compute_hardness_gaussian_features}, |
| 'cw_features': {'hardness_values': [], 'temps': [], 'func': compute_hardness_cw_features} |
| } |
| |
| |
| if run_methods is None: |
| |
| methods = all_methods |
| method_names = list(all_methods.keys()) |
| else: |
| |
| methods = {method: all_methods[method] for method in run_methods if method in all_methods} |
| method_names = run_methods |
| |
| if not methods: |
| print("警告: 未指定有效的方法,将运行所有方法") |
| methods = all_methods |
| method_names = list(all_methods.keys()) |
| else: |
| print(f"将运行以下方法: {', '.join(method_names)}") |
| |
| all_logits = [] |
| all_labels = [] |
| |
| |
| print(f"Calculating hardness using different methods for {num_samples} samples...") |
| |
| for i, (inputs, labels) in enumerate(tqdm(testloader)): |
| if i >= num_samples: |
| break |
| |
| inputs = inputs.to(device) |
| labels = labels.to(device) |
| |
| |
| with torch.no_grad(): |
| logits = model(inputs) |
| |
| all_logits.append(logits.cpu().numpy()) |
| all_labels.append(labels.cpu().numpy()) |
| |
| print(f"\n------ Sample {i+1}/{num_samples} ------") |
| |
| |
| for idx, method_name in enumerate(method_names): |
| method_info = methods[method_name] |
| func = method_info['func'] |
| |
| print(f"\nMethod {idx+1}: {method_name}") |
| |
| |
| if method_name == 'cw_logits': |
| hardness, _ = func(model, inputs, logits, debug=True) |
| elif method_name == 'gaussian_logits': |
| hardness, _ = func(model, inputs, debug=True) |
| elif method_name in ['gaussian_features', 'cw_features']: |
| hardness, _ = func(model, inputs, feature_extractor, debug=True) |
| |
| methods[method_name]['hardness_values'].append(hardness) |
| |
| print("----------------------------------------\n") |
| |
| |
| all_logits = np.vstack(all_logits) |
| all_labels = np.hstack(all_labels) |
| |
| |
| for method_name, method_data in methods.items(): |
| |
| hardness_temps = [0.5 + 1.5 * (h / 10.0) for h in method_data['hardness_values']] |
| methods[method_name]['temps'] = hardness_temps |
| |
| |
| print("\nEvaluating calibration performance...") |
| |
| |
| uncal_probs = F.softmax(torch.tensor(all_logits), dim=1).numpy() |
| uncal_ece = compute_ece(uncal_probs, all_labels) |
| uncal_acc = np.mean(np.argmax(uncal_probs, axis=1) == all_labels) |
| |
| |
| ts = TemperatureScaling() |
| ts.fit(all_logits, all_labels) |
| ts_probs = ts.calibrate(all_logits) |
| ts_ece = compute_ece(ts_probs, all_labels) |
| ts_acc = np.mean(np.argmax(ts_probs, axis=1) == all_labels) |
| |
| |
| results = { |
| 'uncal': {'ece': uncal_ece, 'acc': uncal_acc}, |
| 'ts': {'ece': ts_ece, 'acc': ts_acc, 'temp': ts.temp} |
| } |
| |
| for method_name, method_data in methods.items(): |
| hardness_temps = method_data['temps'] |
| shats_probs = [] |
| |
| for i, logits in enumerate(all_logits): |
| temp = hardness_temps[i] if i < len(hardness_temps) else 1.0 |
| scaled_logits = logits / temp |
| probs = F.softmax(torch.tensor(scaled_logits), dim=1).numpy() |
| shats_probs.append(probs) |
| |
| shats_probs = np.vstack(shats_probs) |
| shats_ece = compute_ece(shats_probs, all_labels) |
| shats_acc = np.mean(np.argmax(shats_probs, axis=1) == all_labels) |
| |
| results[method_name] = { |
| 'ece': shats_ece, |
| 'acc': shats_acc, |
| 'hardness_values': method_data['hardness_values'], |
| 'temps': hardness_temps, |
| 'avg_hardness': np.mean(method_data['hardness_values']), |
| 'avg_temp': np.mean(hardness_temps) |
| } |
| |
| |
| print("\nCalibration Results:") |
| print(f"Number of samples: {len(all_labels)}") |
| print(f"TS optimal temperature: {ts.temp:.4f}") |
| print("\nMethod Avg Hardness Avg Temp Accuracy ECE") |
| print("-" * 60) |
| print(f"Uncal - - {uncal_acc:.4f} {uncal_ece:.4f}") |
| print(f"TS - {ts.temp:.4f} {ts_acc:.4f} {ts_ece:.4f}") |
| |
| for method_name, method_results in results.items(): |
| if method_name not in ['uncal', 'ts']: |
| print(f"{method_name:<10} {method_results['avg_hardness']:.4f} {method_results['avg_temp']:.4f} {method_results['acc']:.4f} {method_results['ece']:.4f}") |
| |
| |
| save_path = os.path.join(TEST_RESULTS_DIR, "hardness_methods_comparison.json") |
| with open(save_path, 'w') as f: |
| json.dump(results, f, indent=4, default=float) |
| |
| print(f"\nResults saved to {save_path}") |
| |
| |
| print("\nCalculating correlations between hardness methods...") |
| correlations = {} |
| |
| if len(methods) > 1: |
| method_names = list(methods.keys()) |
| for i, method1 in enumerate(method_names): |
| for method2 in method_names[i+1:]: |
| h1 = methods[method1]['hardness_values'] |
| h2 = methods[method2]['hardness_values'] |
| |
| min_len = min(len(h1), len(h2)) |
| |
| if min_len > 0: |
| corr = np.corrcoef(h1[:min_len], h2[:min_len])[0, 1] |
| correlations[f"{method1}_vs_{method2}"] = corr |
| print(f"Correlation between {method1} and {method2}: {corr:.4f}") |
| else: |
| print("只有一种方法被运行,无法计算相关性") |
| |
| |
| results['correlations'] = correlations |
| |
| |
| with open(save_path, 'w') as f: |
| json.dump(results, f, indent=4, default=float) |
| |
| return results |
|
|
| if __name__ == "__main__": |
| print("Loading CIFAR-10 dataset...") |
| testloader, _ = load_cifar10(batch_size=1) |
| |
| print("Loading model...") |
| model = load_model() |
| |
| |
| |
| run_methods = ['gaussian_logits', 'gaussian_features'] |
| |
| print("\n--- Comparing different hardness calculation methods ---") |
| start_time = time.time() |
| results = compare_hardness_methods(model, testloader, num_samples=20, run_methods=run_methods) |
| end_time = time.time() |
| |
| print(f"Total execution time: {(end_time - start_time) / 60:.2f} minutes") |
| print(f"Results saved to {TEST_RESULTS_DIR}/hardness_methods_comparison.json") |