TextAttack

GitHub
3.4k 440 简单 3 次阅读 今天MIT数据工具开发框架语言模型
AI 解读 由 AI 自动生成,仅供参考

TextAttack 是一款专为自然语言处理(NLP)设计的开源 Python 框架,致力于提升模型的安全性与鲁棒性。TextAttack 核心解决了 NLP 模型容易受到对抗样本攻击的问题,通过自动生成对抗示例,帮助用户深入理解模型的脆弱点。同时,TextAttack 还能进行数据增强和模型训练,有效提高下游任务的泛化能力。

TextAttack 非常适合 NLP 领域的研究人员和开发者。无论是想评估现有模型的安全性,还是希望开发新的对抗攻击算法,TextAttack 都提供了丰富的组件库和预置配方(如 TextFooler、DeepWordBug)。其独特的模块化设计让自定义转换和约束变得简单,支持通过一行命令即可启动攻击或训练任务。此外,TextAttack 还兼容多 GPU 并行计算,显著提升了大规模实验的效率。对于需要构建更健壮 NLP 系统的团队来说,TextAttack 是一个值得依赖的重要资源。

使用场景

某金融科技公司正在构建智能客服系统,核心需求是确保情感分析模型在面对恶意篡改或用户拼写错误时依然稳定可靠,避免误判导致客诉风险。

没有 TextAttack 时

  • 需从零编写对抗样本生成代码,耗时且易引入逻辑错误
  • 手动构造拼写错误或同义词替换数据增强训练集效率极低
  • 测试模型鲁棒性需维护多套独立脚本,难以统一量化评估
  • 缺乏现成攻击模板,复现学术界最新方法困难重重
  • 环境配置复杂,不同数据集和模型之间迁移成本高昂

使用 TextAttack 后

  • 一条命令行即可运行 TextFooler 等经典攻击算法,秒级生成对抗样本
  • 内置数据增强功能快速扩充高质量训练样本,显著提升泛化能力
  • 统一框架简化模型训练与攻击测试流程,大幅降低维护成本
  • 直接调用预训练模型,无需重复下载配置环境,实现开箱即用
  • 支持并行计算加速攻击过程,在大规模测试中节省大量等待时间

TextAttack 通过标准化流程显著提升了 NLP 模型的抗干扰能力与研发效率。

运行环境要求

操作系统
  • 未说明
GPU

可选,需 CUDA 兼容环境

内存

未说明

依赖
notes默认缓存路径为 ~/.cache/textattack/,可通过 TA_CACHE_DIR 环境变量修改;支持命令行(textattack)和 Python 模块(python -m textattack)调用;部分攻击支持使用 --parallel 选项在多 GPU 上并行运行以加速
python3.6+
未说明
TextAttack hero image

快速开始

TextAttack 🐙

为自然语言处理(NLP)模型生成对抗样本

[TextAttack 文档在 ReadTheDocs 上]

关于设置用法设计

GitHub Runner 覆盖状态 PyPI 版本

TextAttack 演示 GIF

关于

TextAttack 是一个用于自然语言处理(NLP)中的对抗攻击、数据增强和模型训练的 Python 框架。

如果您正在寻找有关 TextAttack 的预训练模型集合的信息,您可能需要查看 TextAttack 模型库 页面。

Slack 频道

有关 TextAttack 的帮助和实时更新,请 加入 TextAttack Slack!

为什么选择 TextAttack?

使用 TextAttack 有很多理由:

  1. 更好地理解 NLP 模型,通过对其运行不同的对抗攻击并检查结果输出
  2. 研究和开发不同的 NLP 对抗攻击,使用 TextAttack 框架和组件库
  3. 增强您的数据集,以提高下游模型的泛化能力和鲁棒性
  4. 训练 NLP 模型,仅使用单个命令即可(包含所有下载!)

设置

安装

您应该运行 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

以下是一些具体示例:

BERT 在 MR 情感分类数据集上的训练上使用 TextFooler:

textattack attack --recipe textfooler --model bert-base-uncased-mr --num-examples 100

DistilBERT 在 Quora 问题对释义识别数据集上的训练上使用 DeepWordBug:

textattack attack --model distilbert-base-uncased-cola --recipe deepwordbug --num-examples 100

