生成NLP模型的对抗示例
[关于readthedocs的TextAttack文档]
关于•设置•使用•设计
TextAttack是NLP中对抗性攻击,数据增强和模型培训的Python框架。
如果您正在寻找有关TextAttack的预培训模型的Menagerie的信息,则可能需要TextAttack Model Zoo页面。
有关与TextAttack相关的帮助和实时更新,请加入TextAttack Slack!
使用TextAttack有很多理由:
您应该运行Python 3.6+以使用此软件包。与CUDA兼容的GPU是可选的,但将大大提高代码速度。 TextAttack可通过PIP获得:
pip install textattack安装TextAttack后,您可以通过命令行( textattack ... )或Python模块( python -m textattack ... )运行它。
提示:TextAttack将文件下载到
~/.cache/textattack/默认情况下。这包括验证的型号,数据集示例和配置文件config.yaml。要更改缓存路径,请设置环境变量TA_CACHE_DIR。 (例如:TA_CACHE_DIR=/tmp/ textattack attack ...)。
textattack --help TextAttack的主要功能都可以通过textattack命令访问。两个非常常见的命令是textattack attack <args>和textattack augment <args> 。您可以使用有关所有命令的更多信息
textattack --help或使用特定命令,例如
textattack attack --help examples/文件夹包括脚本显示训练模型,运行攻击和增强CSV文件的常见TextAttack用法。
文档网站包含解释TextAttack的基本用法的演练,包括构建自定义转换和自定义约束。
textattack attack --help尝试攻击的最简单方法是通过命令行接口, textattack attack 。
提示:如果您的计算机具有多个GPU,则可以使用
--parallel选项在攻击中分发攻击。对于某些攻击,这确实可以帮助性能。 (如果您想并行攻击KERAS模型,请查看examples/attack/attack_keras_parallel.py)
以下是一些具体的例子:
在MR情感分类数据集中受过培训的BERT上的TextFooler :
textattack attack --recipe textfooler --model bert-base-uncased-mr --num-examples 100在Quora问题对培训的Distilbert上的DeepWordBug对识别数据集进行了训练:
textattack attack --model distilbert-base-uncased-cola --recipe deepwordbug --num-examples 100带有光束宽度4的光束搜索和LSTM上的单词嵌入转换和无靶向目标函数的搜索:
textattack attack --model lstm-mr --num-examples 20
--search-method beam-search^beam_width=4 --transformation word-swap-embedding
--constraints repeat stopword max-words-perturbed^max_num_words=2 embedding^min_cos_sim=0.8 part-of-speech
--goal-function untargeted-classification提示:您可以通过
--interactive用户输入的攻击样本,而不是指定数据集和示例数。
textattack attack --recipe [recipe_name]我们包括实施文献攻击的攻击食谱。您可以使用textattack list attack-recipes 。
运行攻击食谱: textattack attack --recipe [recipe_name]

