Package: textattack
TextAttack 🐙Generating adversarial examples for NLP models[TextAttack Documentation on ReadTheDocs]About•Setup•Usage•DesignAboutTextAttack is a Python framework for adversarial attacks, data augmentation, and model training in NLP.If you're looking for information about TextAttack's menagerie of pre-trained models, you might want theTextAttack Model Zoopage.Slack ChannelFor help and realtime updates related to TextAttack, pleasejoin the TextAttack Slack!Why TextAttack?There are lots of reasons to use TextAttack:Understand NLP models betterby running different adversarial attacks on them and examining the outputResearch and develop different NLP adversarial attacksusing the TextAttack framework and library of componentsAugment your datasetto increase model generalization and robustness downstreamTrain NLP modelsusing just a single command (all downloads included!)SetupInstallationYou should be running Python 3.6+ to use this package. A CUDA-compatible GPU is optional but will greatly improve code speed. TextAttack is available through pip:pipinstalltextattackOnce TextAttack is installed, you can run it via command-line (textattack ...)
or via python module (python -m textattack ...).Tip: TextAttack downloads files to~/.cache/textattack/by default. This includes pretrained models,
dataset samples, and the configuration fileconfig.yaml. To change the cache path, set the
environment variableTA_CACHE_DIR. (for example:TA_CACHE_DIR=/tmp/ textattack attack ...).UsageHelp:textattack --helpTextAttack's main features can all be accessed via thetextattackcommand. Two very
common commands aretextattack attack <args>, andtextattack augment <args>. You can see more
information about all commands usingtextattack--helpor a specific command using, for example,textattackattack--helpTheexamples/folder includes scripts showing common TextAttack usage for training models, running attacks, and augmenting a CSV file.Thedocumentation websitecontains walkthroughs explaining basic usage of TextAttack, including building a custom transformation and a custom constraint..Running Attacks:textattack attack --helpThe easiest way to try out an attack is via the command-line interface,textattack attack.Tip:If your machine has multiple GPUs, you can distribute the attack across them using the--paralleloption. For some attacks, this can really help performance. (If you want to attack Keras models in parallel, please check outexamples/attack/attack_keras_parallel.pyinstead)Here are some concrete examples:TextFooler on BERT trained on the MR sentiment classification dataset:textattackattack--recipetextfooler--modelbert-base-uncased-mr--num-examples100DeepWordBug on DistilBERT trained on the Quora Question Pairs paraphrase identification dataset:textattackattack--modeldistilbert-base-uncased-cola--recipedeepwordbug--num-examples100Beam search with beam width 4 and word embedding transformation and untargeted goal function on an LSTM:textattackattack--modellstm-mr--num-examples20\--search-methodbeam-search^beam_width=4--transformationword-swap-embedding\--constraintsrepeatstopwordmax-words-perturbed^max_num_words=2embedding^min_cos_sim=0.8part-of-speech\--goal-functionuntargeted-classificationTip:Instead of specifying a dataset and number of examples, you can pass--interactiveto attack samples inputted by the user.Attacks and Papers Implemented ("Attack Recipes"):textattack attack --recipe [recipe_name]We include attack recipes which implement attacks from the literature. You can list attack recipes usingtextattack list attack-recipes.To run an attack recipe:textattack attack --recipe [recipe_name]Attack Recipe NameGoal FunctionConstraintsEnforcedTransformationSearch MethodMain IdeaAttacks on classification tasks, like sentiment classification and entailment:a2tUntargeted {Classification, Entailment}Percentage of words perturbed, Word embedding distance, DistilBERT sentence encoding cosine similarity, part-of-speech consistencyCounter-fitted word embedding swap (or) BERT Masked Token PredictionGreedy-WIR (gradient)from (["Towards Improving Adversarial Training of NLP Models" (Yoo et al., 2021)](https://arxiv.org/abs/2109.00544))alzantotUntargeted {Classification, Entailment}Percentage of words perturbed, Language Model perplexity, Word embedding distanceCounter-fitted word embedding swapGenetic Algorithmfrom (["Generating Natural Language Adversarial Examples" (Alzantot et al., 2018)](https://arxiv.org/abs/1804.07998))baeUntargeted ClassificationUSE sentence encoding cosine similarityBERT Masked Token PredictionGreedy-WIRBERT masked language model transformation attack from (["BAE: BERT-based Adversarial Examples for Text Classification" (Garg & Ramakrishnan, 2019)](https://arxiv.org/abs/2004.01970)).bert-attackUntargeted ClassificationUSE sentence encoding cosine similarity, Maximum number of words perturbedBERT Masked Token Prediction (with subword expansion)Greedy-WIR(["BERT-ATTACK: Adversarial Attack Against BERT Using BERT" (Li et al., 2020)](https://arxiv.org/abs/2004.09984))checklist{Untargeted, Targeted} Classificationchecklist distancecontract, extend, and substitutes name entitiesGreedy-WIRInvariance testing implemented in CheckList . (["Beyond Accuracy: Behavioral Testing of NLP models with CheckList" (Ribeiro et al., 2020)](https://arxiv.org/abs/2005.04118))clareUntargeted {Classification, Entailment}USE sentence encoding cosine similarityRoBERTa Masked Prediction for token swap, insert and mergeGreedy["Contextualized Perturbation for Textual Adversarial Attack" (Li et al., 2020)](https://arxiv.org/abs/2009.07502))deepwordbug{Untargeted, Targeted} ClassificationLevenshtein edit distance{Character Insertion, Character Deletion, Neighboring Character Swap, Character Substitution}Greedy-WIRGreedy replace-1 scoring and multi-transformation character-swap attack (["Black-box Generation of Adversarial Text Sequences to Evade Deep Learning Classifiers" (Gao et al., 2018)](https://arxiv.org/abs/1801.04354)fast-alzantotUntargeted {Classification, Entailment}Percentage of words perturbed, Language Model perplexity, Word embedding distanceCounter-fitted word embedding swapGenetic AlgorithmModified, faster version of the Alzantot et al. genetic algorithm, from (["Certified Robustness to Adversarial Word Substitutions" (Jia et al., 2019)](https://arxiv.org/abs/1909.00986))hotflip(word swap)Untargeted ClassificationWord Embedding Cosine Similarity, Part-of-speech match, Number of words perturbedGradient-Based Word SwapBeam search(["HotFlip: White-Box Adversarial Examples for Text Classification" (Ebrahimi et al., 2017)](https://arxiv.org/abs/1712.06751))igaUntargeted {Classification, Entailment}Percentage of words perturbed, Word embedding distanceCounter-fitted word embedding swapGenetic AlgorithmImproved genetic algorithm -based word substitution from (["Natural Language Adversarial Attacks and Defenses in Word Level (Wang et al., 2019)"](https://arxiv.org/abs/1909.06723)input-reductionInput ReductionWord deletionGreedy-WIRGreedy attack with word importance ranking , Reducing the input while maintaining the prediction through word importance ranking (["Pathologies of Neural Models Make Interpretation Difficult" (Feng et al., 2018)](https://arxiv.org/pdf/1804.07781.pdf))kuleshovUntargeted ClassificationThought vector encoding cosine similarity, Language model similarity probabilityCounter-fitted word embedding swapGreedy word swap(["Adversarial Examples for Natural Language Classification Problems" (Kuleshov et al., 2018)](https://openreview.net/pdf?id=r1QZ3zbAZ))pruthiUntargeted ClassificationMinimum word length, Maximum number of words perturbed{Neighboring Character Swap, Character Deletion, Character Insertion, Keyboard-Based Character Swap}Greedy searchsimulates common typos (["Combating Adversarial Misspellings with Robust Word Recognition" (Pruthi et al., 2019)](https://arxiv.org/abs/1905.11268)psoUntargeted ClassificationHowNet Word SwapParticle Swarm Optimization(["Word-level Textual Adversarial Attacking as Combinatorial Optimization" (Zang et al., 2020)](https://www.aclweb.org/anthology/2020.acl-main.540/))pwwsUntargeted ClassificationWordNet-based synonym swapGreedy-WIR (saliency)Greedy attack with word importance ranking based on word saliency and synonym swap scores (["Generating Natural Language Adversarial Examples through Probability Weighted Word Saliency" (Ren et al., 2019)](https://www.aclweb.org/anthology/P19-1103/))textbugger: (black-box)Untargeted ClassificationUSE sentence encoding cosine similarity{Character Insertion, Character Deletion, Neighboring Character Swap, Character Substitution}Greedy-WIR([(["TextBugger: Generating Adversarial Text Against Real-world Applications" (Li et al., 2018)](https://arxiv.org/abs/1812.05271)).textfoolerUntargeted {Classification, Entailment}Word Embedding Distance, Part-of-speech match, USE sentence encoding cosine similarityCounter-fitted word embedding swapGreedy-WIRGreedy attack with word importance ranking  (["Is Bert Really Robust?" (Jin et al., 2019)](https://arxiv.org/abs/1907.11932))Attacks on sequence-to-sequence models:morpheusMinimum BLEU ScoreInflection Word SwapGreedy searchGreedy to replace words with their inflections with the goal of minimizing BLEU score (["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 outputCounter-fitted word embedding swapGreedy-WIRGreedy attack with goal of changing every word in the output translation. Currently implemented as black-box with plans to change to white-box as done in paper (["Seq2Sick: Evaluating the Robustness of Sequence-to-Sequence Models with Adversarial Examples" (Cheng et al., 2018)](https://arxiv.org/abs/1803.01128))Recipe Usage ExamplesHere are some examples of testing attacks from the literature from the command-line:TextFooler against BERT fine-tuned on SST-2:textattackattack--modelbert-base-uncased-sst2--recipetextfooler--num-examples10seq2sick (black-box) against T5 fine-tuned for English-German translation:textattackattack--modelt5-en-de--recipeseq2sick--num-examples100Augmenting Text:textattack augmentMany of the components of TextAttack are useful for data augmentation. Thetextattack.Augmenterclass
uses a transformation and a list of constraints to augment data. We also offer  built-in recipes
for data augmentation:wordnetaugments text by replacing words with WordNet synonymsembeddingaugments text by replacing words with neighbors in the counter-fitted embedding space, with a constraint to ensure their cosine similarity is at least 0.8charswapaugments text by substituting, deleting, inserting, and swapping adjacent charactersedaaugments text with a combination of word insertions, substitutions and deletions.checklistaugments text by contraction/extension and by substituting names, locations, numbers.clareaugments text by replacing, inserting, and merging with a pre-trained masked language model.Augmentation Command-Line InterfaceThe easiest way to use our data augmentation tools is withtextattack augment <args>.textattack augmenttakes an input CSV file and text column to augment, along with the number of words to change per augmentation
and the number of augmentations per input example. It outputs a CSV in the same format with all the augmentation
examples corresponding to the proper columns.For example, given the following asexamples.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 .", 0The commandtextattackaugment--input-csvexamples.csv--output-csvoutput.csv--input-columntext--recipeembedding--pct-words-to-swap.1--transformations-per-example2--exclude-originalwill augment thetextcolumn by altering 10% of each example's words, generating twice as many augmentations as original inputs, and exclude the original inputs from the
output CSV. (All of this will be saved toaugment.csvby default.)Tip:Just as running attacks interactively, you can also pass--interactiveto augment samples inputted by the user to quickly try out different augmentation recipes!After augmentation, here are the contents ofaugment.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 .,0The 'embedding' augmentation recipe uses counterfitted embedding nearest-neighbors to augment data.Augmentation Python InterfaceIn addition to the command-line interface, you can augment text dynamically by importing theAugmenterin your own code. AllAugmenterobjects implementaugmentandaugment_manyto generate augmentations
of a string or a list of strings. Here's an example of how to use theEmbeddingAugmenterin a python script:>>>fromtextattack.augmentationimportEmbeddingAugmenter>>>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.']You can also create your own augmenter from scratch by importing transformations/constraints fromtextattack.transformationsandtextattack.constraints. Here's an example that generates augmentations of a string usingWordSwapRandomCharacterDeletion:>>>fromtextattack.transformationsimportWordSwapRandomCharacterDeletion>>>fromtextattack.transformationsimportCompositeTransformation>>>fromtextattack.augmentationimportAugmenter>>>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.']Training Models:textattack trainOur model training code is available viatextattack trainto help you train LSTMs,
CNNs, andtransformersmodels using TextAttack out-of-the-box. Datasets are
automatically loaded using thedatasetspackage.Training ExamplesTrain our default LSTM for 50 epochs on the Yelp Polarity dataset:textattacktrain--model-name-or-pathlstm--datasetyelp_polarity--epochs50--learning-rate1e-5Fine-Tunebert-baseon theCoLAdataset for 5 epochs*:textattacktrain--model-name-or-pathbert-base-uncased--datasetglue^cola--per-device-train-batch-size8--epochs5To check datasets:textattack peek-datasetTo take a closer look at a dataset, usetextattack peek-dataset. TextAttack will print some cursory statistics about the inputs and outputs from the dataset. For example,textattackpeek-dataset--dataset-from-huggingfacesnliwill show information about the SNLI dataset from the NLP package.To list functional components:textattack listThere are lots of pieces in TextAttack, and it can be difficult to keep track of all of them. You can usetextattack listto list components, for example, pretrained models (textattack list models) or available search methods (textattack list search-methods).DesignModelsTextAttack is model-agnostic!  You can useTextAttackto analyze any model that outputs IDs, tensors, or strings. To help users, TextAttack includes pre-trained models for different common NLP tasks. This makes it easier for
users to get started with TextAttack. It also enables a more fair comparison of attacks from
the literature.Built-in Models and DatasetsTextAttack also comes built-in with models and datasets. Our command-line interface will automatically match the correct
dataset to the correct model. We include 82 different (Oct 2020) pre-trained models for each of the nineGLUEtasks, as well as some common datasets for classification, translation, and summarization.A list of available pretrained models and their validation accuracies is available attextattack/models/README.md. You can also view a full list of provided models
& datasets viatextattack attack --help.Here's an example of using one of the built-in models (the SST-2 dataset is automatically loaded):textattackattack--modelroberta-base-sst2--recipetextfooler--num-examples10HuggingFace support:transformersmodels anddatasetsdatasetsWe also provide built-in support fortransformerspretrained modelsand datasets from thedatasetspackage! Here's an example of loading
and attacking a pre-trained model and dataset:textattackattack--model-from-huggingfacedistilbert-base-uncased-finetuned-sst-2-english--dataset-from-huggingfaceglue^sst2--recipedeepwordbug--num-examples10You can explore other pre-trained models using the--model-from-huggingfaceargument, or other datasets by changing--dataset-from-huggingface.Loading a model or dataset from a fileYou can easily try out an attack on a local model or dataset sample. To attack a pre-trained model,
create a short file that loads them as variablesmodelandtokenizer.  Thetokenizermust
be able to transform string inputs to lists or tensors of IDs using a method calledencode(). The
model must take inputs via the__call__method.Custom Model from a fileTo experiment with a model you've trained, you could create the following file
and name itmy_model.py:model=load_your_model_with_custom_code()# replace this line with your model loading codetokenizer=load_your_tokenizer_with_custom_code()# replace this line with your tokenizer loading codeThen, run an attack with the argument--model-from-file my_model.py. The model and tokenizer will be loaded automatically.Custom DatasetsDataset from a fileLoading a dataset from a file is very similar to loading a model from a file. A 'dataset' is any iterable of(input, output)pairs.
The following example would load a sentiment classification dataset from filemy_dataset.py:dataset=[('Today was....',1),('This movie is...',0),...]You can then run attacks on samples from this dataset by adding the argument--dataset-from-file my_dataset.py.Dataset loading via other mechanism, see:more details at hereimporttextattackmy_dataset=[("text",label),....]new_dataset=textattack.datasets.Dataset(my_dataset)Dataset via AttackedText classTo allow for word replacement after a sequence has been tokenized, we include anAttackedTextobject
which maintains both a list of tokens and the original text, with punctuation. We use this object in favor of a list of words or just raw text.Attacks and how to design a new attackWe formulate an attack as consisting of four components: agoal functionwhich determines if the attack has succeeded,constraintsdefining which perturbations are valid, atransformationthat generates potential modifications given an input, and asearch methodwhich traverses through the search space of possible perturbations. The attack attempts to perturb an input text such that the model output fulfills the goal function (i.e., indicating whether the attack is successful) and the perturbation adheres to the set of constraints (e.g., grammar constraint, semantic similarity constraint). A search method is used to find a sequence of transformations that produce a successful adversarial example.This modular design unifies adversarial attack methods into one system, enables us to easily assemble attacks from the literature while re-using components that are shared across attacks. We provides clean, readable implementations of 16 adversarial attack recipes from the literature (see above table). For the first time, these attacks can be benchmarked, compared, and analyzed in a standardized setting.TextAttack is model-agnostic - meaning it can run attacks on models implemented in any deep learning framework. Model objects must be able to take a string (or list of strings) and return an output that can be processed by the goal function. For example, machine translation models take a list of strings as input and produce a list of strings as output. Classification and entailment models return an array of scores. As long as the user's model meets this specification, the model is fit to use with TextAttack.Goal FunctionsAGoalFunctiontakes as input anAttackedTextobject, scores it, and determines whether the attack has succeeded, returning aGoalFunctionResult.ConstraintsAConstrainttakes as input a currentAttackedText, and a list of transformedAttackedTexts. For each transformed option, it returns a boolean representing whether the constraint is met.TransformationsATransformationtakes as input anAttackedTextand returns a list of possible transformedAttackedTexts. For example, a transformation might return all possible synonym replacements.Search MethodsASearchMethodtakes as input an initialGoalFunctionResultand returns a finalGoalFunctionResultThe search is given access to theget_transformationsfunction, which takes as input anAttackedTextobject and outputs a list of possible transformations filtered by meeting all of the attack’s constraints. A search consists of successive calls toget_transformationsuntil the search succeeds (determined usingget_goal_results) or is exhausted.On Benchmarking AttacksSee our analysis paper: Searching for a Search Method: Benchmarking Search Algorithms for Generating NLP Adversarial Examples atEMNLP BlackBoxNLP.As we emphasized in the above paper, we don't recommend to directly compare Attack Recipes out of the box.This comment is due to that attack recipes in the recent literature used different ways or thresholds in setting up their constraints. Without the constraint space held constant, an increase in attack success rate could come from an improved search or transformation method or a less restrictive search space.Our Github on benchmarking scripts and results:TextAttack-Search-Benchmark GithubOn Quality of Generated Adversarial Examples in Natural LanguageOur analysis Paper inEMNLP FindingsWe analyze the generated adversarial examples of two state-of-the-art synonym substitution attacks. We find that their perturbations often do not preserve semantics, and 38% introduce grammatical errors. Human surveys reveal that to successfully preserve semantics, we need to significantly increase the minimum cosine similarities between the embeddings of swapped words and between the sentence encodings of original and perturbed sentences.With constraints adjusted to better preserve semantics and grammaticality, the attack success rate drops by over 70 percentage points.Our Github on Reevaluation results:Reevaluating-NLP-Adversarial-Examples GithubAs we have emphasized in this analysis paper, we recommend researchers and users to be EXTREMELY mindful on the quality of generated adversarial examples in natural languageWe recommend the field to use human-evaluation derived thresholds for setting up constraintsMulti-lingual Supportsee example code:https://github.com/QData/TextAttack/blob/master/examples/attack/attack_camembert.pyfor using our framework to attack French-BERT.see tutorial notebook:https://textattack.readthedocs.io/en/latest/2notebook/Example_4_CamemBERT.htmlfor using our framework to attack French-BERT.SeeREADME_ZH.mdfor our README in ChineseContributing to TextAttackWe welcome suggestions and contributions! Submit an issue or pull request and we will do our best to respond in a timely manner. TextAttack is currently in an "alpha" stage in which we are working to improve its capabilities and design.SeeCONTRIBUTING.mdfor detailed information on contributing.Citing TextAttackIf you use TextAttack for your research, please citeTextAttack: 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}}