🛡 torchattack - A set of adversarial attacks in PyTorch.
Install from GitHub source -
python -m pip install git+https://github.com/spencerwooo/[email protected]
Install from Gitee mirror -
python -m pip install git+https://gitee.com/spencerwoo/[email protected]
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
Load a pretrained model to attack from either torchvision or timm.
from torchattack import AttackModel
# Load a model with `AttackModel`
model = AttackModel.from_pretrained(model_name='resnet50', device=device)
# `AttackModel` automatically attach the model's `transform` and `normalize` functions
transform, normalize = model.transform, model.normalize
Initialize an attack by importing its attack class.
from torchattack import FGSM, MIFGSM
# Initialize an attack
attack = FGSM(model, normalize, device)
# Initialize an attack with extra params
attack = MIFGSM(model, normalize, device, eps=0.03, steps=10, decay=1.0)
Initialize an attack by its name with create_attack()
.
from torchattack import create_attack
# Initialize FGSM attack with create_attack
attack = create_attack('FGSM', model, normalize, device)
# Initialize PGD attack with specific eps with create_attack
attack = create_attack('PGD', model, normalize, device, eps=0.03)
# Initialize MI-FGSM attack with extra args with create_attack
attack_cfg = {'steps': 10, 'decay': 1.0}
attack = create_attack('MIFGSM', model, normalize, device, eps=0.03, attack_cfg=attack_cfg)
Check out torchattack.eval.runner
for a full example.
Gradient-based attacks:
Others:
Name | Publication | Paper (Open Access) | Class Name | |
---|---|---|---|---|
DeepFool | CVPR 2016 | DeepFool: A Simple and Accurate Method to Fool Deep Neural Networks | DeepFool |
|
GeoDA |
|
CVPR 2020 | GeoDA: A Geometric Framework for Black-box Adversarial Attacks | GeoDA |
SSP | CVPR 2020 | A Self-supervised Approach for Adversarial Robustness | SSP |
# Create a virtual environment
python -m venv .venv
source .venv/bin/activate
# Install deps with dev extras
python -m pip install -r requirements.txt
python -m pip install -e ".[dev]"