Giter Club home page Giter Club logo

openattack's Introduction

OpenAttack Logo

Github Runner Covergae Status ReadTheDoc Status PyPI version GitHub release (latest by date) GitHub PRs are Welcome

DocumentationFeatures & UsesUsage ExamplesAttack ModelsToolkit Design

OpenAttack is an open-source Python-based textual adversarial attack toolkit, which handles the whole process of textual adversarial attacking, including preprocessing text, accessing the victim model, generating adversarial examples and evaluation.

Features & Uses

OpenAttack has the following features:

⭐️ Support for all attack types. OpenAttack supports all types of attacks including sentence-/word-/character-level perturbations and gradient-/score-/decision-based/blind attack models;

⭐️ Multilinguality. OpenAttack supports English and Chinese now. Its extensible design enables quick support for more languages;

⭐️ Parallel processing. OpenAttack provides support for multi-process running of attack models to improve attack efficiency;

⭐️ Compatibility with 🤗 Hugging Face. OpenAttack is fully integrated with 🤗 Transformers and Datasets libraries;

⭐️ Great extensibility. You can easily attack a customized victim model on any customized dataset or develop and evaluate a customized attack model.

OpenAttack has a wide range of uses, including:

✅ Providing various handy baselines for attack models;

✅ Comprehensively evaluating attack models using its thorough evaluation metrics;

✅ Assisting in quick development of new attack models with the help of its common attack components;

✅ Evaluating the robustness of a machine learning model against various adversarial attacks;

✅ Conducting adversarial training to improve robustness of a machine learning model by enriching the training data with generated adversarial examples.

Installation

1. Using pip (recommended)

pip install OpenAttack

2. Cloning this repo

git clone https://github.com/thunlp/OpenAttack.git
cd OpenAttack
python setup.py install

After installation, you can try running demo.py to check if OpenAttack works well:

python demo.py

demo

Usage Examples

Attack Built-in Victim Models

OpenAttack builds in some commonly used NLP models like BERT (Devlin et al. 2018) and RoBERTa (Liu et al. 2019) that have been fine-tuned on some commonly used datasets (such as SST-2). You can effortlessly conduct adversarial attacks against these built-in victim models.

The following code snippet shows how to use PWWS, a greedy algorithm-based attack model (Ren et al., 2019), to attack BERT on the SST-2 dataset (the complete executable code is here).

import OpenAttack as oa
import datasets # use the Hugging Face's datasets library
# change the SST dataset into 2-class
def dataset_mapping(x):
    return {
        "x": x["sentence"],
        "y": 1 if x["label"] > 0.5 else 0,
    }
# choose a trained victim classification model
victim = oa.DataManager.loadVictim("BERT.SST")
# choose 20 examples from SST-2 as the evaluation data 
dataset = datasets.load_dataset("sst", split="train[:20]").map(function=dataset_mapping)
# choose PWWS as the attacker and initialize it with default parameters
attacker = oa.attackers.PWWSAttacker()
# prepare for attacking
attack_eval = OpenAttack.AttackEval(attacker, victim)
# launch attacks and print attack results 
attack_eval.eval(dataset, visualize=True)
Customized Victim Model

The following code snippet shows how to use PWWS to attack a customized sentiment analysis model (a statistical model built in NLTK) on SST-2 (the complete executable code is here).

import OpenAttack as oa
import numpy as np
import datasets
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer


# configure access interface of the customized victim model by extending OpenAttack.Classifier.
class MyClassifier(oa.Classifier):
    def __init__(self):
        # nltk.sentiment.vader.SentimentIntensityAnalyzer is a traditional sentiment classification model.
        nltk.download('vader_lexicon')
        self.model = SentimentIntensityAnalyzer()
    
    def get_pred(self, input_):
        return self.get_prob(input_).argmax(axis=1)

    # access to the classification probability scores with respect input sentences
    def get_prob(self, input_):
        ret = []
        for sent in input_:
            # SentimentIntensityAnalyzer calculates scores of “neg” and “pos” for each instance
            res = self.model.polarity_scores(sent)

            # we use 𝑠𝑜𝑐𝑟𝑒_𝑝𝑜𝑠 / (𝑠𝑐𝑜𝑟𝑒_𝑛𝑒𝑔 + 𝑠𝑐𝑜𝑟𝑒_𝑝𝑜𝑠) to represent the probability of positive sentiment
            # Adding 10^−6 is a trick to avoid dividing by zero.
            prob = (res["pos"] + 1e-6) / (res["neg"] + res["pos"] + 2e-6)

            ret.append(np.array([1 - prob, prob]))
        
        # The get_prob method finally returns a np.ndarray of shape (len(input_), 2). See Classifier for detail.
        return np.array(ret)

