Skip to content

About

AI安全算法层面的技术实践,涵盖对抗样本攻击、模型后门攻击、AI数据隐私窃取、数据投毒攻击、预训练模型安全五大模块。为快速测试,该算法合集以lenet与mnist作为测试样本,技术前沿性截至2023年,不涉及LLM,读者可自行迁移

Resources

Stars

7 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AI Security Algorithm Practice

AI安全算法层面的技术实践

涵盖对抗样本攻击、模型后门攻击、AI数据隐私窃取、数据投毒攻击、预训练模型安全五大模块


项目简介

本项目是一个AI安全算法的技术实践合集,专注于深度学习模型在训练和推理阶段面临的安全威胁。通过43个实验任务,系统性地复现和验证了AI安全领域的经典攻击与防御方法。

核心特点:

  • 算法层面: 聚焦算法原理与实现,而非工程化部署
  • 快速验证: 基于LeNet-5 + MNIST的轻量级实验环境
  • 技术前沿: 覆盖截至2023年的主流AI安全技术
  • 可迁移性: 不涉及LLM,读者可自行迁移至其他模型架构

模块架构

AI Security Practice
├── 模块一: 对抗样本攻击 (Adversarial Example Attack)
├── 模块二: 数据投毒攻击 (Data Poisoning Attack)
├── 模块三: 模型后门攻击 (Model Backdoor Attack)
├── 模块四: AI数据隐私窃取 (Data Privacy Attack)
└── 模块五: 预训练模型安全 (Pretrained Model Security)

模块详解

模块一: 对抗样本攻击

核心思想: 在输入数据上添加人眼不可见的扰动,导致模型产生错误预测。

任务 攻击方法 攻击类型 核心算法
01 FGSM 白盒 Fast Gradient Sign Method
02 CW L2 白盒 Carlini-Wagner Attack
03 PBA-AML 黑盒 Prior-Based Boundary Attack
04 ZOO 黑盒 Zeroth Order Optimization
05 CTC Speech 黑盒 CTC Loss Attack
06 DeepSpeech 黑盒 Audio Adversarial Examples
07 FASM 白盒 Feature Adversarial Sparse Mask
08 Physical Attack 物理 Faster R-CNN Physical Attack

关键发现:

  • FGSM: ε=0.3时攻击成功率94.69%
  • CW L2: 攻击成功率100%,扰动更小
  • 黑盒攻击: 需要5000-10000次查询

模块二: 数据投毒攻击

核心思想: 在训练数据中注入恶意样本,影响模型训练过程。

任务 攻击方法 投毒类型 核心算法
09 Text Trigger 后门 文本触发器注入
10 Non-targeted 非目标 随机标签翻转
11 Targeted 目标 特定样本定向攻击
12 GAN Poisoning 生成式 GAN生成投毒样本
13 Feature Collision 特征 特征空间碰撞攻击
14 RecolorAdv 物理 颜色空间对抗
15 Continuous KTT 优化 核触发器攻击
16 Multistep SGD 优化 多步SGD攻击
17 Retrieval Poisoning 检索 检索系统投毒
18 Taylor Poisoning 优化 Taylor展开优化

关键发现:

  • 非目标投毒: 测试准确率仅下降0.37%,但训练过程被污染
  • 目标投毒: 50%投毒比例时攻击成功率70%
  • 文本触发器: 100%攻击成功率

模块三: 模型后门攻击

核心思想: 在模型中植入隐藏后门,仅在特定触发条件下激活恶意行为。

任务 攻击方法 后门类型 核心算法
19 Backdoor Non-clean 投毒式 非干净标签后门
20 Backdoor Clean 投毒式 干净标签后门
21 KDTree Poisoning 投毒式 KD树投毒攻击
22 Ensemble Poisoning 投毒式 集成投毒攻击
23 Model Stealing 非投毒式 模型窃取攻击
24 RNN Evasion 非投毒式 RNN逃逸攻击
25 Feature Replace 非投毒式 特征替换攻击
26 Backdoor Non-clean 投毒式 供应链后门
27 Backdoor Clean 投毒式 供应链干净后门
28 Weight Attack 非投毒式 权重空间攻击
29 Structure Attack 非投毒式 结构空间攻击
30 Supply Chain 供应链 模型库后门植入
31 Neuron Trigger 触发器 神经元触发器优化

关键发现:

  • 干净标签后门: 更难被检测,触发器融入原始内容
  • 供应链攻击: 在HuggingFace等平台植入后门模型
  • 神经元触发器: 针对特定神经元设计触发模式

模块四: AI数据隐私窃取

核心思想: 从模型输出或梯度信息中恢复训练数据或推断敏感信息。

