SeqAttack: a framework for adversarial attacks on token classification models

Overview

SeqAttack: a framework for adversarial attacks on token classification models

SeqAttack is a framework for conducting adversarial attacks against Named Entity Recognition (NER) models and for data augmentation. This library is heavily based on the popular TextAttack framework, and can similarly be used for:

  • Understanding models by running adversarial attacks against them and observing their shortcomings
  • Develop new attack strategies
  • Guided data augmentation, generating additional training samples that can be used to fix a model's shortcomings

The SeqAttack paper is available here.

Setup

Run pip install -r requirements.txt and you're good to go! If you want to run experiments on a fresh virtual machine, check out scripts/gcp.sh which installs all system dependencies for running the code.

The code was tested with python 3.7, if you're using a different version your mileage may vary.

Usage

The main features of the framework are available via the command line interface, wrapped by cli.py. The following subsections describe the usage of the various commands.

Attack

Attacks are executed via the python cli.py attack subcommand. Attack commands are split in two parts:

  • General setup: options common to all adversarial attacks (e.g. model, dataset...)
  • Attack specific setup: options specific to a particular attack strategy

Thus, a typical attack command might look like the following:

python cli.py attack [general-options] attack-recipe [recipe-options]

For example, if we want to attack dslim/bert-base-NER, a NER model trained on CoNLL2003 using deepwordbug as the attack strategy we might run:

python cli.py attack                                            \
       --model-name dslim/bert-base-NER                         \
       --output-path output-dataset.json                        \
       --cache                                                  \
       --dataset-config configs/conll2003-config.json           \
       deepwordbug

The dataset configuration file, configs/conll2003-config.json defines:

  • The dataset path or name (in the latter case it will be downloaded from HuggingFace)
  • The split (e.g. train, test). Only for HuggingFace datasets
  • The human-readable names (a mapping between numerical labels and textual labels), given as a list
  • A labels map, used to remap the dataset's ground truth to align it with the model output as needed. This field can be null if no remapping is needed

In the example above, labels_map is used to align the dataset labels to the output from dslim/bert-base-NER. The dataset labels are the following:

O (0), B-PER (1), I-PER (2), B-ORG (3), I-ORG (4) B-LOC (5), I-LOC (6) B-MISC (7), I-MISC (8)

while the model labels are:

O (0), B-MISC (1), I-MISC (2), B-PER (3), I-PER (4) B-ORG (5), I-ORG (6) B-LOC (7), I-LOC (8)

Thus a remapping is needed and labels_map takes care of it.


The available attack strategies are the following:

Attack Strategy Transformation Constraints Paper
BAE word swap USE sentence cosine similarity https://arxiv.org/abs/2004.01970
BERT-Attack word swap USE sentence cosine similarity, Maximum words perturbed https://arxiv.org/abs/2004.09984
CLARE word swap and insertion USE sentence cosine similarity https://arxiv.org/abs/2009.07502
DeepWordBug character insertion, deletion, swap (ab --> ba) and substitution Levenshtein edit distance https://arxiv.org/abs/1801.04354
Morpheus inflection word swap https://www.aclweb.org/anthology/2020.acl-main.263.pdf
SCPN paraphrasing https://www.aclweb.org/anthology/N18-1170
TextFooler word swap USE sentence cosine similarity, POS match, word-embedding distance https://arxiv.org/abs/1907.11932

The table above is based on this table. In addition to the constraints shown above the attack strategies are also forbidden from modifying and inserting named entities by default.

Evaluation

To evaluate a model against a standard dataset run:

python cli.py evaluate                  \
       --model dslim/bert-base-NER      \
       --dataset conll2003              \
       --split test                     \
       --mode strict                    \

To evaluate the effectivenes of an attack run the following command:

python cli.py evaluate                                  \
       --model dslim/bert-base-NER                      \
       --attacked-dataset experiments/deepwordbug.json  \
       --mode strict                                    \

The above command will compute and display the metrics for the original predictions and their adversarial counterparts.

The evaluation is based on seqeval

Dataset selection

Given a dataset, our victim model may be able to predict some dataset samples perfectly, but it may produce significant errors on others. To evaluate an attack's effectiveness we may want to select samples with a small initial misprediction score. This can be done via the following command:

python cli.py pick-samples                              \
       --model dslim/bert-base-NER                      \
       --dataset-config configs/conll2003-config.json   \
        --max-samples 256                               \
       --max-initial-score 0.5                          \ # The maximum initial misprediction score
       --output-filename cherry-picked.json             \
       --goal-function untargeted

Tests

Tests can be run with pytest

Adversarial examples visualization

The output datasets can be visualized with SeqAttack-Visualization

You might also like...
Adversarial-Information-Bottleneck - Distilling Robust and Non-Robust Features in Adversarial Examples by Information Bottleneck (NeurIPS21)
Super-Fast-Adversarial-Training - A PyTorch Implementation code for developing super fast adversarial training

