文档 • 功能与用途 • 使用示例 • 攻击模型 • 工具包设计
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, }