TextAttack 🐙 is a Python framework for adversarial attacks, data augmentation, and model training in NLP

Overview

TextAttack 🐙

Generating adversarial examples for NLP models

[TextAttack Documentation on ReadTheDocs]

AboutSetupUsageDesign

Github Runner Covergae Status PyPI version

TextAttack Demo GIF

About

TextAttack 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 the TextAttack Model Zoo page.

Slack Channel

For help and realtime updates related to TextAttack, please join the TextAttack Slack!

Why TextAttack?

There are lots of reasons to use TextAttack:

  1. Understand NLP models better by running different adversarial attacks on them and examining the output
  2. Research and develop different NLP adversarial attacks using the TextAttack framework and library of components
  3. Augment your dataset to increase model generalization and robustness downstream
  4. Train NLP models using just a single command (all downloads included!)

Setup

Installation

You 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:

pip install textattack

Once 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 file config.yaml. To change the cache path, set the environment variable TA_CACHE_DIR. (for example: TA_CACHE_DIR=/tmp/ textattack attack ...).

Usage

Help: textattack --help

TextAttack's main features can all be accessed via the textattack command. Two very common commands are textattack attack , and textattack augment . You can see more information about all commands using

textattack --help 

or a specific command using, for example,

textattack attack --help

The examples/ folder includes scripts showing common TextAttack usage for training models, running attacks, and augmenting a CSV file.

The documentation website contains walkthroughs explaining basic usage of TextAttack, including building a custom transformation and a custom constraint..

Running Attacks: textattack attack --help

The 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 --parallel option. For some attacks, this can really help performance. (If you want to attack Keras models in parallel, please check out examples/attack/attack_keras_parallel.py instead)

Here are some concrete examples:

TextFooler on BERT trained on the MR sentiment classification dataset:

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

DeepWordBug on DistilBERT trained on the Quora Question Pairs paraphrase identification dataset:

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

Beam search with beam width 4 and word embedding transformation and untargeted goal function on an 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

Tip: Instead of specifying a dataset and number of examples, you can pass --interactive to 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 using textattack list attack-recipes.

To run an attack recipe: textattack attack --recipe [recipe_name]

TextAttack Overview

Attack Recipe Name Goal Function ConstraintsEnforced Transformation Search Method Main Idea