def dataset_mapping(x):
    return {
        "x": x["sentence"],
        "y": 1 if x["label"] > 0.5 else 0,
    }
    
# load some examples of SST-2 for evaluation
dataset = datasets.load_dataset("sst", split="train[:20]").map(function=dataset_mapping)
# choose the costomized classifier as the victim model
victim = MyClassifier()
# choose PWWS as the attacker and initialize it with default parameters
attacker = oa.attackers.PWWSAttacker()
# prepare for attacking
attack_eval = oa.AttackEval(attacker, victim)
# launch attacks and print attack results 
attack_eval.eval(dataset, visualize=True)
Customized Dataset

The following code snippet shows how to use PWWS to attack an existing fine-tuned sentiment analysis model on a customized dataset (the complete executable code is here).

import OpenAttack as oa
import transformers
import datasets

# load a fine-tuned sentiment analysis model from Transformers (you can also use our fine-tuned Victim.BERT.SST)
tokenizer = transformers.AutoTokenizer.from_pretrained("echarlaix/bert-base-uncased-sst2-acc91.1-d37-hybrid")
model = transformers.AutoModelForSequenceClassification.from_pretrained("echarlaix/bert-base-uncased-sst2-acc91.1-d37-hybrid", num_labels=2, output_hidden_states=False)
victim = oa.classifiers.TransformersClassifier(model, tokenizer, model.bert.embeddings.word_embeddings)

# choose PWWS as the attacker and initialize it with default parameters
attacker = oa.attackers.PWWSAttacker()

# create your customized dataset
dataset = datasets.Dataset.from_dict({
    "x": [
        "I hate this movie.",
        "I like this apple."
    ],
    "y": [
        0, # 0 for negative
        1, # 1 for positive
    ]
})

# prepare for attacking
attack_eval = oa.AttackEval(attacker, victim, metrics = [oa.metric.EditDistance(), oa.metric.ModificationRate()])
# launch attacks and print attack results
attack_eval.eval(dataset, visualize=True)
Multiprocessing

OpenAttack supports convenient multiprocessing to accelerate the process of adversarial attacks. The following code snippet shows how to use multiprocessing in adversarial attacks with Genetic (Alzantot et al. 2018), a genetic algorithm-based attack model (the complete executable code is here).

import OpenAttack as oa
import datasets

def dataset_mapping(x):
    return {
        "x": x["sentence"],
        "y": 1 if x["label"] > 0.5 else 0,
    }

victim = oa.loadVictim("BERT.SST")
dataset = datasets.load_dataset("sst", split="train[:20]").map(function=dataset_mapping)
attacker = oa.attackers.GeneticAttacker()
attack_eval = oa.AttackEval(attacker, victim)
# Using multiprocessing simply by specify num_workers
attack_eval.eval(dataset, visualize=True, num_workers=4)
Chinese Attack

OpenAttack now supports adversarial attacks against English and Chinese victim models. Here is an example code of conducting adversarial attacks against a Chinese review classification model using PWWS.

Customized Attack Model

OpenAttack incorporates many handy components that can be easily assembled into new attack models. Here gives an example of how to design a simple attack model that shuffles the tokens in the original sentence.

Adversarial Training

OpenAttack can easily generate adversarial examples by attacking instances in the training set, which can be added to original training data set to retrain a more robust victim model, i.e., adversarial training. Here gives an example of how to conduct adversarial training with OpenAttack.

More Examples
  • Attack Sentence Pair Classification Models. In addition to single sentence classification models, OpenAttack support attacks against sentence pair classification models. Here is an example code of conducting adversarial attacks against an NLI model with OpenAttack.

  • Customized Evaluation Metric. OpenAttack supports designing a customized adversarial attack evaluation metric. Here gives an example of how to add a customized evaluation metric and use it to evaluate adversarial attacks.

Attack Models