任务 攻击方法 隐私类型 核心算法
32 Data Leakage 数据泄露 生成内容恢复训练数据
33 Sensitive Generation 敏感生成 LLM敏感信息生成
34 Supply Chain Pretrained 供应链 预训练模型后门
35 DAPT 持续攻击 Domain-Adaptive Pre-training
36 ATCON 对比攻击 Adversarial Contrastive Learning
37 Blacklist PPLM 控制攻击 PPLM黑名单绕过
38 GEDI 控制攻击 GeDi控制生成
39 Self Diagnosis 诊断攻击 模型自我诊断漏洞
40 DLG 梯度泄露 Deep Leakage from Gradients
41 Shadow Model 成员推理 影子模型攻击
42 GAN Membership 成员推理 GAN成员推理攻击
43 Attribute Inference 属性推理 敏感属性推断

关键发现:

  • DLG: 从梯度中完美恢复训练图像
  • 成员推理: 准确率可达70-80%
  • 属性推理: 可推断性别、年龄等敏感属性

模块五: 预训练模型安全

核心思想: 针对大规模预训练模型的安全威胁,包括供应链攻击和持续攻击。

任务 攻击方法 安全类型 核心算法
34 Supply Chain 供应链 预训练模型后门植入
35 DAPT 持续攻击 Domain-Adaptive Pre-training Attack
36 ATCON 对比攻击 Adversarial Contrastive Attack
37 Blacklist PPLM 控制攻击 PPLM控制绕过
38 GEDI 控制攻击 GeDi控制生成攻击
39 Self Diagnosis 诊断攻击 模型自我诊断漏洞

关键发现:

  • 预训练模型后门: 可通过微调传播到下游任务
  • 持续攻击: 在模型更新过程中持续注入威胁
  • 控制攻击: 绕过模型安全控制机制

技术栈

核心框架

  • 深度学习: PyTorch 2.x
  • 数据处理: torchvision, torchaudio
  • 模型库: HuggingFace Transformers
  • 可视化: Matplotlib, Seaborn

实验环境

  • GPU: NVIDIA GeForce RTX 4090
  • Python: 3.11+
  • CUDA: 11.8+

测试模型

  • 图像分类: LeNet-5 (MNIST)
  • 目标检测: Faster R-CNN
  • 语音识别: DeepSpeech, CTC Models
  • 文本生成: GPT-2, BERT

快速开始

环境配置

# 克隆项目
git clone <repository-url>
cd ai-security-study-organized

# 创建虚拟环境
python -m venv venv
source venv/bin/activate  # Linux/Mac
# venv\Scripts\activate  # Windows

# 安装依赖
pip install torch torchvision torchaudio
pip install matplotlib seaborn numpy
pip install transformers datasets

运行示例

# 运行FGSM攻击实验
cd 01_fgsm
python fgsm_lesson.py

# 运行CW攻击实验
cd ../02_cw_attack
python cw_attack.py

# 运行DLG隐私攻击实验
cd ../40_dlg
python run_experiment.py

查看结果

每个任务文件夹包含:

  • README.md: 详细说明文档
  • *.py: 实验代码
  • results/: 实验结果和可视化图表

项目结构

ai-security-study-organized/
├── README.md                          # 项目说明
├── 01_fgsm/                          # FGSM对抗攻击
│   ├── README.md
│   ├── fgsm_lesson.py
│   └── results/
│       ├── epsilon_comparison_grid.png
│       ├── epsilon_vs_accuracy.png
│       ├── fgsm_examples.png
│       └── training_curve.png
├── 02_cw_attack/                     # CW对抗攻击
├── 03_pba_aml/                       # 黑盒对抗攻击
├── ...
└── 43_attribute_inference/           # 属性推理攻击

核心算法速查

对抗样本攻击

# FGSM攻击
def fgsm_attack(image, epsilon, data_grad):
    sign_data_grad = data_grad.sign()
    perturbed_image = image + epsilon * sign_data_grad
    perturbed_image = torch.clamp(perturbed_image, 0, 1)
    return perturbed_image

# CW攻击
def cw_attack(model, image, target, c=1e-4, kappa=0, max_iter=1000):
    # 将图像转换为可优化的变量
    w = torch.atanh(image * 2 - 1).detach().requires_grad_(True)
    optimizer = torch.optim.Adam([w], lr=0.01)
    
    for i in range(max_iter):
        # 优化扰动
        perturbed = (torch.tanh(w) + 1) / 2
        output = model(perturbed)
        loss = cw_loss(output, target, c, kappa)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    
    return perturbed.detach()

数据投毒攻击

# 后门触发器注入
def inject_backdoor(image, trigger, position):
    # 在指定位置插入触发器
    poisoned = image.clone()
    x, y = position
    h, w = trigger.shape[2:]
    poisoned[:, :, x:x+h, y:y+w] = trigger
    return poisoned