LSTM 上使用束搜索(束宽为 4)、词嵌入转换和无目标目标函数:

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]

TextAttack 概览
攻击配方名称 目标函数 执行的约束 转换 搜索方法 主要思想

针对分类任务的攻击,如情感分类和蕴含:
a2t 无目标 {分类,蕴含} 扰动单词百分比,词嵌入距离,DistilBERT 句子编码余弦相似度,词性一致性 Counter-fitted 词嵌入交换(或)BERT 掩码标记预测 贪婪-WIR(梯度) 源自 (["Towards Improving Adversarial Training of NLP Models" (Yoo et al., 2021)](https://arxiv.org/abs/2109.00544))
alzantot 无目标 {分类,蕴含} 扰动单词百分比,语言模型困惑度,词嵌入距离 Counter-fitted 词嵌入交换 遗传算法 源自 (["Generating Natural Language Adversarial Examples" (Alzantot et al., 2018)](https://arxiv.org/abs/1804.07998))
bae 无目标分类 USE 句子编码余弦相似度 BERT 掩码标记预测 贪婪-WIR BERT 掩码语言模型转换攻击 源自 (["BAE: BERT-based Adversarial Examples for Text Classification" (Garg & Ramakrishnan, 2019)](https://arxiv.org/abs/2004.01970)).
bert-attack 无目标分类 USE 句子编码余弦相似度,最大扰动单词数 BERT 掩码标记预测(含子词扩展) 贪婪-WIR (["BERT-ATTACK: Adversarial Attack Against BERT Using BERT" (Li et al., 2020)](https://arxiv.org/abs/2004.09984))
checklist {无目标,有目标} 分类 Checklist 距离 收缩、扩展和替换命名实体 贪婪-WIR CheckList 中实现的不变性测试。 (["Beyond Accuracy: Behavioral Testing of NLP models with CheckList" (Ribeiro et al., 2020)](https://arxiv.org/abs/2005.04118))
clare 无目标 {分类,蕴含} USE 句子编码余弦相似度 RoBERTa 掩码预测用于令牌交换、插入和合并 贪婪 ["Contextualized Perturbation for Textual Adversarial Attack" (Li et al., 2020)](https://arxiv.org/abs/2009.07502))
deepwordbug {无目标,有目标} 分类 Levenshtein 编辑距离 {字符插入,字符删除,相邻字符交换,字符替换} 贪婪-WIR 贪婪 replace-1 评分和多变换字符交换攻击 (["Black-box Generation of Adversarial Text Sequences to Evade Deep Learning Classifiers" (Gao et al., 2018)](https://arxiv.org/abs/1801.04354)
faster-alzantot 无目标 {分类,蕴含} 扰动单词百分比,语言模型困惑度,词嵌入距离 Counter-fitted 词嵌入交换 遗传算法 修改版、更快的 Alzantot 等人遗传算法版本,源自 (["Certified Robustness to Adversarial Word Substitutions" (Jia et al., 2019)](https://arxiv.org/abs/1909.00986))
hotflip(单词交换) 无目标分类 词嵌入余弦相似度,词性匹配,扰动单词数量 基于梯度的单词交换 束搜索 (["HotFlip: White-Box Adversarial Examples for Text Classification" (Ebrahimi et al., 2017)](https://arxiv.org/abs/1712.06751))
iga 无目标 {分类,蕴含} 扰动单词百分比,词嵌入距离 Counter-fitted 词嵌入交换 遗传算法 改进的基于遗传算法的单词替换 源自 (["Natural Language Adversarial Attacks and Defenses in Word Level (Wang et al., 2019)"](https://arxiv.org/abs/1909.06723)
input-reduction 输入减少 单词删除 贪婪-WIR 基于单词重要性排名的贪婪攻击,通过单词重要性排名在保持预测的同时减少输入 (["Pathologies of Neural Models Make Interpretation Difficult" (Feng et al., 2018)](https://arxiv.org/pdf/1804.07781.pdf))
kuleshov 无目标分类 思维向量编码余弦相似度,语言模型相似概率 Counter-fitted 词嵌入交换 贪婪单词交换 (["Adversarial Examples for Natural Language Classification Problems" (Kuleshov et al., 2018)](https://openreview.net/pdf?id=r1QZ3zbAZ))
pruthi 无目标分类 最小单词长度,最大扰动单词数 {相邻字符交换,字符删除,字符插入,基于键盘的字符交换} 贪婪搜索 模拟常见拼写错误 (["Combating Adversarial Misspellings with Robust Word Recognition" (Pruthi et al., 2019)](https://arxiv.org/abs/1905.11268)
pso 无目标分类 HowNet 单词交换 粒子群优化 (["Word-level Textual Adversarial Attacking as Combinatorial Optimization" (Zang et al., 2020)](https://www.aclweb.org/anthology/2020.acl-main.540/))
pwws 无目标分类 基于 WordNet 的同义词交换 贪婪-WIR(显著性) 基于单词显著性和同义词交换分数的单词重要性排名的贪婪攻击 (["Generating Natural Language Adversarial Examples through Probability Weighted Word Saliency" (Ren et al., 2019)](https://www.aclweb.org/anthology/P19-1103/))
textbugger:(黑盒) 无目标分类 USE 句子编码余弦相似度 {字符插入,字符删除,相邻字符交换,字符替换} 贪婪-WIR ([(["TextBugger: Generating Adversarial Text Against Real-world Applications" (Li et al., 2018)](https://arxiv.org/abs/1812.05271)).
textfooler 无目标 {分类,蕴含} 词嵌入距离,词性匹配,USE 句子编码余弦相似度 Counter-fitted 词嵌入交换 贪婪-WIR 基于单词重要性排名的贪婪攻击 (["Is Bert Really Robust?" (Jin et al., 2019)](https://arxiv.org/abs/1907.11932))

对序列到序列模型 (sequence-to-sequence models) 的攻击:
morpheus 最小 BLEU 分数 (BLEU Score) 屈折词替换 (Inflection Word Swap) 贪婪搜索 (Greedy search) 贪婪攻击,旨在通过用屈折形式替换单词来最小化 BLEU 分数 (["It’s Morphin’ Time! Combating Linguistic Discrimination with Inflectional Perturbations"](https://www.aclweb.org/anthology/2020.acl-main.263.pdf)
seq2sick : (黑盒 (black-box)) 非重叠输出 (Non-overlapping output) 反事实词嵌入替换 (Counter-fitted word embedding swap) 贪婪-WIR (Greedy-WIR) 贪婪攻击,旨在改变输出翻译中的每个单词。目前实现为黑盒 (black-box),并计划像论文中那样更改为白盒 (white-box) (["Seq2Sick: Evaluating the Robustness of Sequence-to-Sequence Models with Adversarial Examples" (Cheng et al., 2018)](https://arxiv.org/abs/1803.01128))

通用 (General):
bad-characters 定向分类 (Targeted classification)、严格定向分类 (Strict targeted classification)、命名实体识别 (Named entity recognition)、Logit 求和 (Logit sum)、最小化 BLEU 分数 (Minimize Bleu score)、最大化 Levenshtein 分数 (Maximize Levenshtein score) (同形异义符 (Homoglyph)、不可见字符 (Invisible Characters)、重排 (Reorderings)、删除 (Deletions)) 词替换 (Word Swap) 差分进化 (DifferentialEvolution) (["Bad Characters: Imperceptible NLP Attacks" (Boucher et al., 2021)](https://arxiv.org/abs/2106.09898))

配方用法示例

以下是一些来自文献的攻击测试命令行示例:

TextFooler 针对在 SST-2 上微调的 BERT:

textattack attack --model bert-base-uncased-sst2 --recipe textfooler --num-examples 10

seq2sick (黑盒 (black-box)) 针对用于英德翻译微调的 T5:

 textattack attack --model t5-en-de --recipe seq2sick --num-examples 100

文本增强:textattack augment

TextAttack 的许多组件都可用于数据增强 (data augmentation)。textattack.Augmenter 类 使用变换和一组约束来增强数据。我们还提供用于数据增强的内置配方 (recipes):

  • wordnet 通过将单词替换为 WordNet 同义词来增强文本
  • embedding 通过将单词替换为反事实嵌入空间 (counter-fitted embedding space) 中的邻居来增强文本,并带有约束以确保其余弦相似度 (cosine similarity) 至少为 0.8
  • charswap 通过替换、删除、插入和交换相邻字符来增强文本
  • eda (Easy Data Augmentation) 通过使用单词插入、替换和删除的组合来增强文本
  • checklist 通过收缩/扩展以及替换名称、位置、数字来增强文本
  • clare 通过使用预训练的掩码语言模型 (masked language model) 进行替换、插入和合并来增强文本
  • back_trans 通过回译 (backtranslation) 方法来增强文本
  • back_transcription 通过反向转录 (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

“embedding"增强配方使用反事实词嵌入最近邻 (counterfitted embedding nearest-neighbors) 来增强数据。

增强 Python 接口

除了命令行界面外,你还可以在自己的代码中导入 Augmenter(增强器)来动态增强文本。所有的 Augmenter 对象都实现了 augmentaugment_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.transformationstextattack.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.']

提示增强

除了常规文本的增强外,你还可以增强提示(prompts),然后使用大型语言模型(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 来训练 LSTMs(长短期记忆网络)、CNNs(卷积神经网络)和 transformers 模型。数据集使用 datasets 包自动加载。

训练示例

在 Yelp Polarity 数据集上训练我们默认的 LSTM 50 个 epoch(轮次):

textattack train --model-name-or-path lstm --dataset yelp_polarity  --epochs 50 --learning-rate 1e-5

CoLA 数据集上微调 bert-base 5 个 epoch:

textattack train --model-name-or-path bert-base-uncased --dataset glue^cola --per-device-train-batch-size 8 --epochs 5

查看数据集:textattack 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 是模型无关 (model-agnostic) 的!您可以使用 TextAttack 分析任何输出 ID、张量或字符串的模型。为了帮助用户,TextAttack 包含了针对不同常见 NLP(自然语言处理)任务的预训练模型。这使得用户更容易开始使用 TextAttack。它还能更公平地比较文献中的攻击方法。

内置模型和数据集

TextAttack 还内置了模型和数据集。我们的命令行界面会自动将正确的数据集匹配到正确的模型。我们为九个 GLUE 任务中的每一个都包含了 82 个不同的(2020 年 10 月)预训练模型,以及一些用于分类、翻译和摘要的常见数据集。

可用预训练模型列表及其验证准确率可在 textattack/models/README.md 查看。您也可以通过 textattack attack --help 查看所有提供的模型和数据集列表。

以下是使用其中一个内置模型的示例(SST-2 数据集会自动加载):

textattack attack --model roberta-base-sst2 --recipe textfooler --num-examples 10

HuggingFace 支持:transformers 模型与 datasets 数据集

我们还为 transformers 预训练模型 和来自 datasets 的数据集提供了内置支持!以下是加载和攻击预训练模型及数据集的示例:

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 来探索其他数据集。

从文件加载模型或数据集

您可以轻松地在本地模型或数据集样本上尝试攻击。要攻击预训练模型,请创建一个短文件,将它们作为变量 modeltokenizer(分词器)加载。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 运行攻击。模型和 tokenizer 将自动加载。

自定义数据集

从文件加载数据集

从文件加载数据集与从文件加载模型非常相似。“数据集”是任意 (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 类使用数据集

为了允许在序列分词后进行单词替换,我们包含了一个 AttackedText 对象,它维护令牌列表和原始文本(包括标点符号)。我们优先使用此对象,而不是单词列表或纯文本。

攻击及如何设计新攻击

我们将攻击定义为由四个组件组成:目标函数 (Goal Function)(确定攻击是否成功)、约束条件 (Constraints)(定义哪些扰动有效)、变换 (Transformation)(给定输入生成潜在修改)以及搜索方法 (Search Method)(遍历可能扰动的搜索空间)。攻击旨在扰动输入文本,使得模型输出满足目标函数(即指示攻击是否成功),且扰动符合一组约束条件(例如,语法约束、语义相似度约束)。搜索方法用于寻找一系列变换,以产生成功的对抗样本 (adversarial example)。

这种模块化设计将对抗攻击方法统一到一个系统中,使我们能够轻松组装文献中的攻击,同时重用跨攻击共享的组件。我们提供了文献中 16 种对抗攻击配方的干净、可读的实现(见上方表格)。首次,这些攻击可以在标准化设置中进行基准测试、比较和分析。

TextAttack 是模型无关的——意味着它可以在任何深度学习框架实现的模型上运行攻击。模型对象必须能够接受字符串(或字符串列表)并返回可由目标函数处理的输出。例如,机器翻译模型以字符串列表作为输入,并生成字符串列表作为输出。分类和蕴含模型返回一个分数数组。只要用户的模型符合此规范,该模型就适合与 TextAttack 一起使用。

目标函数

GoalFunction 接受 AttackedText 对象作为输入,对其进行评分,并确定攻击是否成功,返回 GoalFunctionResult(目标函数结果)。

约束条件

Constraint 接受当前的 AttackedText 和转换后的 AttackedText 列表作为输入。对于每个转换选项,它返回一个布尔值,表示是否满足约束条件。

变换

Transformation 接受 AttackedText 作为输入,并返回可能的转换后 AttackedText 列表。例如,变换可能会返回所有可能的同义词替换。

搜索方法

SearchMethod 接受初始 GoalFunctionResult 作为输入,并返回最终的 GoalFunctionResult。搜索功能可以访问 get_transformations 函数,该函数接受 AttackedText 对象作为输入,并输出过滤掉未满足所有攻击约束的可能变换列表。搜索由对 get_transformations 的连续调用组成,直到搜索成功(使用 get_goal_results 确定)或耗尽。

关于基准测试攻击

  • 查看我们的分析论文:《Searching for a Search Method: Benchmarking Search Algorithms for Generating NLP Adversarial Examples》,发表于 EMNLP BlackBoxNLP

  • 正如我们在上述论文中强调的,我们不推荐直接开箱即用(out of the box)地比较攻击配方(Attack Recipes)。

  • 这一观点源于近期文献中的攻击配方在设置约束条件(constraints)时使用了不同的方法或阈值。如果约束空间(constraint space)不保持恒定,攻击成功率的提升可能源于搜索(search)或转换方法的改进,或者更宽松的搜索空间(search space)。

  • 我们用于基准测试脚本和结果的 GitHub 仓库:TextAttack-Search-Benchmark Github

关于自然语言中生成的对抗样本 (Adversarial Examples) 的质量

  • 我们的分析论文发表于 EMNLP Findings
  • 我们分析了两种最先进 (State-of-the-art) 的同义词替换攻击生成的对抗样本。我们发现它们的扰动 (perturbations) 通常无法保留语义,且 38% 引入了语法错误。人类调查表明,为了成功保留语义,我们需要显著提高交换词嵌入 (embeddings) 之间以及原始句子与扰动句子的句子编码 (sentence encodings) 之间的最小余弦相似度 (cosine similarities)。当调整约束条件以更好地保留语义和语法正确性 (grammaticality) 时,攻击成功率下降了超过 70 个百分点。
  • 我们用于重新评估结果的 GitHub 仓库:Reevaluating-NLP-Adversarial-Examples Github
  • 正如我们在该分析论文中所强调的,我们建议研究人员和用户格外留意 (EXTREMELY mindful) 自然语言中生成的对抗样本的质量
  • 我们建议该领域使用基于人工评估得出的阈值来设置约束条件

多语言支持

为 TextAttack 做贡献

我们欢迎建议和贡献!提交 Issue 或 Pull Request,我们将尽力及时回复。TextAttack 目前处于"alpha"阶段,我们正在努力改进其功能和设计。

有关贡献的详细信息,请参见 CONTRIBUTING.md

引用 TextAttack

如果您在研究中使用 TextAttack,请引用 TextAttack: A Framework for Adversarial Attacks, Data Augmentation, and Adversarial Training in 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}
}

版本历史

v0.3.102024/03/11
v0.3.92023/09/11
v0.3.82022/11/02
v0.3.72022/08/14
v0.3.52022/05/25
v0.3.42021/11/10
v0.3.32021/08/03
v0.3.22021/07/28
v0.3.02021/06/25
v0.2.152020/12/27
0.2.142020/11/18
0.2.122020/11/13
0.2.02020/07/09
0.1.02020/06/24
0.0.3.02020/06/11
0.0.22020/05/21

常见问题

相似工具推荐

stable-diffusion-webui

stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面,旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点,将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。 无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师,还是想要深入探索模型潜力的开发者与研究人员,都能从中获益。其核心亮点在于极高的功能丰富度:不仅支持文生图、图生图、局部重绘(Inpainting)和外绘(Outpainting)等基础模式,还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外,它内置了 GFPGAN 和 CodeFormer 等人脸修复工具,支持多种神经网络放大算法,并允许用户通过插件系统无限扩展能力。即使是显存有限的设备,stable-diffusion-webui 也提供了相应的优化选项,让高质量的 AI 艺术创作变得触手可及。

162.1k|★★★☆☆|今天
开发框架图像Agent

everything-claude-code

everything-claude-code 是一套专为 AI 编程助手(如 Claude Code、Codex、Cursor 等)打造的高性能优化系统。它不仅仅是一组配置文件,而是一个经过长期实战打磨的完整框架,旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。 通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能,everything-claude-code 能显著提升 AI 在复杂任务中的表现,帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略,使得模型响应更快、成本更低,同时有效防御潜在的攻击向量。 这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库,还是需要 AI 协助进行安全审计与自动化测试,everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目,它融合了多语言支持与丰富的实战钩子(hooks),让 AI 真正成长为懂上

139k|★★☆☆☆|今天
开发框架Agent语言模型

ComfyUI

ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎,专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式,采用直观的节点式流程图界面,让用户通过连接不同的功能模块即可构建个性化的生成管线。 这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景,也能自由组合模型、调整参数并实时预览效果,轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性,不仅支持 Windows、macOS 和 Linux 全平台,还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构,并率先支持 SDXL、Flux、SD3 等前沿模型。 无论是希望深入探索算法潜力的研究人员和开发者,还是追求极致创作自由度的设计师与资深 AI 绘画爱好者,ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能,使其成为当前最灵活、生态最丰富的开源扩散模型工具之一,帮助用户将创意高效转化为现实。

107.7k|★★☆☆☆|2天前
开发框架图像Agent

NextChat

NextChat 是一款轻量且极速的 AI 助手,旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性,以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发,NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。 这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言,它也提供了便捷的自托管方案,支持一键部署到 Vercel 或 Zeabur 等平台。 NextChat 的核心亮点在于其广泛的模型兼容性,原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型,让用户在一个界面即可自由切换不同 AI 能力。此外,它还率先支持 MCP(Model Context Protocol)协议,增强了上下文处理能力。针对企业用户,NextChat 提供专业版解决方案,具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能,满足公司对数据隐私和个性化管理的高标准要求。

87.6k|★★☆☆☆|今天
开发框架语言模型

ML-For-Beginners

ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程,旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周,包含 26 节精炼课程和 52 道配套测验,内容涵盖从基础概念到实际应用的完整流程,有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。 无论是希望转型的开发者、需要补充算法背景的研究人员,还是对人工智能充满好奇的普通爱好者,都能从中受益。课程不仅提供了清晰的理论讲解,还强调动手实践,让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持,通过自动化机制提供了包括简体中文在内的 50 多种语言版本,极大地降低了全球不同背景用户的学习门槛。此外,项目采用开源协作模式,社区活跃且内容持续更新,确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路,ML-For-Beginners 将是理想的起点。

85k|★★☆☆☆|今天
图像数据工具视频

ragflow

RAGFlow 是一款领先的开源检索增强生成(RAG)引擎,旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体(Agent)能力相结合,不仅支持从各类文档中高效提取知识,还能让模型基于这些知识进行逻辑推理和任务执行。 在大模型应用中,幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构(如表格、图表及混合排版),显著提升了信息检索的准确度,从而有效减少模型“胡编乱造”的现象,确保回答既有据可依又具备时效性。其内置的智能体机制更进一步,使系统不仅能回答问题,还能自主规划步骤解决复杂问题。 这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统,还是致力于探索大模型在垂直领域落地的创新者,都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口,既降低了非算法背景用户的上手门槛,也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目,它正成为连接通用大模型与行业专有知识之间的重要桥梁。

77.1k|★★★☆☆|昨天
Agent图像开发框架