Super-Fast-Adversarial-Training This is a PyTorch Implementation code for develo

Quickly comparing your image classification models with the state-of-the-art models (such as DenseNet, ResNet, ...)
Quickly comparing your image classification models with the state-of-the-art models (such as DenseNet, ResNet, ...)

Image Classification Project Killer in PyTorch This repo is designed for those who want to start their experiments two days before the deadline and ki

Pytorch Implementation of Adversarial Deep Network Embedding for Cross-Network Node Classification

Pytorch Implementation of Adversarial Deep Network Embedding for Cross-Network Node Classification (ACDNE) This is a pytorch implementation of the Adv

Semi-supervised Representation Learning for Remote Sensing Image Classification Based on Generative Adversarial Networks

SSRL-for-image-classification Semi-supervised Representation Learning for Remote Sensing Image Classification Based on Generative Adversarial Networks

Image-Scaling Attacks and Defenses
Image-Scaling Attacks and Defenses

Image-Scaling Attacks & Defenses This repository belongs to our publication: Erwin Quiring, David Klein, Daniel Arp, Martin Johns and Konrad Rieck. Ad

Code for "Diversity can be Transferred: Output Diversification for White- and Black-box Attacks"

Output Diversified Sampling (ODS) This is the github repository for the NeurIPS 2020 paper "Diversity can be Transferred: Output Diversification for W

Efficient Sparse Attacks on Videos using Reinforcement Learning
Efficient Sparse Attacks on Videos using Reinforcement Learning

EARL This repository provides a simple implementation of the work "Efficient Sparse Attacks on Videos using Reinforcement Learning" Example: Demo: Her

Comments
  • Some questions about equipment performance

    Some questions about equipment performance

    Hi. I'm trying to reproduce SeqAttack recently. I followed the steps in the README you provided.When I used Clare's method to attack, I found a few examples that didn't attack because of the graphic memory. What is the performence of the equipment you used in the experiment,such as GPU. Looking forward to your reply.Thank you!

    opened by Li-miaom 0
Owner
Walter
Software Developer from 🇮🇹 based in 🇳🇱
Walter
PyTorch implementation of our method for adversarial attacks and defenses in hyperspectral image classification.

Self-Attention Context Network for Hyperspectral Image Classification PyTorch implementation of our method for adversarial attacks and defenses in hyp

null 22 Dec 2, 2022
Adversarial Attacks on Probabilistic Autoregressive Forecasting Models.

Attack-Probabilistic-Models This is the source code for Adversarial Attacks on Probabilistic Autoregressive Forecasting Models. This repository contai

SRI Lab, ETH Zurich 25 Sep 14, 2022
Implementation of Wasserstein adversarial attacks.

Stronger and Faster Wasserstein Adversarial Attacks Code for Stronger and Faster Wasserstein Adversarial Attacks, appeared in ICML 2020. This reposito

null 21 Oct 6, 2022
Defending graph neural networks against adversarial attacks (NeurIPS 2020)

GNNGuard: Defending Graph Neural Networks against Adversarial Attacks Authors: Xiang Zhang ([email protected]), Marinka Zitnik (marinka@hms.

Zitnik Lab @ Harvard 44 Dec 7, 2022
Boosting Adversarial Attacks with Enhanced Momentum (BMVC 2021)

EMI-FGSM This repository contains code to reproduce results from the paper: Boosting Adversarial Attacks with Enhanced Momentum (BMVC 2021) Xiaosen Wa

John Hopcroft Lab at HUST 10 Sep 26, 2022
Stable Neural ODE with Lyapunov-Stable Equilibrium Points for Defending Against Adversarial Attacks

Stable Neural ODE with Lyapunov-Stable Equilibrium Points for Defending Against Adversarial Attacks Stable Neural ODE with Lyapunov-Stable Equilibrium

Kang Qiyu 8 Dec 12, 2022
This is official implementaion of paper "Token Shift Transformer for Video Classification".

This is official implementaion of paper "Token Shift Transformer for Video Classification". We achieve SOTA performance 80.40% on Kinetics-400 val. Paper link

VideoNet 60 Dec 30, 2022
Code for the paper: Adversarial Training Against Location-Optimized Adversarial Patches. ECCV-W 2020.

Adversarial Training Against Location-Optimized Adversarial Patches arXiv | Paper | Code | Video | Slides Code for the paper: Sukrut Rao, David Stutz,

Sukrut Rao 32 Dec 13, 2022
Adversarial Color Enhancement: Generating Unrestricted Adversarial Images by Optimizing a Color Filter

ACE Please find the preliminary version published at BMVC 2020 in the folder BMVC_version, and its extended journal version in Journal_version. Datase

null 28 Dec 25, 2022