According to the level of perturbations imposed on original input, textual adversarial attack models can be categorized into sentence-level, word-level, character-level attack models.

According to the accessibility to the victim model, textual adversarial attack models can be categorized into gradient-based, score-based, decision-based and blind attack models.

TAADPapers is a paper list which summarizes almost all the papers concerning textual adversarial attack and defense. You can have a look at this list to find more attack models.

Currently OpenAttack includes 15 typical attack models against text classification models that cover all attack types.

Here is the list of currently involved attack models.

  • Sentence-level
    • (SEA) Semantically Equivalent Adversarial Rules for Debugging NLP Models. Marco Tulio Ribeiro, Sameer Singh, Carlos Guestrin. ACL 2018. decision [pdf] [code]
    • (SCPN) Adversarial Example Generation with Syntactically Controlled Paraphrase Networks. Mohit Iyyer, John Wieting, Kevin Gimpel, Luke Zettlemoyer. NAACL-HLT 2018. blind [pdf] [code&data]
    • (GAN) Generating Natural Adversarial Examples. Zhengli Zhao, Dheeru Dua, Sameer Singh. ICLR 2018. decision [pdf] [code]
  • Word-level
    • (TextFooler) Is BERT Really Robust? A Strong Baseline for Natural Language Attack on Text Classification and Entailment. Di Jin, Zhijing Jin, Joey Tianyi Zhou, Peter Szolovits. AAAI-20. score [pdf] [code]
    • (PWWS) Generating Natural Language Adversarial Examples through Probability Weighted Word Saliency. Shuhuai Ren, Yihe Deng, Kun He, Wanxiang Che. ACL 2019. score [pdf] [code]
    • (Genetic) Generating Natural Language Adversarial Examples. Moustafa Alzantot, Yash Sharma, Ahmed Elgohary, Bo-Jhang Ho, Mani Srivastava, Kai-Wei Chang. EMNLP 2018. score [pdf] [code]
    • (SememePSO) Word-level Textual Adversarial Attacking as Combinatorial Optimization. Yuan Zang, Fanchao Qi, Chenghao Yang, Zhiyuan Liu, Meng Zhang, Qun Liu and Maosong Sun. ACL 2020. score [pdf] [code]
    • (BERT-ATTACK) BERT-ATTACK: Adversarial Attack Against BERT Using BERT. Linyang Li, Ruotian Ma, Qipeng Guo, Xiangyang Xue, Xipeng Qiu. EMNLP 2020. score [pdf] [code]
    • (BAE) BAE: BERT-based Adversarial Examples for Text Classification. Siddhant Garg, Goutham Ramakrishnan. EMNLP 2020. score [pdf] [code]
    • (FD) Crafting Adversarial Input Sequences For Recurrent Neural Networks. Nicolas Papernot, Patrick McDaniel, Ananthram Swami, Richard Harang. MILCOM 2016. gradient [pdf]
  • Word/Char-level
    • (TextBugger) TEXTBUGGER: Generating Adversarial Text Against Real-world Applications. Jinfeng Li, Shouling Ji, Tianyu Du, Bo Li, Ting Wang. NDSS 2019. gradient score [pdf]
    • (UAT) Universal Adversarial Triggers for Attacking and Analyzing NLP. Eric Wallace, Shi Feng, Nikhil Kandpal, Matt Gardner, Sameer Singh. EMNLP-IJCNLP 2019. gradient [pdf] [code] [website]
    • (HotFlip) HotFlip: White-Box Adversarial Examples for Text Classification. Javid Ebrahimi, Anyi Rao, Daniel Lowd, Dejing Dou. ACL 2018. gradient [pdf] [code]
  • Char-level
    • (VIPER) Text Processing Like Humans Do: Visually Attacking and Shielding NLP Systems. Steffen Eger, Gözde Gül ¸Sahin, Andreas Rücklé, Ji-Ung Lee, Claudia Schulz, Mohsen Mesgar, Krishnkant Swarnkar, Edwin Simpson, Iryna Gurevych. NAACL-HLT 2019. score [pdf] [code&data]
    • (DeepWordBug) Black-box Generation of Adversarial Text Sequences to Evade Deep Learning Classifiers. Ji Gao, Jack Lanchantin, Mary Lou Soffa, Yanjun Qi. IEEE SPW 2018. score [pdf] [code]

The following table illustrates the comparison of the attack models.