Attacks on classification tasks, like sentiment classification and entailment:
a2t Untargeted {Classification, Entailment} Percentage of words perturbed, Word embedding distance, DistilBERT sentence encoding cosine similarity, part-of-speech consistency Counter-fitted word embedding swap (or) BERT Masked Token Prediction Greedy-WIR (gradient) from (["Towards Improving Adversarial Training of NLP Models" (Yoo et al., 2021)](https://arxiv.org/abs/2109.00544))
alzantot Untargeted {Classification, Entailment} Percentage of words perturbed, Language Model perplexity, Word embedding distance Counter-fitted word embedding swap Genetic Algorithm from (["Generating Natural Language Adversarial Examples" (Alzantot et al., 2018)](https://arxiv.org/abs/1804.07998))
bae Untargeted Classification USE sentence encoding cosine similarity BERT Masked Token Prediction Greedy-WIR BERT masked language model transformation attack from (["BAE: BERT-based Adversarial Examples for Text Classification" (Garg & Ramakrishnan, 2019)](https://arxiv.org/abs/2004.01970)).
bert-attack Untargeted Classification USE sentence encoding cosine similarity, Maximum number of words perturbed BERT 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} Classification checklist distance contract, extend, and substitutes name entities Greedy-WIR Invariance testing implemented in CheckList . (["Beyond Accuracy: Behavioral Testing of NLP models with CheckList" (Ribeiro et al., 2020)](https://arxiv.org/abs/2005.04118))
clare Untargeted {Classification, Entailment} USE sentence encoding cosine similarity RoBERTa Masked Prediction for token swap, insert and merge Greedy ["Contextualized Perturbation for Textual Adversarial Attack" (Li et al., 2020)](https://arxiv.org/abs/2009.07502))
deepwordbug {Untargeted, Targeted} Classification Levenshtein edit distance {Character Insertion, Character Deletion, Neighboring Character Swap, Character Substitution} Greedy-WIR Greedy 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-alzantot Untargeted {Classification, Entailment} Percentage of words perturbed, Language Model perplexity, Word embedding distance Counter-fitted word embedding swap Genetic Algorithm Modified, 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 Classification Word Embedding Cosine Similarity, Part-of-speech match, Number of words perturbed Gradient-Based Word Swap Beam search (["HotFlip: White-Box Adversarial Examples for Text Classification" (Ebrahimi et al., 2017)](https://arxiv.org/abs/1712.06751))
iga Untargeted {Classification, Entailment} Percentage of words perturbed, Word embedding distance Counter-fitted word embedding swap Genetic Algorithm Improved 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-reduction Input Reduction Word deletion Greedy-WIR Greedy 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))
kuleshov Untargeted Classification Thought vector encoding cosine similarity, Language model similarity probability Counter-fitted word embedding swap Greedy word swap (["Adversarial Examples for Natural Language Classification Problems" (Kuleshov et al., 2018)](https://openreview.net/pdf?id=r1QZ3zbAZ))
pruthi Untargeted Classification Minimum word length, Maximum number of words perturbed {Neighboring Character Swap, Character Deletion, Character Insertion, Keyboard-Based Character Swap} Greedy search simulates common typos (["Combating Adversarial Misspellings with Robust Word Recognition" (Pruthi et al., 2019)](https://arxiv.org/abs/1905.11268)
pso Untargeted Classification HowNet Word Swap Particle Swarm Optimization (["Word-level Textual Adversarial Attacking as Combinatorial Optimization" (Zang et al., 2020)](https://www.aclweb.org/anthology/2020.acl-main.540/))
pwws Untargeted Classification WordNet-based synonym swap Greedy-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 Classification USE 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)).
textfooler Untargeted {Classification, Entailment} Word Embedding Distance, Part-of-speech match, USE sentence encoding cosine similarity Counter-fitted word embedding swap Greedy-WIR Greedy 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:
morpheus Minimum BLEU Score Inflection Word Swap Greedy search Greedy 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 output Counter-fitted word embedding swap Greedy-WIR Greedy 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 Examples

Here are some examples of testing attacks from the literature from the command-line:

TextFooler against BERT fine-tuned on SST-2:

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

seq2sick (black-box) against T5 fine-tuned for English-German translation:

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

Augmenting Text: textattack augment

Many of the components of TextAttack are useful for data augmentation. The textattack.Augmenter class uses a transformation and a list of constraints to augment data. We also offer built-in recipes for data augmentation:

  • wordnet augments text by replacing words with WordNet synonyms
  • embedding augments text by replacing words with neighbors in the counter-fitted embedding space, with a constraint to ensure their cosine similarity is at least 0.8
  • charswap augments text by substituting, deleting, inserting, and swapping adjacent characters
  • eda augments text with a combination of word insertions, substitutions and deletions.
  • checklist augments text by contraction/extension and by substituting names, locations, numbers.
  • clare augments text by replacing, inserting, and merging with a pre-trained masked language model.

Augmentation Command-Line Interface

The easiest way to use our data augmentation tools is with textattack augment . textattack augment takes 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 as 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

The command

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

will augment the text column 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 to augment.csv by default.)

Tip: Just as running attacks interactively, you can also pass --interactive to augment samples inputted by the user to quickly try out different augmentation recipes!

After augmentation, here are the contents of 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

The 'embedding' augmentation recipe uses counterfitted embedding nearest-neighbors to augment data.

Augmentation Python Interface

In addition to the command-line interface, you can augment text dynamically by importing the Augmenter in your own code. All Augmenter objects implement augment and augment_many to generate augmentations of a string or a list of strings. Here's an example of how to use the EmbeddingAugmenter in a python script:

>>> 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.']

You can also create your own augmenter from scratch by importing transformations/constraints from textattack.transformations and textattack.constraints. Here's an example that generates augmentations of a string using 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.']

Training Models: textattack train

Our model training code is available via textattack train to help you train LSTMs, CNNs, and transformers models using TextAttack out-of-the-box. Datasets are automatically loaded using the datasets package.

Training Examples

Train our default LSTM for 50 epochs on the Yelp Polarity dataset:

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

Fine-Tune bert-base on the CoLA dataset for 5 epochs*:

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

To check datasets: textattack peek-dataset

To take a closer look at a dataset, use textattack peek-dataset. TextAttack will print some cursory statistics about the inputs and outputs from the dataset. For example,

textattack peek-dataset --dataset-from-huggingface snli

will show information about the SNLI dataset from the NLP package.

To list functional components: textattack list

There are lots of pieces in TextAttack, and it can be difficult to keep track of all of them. You can use textattack list to list components, for example, pretrained models (textattack list models) or available search methods (textattack list search-methods).

Design

Models

TextAttack is model-agnostic! You can use TextAttack to 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 Datasets

TextAttack 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 nine GLUE tasks, as well as some common datasets for classification, translation, and summarization.

A list of available pretrained models and their validation accuracies is available at textattack/models/README.md. You can also view a full list of provided models & datasets via textattack attack --help.

Here's an example of using one of the built-in models (the SST-2 dataset is automatically loaded):

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

HuggingFace support: transformers models and datasets datasets

We also provide built-in support for transformers pretrained models and datasets from the datasets package! Here's an example of loading and attacking a pre-trained model and dataset:

textattack attack --model-from-huggingface distilbert-base-uncased-finetuned-sst-2-english --dataset-from-huggingface glue^sst2 --recipe deepwordbug --num-examples 10

You can explore other pre-trained models using the --model-from-huggingface argument, or other datasets by changing --dataset-from-huggingface.

Loading a model or dataset from a file

You 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 variables model and tokenizer. The tokenizer must be able to transform string inputs to lists or tensors of IDs using a method called encode(). The model must take inputs via the __call__ method.

Custom Model from a file

To experiment with a model you've trained, you could create the following file and name it 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

Then, run an attack with the argument --model-from-file my_model.py. The model and tokenizer will be loaded automatically.

Custom Datasets

Dataset from a file

Loading 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 file my_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 via AttackedText class

To allow for word replacement after a sequence has been tokenized, we include an AttackedText object 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.

Dataset loading via other mechanism, see: here

Attacks and how to design a new attack

We formulate an attack as consisting of four components: a goal function which determines if the attack has succeeded, constraints defining which perturbations are valid, a transformation that generates potential modifications given an input, and a search method which 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 Functions

A GoalFunction takes as input an AttackedText object, scores it, and determines whether the attack has succeeded, returning a GoalFunctionResult.

Constraints

A Constraint takes as input a current AttackedText, and a list of transformed AttackedTexts. For each transformed option, it returns a boolean representing whether the constraint is met.

Transformations

A Transformation takes as input an AttackedText and returns a list of possible transformed AttackedTexts. For example, a transformation might return all possible synonym replacements.

Search Methods

A SearchMethod takes as input an initial GoalFunctionResult and returns a final GoalFunctionResult The search is given access to the get_transformations function, which takes as input an AttackedText object and outputs a list of possible transformations filtered by meeting all of the attack’s constraints. A search consists of successive calls to get_transformations until the search succeeds (determined using get_goal_results) or is exhausted.

On Benchmarking Attacks

  • See our analysis paper: Searching for a Search Method: Benchmarking Search Algorithms for Generating NLP Adversarial Examples at EMNLP 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 Github

On Quality of Generated Adversarial Examples in Natural Language

  • Our analysis Paper in EMNLP Findings
  • We 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 Github
  • As 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 language
  • We recommend the field to use human-evaluation derived thresholds for setting up constraints

Multi-lingual Support

Contributing to TextAttack

We 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.

See CONTRIBUTING.md for detailed information on contributing.

Citing TextAttack

If you use TextAttack for your research, please cite 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}
}
Issues
  • How to accelerate attack in parallel through API

    How to accelerate attack in parallel through API

    Hi,

    I'm developing my project with TextAttack API. I wonder how can I parallel the attack to accelerate? Here is the current code I'm using:

        
        model_wrapper = textattack.models.wrappers.HuggingFaceModelWrapper(
            model, tokenizer, batch_size=args.model_batch_size
        )
        recipe = PWWSRen2019.build(model_wrapper)
        
        for idx, result in enumerate(recipe.attack_dataset(dataset)):
            
            print(("-" * 20), f"Result {idx+1}", ("-" * 20))
            print(result.__str__(color_method="ansi"))
            print()
            if idx > 100:
                break
    

    The code returns one result at one time in the loop. Because I want to check the overall performance of the whole dataset so I only care the accuracy. How can I make full use of the GPU memory and accelerate the process? It seems the batch_size of model_wrapper does not help.

    Thanks

    enhancement question 
    opened by ziqi-zhang 17
  •  Support for spaCy models

    Support for spaCy models

    Hi, I was asked by @jxmorris12 to create this issue in connection to my original question on Stackoverflow: https://stackoverflow.com/questions/61889477/using-spacy-models-with-allennlp-interpret-or-textattack/61897642?noredirect=1#comment109982631_61897642

    I tried to figure out how to use Textattack with spaCy models, but was unsuccessful. I'll be grateful for any help :)

    documentation question 
    opened by katarkor 17
  • Add chinese version of readme

    Add chinese version of readme

    Thanks for releasing the powerful TextAttack🎉 For chinese fellows easier to get started with TextAttack, I translate the reademe to chinese. I try my best to adheres to 信、达、雅, the translation principles. But only the content is guaranteed to be informative. This chinese version may need some major review. Despite all this, it's still a good startpoint. Look forward to receiving your reply~

    opened by Opdoop 17
  • Addition of optional language/model parameters to constraints (and download method adjustment)

    Addition of optional language/model parameters to constraints (and download method adjustment)

    What does this PR do?

    Summary

    This PR adds optional language/model parameters to the __init__ of multiple constraint. This enables usage of the constraints for other languages than English and even multilingual use cases. Also it contains some changes of resource download logic.

    Additions

    • Optional language/model parameters for multiple constraints (previously hard-coded configurations are set as default values)

    Changes

    • Download logic of resources has been changed (see download_from_s3 method)

    Checklist

    • [ X ] The title of your pull request should be a summary of its contribution.
    • [ X ] Please write detailed description of what parts have been newly added and what parts have been modified. Please also explain why certain changes were made.
    • [ X ] If your pull request addresses an issue, please mention the issue number in the pull request description to make sure they are linked (and people consulting the issue know you are working on it)
    • [ X ] To indicate a work in progress please mark it as a draft on Github.
    • [ X ] Make sure existing tests pass.
    • [ X ] Add relevant tests. No quality testing = no merge.
    • [ X ] All public methods must have informative docstrings that work nicely with sphinx. For new modules/files, please add/modify the appropriate .rst file in TextAttack/docs/apidoc.'
    opened by alexander-zap 17
  • Fix incorrect `__eq__` method of `AttackedText` in `textattack/shared/attacked_text.py`

    Fix incorrect `__eq__` method of `AttackedText` in `textattack/shared/attacked_text.py`

    What does this PR do?

    Summary

    fix incorrect __eq__ method of AttackedText in textattack/shared/attacked_text.py

    ~~Another thing is that I added DownloadConfig in textattack/datasets/huggingface_dataset.py to try to use a proxy for downloading things from huggingface. This is irrelevant to this pull request.~~

    Additions

    • in the __eq__ method of AttackedText, an additional check of equal number of dict items of attack_attrs is added. If this correction was not done, the __eq__ is incorrect, as illustrated in the following example
    from textattack.shared.attacked_text import AttackedText
    at1 = AttackedText("hehe", attack_attrs={"hehe":1})
    at2 = AttackedText("hehe", attack_attrs={"hehe":1, "haha":2})
    
    print(at1 == at2)
    print(at2 == at1)
    

    whose outcome would be

    True
    False
    

    Changes

    • NA

    Deletions

    • NA

    Checklist

    • [√] The title of your pull request should be a summary of its contribution.
    • [√] Please write detailed description of what parts have been newly added and what parts have been modified. Please also explain why certain changes were made.
    • [√] If your pull request addresses an issue, please mention the issue number in the pull request description to make sure they are linked (and people consulting the issue know you are working on it)
    • [√] To indicate a work in progress please mark it as a draft on Github.
    • [√] Make sure existing tests pass.
    • [√] Add relevant tests. No quality testing = no merge.
    • [√] All public methods must have informative docstrings that work nicely with sphinx. For new modules/files, please add/modify the appropriate .rst file in TextAttack/docs/apidoc.'
    opened by wenh06 16
  • Attack via API

    Attack via API

    What does this PR do?

    Summary

    Performing attacks using the TextAttack API is quite limiting compared to using the command line commands because the users have to write their own code to support logging, saving checkpoint, and parallel processing. This PR intends to introduce some new support for attacking using TextAttack's API so that what can be done in command line can also be done using the API. However, this version does break a lot of backward compatibilities.

    Additions

    • Added new dataclasses AttackArgs, AugmenterArgs, DatasetArgs, ModelArgs that are intended to represent arguments for specific features of TextAttack.
    • Added new module named textattack.Attacker.Attacker takes in Attack, textattack.datasets.Dataset, and AttackArgs objects to perform attacks on the datasets with the same features for logging and saving checkpoints as the command line version.
    • Added textattack.datasets.Dataset class. This takes in a list (or list-like) of tuples of (input, output) format. It is intended to the be the most basic class that other dataset classes extend from. The idea is to require all "dataset" inputs to be of type textattack.datasets.Dataset, so it's clear the users what they need to pass as a "dataset" (behavior, an arbitrary list counted as a "dataset" technically).

    Changes

    • Removed attack_dataset method from Attack class and removed all the generator-related functionalities. Generator design is neat, but is less readable and maintainable. The idea is to remove all dataset-level attack features from Attack class and make Attacker handle the dataset level attacks. Attack is solely responsible for attacking single examples.
    • Updated textattack.datasets.HuggingFaceDatasets to allow users to pass in their own datasets.Dataset objects (instead of just taking in name, subset, and split to load the dataset).
    • Updated modules in textattack.commands to work with the new APIs.
    opened by jinyongyoo 14
  • Fix for tut0

    Fix for tut0

    Minimal changes for files blocking successful run of tut0

    opened by sanchit97 13
  • Enhance augment function

    Enhance augment function

    What does this PR do?

    Summary

    This PR introduces 2 new augmenter parameters, high_yield and fast_augment. The high_yield option was originally implemented in pull request #507 that still requires additional implementation before merging.

    When high_yield is set to True, every augmentation that fits the criteria of a successful transformation will be added to the final output. In most cases, the high-yield augmenter will generate far more augmentations than what users specify in transformations_per_example.

    When fast_augment is set to True, the augmenter terminate and return transformations_per_example number of transformations when the number of successful augmentations reaches transformations_per_example.

    This improves the running time of the augmenter but may cause skewness in returned augmentations (speed is improved via early stop).

    Additions

    • Added high_yield and fast_augment parameters in augmenter

    Changes

    • Changed the augment function, augmenter parser, and augment_command

    Checklist

      • [x] The title of your pull request should be a summary of its contribution.
      • [x] Please write a detailed description of what parts have been newly added and what parts have been modified. Please also explain why certain changes were made.
    • [ ] If your pull request addresses an issue, please mention the issue number in the pull request description to make sure they are linked (and people consulting the issue know you are working on it)
      • [x] To indicate a work in progress please mark it as a draft on Github.
      • [x] Make sure existing tests pass.
    • [ ] Add relevant tests. No quality testing = no merge.
    • [ ] All public methods must have informative docstrings that work nicely with sphinx. For new modules/files, please add/modify the appropriate .rst file in TextAttack/docs/apidoc.'
    augmentation 
    opened by Hanyu-Liu-123 12
  • ValueError: Unsupported dataset schema #449

    ValueError: Unsupported dataset schema #449

    I am running adversarial training on NLP models and I am getting an error " ValueError: Unsupported dataset schema ". When I run the following code: import textattack import transformers from textattack.datasets import HuggingFaceDataset

    model = transformers.AutoModelForSequenceClassification.from_pretrained("bert-base-uncased") tokenizer = transformers.AutoTokenizer.from_pretrained("bert-base-uncased") model_wrapper = textattack.models.wrappers.HuggingFaceModelWrapper(model, tokenizer)

    We only use DeepWordBugGao2018 to demonstration purposes. attack = textattack.attack_recipes.DeepWordBugGao2018.build(model_wrapper) train_dataset = HuggingFaceDataset('squad', split='train') eval_dataset = HuggingFaceDataset('squad', split='validation')

    Train for 3 epochs with 1 initial clean epochs, 1000 adversarial examples per epoch, learning rate of 5e-5, and effective batch size of 32 (8x4). training_args = textattack.TrainingArgs( num_epochs=3, num_clean_epochs=1, num_train_adv_examples=1000, learning_rate=5e-5, per_device_train_batch_size=8, gradient_accumulation_steps=4, log_to_tb=True, )

    trainer = textattack.Trainer( model_wrapper, "classification", attack,

    eval_dataset, training_args ) trainer.train() @jxmorris12

    bug 
    opened by marwanomar1 12
  • total_adv_training_steps might be wrong?

    total_adv_training_steps might be wrong?

    Hi, thanks for the amazing project.

    I've got some questions about the calculation of total_adv_training_steps in trainer.py https://github.com/QData/TextAttack/blob/a0ec175fb3a94fdd25f8c10d3e4b29a7f6547a52/textattack/trainer.py#L613 If the training_args.self.num_train_adv_examples is given with a float, which indicates the fraction of the training sets, won't the calculation seem a bit odd? I think it should look like

    if isinstance(self.training_args.num_train_adv_examples, float):
      total_adv_training_steps = math.ceil(
                (len(self.train_dataset) + len(self.train_dataset) *  self.training_args.num_train_adv_examples)
                / (train_batch_size * self.training_args.gradient_accumulation_steps)
            ) * (self.training_args.num_epochs - num_clean_epochs)
    elif isinstance(self.training_args.num_train_adv_examples, int) and self.training_args.num_train_adv_examples > 0:
       total_adv_training_steps = math.ceil(
                (len(self.train_dataset) + self.training_args.num_train_adv_examples)
                / (train_batch_size * self.training_args.gradient_accumulation_steps)
            ) * (self.training_args.num_epochs - num_clean_epochs)
    else:
        ### I assume each training instance will have a adversarial counterpart, thus multiply by 2
        total_adv_training_steps = math.ceil(
                (len(self.train_dataset) * 2 
                / (train_batch_size * self.training_args.gradient_accumulation_steps)
            ) * (self.training_args.num_epochs - num_clean_epochs)
    

    In fact, I am not quite sure how to properly handle the case when training_args.num_train_adv_examples, since we cannot know how many successful attacks will there be if we are attacking the whole training dataset.

    opened by d223302 0
  • Cannot use textattack (import not working)

    Cannot use textattack (import not working)

    Describe the bug I try to use this library and start with importing it. But it says "ImportError: cannot import name 'FailedAttackResult' from 'textattack.attack_results' (/opt/conda/lib/python3.7/site-packages/textattack/attack_results/init.py)"

    To Reproduce Steps to reproduce the behavior:

    1. Run following command !pip install textattack
    2. Run following code import textattack
    3. See error
    • Textattack version 0.3.4

    Additional context I also tried to use version 0.3.3 and install tensorflow_text additionally, but it doesn't help.

    opened by 25icecreamflavors 0
  • Fix extra quotation marks issue

    Fix extra quotation marks issue

    What does this PR do?

    Summary

    When augmenting from CSV files, we use the CSV sniffer to try automatically inferring the correct CSV format. This works most of the time but does not function properly when there're more than 2 double quotation marks within a line, due to the fact that double quotation marks are recognized as escape characters by CSV sniffer.

    The workaround first goes through the input CSV file, replaces double quotation marks with single quotation marks, and then creates a temporary CSV file to store the modified inputs. We need to create the temp file because we couldn't directly provide the modified inputs (list of strings) to the CSV sniffer, so the modified lines need to be saved to a CSV file and that file will be read by the sniffer.

    Users will be warned on which lines of the original input file are modified.

    Additions

    • csv_reader_workaround()
    opened by Hanyu-Liu-123 0
  • Bump tensorflow from 2.5.0 to 2.5.2 in /docs

    Bump tensorflow from 2.5.0 to 2.5.2 in /docs

    Bumps tensorflow from 2.5.0 to 2.5.2.

    Release notes

    Sourced from tensorflow's releases.

    TensorFlow 2.5.2

    Release 2.5.2

    This release introduces several vulnerability fixes:

    • Fixes a code injection issue in saved_model_cli (CVE-2021-41228)
    • Fixes a vulnerability due to use of uninitialized value in Tensorflow (CVE-2021-41225)
    • Fixes a heap OOB in FusedBatchNorm kernels (CVE-2021-41223)
    • Fixes an arbitrary memory read in ImmutableConst (CVE-2021-41227)
    • Fixes a heap OOB in SparseBinCount (CVE-2021-41226)
    • Fixes a heap OOB in SparseFillEmptyRows (CVE-2021-41224)
    • Fixes a segfault due to negative splits in SplitV (CVE-2021-41222)
    • Fixes segfaults and vulnerabilities caused by accesses to invalid memory during shape inference in Cudnn* ops (CVE-2021-41221)
    • Fixes a null pointer exception when Exit node is not preceded by Enter op (CVE-2021-41217)
    • Fixes an integer division by 0 in tf.raw_ops.AllToAll (CVE-2021-41218)
    • Fixes an undefined behavior via nullptr reference binding in sparse matrix multiplication (CVE-2021-41219)
    • Fixes a heap buffer overflow in Transpose (CVE-2021-41216)
    • Prevents deadlocks arising from mutually recursive tf.function objects (CVE-2021-41213)
    • Fixes a null pointer exception in DeserializeSparse (CVE-2021-41215)
    • Fixes an undefined behavior arising from reference binding to nullptr in tf.ragged.cross (CVE-2021-41214)
    • Fixes a heap OOB read in tf.ragged.cross (CVE-2021-41212)
    • Fixes a heap OOB read in all tf.raw_ops.QuantizeAndDequantizeV* ops (CVE-2021-41205)
    • Fixes an FPE in ParallelConcat (CVE-2021-41207)
    • Fixes FPE issues in convolutions with zero size filters (CVE-2021-41209)
    • Fixes a heap OOB read in tf.raw_ops.SparseCountSparseOutput (CVE-2021-41210)
    • Fixes vulnerabilities caused by incomplete validation in boosted trees code (CVE-2021-41208)
    • Fixes vulnerabilities caused by incomplete validation of shapes in multiple TF ops (CVE-2021-41206)
    • Fixes a segfault produced while copying constant resource tensor (CVE-2021-41204)
    • Fixes a vulnerability caused by unitialized access in EinsumHelper::ParseEquation (CVE-2021-41201)
    • Fixes several vulnerabilities and segfaults caused by missing validation during checkpoint loading (CVE-2021-41203)
    • Fixes an overflow producing a crash in tf.range (CVE-2021-41202)
    • Fixes an overflow producing a crash in tf.image.resize when size is large (CVE-2021-41199)
    • Fixes an overflow producing a crash in tf.tile when tiling tensor is large (CVE-2021-41198)
    • Fixes a vulnerability produced due to incomplete validation in tf.summary.create_file_writer (CVE-2021-41200)
    • Fixes multiple crashes due to overflow and CHECK-fail in ops with large tensor shapes (CVE-2021-41197)
    • Fixes a crash in max_pool3d when size argument is 0 or negative (CVE-2021-41196)
    • Fixes a crash in tf.math.segment_* operations (CVE-2021-41195)
    • Updates curl to 7.78.0 to handle CVE-2021-22922, CVE-2021-22923, CVE-2021-22924, CVE-2021-22925, and CVE-2021-22926.

    TensorFlow 2.5.1

    Release 2.5.1

    This release introduces several vulnerability fixes:

    • Fixes a heap out of bounds access in sparse reduction operations (CVE-2021-37635)
    • Fixes a floating point exception in SparseDenseCwiseDiv (CVE-2021-37636)
    • Fixes a null pointer dereference in CompressElement (CVE-2021-37637)
    • Fixes a null pointer dereference in RaggedTensorToTensor (CVE-2021-37638)
    • Fixes a null pointer dereference and a heap OOB read arising from operations restoring tensors (CVE-2021-37639)
    • Fixes an integer division by 0 in sparse reshaping (CVE-2021-37640)

    ... (truncated)

    Changelog

    Sourced from tensorflow's changelog.

    Release 2.5.2

    This release introduces several vulnerability fixes:

    ... (truncated)

    Commits
    • 957590e Merge pull request #52873 from tensorflow-jenkins/relnotes-2.5.2-20787
    • 2e1d16d Update RELEASE.md
    • 2fa6dd9 Merge pull request #52877 from tensorflow-jenkins/version-numbers-2.5.2-192
    • 4807489 Merge pull request #52881 from tensorflow/fix-build-1-on-r2.5
    • d398bdf Disable failing test
    • 857ad5e Merge pull request #52878 from tensorflow/fix-build-1-on-r2.5
    • 6c2a215 Disable failing test
    • f5c57d4 Update version numbers to 2.5.2
    • e51f949 Insert release notes place-fill
    • 2620d2c Merge pull request #52863 from tensorflow/fix-build-3-on-r2.5
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependency issue 
    opened by dependabot[bot] 1
  • Misleading Tutorial 10: Explaining Attacking BERT models using Captum

    Misleading Tutorial 10: Explaining Attacking BERT models using Captum

    I would like to use TextAttack with the BERT model together with Captum. A tutorial covers the topic I am interested in -https://textattack.readthedocs.io/en/latest/2notebook/Example_5_Explain_BERT.html but It looks like broken in a half. It does not use any attributions computed from Captum.

    I found another one: https://github.com/P3n9W31/TextAttack/blob/aa736d26b423f0f3d311e02353069899adc1744c/docs/2notebook/Example_5_Explain_BERT.ipynb , which seems to be using an older version of TextAttack.

    Anyway, I finally managed to achieve what I wanted by combining those two + browsing source code.

    Should the tutorial be updated? I could try to update it and create a merge request, but it will need a review as I am not experienced user of TextAttack.

    documentation 
    opened by mbednarski 3
  • add language options

    add language options

    What does this PR do?

    Summary

    This PR adds language options to transformations.

    Additions

    • french_recipe.py
    • spanish_recipe.py

    two basic recipes that uses WordNet transformation to transform French/Spanish synonyms, and uses change_name and change_location transformations.

    Changes

    • data.py
    • word_swap_change_name.py
    • word_swap_change_location.py

    Spanish and French data has been added to data.py to support multilingual name and location transformation. The user can now add a parameter to these two transformations such as transformation = word_swap_change_name(language = "spanish") which was previously not possible

    • docs/2notebook/Example_4_CamemBERT.ipynb

    This multilingual tutorial has been updated to use the new french recipe

    Here is a snippet of code that demonstrates the changes made

    Screen Shot 2021-11-12 at 6 02 45 AM

    opened by cogeid 7
  • Delete Transformation does not work properly with Augmentation

    Delete Transformation does not work properly with Augmentation

    When deletion is performed to AttackedText, its modified_indices is not updated in our current implementation. Since the deleted word is no longer present after the deletion, we need to find a way to record that modified index.

    For example, suppose we have the text "Today is a good day" and delete the first word ("Today"), we can't set modified index to 0 because, after the transformation, index 0 should correspond to "is".

    This is also an issue for back translation, since we also couldn't update modified_indices with our current implementation when a sentence is translated to another language and translated back. Because augmentation requiresmodified_indices to keep track of how much the input sentence is perturbed, we need to either update how augmenter keep tracks of changes or update how AttackedText keep tracks of changes.

    enhancement 
    opened by Hanyu-Liu-123 0
  • Search method of the DeepWordBug recipe might should be adjusted

    Search method of the DeepWordBug recipe might should be adjusted

    The search method of the DeepWordBug recipe is GreedyWordSwapWIR WITHOUT specifying its wir_method. The default wir_method for GreedyWordSwapWIR is unk which replaces the word with an oov word or token for computation of importance score or something like that. However, in the paper which introduces the DeepWordBug recipe, in page 3 (page 52) starting from the 8th line of the right column, it is stated that

    Therefore, we directly measure ΔiF(x) by removing the ith word. Comparing the prediction before and after a word is removed reflects how the word influences the classification result.
    

    So, should this line

    search_method = GreedyWordSwapWIR()
    

    be replaced with

    search_method = GreedyWordSwapWIR(wir_method="delete")
    

    ? Thank you very much!

    question 
    opened by wenh06 0
  • To Improve the Metric Module

    To Improve the Metric Module

    @sanchit97 This looks awesome! Thank you for the hard work! This will be a great addition to TextAttack.

    One (just one I promise!) concern I have is the perplexity numbers from the test output. They looks a little bit too high (200-300, 1000-2000), though I cannot see any issues with the code. One reason might be that we're just using poor samples for testing, but maybe we can do a sanity check on a larger number of samples (e.g. 1000 IMDB, Yelp, etc) just to make sure.

    Otherwise, most of my comments are minor ones about the docstring. I'm going to approve the PR since code and design looks good! 🤗

    Lastly, these are some possible suggestions on how we can improve Metrics module later on in the future (not necessary for this PR).

    • Batched passes with GPT2: I know doing batches with GPT2 is tricky b/c there are no padding tokens, but we can manually set them to be EOS token and then use attention masking to make sure we don't use the padding tokens. Also we need to make sure that we set the labels with EOS tokens to be -100 when calculating the loss. This will speed up the perplexity metric a lot.
    • Global object sharing for GPT2 and USE: note than we also use GPT2 and USE as part of our constraints, so it's possible that we already loaded the model onto our GPUs when running the attacks. It would be nice if we could reuse them for metrics without instantiating new models (very easy to hit GPU OOM). One solution is to make a GLOBAL_SHARED_OBJECTS dictionary within shared/utils, make it global scope, and then insert GPT2 and USE models into the dictionary whenever we instantiate them the first time and reuse them later in other modules.

    Originally posted by @jinyongyoo in https://github.com/QData/TextAttack/pull/514#pullrequestreview-759330856

    enhancement 
    opened by qiyanjun 3
  • Trainer's bug during adversarial training

    Trainer's bug during adversarial training

    Describe the bug Bug in File "textattack/trainer.py", line 213, in _generate_adversarial_examples. Missing a column for the "adversarial_example" tag.

    adversarial_examples = [
        (
            tuple(r.perturbed_result.attacked_text._text_input.values()),
            r.perturbed_result.ground_truth_output,
            "adversarial_example",
        )
        for r in results
        if isinstance(r, (SuccessfulAttackResult, MaximizedAttackResult))
    ]
    

    The list of adversarial examples declared in File "textattack/trainer.py", line 202, in _generate_adversarial_examples contains 3 columns:

    1. The raw text
    2. The ground truth label
    3. An "adversarial_example" tag to differentiate it from clean examples.

    However, line 213 misses a column for the adversarial tag, which leads to it being neglected by the collate_fn later in the code.

    Expected behavior The adversarial tag should be retrieved and the statement if len(item) == 3 should be evaluated to True.

    Screenshots or Traceback image I tried adversarial training with a dataset of a single example. The picture above is a batch containing a clean example and its corresponding adversarial example (successfully attacked). However, they were both marked as clean examples.

    System Information (please complete the following information):

    • OS: Linux
    • Library versions: pytorch==1.8.1, transformers==4.9.1
    • Textattack version: textattack==0.3.0
    bug 
    opened by dangne 3
Releases(v0.3.4)
  • v0.3.4(Nov 10, 2021)

    What's Changed

    • [CODE] Keras parallel attack fix - Issue #499 by @sanchit97 in https://github.com/QData/TextAttack/pull/515
    • Bump tensorflow from 2.4.2 to 2.5.1 in /docs by @dependabot in https://github.com/QData/TextAttack/pull/517
    • Add a high level overview diagram to docs by @cogeid in https://github.com/QData/TextAttack/pull/519
    • readtheDoc fix by @qiyanjun in https://github.com/QData/TextAttack/pull/522
    • Add new attack recipe A2T by @jinyongyoo in https://github.com/QData/TextAttack/pull/523
    • Fix incorrect __eq__ method of AttackedText in textattack/shared/attacked_text.py by @wenh06 in https://github.com/QData/TextAttack/pull/509
    • Fix a bug when running textattack eval with --num-examples=-1 by @dangne in https://github.com/QData/TextAttack/pull/521
    • New metric module to improve flexibility and intuitiveness - moved from #475 by @sanchit97 in https://github.com/QData/TextAttack/pull/514
    • Update installation.md to add FAQ on installation by @qiyanjun in https://github.com/QData/TextAttack/pull/535
    • Fix dataset-split bug by @Hanyu-Liu-123 in https://github.com/QData/TextAttack/pull/533
    • Update by @Hanyu-Liu-123 in https://github.com/QData/TextAttack/pull/541
    • add custom dataset API use example in doc by @qiyanjun in https://github.com/QData/TextAttack/pull/543
    • Fix logger initiation bug by @Hanyu-Liu-123 in https://github.com/QData/TextAttack/pull/539
    • Updated Tutorial 0 to use the Rotten Tomatoes dataset instead of the … by @srujanjoshi in https://github.com/QData/TextAttack/pull/542
    • Back translation transformation by @cogeid in https://github.com/QData/TextAttack/pull/534
    • Fixed a bug in the allennlp tutorial by @donggrant in https://github.com/QData/TextAttack/pull/546
    • Logger bug fix by @ankitgv0 in https://github.com/QData/TextAttack/pull/551
    • add "textattack[tensorflow]" option in all tutorials by @qiyanjun in https://github.com/QData/TextAttack/pull/559
    • Fix CLARE Extra Character Bug by @Hanyu-Liu-123 in https://github.com/QData/TextAttack/pull/556
    • Fix metric-module Issue#532 by @sanchit97 in https://github.com/QData/TextAttack/pull/540
    • Add API docstrings for back translation by @cogeid in https://github.com/QData/TextAttack/pull/563
    • Fixed the "no attribute" error from #536 by @ankitgv0 in https://github.com/QData/TextAttack/pull/552
    • Enhance augment function by @Hanyu-Liu-123 in https://github.com/QData/TextAttack/pull/531
    • fix read-the-doc installation issue / clean up and add new docstrings for recently added classes/packages by @qiyanjun in https://github.com/QData/TextAttack/pull/569

    New Contributors

    • @wenh06 made their first contribution in https://github.com/QData/TextAttack/pull/509
    • @dangne made their first contribution in https://github.com/QData/TextAttack/pull/521
    • @srujanjoshi made their first contribution in https://github.com/QData/TextAttack/pull/542
    • @donggrant made their first contribution in https://github.com/QData/TextAttack/pull/546
    • @ankitgv0 made their first contribution in https://github.com/QData/TextAttack/pull/551

    Full Changelog: https://github.com/QData/TextAttack/compare/v0.3.3...v0.3.4

    Source code(tar.gz)
    Source code(zip)
  • v0.3.3(Aug 3, 2021)

    1. Merge pull request #508 from QData/example_bug_fix

    2. Merge pull request #505 from QData/s3-model-fix

    3. Merge pull request #503 from QData/multilingual-doc

    4. Merge pull request #502 from QData/Notebook-10-bug-fix

    5. Merge pull request #500 from QData/docstring-rework-missing

    6. Merge pull request #497 from QData/dependabot/pip/docs/tensorflow-2.4.2

    7. Merge pull request #495 from QData/readthedoc-fix

    Source code(tar.gz)
    Source code(zip)
  • v0.3.2(Jul 28, 2021)

    Multiple bug fixes:

    • Merge pull request #473 from cogeid/file-redirection-fix

    • Merge pull request #469 from xinzhel/allennlp_doc

    • Merge pull request #477 from cogeid/Fix-RandomSwap-and-RandomSynonymI…

    • Merge pull request #484 from QData/update-torch-version

    • Merge pull request #490 from QData/scipy-version-plus-two-doc-updates

    • Merge pull request #420 from QData/multilingual

    • Merge pull request #495 from QData/readthedoc-fix

    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Jun 25, 2021)

    New Updated API

    We have added two new classes called Attacker and Trainer that can be used to perform adversarial attacks and adversarial training with full logging support and multi-GPU parallelism. This is intended to provide an alternative way of performing attacks and training for custom models and datasets.

    Attacker: Running Adversarial Attacks

    Below is an example use of Attacker to attack BERT model finetuned on IMDB dataset using TextFooler method. AttackArgs class is used to set the parameters of the attacks, including the number of examples to attack, CSV file to log the results, and the interval at which to save checkpoint.

    Screen Shot 2021-06-24 at 8 34 44 PM

    More details about Attacker and AttackArgs can be found here.

    Trainer: Running Adversarial Training

    Previously, TextAttack supported adversarial training in a limited manner. Users could only train models using the CLI command, and not every aspects of training was available for tuning.

    Trainer class introduces an easy way to train custom PyTorch/Transformers models on a custom dataset. Below is an example where we finetune BERT on IMDB dataset with an adversarial attack called DeepWordBug.

    Screen Shot 2021-06-25 at 9 28 57 PM

    Dataset

    Previously, datasets passed to TextAttack were simply expected to be an iterable of (input, target) tuples. While this offers flexibility, it prevents users from passing key information about the dataset that TextAttack can use to provide better experience (e.g. label names, label remapping, input column names used for printing).

    We instead explicitly define Dataset class that users can use or subclass for their own datasets.

    Bug Fixes:

    • #467: Don't check self.target_max_score when it is already known to be None.
    • #417: Fixed bug where in masked_lm transformations only subwords were candidates for top_words.
    Source code(tar.gz)
    Source code(zip)
  • v0.2.15(Dec 27, 2020)

    CLARE Attack (#356, #392)

    We have added a new attack proposed by "Contextualized Perturbation for Textual Adversarial Attack" (Li et al., 2020). There's also a corresponding augmenter recipe using CLARE. Thanks to @Hanyu-Liu-123, @cookielee77.

    Custom Word Embedding (#333, #399)

    We have added support for custom word embedding via AbstractWordEmbedding, WordEmbedding, GensimWordEmbedding fromtextattack.shared. These three classes allow users to use their own custom word embeddings for transformations and constraints that require custom word embeddings. Thanks @tsinggggg and @alexander-zap for contributing!

    Bug Fixes and Changes

    • We fixed a bug that caused TextAttack to report fewer number of average queries than what it should be reporting (#350, thanks @ a1noack).
    • Update the dataset split used to evaluate robustness during adversarial training (#361, thanks @Opdoop).
    • Updated default parameters for TextBugger recipe (#373)
    • Fixed an issue with TextBugger by updating the default method used to segment text into words to work with homoglyphs. (#376, thanks @lethaiq!)
    • Updated ModelWrapper to not require get_grad method to be defined. (#381)
    • Fixed an issue with WordSwapMaskedLM that was causing words with lowest probability to be picked first. (#396)
    Source code(tar.gz)
    Source code(zip)
  • 0.2.14(Nov 18, 2020)

    Improvements

    Bug fixing Matching documentation in Readme.md and the files in /doc folder add checklist add multilingual USE add gradient-based word importance ranking update to a more complete API documentation add cola constraint add the lazy loader

    Source code(tar.gz)
    Source code(zip)
  • 0.2.12(Nov 13, 2020)

    Big Improvements

    • add checklist
    • add multilingual USE
    • add gradient-based word importance ranking
    • update to a more complete API documentation
    • add cola constraint
    • add the lazy loader
    Source code(tar.gz)
    Source code(zip)
  • 0.2.0(Jul 9, 2020)

    Big Improvements

    • Add tons of (over 70!) pre-trained models (#192, see Model Zoo page!)
    • Data augmentation integrated into training! (#195, thanks @jakegrigsby)
    • Allow for maximization goal functions (#151, thanks @uvafan )

    New Attacks

    • Add the Improved Genetic Algorithm (#183, thanks @sherlockyyc!)
    • Add BAE and BERT-Attack attack recipes (#160)
    • Add PWWS attack (#168, thanks @jakegrigsby)
    • Add typo-based attack from Pruthi et al. (#191, thanks @jakegrigsby )
    • Easy Data Augmentation augmentation recipe (#168, thanks @jakegrigsby)
    • Add input reduction attack from Feng et al. (#161, thanks @uvafan)

    Smaller Improvements

    • more accurate attack recipes for BAE and TextFooler (#199)
    • important fixes to model training code (#186, thanks so much @jind11!!)
    • abstract classes, better string representations when printing attacks to console (#202)
    • genetic algorithm improvements (#160, thanks @jinyongyoo )
    • fixes to parallel attacks (#164, thanks @jinyongyoo )
    • datasets to test out T5 on seq2seq attacks (#176)

    Bug Fixes

    • correctly print attack perturbed words in color, even when words are deleted & inserted (#200)
    • fix print_step bug with alzantot recipe (#195, thanks @heytitle for reporting!)
    • fix some annoying issues with dependency versioning
    Source code(tar.gz)
    Source code(zip)
  • 0.1.0(Jun 24, 2020)

    Version 0.1.0 is our biggest release yet! Here's a summary of the changes:

    Backwards compatibility note: python -m textattack <args> is renamed to python -m textattack attack <args>. Or, better yet, textattack attack <args>!

    Big improvements

    • add textattack command (#132)
      • add textattack augment, textattack eval, textattack attack, textattack list (#132)
      • add textattack train, textattack peek-dataset, and lots of infrastructure for training models (#139)
    • Move all datasets to nlp format; temporarily remove non-NLP datasets (AGNews, English->German translation) (#134)

    Smaller improvements

    • Better output formatted -- show labels ("Positive", "Entailment") and confidence score (91%) in output (#142)
    • add MaxLengthModification constraint that prevents modifications beyond tokenizer max_length (#143)
    • Add pytest tests and code formatting with black; run tests on Python 3.6, 3.7, 3.8 with Travis CI (#127, #136)
    • Update NLTK part-of-speech constraint and support part-of-speech tagging with FLAIR instead (#135)
    • add BERTScore constrained based on "BERTScore: Evaluating Text Generation with BERT" (Zhang et al, 2019) (#146)
    • make logging to file optional (#145)
    • Updates to Checkpoint class; track attack results in a worklist; attack resume fixes (#128, #141)
    • Silence Weights & Biases warning message when not being used (#130)
    • Optionally point all cache directories to a universal cache directory, TA_CACHE_DIR (#150)

    Bug fixes

    • Fix a bug that can be encountered when resuming attacks from checkpoints (#149)
    • Fix a bug in Greedy word-importance-ranking deletion (#152)
    • Documentation updates and fixes (#153)
    Source code(tar.gz)
    Source code(zip)
  • 0.0.3.0(Jun 11, 2020)

    big changes:

    • load transformers models from the command-line using the --model-from-huggingface option
    • load nlp datasets from the command-line using the --dataset-from-nlp option
    • command-line support for custom attacks, models, and datasets: --attack-from-file, --model-from-file, --dataset-from-file
    • implement attack recipe for TextBugger attack
    • add WordDeletion transformation

    small changes:

    • support white-box transformations via the command-line
    • allow Greedy-WIR to rank things in order of ascending importance
    • use fast tokenizers behind the scenes
    • fix some bugs with the attack Checkpoint class
    • some abbreviated syntax (textattack.shared.utils.get_logger() -> textattack.shared.logger, textattack.shared.utils.get_device() -> textattack.shared.utils.device)
    • substantially decrease overall TokenizedText memory usage
    Source code(tar.gz)
    Source code(zip)
  • 0.0.2(May 21, 2020)

    0.0.2: Better documentation, attack checkpoints, PreTransformationConstraints, and more

    • Major documentation restructure (check it out)
    • Some refactoring and variable renames to make it easier to jump right in and start working with TextAttack
    • Introduction of PreTransformationConstraints: constraints now can be applied before the transformation to prevent word modifications at certain indices. This abstraction allowed us to remove the notion of modified_indices from search methods, which paves the way for us to introduce attacks that insert or delete words and phrases, as opposed to simply swapping words.
    • Separation of Attack and SearchMethod: search methods are now a parameter to the attack instead of different subclasses of Attack. This syntax fits better with our framework and enforces a clearer sense of separation between the responsibilities of the attack and those of the search method.
    • Transformation and constraint compatibility: Constraints now ensure they're compatible with a specific transformation via a check_compatibility method
    • Goal function scores are now normalized between 0 and 1: UntargetedClassification and NonOverlappingOutput now return scores between 0 and 1.
    • Attack Checkpoints: Attacks can now save and resume their progress. This is really useful for running long, expensive attacks. python-m textattack supports new checkpoint-related arguments: --checkpoint-interval and --checkpoint-dir
    • Weights & Biases: Log attack results to Weights & Biases by adding the --enable-wandb flag
    Source code(tar.gz)
    Source code(zip)
Owner
QData
http://www.cs.virginia.edu/yanjun/
QData
Parrot is a paraphrase based utterance augmentation framework purpose built to accelerate training NLU models

Parrot is a paraphrase based utterance augmentation framework purpose built to accelerate training NLU models. A paraphrase framework is more than just a paraphrasing model.

Prithivida 334 Dec 2, 2021
Grading tools for Advanced NLP (11-711)Grading tools for Advanced NLP (11-711)

Grading tools for Advanced NLP (11-711) Installation You'll need docker and unzip to use this repo. For docker, visit the official guide to get starte

Hao Zhu 1 Oct 3, 2021
Explore different way to mix speech model(wav2vec2, hubert) and nlp model(BART,T5,GPT) together

SpeechMix Explore different way to mix speech model(wav2vec2, hubert) and nlp model(BART,T5,GPT) together. Introduction For the same input: from datas

Eric Lam 6 Nov 17, 2021
Universal Adversarial Triggers for Attacking and Analyzing NLP (EMNLP 2019)

Universal Adversarial Triggers for Attacking and Analyzing NLP This is the official code for the EMNLP 2019 paper, Universal Adversarial Triggers for

Eric Wallace 213 Nov 24, 2021
✨Rubrix is a production-ready Python framework for exploring, annotating, and managing data in NLP projects.

✨A Python framework to explore, label, and monitor data for NLP projects

Recognai 622 Nov 30, 2021
:mag: End-to-End Framework for building natural language search interfaces to data by utilizing Transformers and the State-of-the-Art of NLP. Supporting DPR, Elasticsearch, HuggingFace’s Modelhub and much more!

Haystack is an end-to-end framework that enables you to build powerful and production-ready pipelines for different search use cases. Whether you want

deepset 1.4k Feb 18, 2021
NLP Core Library and Model Zoo based on PaddlePaddle 2.0

PaddleNLP 2.0拥有丰富的模型库、简洁易用的API与高性能的分布式训练的能力,旨在为飞桨开发者提升文本建模效率,并提供基于PaddlePaddle 2.0的NLP领域最佳实践。

null 2.3k Nov 26, 2021
Learn meanings behind words is a key element in NLP. This project concentrates on the disambiguation of preposition senses. Therefore, we train a bert-transformer model and surpass the state-of-the-art.

New State-of-the-Art in Preposition Sense Disambiguation Supervisor: Prof. Dr. Alexander Mehler Alexander Henlein Institutions: Goethe University TTLa

Dirk Neuhäuser 3 Aug 11, 2021
Kashgari is a production-level NLP Transfer learning framework built on top of tf.keras for text-labeling and text-classification, includes Word2Vec, BERT, and GPT2 Language Embedding.

Kashgari Overview | Performance | Installation | Documentation | Contributing ?? ?? ?? We released the 2.0.0 version with TF2 Support. ?? ?? ?? If you

Eliyar Eziz 2.2k Nov 26, 2021
Kashgari is a production-level NLP Transfer learning framework built on top of tf.keras for text-labeling and text-classification, includes Word2Vec, BERT, and GPT2 Language Embedding.

Kashgari Overview | Performance | Installation | Documentation | Contributing ?? ?? ?? We released the 2.0.0 version with TF2 Support. ?? ?? ?? If you

Eliyar Eziz 2k Feb 9, 2021
Code associated with the "Data Augmentation using Pre-trained Transformer Models" paper

Data Augmentation using Pre-trained Transformer Models Code associated with the Data Augmentation using Pre-trained Transformer Models paper Code cont

null 35 Nov 3, 2021
This is the code for the EMNLP 2021 paper AEDA: An Easier Data Augmentation Technique for Text Classification

The baseline code is for EDA: Easy Data Augmentation techniques for boosting performance on text classification tasks

Akbar Karimi 49 Nov 24, 2021
Scikit-learn style model finetuning for NLP

Scikit-learn style model finetuning for NLP Finetune is a library that allows users to leverage state-of-the-art pretrained NLP models for a wide vari

indico 656 Nov 26, 2021
Scikit-learn style model finetuning for NLP

Scikit-learn style model finetuning for NLP Finetune is a library that allows users to leverage state-of-the-art pretrained NLP models for a wide vari

indico 631 Feb 2, 2021
NeurIPS'21: Probabilistic Margins for Instance Reweighting in Adversarial Training (Pytorch implementation).

source code for NeurIPS21 paper robabilistic Margins for Instance Reweighting in Adversarial Training

null 1 Oct 26, 2021
fastNLP: A Modularized and Extensible NLP Framework. Currently still in incubation.

fastNLP fastNLP是一款轻量级的自然语言处理(NLP)工具包,目标是快速实现NLP任务以及构建复杂模型。 fastNLP具有如下的特性: 统一的Tabular式数据容器,简化数据预处理过程; 内置多种数据集的Loader和Pipe,省去预处理代码; 各种方便的NLP工具,例如Embedd

fastNLP 2.4k Nov 27, 2021
fastNLP: A Modularized and Extensible NLP Framework. Currently still in incubation.

fastNLP fastNLP是一款轻量级的自然语言处理(NLP)工具包,目标是快速实现NLP任务以及构建复杂模型。 fastNLP具有如下的特性: 统一的Tabular式数据容器,简化数据预处理过程; 内置多种数据集的Loader和Pipe,省去预处理代码; 各种方便的NLP工具,例如Embedd

fastNLP 2k Feb 14, 2021
Data loaders and abstractions for text and NLP

torchtext This repository consists of: torchtext.data: Generic data loaders, abstractions, and iterators for text (including vocabulary and word vecto

null 2.9k Nov 24, 2021
Data loaders and abstractions for text and NLP

torchtext This repository consists of: torchtext.data: Generic data loaders, abstractions, and iterators for text (including vocabulary and word vecto

null 2.6k Feb 18, 2021