| 攻击食谱名称 | 目标功能 | 约束森林 | 转型 | 搜索方法 | 大意 |
|---|---|---|---|---|---|
对分类任务的攻击,例如情感分类和构成: | |||||
a2t | 未定位的{分类,需要} | 单词的百分比扰动,单词嵌入距离,编码余弦相似性的大杂项句子,词性一致性 | 反拟合的单词嵌入交换(或)bert蒙版的令牌预测 | 贪婪 - 威尔(渐变) | 从[[“改善NLP模型的对抗训练”(Yoo等,2021)](https://arxiv.org/abs/2109.00544)) |
alzantot | 未定位的{分类,需要} | 单词百分比扰动,语言模型困惑,单词嵌入距离 | 反拟合的单词嵌入交换 | 遗传算法 | 来自([“生成自然语言对抗性示例”(Alzantot等,2018)](https://arxiv.org/abs/1804.07998)) |
bae | 非目标分类 | 使用编码余弦相似性的句子 | 伯特蒙面的令牌预测 | 贪婪 - 威尔 | Bert掩盖语言模型转换攻击([“ BAE:基于Bert的基于Bert的对抗性示例)文本分类”(Garg&Ramakrishnan,2019年)](https://arxiv.org/abs/2004.01970))。 |
bert-attack | 非目标分类 | 使用编码余弦相似性的句子,最大数量的单词扰动 | Bert掩盖令牌预测(带子字扩展) | 贪婪 - 威尔 | ([“ Bert-Attack:使用Bert对Bert对Bert的对抗性攻击”(Li等,2020)](https://arxiv.org/abs/2004.09984)) |
checklist | {未靶向的,有针对性的}分类 | 清单距离 | 合同,扩展和替代名称实体 | 贪婪 - 威尔 | 在清单中实施的不变性测试。 ([“超越准确性:使用清单的NLP模型的行为测试”(Ribeiro等,2020)](https://arxiv.org/abs/2005.04118)) |
clare | 未定位的{分类,需要} | 使用编码余弦相似性的句子 | 罗伯塔(Roberta)掩盖了令牌交换,插入和合并的预测 | 贪婪的 | [“文本对抗攻击的上下文化扰动”(Li等,2020)](https://arxiv.org/abs/2009.07502)) |
deepwordbug | {未靶向的,有针对性的}分类 | Levenshtein编辑距离 | {字符插入,字符删除,相邻的字符交换,字符替代} | 贪婪 - 威尔 | 贪婪的替换-1评分和多转化字符 - 划分攻击([“黑框生成对抗性文本序列,逃避深度学习分类器”(Gao等,2018)](https://arxiv.org/abs/1801.04354) |
faster-alzantot | 未定位的{分类,需要} | 单词百分比扰动,语言模型困惑,单词嵌入距离 | 反拟合的单词嵌入交换 | 遗传算法 | Alzantot等人的修改速度更快。遗传算法,摘自([“认证的鲁棒性到对抗性单词替代”(Jia等,2019)](https://arxiv.org/abs/1909.00986)))) |
hotflip (单词交换) | 非目标分类 | 单词嵌入余弦相似性,言论一部分匹配,单词数量扰动 | 基于梯度的单词交换 | 梁搜索 | ([“ Hotflip:White-Box的文本分类示例”(Ebrahimi等,2017)](https://arxiv.org/abs/1712.06751)) |
iga | 未定位的{分类,需要} | 单词百分比扰动,单词嵌入距离 | 反拟合的单词嵌入交换 | 遗传算法 | 改进的基于遗传算法的单词替换([“自然语言对抗性攻击和言语级别(Wang等,2019)”](https://arxiv.org/abs/1909.06723) |
input-reduction | 减少输入 | 单词删除 | 贪婪 - 威尔 | 具有单词重要性排名的贪婪攻击,在通过单词重要性排名保持预测的同时减少了输入(“神经模型的病理学使解释变得困难”(Feng等,2018)](https://arxiv.org/pdf/pdf/1804.07781.pdf)) | |
kuleshov | 非目标分类 | 思想矢量编码余弦相似性,语言模型相似性概率 | 反拟合的单词嵌入交换 | 贪婪的单词交换 | ([“自然语言分类问题的对抗性示例”(Kuleshov等,2018)](https://openreview.net/pdf?id=r1qz3zbaz)) |
pruthi | 非目标分类 | 最小单词长度,最大单词数量扰动 | {相邻字符交换,字符删除,字符插入,基于键盘的字符交换} | 贪婪的搜索 | 模拟常见的错别字([[“用强有力的单词识别来对抗对抗性拼写错误”(Pruthi等,2019)](https://arxiv.org/abs/1905.11268) |
pso | 非目标分类 | Hownet Word交换 | 粒子群优化 | ([“单词级文本对抗性攻击作为组合优化”(Zang等,2020)](https://www.aclweb.org/anthology/2020.acl-main.540/)) | |
pwws | 非目标分类 | 基于WordNet的同义词交换 | 贪婪 - 威尔(显着) | 基于单词显着性和同义词交换分数(“通过概率加权单词显着性生成自然语言对抗性示例”(Ren等,2019)](https://wwwwww.aclweb.org/anthology/anthology/p19-1103/),贪婪的攻击态度的贪婪攻击([[“通过概率加权单词显着性生成自然语言对抗性示例)) | |
textbugger :(黑框) | 非目标分类 | 使用编码余弦相似性的句子 | {字符插入,字符删除,相邻的字符交换,字符替代} | 贪婪 - 威尔 | ([[[[“ TextBugger:针对现实世界应用程序)生成对抗文本”(Li等,2018)](https://arxiv.org/abs/1812.05271))。 |
textfooler | 未定位的{分类,需要} | 单词嵌入距离,言论部分匹配,使用编码余弦相似性的句子 | 反拟合的单词嵌入交换 | 贪婪 - 威尔 | 贪婪的攻击与单词重要性排名([“伯特真的很健壮?”(Jin等,2019)](https://arxiv.org/abs/1907.11932) |
对序列到序列模型的攻击: | |||||
morpheus | 最低BLEU得分 | 拐点交换 | 贪婪的搜索 | 贪婪地将单词用拐点替换为最小化bleu得分的目标([“是吗啡的时间!用拐点扰动来打击语言歧视”] | |
seq2sick :(黑色框) | 非重叠输出 | 反拟合的单词嵌入交换 | 贪婪 - 威尔 | 贪婪的攻击,目标是更改输出翻译中的每个单词。目前以Black-box的形式实施,并计划将其更改为纸张中的白色框([“ seq2sick:使用对抗性示例评估序列到序列模型的鲁棒性”(Cheng等,2018)](https://arxiv.org/arxiv.org/abs/1803.01128)))))))))) | |
以下是来自命令行的文献测试攻击的一些示例:
在SST-2上对Bert进行了微调的文本词机:
textattack attack --model bert-base-uncased-sst2 --recipe textfooler --num-examples 10seq2sick(黑盒)针对T5微调用于英语 - 德语翻译:
textattack attack --model t5-en-de --recipe seq2sick --num-examples 100textattack augment TextAttack的许多组件对于数据增强都是有用的。 textattack.Augmenter类使用转换和约束列表来增强数据。我们还提供用于数据增强的内置食谱:
wordnet通过用WordNet同义词替换单词来增强文本embedding增强文本,并具有限制,以确保其余弦相似性至少为0.8charswapeda通过单词插入,替换和删除的结合增强文本。checklist通过收缩/扩展和替换名称,位置,数字来增强文本。clare通过更换,插入和合并预先训练的蒙版语言模型来增强文本。back_trans通过反向翻译方法增强文本。back_transcription增强文本通过后转录方法。 使用我们的数据增强工具的最简单方法是使用textattack augment <args> 。 textattack augment将输入CSV文件和文本列进行增强,以及要更改每个扩展的单词数以及每个输入示例的增强次数。它以相同格式输出CSV,其中所有与适当列相对应的增强示例。
例如,给定以下为examples.csv :
"text",label
"the rock is destined to be the 21st century's new conan and that he's going to make a splash even greater than arnold schwarzenegger , jean- claud van damme or steven segal.", 1
"the gorgeously elaborate continuation of 'the lord of the rings' trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .", 1
"take care of my cat offers a refreshingly different slice of asian cinema .", 1
"a technically well-made suspenser . . . but its abrupt drop in iq points as it races to the finish line proves simply too discouraging to let slide .", 0
"it's a mystery how the movie could be released in this condition .", 0
命令
textattack augment --input-csv examples.csv --output-csv output.csv --input-column text --recipe embedding --pct-words-to-swap .1 --transformations-per-example 2 --exclude-original将通过更改每个示例的单词的10%,生成两倍的增强量来增强text列,并从输出CSV中排除原始输入的两倍。 (默认情况下,所有这些都将保存到augment.csv 。)
提示:正如运行攻击性互动一样,您也可以通过
--interactive与用户输入的增强样品相互作用,以快速尝试不同的增强食谱!
增强后,以下是augment.csv的内容:
text,label
"the rock is destined to be the 21st century's newest conan and that he's gonna to make a splashing even stronger than arnold schwarzenegger , jean- claud van damme or steven segal.",1
"the rock is destined to be the 21tk century's novel conan and that he's going to make a splat even greater than arnold schwarzenegger , jean- claud van damme or stevens segal.",1
the gorgeously elaborate continuation of 'the lord of the rings' trilogy is so huge that a column of expression significant adequately describe co-writer/director pedro jackson's expanded vision of j . rs . r . tolkien's middle-earth .,1
the gorgeously elaborate continuation of 'the lordy of the piercings' trilogy is so huge that a column of mots cannot adequately describe co-novelist/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth .,1
take care of my cat offerings a pleasantly several slice of asia cinema .,1
taking care of my cat offers a pleasantly different slice of asiatic kino .,1
a technically good-made suspenser . . . but its abrupt drop in iq points as it races to the finish bloodline proves straightforward too disheartening to let slide .,0
a technically well-made suspenser . . . but its abrupt drop in iq dot as it races to the finish line demonstrates simply too disheartening to leave slide .,0
it's a enigma how the film wo be releases in this condition .,0
it's a enigma how the filmmaking wo be publicized in this condition .,0
“嵌入”增强食谱使用对接嵌入最接近的邻居的嵌入式数据来增强数据。
除命令行界面外,您还可以通过在自己的代码中导入Augmenter来动态增强文本。所有Augmenter对象都会实现augment和augment_many ,以生成字符串或字符串列表的增强。这是如何在python脚本中使用EmbeddingAugmenter的示例:
> >> from textattack . augmentation import EmbeddingAugmenter
> >> augmenter = EmbeddingAugmenter ()
> >> s = 'What I cannot create, I do not understand.'
> >> augmenter . augment ( s )
[ 'What I notable create, I do not understand.' , 'What I significant create, I do not understand.' , 'What I cannot engender, I do not understand.' , 'What I cannot creating, I do not understand.' , 'What I cannot creations, I do not understand.' , 'What I cannot create, I do not comprehend.' , 'What I cannot create, I do not fathom.' , 'What I cannot create, I do not understanding.' , 'What I cannot create, I do not understands.' , 'What I cannot create, I do not understood.' , 'What I cannot create, I do not realise.' ]您还可以通过从textattack.transformations和textattack.constraints导入转换/约束来从头开始创建自己的增强器。这是一个示例,该示例使用WordSwapRandomCharacterDeletion生成字符串的增强:
> >> from textattack . transformations import WordSwapRandomCharacterDeletion
> >> from textattack . transformations import CompositeTransformation
> >> from textattack . augmentation import Augmenter
> >> transformation = CompositeTransformation ([ WordSwapRandomCharacterDeletion ()])
> >> augmenter = Augmenter ( transformation = transformation , transformations_per_example = 5 )
> >> s = 'What I cannot create, I do not understand.'
> >> augmenter . augment ( s )
[ 'What I cannot creae, I do not understand.' , 'What I cannot creat, I do not understand.' , 'What I cannot create, I do not nderstand.' , 'What I cannot create, I do nt understand.' , 'Wht I cannot create, I do not understand.' ]除了增加常规文本的增强外,您还可以使用大型语言模型(LLMS)增强提示,然后对增强提示产生响应。使用与上述相同的Augmenter进行增强。要产生响应,您可以使用自己的LLM,HuggingFace LLM或OpenAI LLM。这是使用预定的HuggingFace LLM的示例:
> >> from textattack . augmentation import EmbeddingAugmenter
> >> from transformers import AutoModelForSeq2SeqLM , AutoTokenizer
> >> from textattack . llms import HuggingFaceLLMWrapper
> >> from textattack . prompt_augmentation import PromptAugmentationPipeline
> >> augmenter = EmbeddingAugmenter ( transformations_per_example = 3 )
> >> model = AutoModelForSeq2SeqLM . from_pretrained ( "google/flan-t5-small" )
> >> tokenizer = AutoTokenizer . from_pretrained ( "google/flan-t5-small" )
> >> model_wrapper = HuggingFaceLLMWrapper ( model , tokenizer )
> >> pipeline = PromptAugmentationPipeline ( augmenter , model_wrapper )
> >> pipeline ( "Classify the following piece of text as `positive` or `negative`: This movie is great!" )
[( 'Classify the following piece of text as `positive` or `negative`: This film is great!' , [ 'positive' ]), ( 'Classify the following piece of text as `positive` or `negative`: This movie is fabulous!' , [ 'positive' ]), ( 'Classify the following piece of text as `positive` or `negative`: This movie is wonderful!' , [ 'positive' ])]textattack train我们的模型培训代码可通过textattack train获得,可帮助您使用TextAttack开箱即用的TextAttack培训LSTMS,CNN和transformers模型。数据集使用datasets软件包自动加载。
在Yelp Polarity数据集上训练我们的默认LSTM为50个时期:
textattack train --model-name-or-path lstm --dataset yelp_polarity --epochs 50 --learning-rate 1e-5 5个时期的CoLA数据集上的微调bert-base *:
textattack train --model-name-or-path bert-base-uncased --dataset glue^cola --per-device-train-batch-size 8 --epochs 5textattack peek-dataset要仔细查看数据集,请使用textattack peek-dataset 。 TextAttack将打印一些有关数据集输入和输出的粗略统计信息。例如,
textattack peek-dataset --dataset-from-huggingface snli将从NLP软件包中显示有关SNLI数据集的信息。
textattack list TextAttack中有很多碎片,很难跟踪所有内容。您可以使用textattack list来列出组件,例如,预处理的模型( textattack list models )或可用的搜索方法( textattack list search-methods )。
TextAttack是模型的刺激性!您可以使用TextAttack分析输出ID,张量或字符串的任何模型。为了帮助用户,TextAttack包括针对不同常见NLP任务的预训练模型。这使用户更容易开始TextAttack。它还可以对文献的攻击进行更公平的比较。
TextAttack还带有模型和数据集。我们的命令行接口将自动将正确的数据集与正确的模型匹配。我们包括82个不同的(2020年10月)的预训练模型,用于九个胶水任务中的每一个,以及一些用于分类,翻译和摘要的常见数据集。
可在TextAttack/Models/readme.md上获得可用预验证的型号及其验证精度的列表。您还可以通过textattack attack --help查看提供的模型和数据集的完整列表。
这是使用内置模型之一(自动加载SST-2数据集)的一个示例:
textattack attack --model roberta-base-sst2 --recipe textfooler --num-examples 10transformers模型和datasets数据集我们还提供了来自datasets transformers软件包预读的型号和数据集的内置支持!这是加载和攻击预训练模型和数据集的示例:
textattack attack --model-from-huggingface distilbert-base-uncased-finetuned-sst-2-english --dataset-from-huggingface glue^sst2 --recipe deepwordbug --num-examples 10您可以通过更改 - 数据图--model-from-huggingface --dataset-from-huggingface来探索其他预训练的模型,或其他数据集。
您可以轻松地尝试对本地型号或数据集示例进行攻击。要攻击预训练的模型,请创建一个简短的文件,将它们作为变量model和tokenizer加载。 tokenizer必须能够使用称为encode()的方法将字符串输入转换为ID的列表或张量。该模型必须通过__call__方法进行输入。
要尝试您训练的模型,您可以创建以下文件并将其命名my_model.py :
model = load_your_model_with_custom_code () # replace this line with your model loading code
tokenizer = load_your_tokenizer_with_custom_code () # replace this line with your tokenizer loading code然后,使用参数进行攻击--model-from-file my_model.py 。模型和令牌将自动加载。
从文件加载数据集与从文件加载模型非常相似。一个“数据集”是(input, output)对的任何值得一提的。以下示例将从文件my_dataset.py加载情感分类数据集:
dataset = [( 'Today was....' , 1 ), ( 'This movie is...' , 0 ), ...]然后,您可以通过添加参数--dataset-from-file my_dataset.py来自此数据集的样本进行攻击。
import textattack
my_dataset = [( "text" , label ),....]
new_dataset = textattack . datasets . Dataset ( my_dataset )为了允许在序列化后替换单词,我们包括一个AttackedText对象,该对象既可以维护令牌列表又有标点符号。我们使用此对象来支持单词列表或原始文本。
我们将攻击制定为由四个组成部分组成的攻击:一个确定攻击是否成功的目标函数,定义哪些扰动有效的约束,一种转换,该转换产生了给定输入的潜在修改,以及通过可能扰动的搜索空间遍历搜索空间。攻击试图扰动输入文本,以使模型输出符合目标函数(即指示攻击成功),并且扰动遵守了一组约束(例如,语法约束,语义相似性约束)。搜索方法用于找到一系列转换序列,以产生成功的对抗示例。
这种模块化设计将对抗性攻击方法统一到一个系统中,使我们能够轻松地从文献中组装出攻击,同时重新使用跨攻击共享的组件。我们提供了文献中16种对抗性攻击食谱的干净,可读的实现(请参见上表)。这些攻击首次可以在标准化的环境中进行基准,比较和分析。
TextAttack是模型 - 敏锐的 - 意味着它可以对任何深度学习框架中实现的模型进行攻击。模型对象必须能够采用字符串(或字符串列表)并返回可以通过目标函数处理的输出。例如,机器翻译模型将字符串列表作为输入列表,并产生字符串列表作为输出。分类和组成模型返回分数数组。只要用户的模型符合此规范,该模型就可以与TextAttack一起使用。
GoalFunction将作为输入作为AttackedText对象,对其进行评分,并确定攻击是否成功,返回GoalFunctionResult 。
Constraint将当前AttackedText作为输入,以及转换的AttackedText文本列表。对于每个转换的选项,它返回一个布尔来表示约束是否满足。
Transformation为输入AttackedText ,并返回可能转换的AttackedText s的列表。例如,转换可能会返回所有可能的同义词替代品。
SearchMethod将作为输入作为初始GoalFunctionResult恢复并返回最终的GoalFunctionResult ,搜索可以访问get_transformations函数,该功能将作为输入作为AttackedText对象,并通过满足所有攻击的约束来输出可能转换的列表。搜索由连续的调用get_transformations组成,直到搜索成功(使用get_goal_results确定)或精疲力尽。
请参阅我们的分析论文:搜索搜索方法:基于EMNLP BlackBoxNLP生成NLP对抗示例的基准测试搜索算法。
正如我们在上面的论文中强调的那样,我们不建议直接比较开箱即用的攻击食谱。
此评论是由于最近文献中的攻击食谱在设置其约束时使用了不同的方式或阈值。如果没有约束空间的恒定,攻击成功率的提高可能来自改进的搜索或转换方法或限制性较小的搜索空间。
我们在基准脚本和结果上的github:TextAttack-Search-Search基准GitHub
请参阅示例代码:https://github.com/qdata/textattack/blob/master/master/examples/attack/attack_camembert.py使用我们的框架来攻击French-bert。
请参阅教程笔记本:https://textattack.readthedocs.io/en/latest/2notebook/example_4_camembert.html使用我们的框架来攻击法语 - 伯特。
请参阅readme_zh.md以获取中文的读书我
我们欢迎建议和贡献!提交问题或提取请求,我们将尽力及时做出回应。 TextAttack目前处于“ Alpha”阶段,我们正在努力提高其功能和设计。
有关贡献的详细信息,请参见贡献。
如果您使用TextAttack进行研究,请引用TextAttack:NLP中的对抗性攻击,数据增强和对抗性培训的框架。
@inproceedings { morris2020textattack ,
title = { TextAttack: A Framework for Adversarial Attacks, Data Augmentation, and Adversarial Training in NLP } ,
author = { Morris, John and Lifland, Eli and Yoo, Jin Yong and Grigsby, Jake and Jin, Di and Qi, Yanjun } ,
booktitle = { Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations } ,
pages = { 119--126 } ,
year = { 2020 }
}