Model Accessibility Perturbation Main Idea
SEA Decision Sentence Rule-based paraphrasing
SCPN Blind Sentence Paraphrasing
GAN Decision Sentence Text generation by encoder-decoder
TextFooler Score Word Greedy word substitution
PWWS Score Word Greedy word substitution
Genetic Score Word Genetic algorithm-based word substitution
SememePSO Score Word Particle Swarm Optimization-based word substitution
BERT-ATTACK Score Word Greedy contextualized word substitution
BAE Score Word Greedy contextualized word substitution and insertion
FD Gradient Word Gradient-based word substitution
TextBugger Gradient, Score Word+Char Greedy word substitution and character manipulation
UAT Gradient Word, Char Gradient-based word or character manipulation
HotFlip Gradient Word, Char Gradient-based word or character substitution
VIPER Blind Char Visually similar character substitution
DeepWordBug Score Char Greedy character manipulation

Toolkit Design

Considering the significant distinctions among different attack models, we leave considerable freedom for the skeleton design of attack models, and focus more on streamlining the general processing of adversarial attacking and the common components used in attack models.

OpenAttack has 7 main modules:

toolkit_framework

  • TextProcessor: processing the original text sequence to assist attack models in generating adversarial examples;
  • Victim: wrapping victim models;
  • Attacker: comprising various attack models;
  • AttackAssist: packing different word/character substitution methods that are used in word-/character-level attack models and some other components used in sentence-level attack models like the paraphrasing model;
  • Metric: providing several adversarial example quality metrics that can serve as either the constraints on the adversarial examples during attacking or evaluation metrics for evaluating adversarial attacks;
  • AttackEval: evaluating textual adversarial attacks from attack effectiveness, adversarial example quality and attack efficiency;
  • DataManager: managing all data and saved models that are used in other modules.

Citation

Please cite our paper if you use this toolkit:

@inproceedings{zeng2020openattack,
  title={{Openattack: An open-source textual adversarial attack toolkit}},
  author={Zeng, Guoyang and Qi, Fanchao and Zhou, Qianrui and Zhang, Tingji and Hou, Bairu and Zang, Yuan and Liu, Zhiyuan and Sun, Maosong},
  booktitle={Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing: System Demonstrations},
  pages={363--371},
  year={2021},
  url={https://aclanthology.org/2021.acl-demo.43},
  doi={10.18653/v1/2021.acl-demo.43}
}

Contributors

We thank all the contributors to this project. And more contributions are very welcome.

openattack's People

Contributors

a710128 avatar cgq15 avatar cypredar avatar dawnranger avatar dependabot[bot] avatar e-tornike avatar fanchao-qi avatar helloxcq avatar hongcheng-gao avatar raibows avatar zhougr18 avatar zixianma avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openattack's Issues

How to load new trained BERT model?

Is there any example code showing how to load my own trained BERT model (trained using Huggingface's Transformer library). I have my own BERT classifier codes as well as the model weights trained on my dataset, I can load the trained weights to initialize the model using Huggingface's codes, but how do I do that using your OpenAttack.DataManager and use it as the target model for attacking?
Some simple example would be really appreciated!

decode problem

Hi. When I tried the first example in "Usage Examples" on my Linux PC, I met a decode problem:

Traceback (most recent call last):
File "/root/root/Desktop/textAttackTest/test.py", line 7, in
attacker = oa.attackers.GeneticAttacker()
File "/usr/local/miniconda3/lib/python3.6/site-packages/OpenAttack/attackers/genetic.py", line 71, in init
self.config["substitute"] = CounterFittedSubstitute()
File "/usr/local/miniconda3/lib/python3.6/site-packages/OpenAttack/substitutes/counter_fit.py", line 16, in init
self.wordvec = DataManager.load("AttackAssist.CounterFit")
File "/usr/local/miniconda3/lib/python3.6/site-packages/OpenAttack/data_manager.py", line 73, in load
cls.data_path[data_name]
File "/usr/local/miniconda3/lib/python3.6/site-packages/OpenAttack/data/counter_fit.py", line 22, in LOAD
for line in f.readlines():
File "/usr/local/miniconda3/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1640: ordinal not in range(128)
It seemed nothing got wrong.
Any idea? Thanks.

How to deal with multi-label target?

What if I want to attack models on a dataset with more than 2 labels ('pos' / 'neg')? I only see models with get_prob function returning only probability for 2 labels.

data/chinese_word2vec has bugs

the LOAD method in data/chinese_word2vec has bugs. You can try with

from collections import Counter
Counter(word2id.values()).most_common()

and see what will happen. The point is that the words have duplicates.
The correct ways should be

# 2x faster, but much more memory consuming
content = list(filter(lambda l: len(l)==301, [line.strip().split(' ') for line in f.readlines()]))
id2vec = np.array([line[1:] for line in content], dtype=float)
word2id = {line[0]:i for i,line in enumerate(content)}

or

id2vec = []
word2id = {}
for idx, line in enumerate(f.readlines()):
    tmp = line.strip().split(' ')
    word = tmp[0]
    embed = np.array([float(x) for x in tmp[1:]])
    if len(embed) != 300:
        continue
    word2id[word] = idx
    id2vec.append(embed)
    print(f"processed {idx+1} lines", end="\r")
id2vec = np.stack(id2vec)

Implementation Error for UAT

It seems that in attacker/uat.py, the call function of the attacker just returns the originally initialised triggers without performing any search :o

Tokenizers in pertained models do not have a lang tag

what I did:

import OpenAttack as oa
victim = oa.DataManager.loadVictim("ROBERTA.AG")

Then

  • victim.tokenizer.TAGS is {None}
  • victim.tokenizer.__lang_tag gets AttributeError: 'TransformersTokenizer' object has no attribute '__lang_tag'

I tried to fix it by victim.tokenizer.__lang_tag = oa.tags.TAG_English. But it does not resolve the issue. I still get the same errors.

[Need helps] OpenAttack may Cause the OS reboot without any warnings

Hi!
I met a weird bug that is the OS will reboot suddenly when trying to run the example code of OpenAttack.
Here is my environment:

  • OS: Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-52-generic x86_64)
  • Python: 3.7.9 (Anaconda)
  • OpenAttack: 1.1.1
  • CPU: Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
  • Mem: 64GB

It works well when running the demo.py in the root directory of OpenAttack. But will cause the OS reboot in few seconds with running below example codes:

from torch import nn, optim
from torch.utils.data import DataLoader
from tqdm import tqdm
import argparse
import re
import torch
import OpenAttack as oa


if __name__ == '__main__':
        device = torch.device('cuda:0')
        print('hello?')
        victim = oa.DataManager.load("Victim.BERT.SST")
        # choose an evaluation dataset
        dataset = oa.DataManager.load("Dataset.SST.sample")

        # choose Genetic as the attacker and initialize it with default parameters
        attacker = oa.attackers.GeneticAttacker()
        # # prepare for attacking
        attack_eval = oa.attack_evals.DefaultAttackEval(attacker, victim)
        # # launch attacks and print attack results
        attack_eval.eval(dataset, visualize=True)

The cpuinfo shows that the cpu reaches full load soon after runing the above codes. And it will reboot in few seconds with no output, no exit codes, no warnings. Monitoring the temperature/fans/ power of CPU, there is nothing irregular. And I even try to read the kernel log(/var/log/syslog) to find what happend, but there is no useful messages indicating no kernel dead messages. Seems like the server has something wrong in the power supply or hardware. It confused me for several days.

Today I try to run the cpu-stress(s-tui package), the cpu also reaches full load. But it still works well after nearly 20 minutes stress-testing. it's very weird.

Hope to get your help. Sincere thanks to you!

Question about the implemention of Hotflip

Hotflip is based on the gradient in the original papper. I used the HotflipAttacker to attack a LSTM classifier successfully, but I found no gradient fetch process in the source code. I would like to ask whether the HotflipAttacker in the OpenAttack is consistent with the original papper?
Looking forward to your reply and thank you.

'str' object has no attribute 'softmax'

Hi, I ran into a bug when I just copied the codes listed as simple usage:

import OpenAttack as oa
victim = oa.DataManager.load("Victim.BERT.SST")
print(victim)
# choose an evaluation dataset
dataset = oa.DataManager.load("Dataset.SST.sample")
# choose Genetic as the attacker and initialize it with default parameters
attacker = oa.attackers.GeneticAttacker()
# prepare for attacking
attack_eval = oa.attack_evals.DefaultAttackEval(attacker, victim)
# launch attacks and print attack results
attack_eval.eval(dataset, visualize=True)

It threw an AttributeError: 'str' object has no attribute 'softmax'
Could you tell me how to solve the problem?

tensorflow.python.framework.errors_impl.NotFoundError

Hi, I ran into a bug when I just copied the codes listed as simple usage:

import OpenAttack as oa
victim = oa.DataManager.load("Victim.BERT.SST")

choose an evaluation dataset

dataset = oa.DataManager.load("Dataset.SST.sample")

choose TextFooler as the attacker and initialize it with default parameters

attacker = oa.attackers.TextFoolerAttacker()

prepare for attacking

attack_eval = oa.attack_evals.DefaultAttackEval(attacker, victim)

launch attacks and print attack results

attack_eval.eval(dataset, visualize=True)

It threw an tensorflow.python.framework.errors_impl.NotFoundError: Op type not registered 'SentencepieceOp' in binary running on DESKTOP-4S1SUPC. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) tf.contrib.resampler should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed.