# 标签翻转攻击
def label_flipping_attack(dataset, flip_rate=0.1):
    n_flips = int(len(dataset) * flip_rate)
    indices = np.random.choice(len(dataset), n_flips, replace=False)
    
    for idx in indices:
        image, label = dataset[idx]
        # 随机翻转到其他标签
        new_label = random.choice([l for l in range(10) if l != label])
        dataset[idx] = (image, new_label)
    
    return dataset

隐私攻击

# DLG梯度泄露攻击
def dlg_attack(model, gradients, data_size):
    # 初始化dummy数据
    dummy_data = torch.randn(data_size).requires_grad_(True)
    dummy_label = torch.randn(1, 10).requires_grad_(True)
    
    optimizer = torch.optim.LBFGS([dummy_data, dummy_label])
    
    for i in range(300):
        def closure():
            optimizer.zero_grad()
            pred = model(dummy_data)
            loss = cross_entropy(pred, dummy_label)
            dummy_grad = torch.autograd.grad(loss, model.parameters())
            
            # 计算梯度差异
            grad_diff = sum(
                ((dg - g) ** 2).sum()
                for dg, g in zip(dummy_grad, gradients)
            )
            grad_diff.backward()
            return grad_diff
        
        optimizer.step(closure)
    
    return dummy_data, dummy_label

防御方法总结

对抗防御

防御方法 原理 适用场景
对抗训练 使用对抗样本训练模型 通用对抗防御
输入变换 随机裁剪、旋转、滤波 实时防御
检测方法 检测对抗样本特征 入侵检测

投毒防御

防御方法 原理 适用场景
数据清洗 检测并移除异常样本 训练数据净化
鲁棒训练 使用鲁棒损失函数 训练过程防护
模型集成 多模型投票决策 推理阶段防护

后门防御

防御方法 原理 适用场景
模型验证 验证模型来源完整性 供应链安全
安全扫描 检测后门触发模式 模型审计
神经元分析 识别异常激活神经元 运行时检测

隐私防御

防御方法 原理 适用场景
差分隐私 训练时添加噪声 训练数据保护
安全聚合 加密梯度传输 联邦学习
输出过滤 过滤敏感信息 推理阶段防护

参考文献

对抗样本

  1. Goodfellow, I. J., et al. (2014). Explaining and harnessing adversarial examples. ICLR.
  2. Carlini, N., & Wagner, D. (2017). Towards evaluating the robustness of neural networks. IEEE S&P.
  3. Ilyas, A., et al. (2018). Black-box adversarial attacks with limited queries and information. ICML.

数据投毒

  1. Gu, T., et al. (2017). BadNets: Identifying vulnerabilities in the ML model supply chain. arXiv.
  2. Shafahi, A., et al. (2018). Poison frogs! Targeted clean-label poisoning attacks. NeurIPS.

模型后门

  1. Liu, Y., et al. (2018). Trojaning attack on neural networks. NDSS.
  2. Turner, A., et al. (2019). Clean-label backdoor attacks. ICLR.

隐私攻击

  1. Zhu, L., et al. (2019). Deep leakage from gradients. NeurIPS.
  2. Shokri, R., et al. (2017). Membership inference attacks against machine learning models. IEEE S&P.

预训练模型安全

  1. Chen, K., et al. (2021). Targeted backdoor attacks on deep learning systems using data poisoning. arXiv.
  2. Li, S., et al. (2021). Backdoor attacks on pre-trained language models. arXiv.

迁移指南

本项目基于LeNet-5 + MNIST进行快速验证,读者可按以下方式迁移至其他模型和数据集:

模型迁移

# 替换模型定义
# 原始: LeNet-5
model = LeNet5()

# 迁移: ResNet-18
model = torchvision.models.resnet18(pretrained=True)
model.fc = nn.Linear(model.fc.in_features, 10)

# 迁移: ViT
model = ViTForImageClassification.from_pretrained(
    'google/vit-base-patch16-224',
    num_labels=10
)

数据集迁移

# 替换数据加载
# 原始: MNIST
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])
dataset = MNIST(root='./data', train=True, transform=transform)

# 迁移: CIFAR-10
transform = transforms.Compose([
    transforms.RandomCrop(32, padding=4),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
])
dataset = CIFAR10(root='./data', train=True, transform=transform)

# 迁移: ImageNet
transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
dataset = ImageFolder(root='./data/imagenet', transform=transform)

参数调整建议

参数 MNIST CIFAR-10 ImageNet
Batch Size 64 128 256
Learning Rate 0.01 0.1 0.01
Epochs 10 100 90
Epsilon (FGSM) 0.3 8/255 4/255

联系方式

如有问题或建议,请通过以下方式联系:

  • Wechat:Gach0ng

About

AI安全算法层面的技术实践,涵盖对抗样本攻击、模型后门攻击、AI数据隐私窃取、数据投毒攻击、预训练模型安全五大模块。为快速测试,该算法合集以lenet与mnist作为测试样本,技术前沿性截至2023年,不涉及LLM,读者可自行迁移

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors