• Stars
    star
    135
  • Rank 261,270 (Top 6 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created almost 2 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An open-source toolkit for textual backdoor attack and defense (NeurIPS 2022 D&B, Spotlight)

OpenBackdoor

Documentation Status GitHub PRs are Welcome

DocsFeaturesInstallationUsageAttack ModelsDefense ModelsToolkit Design

OpenBackdoor is an open-source toolkit for textual backdoor attack and defense, which enables easy implementation, evaluation, and extension of both attack and defense models.

Features

OpenBackdoor has the following features:

  • Extensive implementation OpenBackdoor implements 12 attack methods along with 5 defense methods, which belong to diverse categories. Users can easily replicate these models in a few lines of code.

  • Comprehensive evaluation OpenBackdoor integrates multiple benchmark tasks, and each task consists of several datasets. Meanwhile, OpenBackdoor supports Huggingface's Transformers and Datasets libraries.

  • Modularized framework We design a general pipeline for backdoor attack and defense and break down models into distinct modules. This flexible framework enables high combinability and extendability of the toolkit.

Installation

You can install OpenBackdoor through Git

Git

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

Download Datasets

OpenBackdoor supports multiple tasks and datasets. You can download the datasets for each task with bash scripts. For example, download sentiment analysis datasets by

cd datasets
bash download_sentiment_analysis.sh
cd ..

Usage

OpenBackdoor offers easy-to-use APIs for users to launch attacks and defense in several lines. The below code blocks present examples of built-in attack and defense. After installation, you can try running demo_attack.py and demo_defend.py to check if OpenBackdoor works well:

Attack

# Attack BERT on SST-2 with BadNet
import openbackdoor as ob 
from openbackdoor import load_dataset
# choose BERT as victim model 
victim = ob.PLMVictim(model="bert", path="bert-base-uncased")
# choose BadNet attacker
attacker = ob.Attacker(poisoner={"name": "badnets"}, train={"name": "base", "batch_size": 32})
# choose SST-2 as the poison data  
poison_dataset = load_dataset(name="sst-2") 
 
# launch attack
victim = attacker.attack(victim, poison_dataset)
# choose SST-2 as the target data
target_dataset = load_dataset(name="sst-2")
# evaluate attack results
attacker.eval(victim, target_dataset)

Defense

# Defend BadNet attack BERT on SST-2 with ONION
import openbackdoor as ob 
from openbackdoor import load_dataset
# choose BERT as victim model 
victim = ob.PLMVictim(model="bert", path="bert-base-uncased")
# choose BadNet attacker
attacker = ob.Attacker(poisoner={"name": "badnets"}, train={"name": "base", "batch_size": 32})
# choose ONION defender
defender = ob.defenders.ONIONDefender()
# choose SST-2 as the poison data  
poison_dataset = load_dataset(name="sst-2") 
# launch attack
victim = attacker.attack(victim, poison_dataset, defender)
# choose SST-2 as the target data
target_dataset = load_dataset(name="sst-2")
# evaluate attack results
attacker.eval(victim, target_dataset, defender)

Results

OpenBackdoor summarizes the results in a dictionary and visualizes key messages as below:

results

Play with configs

OpenBackdoor supports specifying configurations using .json files. We provide example config files in configs.

To use a config file, just run the code

python demo_attack.py --config_path configs/base_config.json

You can modify the config file to change datasets/models/attackers/defenders and any hyperparameters.

Plug your own attacker/defender

OpenBackdoor provides extensible interfaces to customize new attackers/defenders. You can define your own attacker/defender class

Customize Attacker
class Attacker(object):

    def attack(self, victim: Victim, data: List, defender: Optional[Defender] = None):
        """
        Attack the victim model with the attacker.

        Args:
            victim (:obj:`Victim`): the victim to attack.
            data (:obj:`List`): the dataset to attack.
            defender (:obj:`Defender`, optional): the defender.

        Returns:
            :obj:`Victim`: the attacked model.

        """
        poison_dataset = self.poison(victim, data, "train")

        if defender is not None and defender.pre is True:
            poison_dataset["train"] = defender.correct(poison_data=poison_dataset['train'])
        backdoored_model = self.train(victim, poison_dataset)
        return backdoored_model

    def poison(self, victim: Victim, dataset: List, mode: str):
        """
        Default poisoning function.

        Args:
            victim (:obj:`Victim`): the victim to attack.
            dataset (:obj:`List`): the dataset to attack.
            mode (:obj:`str`): the mode of poisoning.
        
        Returns:
            :obj:`List`: the poisoned dataset.

        """
        return self.poisoner(dataset, mode)

    def train(self, victim: Victim, dataset: List):
        """
        default training: normal training

        Args:
            victim (:obj:`Victim`): the victim to attack.
            dataset (:obj:`List`): the dataset to attack.
    
        Returns:
            :obj:`Victim`: the attacked model.
        """
        return self.poison_trainer.train(victim, dataset, self.metrics)

An attacker contains a poisoner and a trainer. The poisoner is used to poison the dataset. The trainer is used to train the backdoored model.

You can set your own data poisoning algorithm as a poisoner

class Poisoner(object):

    def poison(self, data: List):
        """
        Poison all the data.

        Args:
            data (:obj:`List`): the data to be poisoned.
        
        Returns:
            :obj:`List`: the poisoned data.
        """
        return data

And control the training schedule by a trainer

class Trainer(object):

    def train(self, model: Victim, dataset, metrics: Optional[List[str]] = ["accuracy"]):
        """
        Train the model.

        Args:
            model (:obj:`Victim`): victim model.
            dataset (:obj:`Dict`): dataset.
            metrics (:obj:`List[str]`, optional): list of metrics. Default to ["accuracy"].
        Returns:
            :obj:`Victim`: trained model.
        """

        return self.model
Customize Defender

To write a custom defender, you need to modify the base defender class. In OpenBackdoor, we define two basic methods for a defender.

  • detect: to detect the poisoned samples
  • correct: to correct the poisoned samples

You can also implement other kinds of defenders.

class Defender(object):
    """
    The base class of all defenders.

    Args:
        name (:obj:`str`, optional): the name of the defender.
        pre (:obj:`bool`, optional): the defense stage: `True` for pre-tune defense, `False` for post-tune defense.
        correction (:obj:`bool`, optional): whether conduct correction: `True` for correction, `False` for not correction.
        metrics (:obj:`List[str]`, optional): the metrics to evaluate.
    """
    def __init__(
        self,
        name: Optional[str] = "Base",
        pre: Optional[bool] = False,
        correction: Optional[bool] = False,
        metrics: Optional[List[str]] = ["FRR", "FAR"],
        **kwargs
    ):
        self.name = name
        self.pre = pre
        self.correction = correction
        self.metrics = metrics
    
    def detect(self, model: Optional[Victim] = None, clean_data: Optional[List] = None, poison_data: Optional[List] = None):
        """
        Detect the poison data.

        Args:
            model (:obj:`Victim`): the victim model.
            clean_data (:obj:`List`): the clean data.
            poison_data (:obj:`List`): the poison data.
        
        Returns:
            :obj:`List`: the prediction of the poison data.
        """
        return [0] * len(poison_data)

    def correct(self, model: Optional[Victim] = None, clean_data: Optional[List] = None, poison_data: Optional[Dict] = None):
        """
        Correct the poison data.

        Args:
            model (:obj:`Victim`): the victim model.
            clean_data (:obj:`List`): the clean data.
            poison_data (:obj:`List`): the poison data.
        
        Returns:
            :obj:`List`: the corrected poison data.
        """
        return poison_data

Attack Models

  1. (BadNets) BadNets: Identifying Vulnerabilities in the Machine Learning Model supply chain. Tianyu Gu, Brendan Dolan-Gavitt, Siddharth Garg. 2017. [paper]
  2. (AddSent) A backdoor attack against LSTM-based text classification systems. Jiazhu Dai, Chuanshuai Chen. 2019. [paper]
  3. (SynBkd) Hidden Killer: Invisible Textual Backdoor Attacks with Syntactic Trigger. Fanchao Qi, Mukai Li, Yangyi Chen, Zhengyan Zhang, Zhiyuan Liu, Yasheng Wang, Maosong Sun. 2021. [paper]
  4. (StyleBkd) Mind the Style of Text! Adversarial and Backdoor Attacks Based on Text Style Transfer. Fanchao Qi, Yangyi Chen, Xurui Zhang, Mukai Li, Zhiyuan Liu, Maosong Sun. 2021. [paper]
  5. (POR) Backdoor Pre-trained Models Can Transfer to All. Lujia Shen, Shouling Ji, Xuhong Zhang, Jinfeng Li, Jing Chen, Jie Shi, Chengfang Fang, Jianwei Yin, Ting Wang. 2021. [paper]
  6. (TrojanLM) Trojaning Language Models for Fun and Profit. Xinyang Zhang, Zheng Zhang, Shouling Ji, Ting Wang. 2021. [paper]
  7. (SOS) Rethinking Stealthiness of Backdoor Attack against NLP Models. Wenkai Yang, Yankai Lin, Peng Li, Jie Zhou, Xu Sun. 2021. [paper]
  8. (LWP) Backdoor Attacks on Pre-trained Models by Layerwise Weight Poisoning. Linyang Li, Demin Song,Xiaonan Li, Jiehang Zeng, Ruotian Ma, Xipeng Qiu. 2021. [paper]
  9. (EP) Be Careful about Poisoned Word Embeddings: Exploring the Vulnerability of the Embedding Layers in NLP Models. Wenkai Yang, Lei Li, Zhiyuan Zhang, Xuancheng Ren, Xu Sun, Bin He. 2021. [paper]
  10. (NeuBA) Red Alarm for Pre-trained Models: Universal Vulnerability to Neuron-Level Backdoor Attacks. Zhengyan Zhang, Guangxuan Xiao, Yongwei Li, Tian Lv, Fanchao Qi, Zhiyuan Liu, Yasheng Wang, Xin Jiang, Maosong Sun. 2021. [paper]
  11. (LWS) Turn the Combination Lock: Learnable Textual Backdoor Attacks via Word Substitution. Fanchao Qi, Yuan Yao, Sophia Xu, Zhiyuan Liu, Maosong Sun. 2021. [paper]
  12. (RIPPLES) Weight Poisoning Attacks on Pre-trained Models. Keita Kurita, Paul Michel, Graham Neubig. 2020. [paper]

Defense Models

  1. (ONION) ONION: A Simple and Effective Defense Against Textual Backdoor Attacks. Fanchao Qi, Yangyi Chen, Mukai Li, Yuan Yao,Zhiyuan Liu, Maosong Sun. 2021. [paper]
  2. (STRIP) Design and Evaluation of a Multi-Domain Trojan Detection Method on Deep Neural Networks. Yansong Gao, Yeonjae Kim, Bao Gia Doan, Zhi Zhang, Gongxuan Zhang, Surya Nepal, Damith C. Ranasinghe, Hyoungshick Kim. 2019. [paper]
  3. (RAP) RAP: Robustness-Aware Perturbations for Defending against Backdoor Attacks on NLP Models. Wenkai Yang, Yankai Lin, Peng Li, Jie Zhou, Xu Sun. 2021. [paper]
  4. (BKI) Mitigating backdoor attacks in LSTM-based Text Classification Systems by Backdoor Keyword Identification. Chuanshuai Chen, Jiazhu Dai. 2021. [paper]

Tasks and Datasets

OpenBackdoor integrates 5 tasks and 11 datasets, which can be downloaded from bash scripts in datasets. We list the tasks and datasets below:

  • Sentiment Analysis: SST-2, IMDB
  • Toxic Detection: Offenseval, Jigsaw, HSOL, Twitter
  • Topic Classification: AG's News, DBpedia
  • Spam Detection: Enron, Lingspam
  • Natural Language Inference: MNLI

Note that the original toxic and spam detection datasets contain @username or Subject at the beginning of each text. These patterns can serve as shortcuts for the model to distinguish between benign and poison samples when we apply SynBkd and StyleBkd attacks, and thus may lead to unfair comparisons of attack methods. Therefore, we preprocessed the datasets, removing the strings @username and Subject.

Toolkit Design

pipeline OpenBackdoor has 6 main modules following a pipeline design:

  • Dataset: Loading and processing datasets for attack/defense.
  • Victim: Target PLM models.
  • Attacker: Packing up poisoner and trainer to carry out attacks.
  • Poisoner: Generating poisoned samples with certain algorithms.
  • Trainer: Training the victim model with poisoned/clean datasets.
  • Defender: Comprising training-time/inference-time defenders.

Citation

If you find our toolkit useful, please kindly cite our paper:

@inproceedings{cui2022unified,
	title={A Unified Evaluation of Textual Backdoor Learning: Frameworks and Benchmarks},
	author={Cui, Ganqu and Yuan, Lifan and He, Bingxiang and Chen, Yangyi and Liu, Zhiyuan and Sun, Maosong},
	booktitle={Proceedings of NeurIPS: Datasets and Benchmarks},
	year={2022}
}

More Repositories

1

GNNPapers

Must-read papers on graph neural networks (GNN)
15,490
star
2

WantWords

An open-source online reverse dictionary.
JavaScript
6,933
star
3

OpenNRE

An Open-Source Package for Neural Relation Extraction (NRE)
Python
4,232
star
4

OpenPrompt

An Open-Source Framework for Prompt-Learning.
Python
4,145
star
5

PromptPapers

Must-read papers on prompt-based tuning for pre-trained language models.
3,912
star
6

OpenKE

An Open-Source Package for Knowledge Embedding (KE)
Python
3,725
star
7

PLMpapers

Must-read Papers on pre-trained language models.
3,161
star
8

NRLPapers

Must-read papers on network representation learning (NRL) / network embedding (NE)
TeX
2,520
star
9

UltraChat

Large-scale, Informative, and Diverse Multi-round Chat Data (and Models)
Python
2,118
star
10

THULAC-Python

An Efficient Lexical Analyzer for Chinese
Python
1,972
star
11

OpenNE

An Open-Source Package for Network Embedding (NE)
Python
1,672
star
12

KRLPapers

Must-read papers on knowledge representation learning (KRL) / knowledge embedding (KE)
TeX
1,528
star
13

TAADpapers

Must-read Papers on Textual Adversarial Attack and Defense
Python
1,459
star
14

ERNIE

Source code and dataset for ACL 2019 paper "ERNIE: Enhanced Language Representation with Informative Entities"
Python
1,403
star
15

KB2E

Knowledge Graph Embeddings including TransE, TransH, TransR and PTransE
C++
1,360
star
16

NREPapers

Must-read papers on neural relation extraction (NRE)
TeX
1,023
star
17

OpenCLaP

Open Chinese Language Pre-trained Model Zoo
971
star
18

WebCPM

Official codes for ACL 2023 paper "WebCPM: Interactive Web Search for Chinese Long-form Question Answering"
HTML
952
star
19

OpenDelta

A plug-and-play library for parameter-efficient-tuning (Delta Tuning)
Python
938
star
20

RCPapers

Must-read papers on Machine Reading Comprehension
890
star
21

NRE

Neural Relation Extraction, including CNN, PCNN, CNN+ATT, PCNN+ATT
C++
812
star
22

ToolLearningPapers

777
star
23

THULAC

An Efficient Lexical Analyzer for Chinese
C++
772
star
24

FewRel

A Large-Scale Few-Shot Relation Extraction Dataset
Python
716
star
25

THUOCL

THUOCL(THU Open Chinese Lexicon)中文词库
697
star
26

Chinese_Rumor_Dataset

中文谣言数据
672
star
27

OpenAttack

An Open-Source Package for Textual Adversarial Attack.
Python
652
star
28

DocRED

Dataset and codes for ACL 2019 DocRED: A Large-Scale Document-Level Relation Extraction Dataset.
Python
605
star
29

OpenHowNet

Core Data of HowNet and OpenHowNet Python API
Python
592
star
30

TensorFlow-TransX

An implementation of TransE and its extended models for Knowledge Representation Learning on TensorFlow
Python
511
star
31

LegalPapers

Must-read Papers on Legal Intelligence
450
star
32

OpenMatch

An Open-Source Package for Information Retrieval.
Python
444
star
33

CAIL

Chinese AI & Law Challenge
439
star
34

BERT-KPE

Python
437
star
35

Fast-TransX

An Efficient implementation of TransE and its extended models for Knowledge Representation Learning
C++
396
star
36

TensorFlow-Summarization

Python
390
star
37

Few-NERD

Code and data of ACL 2021 paper "Few-NERD: A Few-shot Named Entity Recognition Dataset"
Python
376
star
38

SOS4NLP

Survey of Surveys for Natural Language Processing (SOS4NLP)
327
star
39

THULAC-Java

An Efficient Lexical Analyzer for Chinese
Java
325
star
40

NSC

Neural Sentiment Classification
Python
287
star
41

BMCourse

The repo for Tsinghua summer course: Interdisciplinary Seminar on Big Models
Python
269
star
42

Chinese_NRE

Source code for ACL 2019 paper "Chinese Relation Extraction with Multi-Grained Information and External Linguistic Knowledge"
Python
264
star
43

DeltaPapers

Must-read Papers of Parameter-Efficient Tuning (Delta Tuning) Methods on Pre-trained Models.
259
star
44

PL-Marker

Source code for "Packed Levitated Marker for Entity and Relation Extraction"
Python
252
star
45

SE-WRL

Improved Word Representation Learning with Sememes
C
197
star
46

THUCTC

An Efficient Chinese Text Classifier
Java
196
star
47

InfLLM

The code of our paper "InfLLM: Unveiling the Intrinsic Capacity of LLMs for Understanding Extremely Long Sequences with Training-Free Memory"
Python
196
star
48

SCPapers

Must-read Papers on Sememe Computation
193
star
49

KnowledgeablePromptTuning

kpt code
Python
192
star
50

CANE

Source code and datasets of "CANE: Context-Aware Network Embedding for Relation Modeling"
Python
190
star
51

JointNRE

Joint Neural Relation Extraction with Text and KGs
Python
185
star
52

HATT-Proto

Code and dataset of AAAI2019 paper Hybrid Attention-Based Prototypical Networks for Noisy Few-Shot Relation Classification
Python
180
star
53

LLaVA-UHD

LLaVA-UHD: an LMM Perceiving Any Aspect Ratio and High-Resolution Images
Python
169
star
54

NLP-THU

NLP Course Material & QA
164
star
55

KernelGAT

The source codes for Fine-grained Fact Verification with Kernel Graph Attention Network.
Python
161
star
56

LegalPLMs

Source code and checkpoints for legal pre-trained language models.
Python
158
star
57

EntityDuetNeuralRanking

Entity-Duet Neural Ranking Model
Python
153
star
58

PTR

Prompt Tuning with Rules
Python
151
star
59

OOP-THU

OOP Course Material & QA
149
star
60

Auto_CLIWC

Code for Chinese LIWC Lexicon Expansion via Hierarchical Classification of Word Embeddings with Sememe Attention (AAAI18)
Python
136
star
61

attribute_charge

The source code of our COLING'18 paper "Few-Shot Charge Prediction with Discriminative Legal Attributes".
Python
126
star
62

ConceptFlow

Python
119
star
63

THUCKE

THU Chinese Keyphrase Extraction Toolkit
C++
118
star
64

CAIL2018

Python
111
star
65

KR-EAR

Knowledge Representation Learning with Entities, Attributes and Relations
C++
111
star
66

Neural-Snowball

Code and dataset of AAAI2020 Paper Neural Snowball for Few-Shot Relation Learning
Python
111
star
67

ChatEval

Codes for our paper "ChatEval: Towards Better LLM-based Evaluators through Multi-Agent Debate"
Python
109
star
68

MultiRD

Code and data of the AAAI-20 paper "Multi-channel Reverse Dictionary Model"
Python
106
star
69

TransNet

Source code and datasets of IJCAI2017 paper "TransNet: Translation-Based Network Representation Learning for Social Relation Extraction".
Jupyter Notebook
103
star
70

RE-Context-or-Names

Bert-based models(BERT, MTB, CP) for relation extraction.
Python
100
star
71

AGE

Source code and dataset for KDD 2020 paper "Adaptive Graph Encoder for Attributed Graph Embedding"
Python
99
star
72

GEAR

Source code for ACL 2019 paper "GEAR: Graph-based Evidence Aggregating and Reasoning for Fact Verification"
Python
95
star
73

HNRE

Hierarchical Neural Relation Extraction
Python
95
star
74

LEVEN

Source code and dataset for ACL2022 Findings Paper "LEVEN: A Large-Scale Chinese Legal Event Detection dataset"
Python
94
star
75

TopJudge

Python
93
star
76

Prompt-Transferability

On Transferability of Prompt Tuning for Natural Language Processing
Python
85
star
77

SememePSO-Attack

Code and data of the ACL 2020 paper "Word-level Textual Adversarial Attacking as Combinatorial Optimization"
Python
85
star
78

XQA

Dataset and baseline for ACL 2019 paper "XQA: A Cross-lingual Open-domain Question Answering Dataset"
Python
84
star
79

HMEAE

Source code for EMNLP-IJCNLP 2019 paper "HMEAE: Hierarchical Modular Event Argument Extraction".
Python
84
star
80

ERICA

Source code for ACL 2021 paper "ERICA: Improving Entity and Relation Understanding for Pre-trained Language Models via Contrastive Learning"
Python
82
star
81

CLAIM

77
star
82

TKRL

Representation Learning of Knowledge Graphs with Hierarchical Types (IJCAI-2016)
C++
76
star
83

TLNN

Source code for EMNLP-IJCNLP 2019 paper "Event Detection with Trigger-Aware Lattice Neural Network".
Python
75
star
84

MMDW

Max-margin DeepWalk
Java
71
star
85

KV-PLM

Source code for "A Deep-learning System Bridging Molecule Structure and Biomedical Text with Comprehension Comparable to Human Professionals"
Python
71
star
86

KNET

Neural Entity Typing with Knowledge Attention
Python
69
star
87

SelectiveMasking

Source code for "Train No Evil: Selective Masking for Task-Guided Pre-Training"
Python
68
star
88

NeuIRPapers

Must-read Papers on Neural Information Retrieval
68
star
89

MoEfication

Python
66
star
90

Adv-ED

Source code and dataset for NAACL 2019 paper "Adversarial Training for Weakly Supervised Event Detection".
Python
66
star
91

CorefBERT

Source code for EMNLP 2020 paper "Coreferential Reasoning Learning for Language Representation"
Python
65
star
92

ConversationQueryRewriter

Code and Data for SIGIR 2020 Paper "Few-Shot Generative Conversational Query Rewriting"
Roff
63
star
93

MuGNN

Source code for ACL2019 paper "Multi-Channel Graph Neural Network for Entity Alignment".
Python
62
star
94

sememe_prediction

Codes for Lexical Sememe Prediction via Word Embeddings and Matrix Factorization (IJCAI 2017).
Python
60
star
95

DIAG-NRE

Source code for ACL 2019 paper "DIAG-NRE: A Neural Pattern Diagnosis Framework for Distantly Supervised Neural Relation Extraction".
Python
59
star
96

topical_word_embeddings

Topical Word Embeddings
Python
57
star
97

QuoteR

Official code and data of the ACL 2022 paper "QuoteR: A Benchmark of Quote Recommendation for Writing"
Python
57
star
98

paragraph2vec

Paragraph Vector Implementation
Python
56
star
99

DKRL

Representation Learning of Knowledge Graphs with Entity Descriptions (AAAI-2016)
C++
54
star
100

Ouroboros

Ouroboros: Speculative Decoding with Large Model Enhanced Drafting
Python
51
star