生成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 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 }
}