文档 • 功能与用途 • 使用示例 • 攻击模型 • 工具包设计
OpenAttack 是一个基于 Python 的开源文本对抗攻击工具包,它处理文本对抗攻击的完整流程,包括文本预处理、访问受害者模型、生成对抗样本和评估。
⭐️ 支持所有攻击类型。OpenAttack 支持所有类型的攻击,包括句子级/单词级/字符级扰动以及基于梯度/得分/决策/盲攻击模型;
⭐️ 多语言支持。OpenAttack 目前支持中文和英文。其可扩展的设计能够快速支持更多语言;
⭐️ 并行处理。OpenAttack 提供对攻击模型的多进程运行支持,以提高攻击效率;
⭐️ 与 🤗 Hugging Face 兼容。OpenAttack 与 🤗 Transformers 和 Datasets 库完全集成;
⭐️ 优秀的可扩展性。您可以轻松攻击自定义的 受害者模型 在任何自定义的 数据集 上,或者开发和评估自定义的 攻击模型。
✅ 提供各种便捷的攻击模型 基线;
✅ 使用全面的评估指标对攻击模型进行综合 评估;
✅ 借助其通用攻击组件,协助快速开发 新的攻击模型;
✅ 评估机器学习模型对各种对抗攻击的 鲁棒性;
✅ 通过使用生成的对抗样本丰富训练数据,进行 对抗训练 以提高机器学习模型的鲁棒性。
pip(推荐)```bashpip install OpenAttack
#### 2. 克隆此仓库```bash
git clone https://github.com/thunlp/OpenAttack.git
cd OpenAttack
python setup.py install
安装后,您可以尝试运行 demo.py 以检查OpenAttack是否正常工作:```
python demo.py

## 使用示例
#### 攻击内置受害者模型
OpenAttack 内置了一些常用的 NLP 模型,如 BERT([Devlin 等人,2018](https://arxiv.org/abs/1810.04805))和 RoBERTa([Liu 等人,2019](https://arxiv.org/abs/1907.11692)),这些模型已在一些常用的数据集(如 [SST-2](https://nlp.stanford.edu/sentiment/treebank.html))上进行了微调。您可以轻松地对这些内置的受害者模型进行对抗性攻击。
以下代码片段展示了如何使用基于贪心算法的攻击模型 PWWS([Ren 等人,2019](https://www.aclweb.org/anthology/P19-1103.pdf))来攻击 SST-2 数据集上的 BERT 模型(完整可执行代码见[此处](https://github.com/thunlp/openattack/blob/master/examples/workflow.py))。```python
import OpenAttack as oa
import datasets # use the Hugging Face's datasets library
# change the SST dataset into 2-class
def dataset_mapping(x):
return {
"x": x["sentence"],
"y": 1 if x["label"] > 0.5 else 0,
}
# choose a trained victim classification model
victim = oa.DataManager.loadVictim("BERT.SST")
# choose 20 examples from SST-2 as the evaluation data
dataset = datasets.load_dataset("sst", split="train[:20]").map(function=dataset_mapping)
# choose PWWS as the attacker and initialize it with default parameters
attacker = oa.attackers.PWWSAttacker()
# prepare for attacking
attack_eval = OpenAttack.AttackEval(attacker, victim)
# launch attacks and print attack results
attack_eval.eval(dataset, visualize=True)
以下代码片段展示了如何使用 PWWS 在 SST-2 上攻击一个自定义的情感分析模型(一个基于 NLTK 构建的统计模型)(完整的可执行代码见此处)。
class MyClassifier(oa.Classifier): def init(self): # nltk.sentiment.vader.SentimentIntensityAnalyzer is a traditional sentiment classification model. nltk.download('vader_lexicon') self.model = SentimentIntensityAnalyzer()
def get_pred(self, input_):
return self.get_prob(input_).argmax(axis=1)
# access to the classification probability scores with respect input sentences
def get_prob(self, input_):
ret = []
for sent in input_:
# SentimentIntensityAnalyzer calculates scores of “neg” and “pos” for each instance
res = self.model.polarity_scores(sent)
# we use 𝑠𝑜𝑐𝑟𝑒_𝑝𝑜𝑠 / (𝑠𝑐𝑜𝑟𝑒_𝑛𝑒𝑔 + 𝑠𝑐𝑜𝑟𝑒_𝑝𝑜𝑠) to represent the probability of positive sentiment
# Adding 10^−6 is a trick to avoid dividing by zero.
prob = (res["pos"] + 1e-6) / (res["neg"] + res["pos"] + 2e-6)
ret.append(np.array([1 - prob, prob]))
# The get_prob method finally returns a np.ndarray of shape (len(input_), 2). See Classifier for detail.
return np.array(ret)
def dataset_mapping(x): return { "x": x["sentence"], "y": 1 if x["label"] > 0.5 else 0, }
dataset = datasets.load_dataset("sst", split="train[:20]").map(function=dataset_mapping)
victim = MyClassifier()
attacker = oa.attackers.PWWSAttacker()
attack_eval = oa.AttackEval(attacker, victim)
attack_eval.eval(dataset, visualize=True)
</details>
<details>
<summary><strong>自定义数据集</strong></summary>
以下代码片段展示了如何使用PWWS攻击在**自定义**数据集上微调的情感分析模型(完整可执行代码请参见[此处](https://github.com/thunlp/openattack/blob/master/examples/custom_dataset.py))。```python
import OpenAttack as oa
import transformers
import datasets
# load a fine-tuned sentiment analysis model from Transformers (you can also use our fine-tuned Victim.BERT.SST)
tokenizer = transformers.AutoTokenizer.from_pretrained("echarlaix/bert-base-uncased-sst2-acc91.1-d37-hybrid")
model = transformers.AutoModelForSequenceClassification.from_pretrained("echarlaix/bert-base-uncased-sst2-acc91.1-d37-hybrid", num_labels=2, output_hidden_states=False)
victim = oa.classifiers.TransformersClassifier(model, tokenizer, model.bert.embeddings.word_embeddings)
# choose PWWS as the attacker and initialize it with default parameters
attacker = oa.attackers.PWWSAttacker()
# create your customized dataset
dataset = datasets.Dataset.from_dict({
"x": [
"I hate this movie.",
"I like this apple."
],
"y": [
0, # 0 for negative
1, # 1 for positive
]
})
# prepare for attacking
attack_eval = oa.AttackEval(attacker, victim, metrics = [oa.metric.EditDistance(), oa.metric.ModificationRate()])
# launch attacks and print attack results
attack_eval.eval(dataset, visualize=True)
OpenAttack 支持便捷的多进程处理,以加速对抗攻击的过程。以下代码片段展示了如何在对抗攻击中使用多进程处理与 Genetic(Alzantot et al. 2018),一种基于遗传算法的攻击模型(完整可执行代码见此处)。```python import OpenAttack as oa import datasets
def dataset_mapping(x): return { "x": x["sentence"], "y": 1 if x["label"] > 0.5 else 0, }
victim = oa.loadVictim("BERT.SST") dataset = datasets.load_dataset("sst", split="train[:20]").map(function=dataset_mapping) attacker = oa.attackers.GeneticAttacker() attack_eval = oa.AttackEval(attacker, victim)
attack_eval.eval(dataset, visualize=True, num_workers=4)
</details>
<details>
<summary><strong>中文攻击</strong></summary>
OpenAttack 现已支持针对英文和中文受害者模型的对抗攻击。[这里](https://github.com/thunlp/openattack/blob/master/examples/chinese.py) 提供了一个示例代码,展示如何使用 PWWS 对中文评论分类模型进行对抗攻击。
</details>
<details>
<summary><strong>自定义攻击模型</strong></summary>
OpenAttack 集成了许多便捷组件,可轻松组合成新的攻击模型。[这里](https://github.com/thunlp/openattack/blob/master/examples/custom_attacker.py) 给出了一个示例,展示了如何设计一个简单的攻击模型,用于打乱原始句子中的词元。
</details>
<details>
<summary><strong>对抗训练</strong></summary>
OpenAttack 可以通过攻击训练集中的实例来轻松生成对抗样本,这些样本可以添加到原始训练数据集中,以重新训练更鲁棒的受害者模型,即对抗训练。[这里](https://github.com/thunlp/openattack/blob/master/examples/adversarial_training.py) 给出了如何使用 OpenAttack 进行对抗训练的示例。
</details>
<details>
<summary><strong>更多示例</strong></summary>
- 攻击句子对分类模型。除了单句子分类模型外,OpenAttack 还支持攻击句子对分类模型。[这里](https://github.com/thunlp/openattack/blob/master/examples/nli_attack.py) 提供了一个使用 OpenAttack 对 NLI 模型进行对抗攻击的示例代码。
- 自定义评估指标。OpenAttack 支持设计自定义的对抗攻击评估指标。[这里](https://github.com/thunlp/openattack/blob/master/examples/custom_eval.py) 给出了一个示例,说明如何添加自定义评估指标并用于评估对抗攻击。
</details>
## 攻击模型
根据对原始输入施加扰动的层次,文本对抗攻击模型可分为句子级、词级和字符级攻击模型。
根据对受害者模型的可访问性,文本对抗攻击模型可分为基于梯度、基于评分、基于决策和盲攻击模型。
> [TAADPapers](https://github.com/thunlp/TAADpapers) 是一个论文列表,总结了几乎所有关于文本对抗攻击与防御的论文。您可以查看此列表以发现更多攻击模型。
目前,OpenAttack 包含 15 种典型的针对文本分类模型的攻击模型,涵盖了**所有**攻击类型。
以下是当前涉及的攻击模型列表。
- 句子级
- (SEA) **Semantically Equivalent Adversarial Rules for Debugging NLP Models**. *Marco Tulio Ribeiro, Sameer Singh, Carlos Guestrin*. ACL 2018. `decision` [[pdf](https://aclweb.org/anthology/P18-1079)] [[code](https://github.com/marcotcr/sears)]
- (SCPN) **Adversarial Example Generation with Syntactically Controlled Paraphrase Networks**. *Mohit Iyyer, John Wieting, Kevin Gimpel, Luke Zettlemoyer*. NAACL-HLT 2018. `blind` [[pdf](https://www.aclweb.org/anthology/N18-1170)] [[code&data](https://github.com/miyyer/scpn)]
- (GAN) **Generating Natural Adversarial Examples**. *Zhengli Zhao, Dheeru Dua, Sameer Singh*. ICLR 2018. `decision` [[pdf](https://arxiv.org/pdf/1710.11342.pdf)] [[code](https://github.com/zhengliz/natural-adversary)]
- 词级
- (TextFooler) **Is BERT Really Robust? A Strong Baseline for Natural Language Attack on Text Classification and Entailment**. *Di Jin, Zhijing Jin, Joey Tianyi Zhou, Peter Szolovits*. AAAI-20. `score` [[pdf](https://arxiv.org/pdf/1907.11932v4)] [[code](https://github.com/wqj111186/TextFooler)]
- (PWWS) **Generating Natural Language Adversarial Examples through Probability Weighted Word Saliency**. *Shuhuai Ren, Yihe Deng, Kun He, Wanxiang Che*. ACL 2019. `score` [[pdf](https://www.aclweb.org/anthology/P19-1103.pdf)] [[code](https://github.com/JHL-HUST/PWWS/)]
- (Genetic) **Generating Natural Language Adversarial Examples**. *Moustafa Alzantot, Yash Sharma, Ahmed Elgohary, Bo-Jhang Ho, Mani Srivastava, Kai-Wei Chang*. EMNLP 2018. `score` [[pdf](https://www.aclweb.org/anthology/D18-1316)] [[code](https://github.com/nesl/nlp_adversarial_examples)]
- (SememePSO) **Word-level Textual Adversarial Attacking as Combinatorial Optimization**. *Yuan Zang, Fanchao Qi, Chenghao Yang, Zhiyuan Liu, Meng Zhang, Qun Liu and Maosong Sun*. ACL 2020. `score` [[pdf](https://www.aclweb.org/anthology/2020.acl-main.540.pdf)] [[code](https://github.com/thunlp/SememePSO-Attack)]
- (BERT-ATTACK) **BERT-ATTACK: Adversarial Attack Against BERT Using BERT**. *Linyang Li, Ruotian Ma, Qipeng Guo, Xiangyang Xue, Xipeng Qiu*. EMNLP 2020. `score` [[pdf](https://www.aclweb.org/anthology/2020.emnlp-main.500.pdf)] [[code](https://github.com/LinyangLee/BERT-Attack)]
- (BAE) **BAE: BERT-based Adversarial Examples for Text Classification**. *Siddhant Garg, Goutham Ramakrishnan. EMNLP 2020*. `score` [[pdf](https://www.aclweb.org/anthology/2020.emnlp-main.498.pdf)] [[code](https://github.com/QData/TextAttack/blob/master/textattack/attack_recipes/bae_garg_2019.py)]
- (FD) **Crafting Adversarial Input Sequences For Recurrent Neural Networks**. *Nicolas Papernot, Patrick McDaniel, Ananthram Swami, Richard Harang*. MILCOM 2016. `gradient` [[pdf](https://arxiv.org/pdf/1604.08275.pdf)]
- 词/字符级
- (TextBugger) **TEXTBUGGER: Generating Adversarial Text Against Real-world Applications**. *Jinfeng Li, Shouling Ji, Tianyu Du, Bo Li, Ting Wang*. NDSS 2019. `gradient` `score` [[pdf](https://arxiv.org/pdf/1812.05271.pdf)]
- (UAT) **Universal Adversarial Triggers for Attacking and Analyzing NLP.** *Eric Wallace, Shi Feng, Nikhil Kandpal, Matt Gardner, Sameer Singh*. EMNLP-IJCNLP 2019. `gradient` [[pdf](https://arxiv.org/pdf/1908.07125.pdf)] [[code](https://github.com/Eric-Wallace/universal-triggers)] [[website](http://www.ericswallace.com/triggers)]
- (HotFlip) **HotFlip: White-Box Adversarial Examples for Text Classification**. *Javid Ebrahimi, Anyi Rao, Daniel Lowd, Dejing Dou*. ACL 2018. `gradient` [[pdf](https://www.aclweb.org/anthology/P18-2006)] [[code](https://github.com/AnyiRao/WordAdver)]
- 字符级
- (VIPER) **Text Processing Like Humans Do: Visually Attacking and Shielding NLP Systems**. *Steffen Eger, Gözde Gül ¸Sahin, Andreas Rücklé, Ji-Ung Lee, Claudia Schulz, Mohsen Mesgar, Krishnkant Swarnkar, Edwin Simpson, Iryna Gurevych*. NAACL-HLT 2019. `score` [[pdf](https://www.aclweb.org/anthology/N19-1165)] [[code&data](https://github.com/UKPLab/naacl2019-like-humans-visual-attacks)]
- (DeepWordBug) **Black-box Generation of Adversarial Text Sequences to Evade Deep Learning Classifiers**. *Ji Gao, Jack Lanchantin, Mary Lou Soffa, Yanjun Qi*. IEEE SPW 2018. `score` [[pdf](https://ieeexplore.ieee.org/document/8424632)] [[code](https://github.com/QData/deepWordBug)]
以下表格展示了攻击模型的比较。
| 模型 | 可访问性 | 扰动层次 | 主要思想 |
| :---------: | :-------------: | :----------: | :-------------------------------------------------- |
| SEA | 决策 | 句子 | 基于规则的同义改写 |
| SCPN | 盲 | 句子 | 同义改写 |
| GAN | 决策 | 句子 | 通过编码器-解码器生成文本 |
| TextFooler | 评分 | 词 | 贪心词替换 |
| PWWS | 评分 | 词 | 贪心词替换 |
| Genetic | 评分 | 词 | 基于遗传算法的词替换 |
| SememePSO | 评分 | 词 | 基于粒子群优化的词替换 |
| BERT-ATTACK | 评分 | 词 | 贪心的上下文化词替换 |
| BAE | 评分 | 词 | 贪心的上下文化词替换与插入 |
| FD | 梯度 | 词 | 基于梯度的词替换 |
| TextBugger | 梯度, 评分 | 词+字符 | 贪心词替换与字符操作 |
| UAT | 梯度 | 词, 字符 | 基于梯度的词或字符操作 |
| HotFlip | 梯度 | 词, 字符 | 基于梯度的词或字符替换 |
| VIPER | 盲 | 字符 | 视觉相似字符替换 |
| DeepWordBug | 评分 | 字符 | 贪心字符操作 |
## 工具包设计
考虑到不同攻击模型之间的显著差异,我们在攻击模型骨架设计上保留了相当大的自由度,并更多地关注简化对抗攻击的一般处理以及攻击模型中使用的通用组件。
OpenAttack 包含 7 个主要模块:
<img src="https://assets.kitploit.com/production/public/readmes/4421/3c70579cf4ea406c82bd3bf407eb9c1e1e8b8ffb3b3c4eede4fe2812ff76eebf.png" alt="toolkit_framework" style="zoom:40%;" />
* **TextProcessor**:处理原始文本序列,以协助攻击模型生成对抗样本;
* **Victim**:封装受害者模型;
* **Attacker**:包含各种攻击模型;
* **AttackAssist**:打包不同的词/字符替换方法(用于词/字符级攻击模型)以及句子级攻击模型中使用的其他组件(如同义改写模型);
* **Metric**:提供多种对抗样本质量指标,这些指标既可作为攻击过程中对抗样本的约束条件,也可作为评估对抗攻击的评估指标;
* **AttackEval**:从攻击有效性、对抗样本质量和攻击效率三个方面评估文本对抗攻击;
* **DataManager**:管理其他模块中使用的所有数据和已保存模型。
## 引用
如果您使用此工具包,请引用我们的[论文](https://aclanthology.org/2021.acl-demo.43.pdf):```
@inproceedings{zeng2020openattack,
title={{Openattack: An open-source textual adversarial attack toolkit}},
author={Zeng, Guoyang and Qi, Fanchao and Zhou, Qianrui and Zhang, Tingji and Hou, Bairu and Zang, Yuan and Liu, Zhiyuan and Sun, Maosong},
booktitle={Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing: System Demonstrations},
pages={363--371},
year={2021},
url={https://aclanthology.org/2021.acl-demo.43},
doi={10.18653/v1/2021.acl-demo.43}
}
我们感谢这个项目的所有贡献者。更多的贡献非常欢迎。