Could you tell me how to solve the problem?

tensorflow.python.framework.errors_impl.NotFoundError

Hi, After I upgraded OpenAttack to the latest version, 2.0.1, I still encountered this error. (tensorflow.python.framework.errors_impl.NotFoundError: Op type not registered 'SentencepieceOp' in binary running on DESKTOP-4S1SUPC. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) tf.contrib.resampler should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed.)

I found that it only occurs in the TextFooler attack method, and it usually works under other attack methods.

Hope to get your help. Sincere thanks to you!

Is OpenAttack only can attack classifiers ?

I'm very sorry I didn't read the paper. I am doing some text modification for others, but I'm unfamiliar with this field. I found the attackers generate adversarial examples need a classifier. I want to know whether I can use OpenAttack to generate the adversarial examples of my dataset, which comes from dailydialogue, without classifier to attack dialouge system.

More general attack in HotFlip

I find the HotFlip attacker only supports substitution. However, in HotFlip paper, it said, "HotFlip also supports insertion and deletion operations by representing them as sequences of character substitutions."

I find HotFlip can be generalized to almost arbitrary string transformations. In our paper, we defined a DSL for specifying a string transformation as an attack model. (https://arxiv.org/abs/2002.09579)
And I have implemented a prototype in https://github.com/ForeverZyh/A3T/blob/master/DSL/transformations.py.
However, the code is not clean and I've also used multiprocessing to speed up the adversarial training, limiting the generalizability.

I would like to contribute to this project. If you find it is interesting, we can probably have a chat.

How to load custom dataset

Hi, I'm wondering how I could load a dataset and turn it into the format which OpenAttack.DataManager.loadDataset returns in, or I should manually create some OpenAttack.utils.dataset.DataInstances and modify their properties?

Chinese Attack?

Hi, does your toolkit support Chinese attack? I saw that you have implemented hownet for word substitution, but there isn't any specific attacker or evaluation metric for Chinese. Thank you!

Support for multilanguage attack?

OpenAttack seems like a very versatile attacking framework. I wonder if the module has any support for non-English attack? For example, if I want to attack a French/Spanish/German model, is there a tutorial for such scenario? Really appreciate any help !

I had A problem run demo.py

I had a problem with the last sentence of the demo(“attack_eval.eval(dataset, visualize=True)”), and I don't know why
image

PWWS attack

It seems the implementation of PWWS attack is different from the original work.
Could you explain about the differences?
Also, could you explain what's the difference between impelentations of TextAttack and OpenAttack?

OverflowError: signed integer is greater than maximum

Hello,

I've noticed that a few scripts, such as workflow.py, give overflow errors. I'm using Python 3.8 in anaconda environment with all required libraries installed, Can you please share your thoughts on this? Thank you!

Traceback (most recent call last):
File "examples/workflow.py", line 24, in
main()
File "examples/workflow.py", line 7, in main
clsf = OpenAttack.DataManager.load("Victim.BiLSTM.SST")
File "/Users/user/opt/anaconda3/envs/lib/python3.8/site-packages/OpenAttack-1.1.1-py3.8.egg/OpenAttack/data_manager.py", line 72, in load
cls.data_reference[data_name] = cls.data_loader[data_name](
File "/Users/user/opt/anaconda3/envs/lib/python3.8/site-packages/OpenAttack-1.1.1-py3.8.egg/OpenAttack/data/victim_bilstm.py", line 50, in LOAD
word_vector = OpenAttack.DataManager.load("AttackAssist.GloVe")
File "/Users/user/opt/anaconda3/envs/lib/python3.8/site-packages/OpenAttack-1.1.1-py3.8.egg/OpenAttack/data_manager.py", line 64, in load
cls.download(data_name)
File "/Users/user/opt/anaconda3/envs/lib/python3.8/site-packages/OpenAttack-1.1.1-py3.8.egg/OpenAttack/data_manager.py", line 175, in download
cls.data_downloaddata_name
File "/Users/user/opt/anaconda3/envs/lib/python3.8/site-packages/OpenAttack-1.1.1-py3.8.egg/OpenAttack/utils/zip_downloader.py", line 16, in DOWNLOAD
zf = zipfile.ZipFile(io.BytesIO(f.read()))
File "/Users/user/opt/anaconda3/envs/lib/python3.8/http/client.py", line 471, in read
s = self._safe_read(self.length)
File "/Users/user/opt/anaconda3/envs/lib/python3.8/http/client.py", line 612, in _safe_read
data = self.fp.read(amt)
File "/Users/user/opt/anaconda3/envs/lib/python3.8/socket.py", line 669, in readinto
return self._sock.recv_into(b)
File "/Users/user/opt/anaconda3/envs/lib/python3.8/ssl.py", line 1241, in recv_into
return self.read(nbytes, buffer)
File "/Users/user/opt/anaconda3/envs/lib/python3.8/ssl.py", line 1099, in read
return self._sslobj.read(len, buffer)
OverflowError: signed integer is greater than maximum

Potential bug in word substitution

I met with a crash at this line for some examples:

token = word.replace('_', ' ').split()[0]

The reason behind this is when word is composed of only "_" characters, e.g. word="_", the code would run into a IndexError: list index out of range exception.
So I think perform some checks before this line should avoid this problem.

generate adversarial samples API needed

After updating, attack_evals.DefaultAttackEval no longer exist. The test below is broken.

OpenAttack.attack_evals.DefaultAttackEval(attacker, time_clsf, num_process=2).eval(dataset, progress_bar=True),

Because we don't have DefaultAttackEval anymore, it seems like we don't have a function to generate adversarial examples. The TODO below implementation is now emergent.
## TODO generate adversarial samples

unable to load any dataset

there is no any dataset in OpenAttack.DataManager.AVAILABLE_DATAS:

['AttackAssist.ChineseWord2Vec',
 'AttackAssist.CiLin',
 'AttackAssist.CounterFit',
 'AttackAssist.DCES',
 'AttackAssist.FYH',
 'AttackAssist.GAN',
 'AttackAssist.GloVe',
 'AttackAssist.HowNet',
 'AttackAssist.HownetSubstituteDict',
 'TProcess.NLTKPerceptronPosTagger',
 'TProcess.NLTKSentTokenizer',
 'TProcess.NLTKWordNet',
 'TProcess.NLTKWordNetDelemma',
 'AttackAssist.SCPN',
 'AttackAssist.SentenceTransformer',
 'AttackAssist.SGAN',
 'AttackAssist.SIM',
 'TProcess.StanfordNER',
 'TProcess.StanfordParser',
 'test',
 'AttackAssist.TranslationModels',
 'AttackAssist.UniversalSentenceEncoder',
 'Victim.ALBERT.AG',
 'Victim.ALBERT.IMDB',
 'Victim.ALBERT.MNLI',
 'Victim.ALBERT.SNLI',
 'Victim.ALBERT.SST',
 'Victim.BERT.SST',
 'Victim.BERT.AMAZON_ZH',
 'Victim.BERT.MNLI',
 'Victim.BERT.SNLI',
 'Victim.BiLSTM.SST',
 'Victim.BiLSTM.IMDB',
 'Victim.ROBERTA.AG',
 'Victim.ROBERTA.IMDB',
 'Victim.ROBERTA.MNLI',
 'Victim.ROBERTA.SNLI',
 'Victim.ROBERTA.SST',
 'Victim.XLNET.AG',
 'Victim.XLNET.IMDB',
 'Victim.XLNET.MNLI',
 'Victim.XLNET.SNLI',
 'Victim.XLNET.SST',
 'AttackAssist.Word2Vec']

and dataset cannot be loaded manually since Dataset and DataInstance are removed

Is there any other way to load custom dataset?

How to handle inputs consisting of sentence pairs?

Hi,
I tried attacking a victim model for SNLI with inputs being pairs of sentences. The underlying HuggingfaceClassifier expects a string as input, hence I am wondering what is the expected way of handling sentence boundary in this situation.
I tried including a [SEP] token at the sentence boundary, but this resulted in the token being attacked sometimes, which seems to be an undesired attack.
Or a simple concatenation of the premise and hypothesis sentences should do the job without indicating the boundaries between the sentences?
Thanks for the help in advance.

Some exceptions happen when starting the Built-in attack

I tried to start the demo code in readme.md, but it seems that some exceptions have happened....

The code is shown as below:

import OpenAttack as oa

choose a trained victim classification model

victim = oa.DataManager.load("Victim.BERT.SST")

choose an evaluation dataset

dataset = oa.DataManager.load("Dataset.SST.sample")

choose Genetic as the attacker and initialize it with default parameters

attacker = oa.attackers.GeneticAttacker()

prepare for attacking

attack_eval = oa.attack_evals.DefaultAttackEval(attacker, victim)

launch attacks and print attack results

attack_eval.eval(dataset, visualize=False)

And the exceptions are as below:

0%| | 0/1000 [00:00<?, ?it/s]C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\transformers\tokenization_utils_base.py:1770: FutureWarning: The pad_to_max_length argument is deprecated and will be removed in a future version, use padding=True or padding='longest' to pad to the longest sequence in the batch, or use padding='max_length' to pad to a max length. In this case, you can give a specific length with max_length (e.g. max_length=45) or leave max_length to None to pad to the maximal input size of the model (e.g. 512 for Bert).
FutureWarning,
0%| | 0/1000 [00:01<?, ?it/s]
Traceback (most recent call last):
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\OpenAttack\data_manager.py", line 73, in load
cls.data_path[data_name]
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\OpenAttack\data\nltk_senttokenizer.py", line 17, in LOAD
return import("nltk").data.load(os.path.join(path, "english.pickle")).tokenize
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\nltk\data.py", line 752, in load
opened_resource = _open(resource_url)
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\nltk\data.py", line 882, in _open
return urlopen(resource_url)
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\urllib\request.py", line 525, in open
response = self._open(req, data)
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\urllib\request.py", line 548, in _open
'unknown_open', req)
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\urllib\request.py", line 1389, in unknown_open
raise URLError('unknown url type: %s' % type)
urllib.error.URLError:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "e:\ResearchTraining\openAttack\test.py", line 11, in
attack_eval.eval(dataset, visualize=False)
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\OpenAttack\attack_evals\default.py", line 96, in eval
for data, x_adv, y_adv, info in (tqdm(self.eval_results(dataset), total=total_len) if self.__progress_bar else self.eval_results(dataset)):
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\tqdm\std.py", line 1129, in iter
for obj in iterable:
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\OpenAttack\attack_evals\default.py", line 151, in eval_results
res = self.attacker(self.classifier, data.x, data.target)
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\OpenAttack\attackers\genetic.py", line 86, in call
x_orig = self.config["processor"].get_tokens(x_orig)
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\OpenAttack\text_processors\default.py", line 37, in get_tokens
self.__tokenize = self.__make_tokenizer( DataManager.load("TProcess.NLTKSentTokenizer") )
File "C:\Users\13189\Anaconda3\envs\Envtextworld\lib\site-packages\OpenAttack\data_manager.py", line 76, in load
raise DataNotExistException(data_name, cls.data_path[data_name])
OpenAttack.exceptions.data_manager.DataNotExistException: ('TProcess.NLTKSentTokenizer', 'E:\ResearchTraining\openAttack\data\TProcess.NLTKSentTokenizer')

Sorry but I don't know how to solve this problem......Please help me. Thank you !

workflow更改数据集和攻击模型后的问题

有一个问题想请教一下,在跑workflow这个代码时,做了以下更改,将数据集换成BiLSTM.IMDB,攻击模型换成TEXTBUGGER,“x”:x["text"];但出现TypeError错误。如附件中图所示。请问怎么进行调试,谢谢!
1
2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.