AI模型安全:对抗攻击与防御技术全景
AI模型面临的安全威胁远超传统软件。对抗攻击可以在人眼不可察觉的扰动下让模型完全失效,数据投毒可以在训练阶段植入后门,模型窃取可以复制商业模型的能力。本文将系统梳理AI安全威胁模型和防御技术,帮助构建更鲁棒的AI系统。
一、对抗攻击基础
1.1 对抗样本的生成
import torch import torch.nn as nn import torch.nn.functional as F class AdversarialAttacks: """对抗攻击方法""" def __init__(self, model): self.model = model self.model.eval() def fgsm_attack(self, image, epsilon, data_grad): """ FGSM: Fast Gradient Sign Method 沿梯度方向添加扰动 """ # 收集梯度的元素符号 sign_data_grad = data_grad.sign() # 创建对抗样本 perturbed_image = image + epsilon * sign_data_grad # 保持像素值在有效范围 perturbed_image = torch.clamp(perturbed_image, 0, 1) return perturbed_image def pgd_attack(self, image, label, epsilon, alpha, num_iter): """ PGD: Projected Gradient Descent 迭代式攻击,更强的对抗样本 """ perturbed_image = image.clone().detach() for _ in range(num_iter): perturbed_image.requires_grad = True # 前向传播 output = self.model(perturbed_image) loss = F.cross_entropy(output, label) # 反向传播 self.model.zero_grad() loss.backward() # 更新对抗样本 with torch.no_grad(): perturbed_image = perturbed_image + alpha * perturbed_image.grad.sign() # 投影回epsilon球 perturbation = torch.clamp(perturbed_image - image, -epsilon, epsilon) perturbed_image = torch.clamp(image + perturbation, 0, 1) return perturbed_image.detach() def cw_attack(self, image, label, c=1e-4, kappa=0, max_iter=1000, lr=0.01): """ C&W攻击: 优化-based攻击,通常能绕过防御 """ # 定义优化变量 w = torch.atanh((image - 0.5) * 1.99999) w.requires_grad = True optimizer = torch.optim.Adam([w], lr=lr) for step in range(max_iter): # 从w重构图像 adv_image = 0.5 * torch.tanh(w) + 0.5 # 计算损失 output = self.model(adv_image) # f函数:确保目标类别得分最高 real = output[0, label] other = torch.max(output[0, torch.arange(len(output[0])) != label]) f_loss = torch.clamp(other - real + kappa, min=0) # L2距离 l2_dist = torch.sum((adv_image - image) ** 2) # 总损失 loss = l2_dist + c * f_loss optimizer.zero_grad() loss.backward() optimizer.step() # 检查是否成功 if f_loss.item() == 0: break return adv_image.d